├── .gitignore
├── README.md
├── license.txt
├── pom.xml
└── src
├── JavaLinuxNet.iml
├── main
└── java
│ └── org
│ └── it4y
│ ├── demo
│ ├── DemoTestApp.java
│ ├── HttpProxyThread.java
│ ├── TNetlinkRoutingListener.java
│ ├── TProxyListener.java
│ ├── TestRunner.java
│ ├── TestThread.java
│ └── TunTapInterfaceListener.java
│ ├── jni
│ ├── JNILoader.java
│ ├── SocketOptions.java
│ ├── libc.java
│ ├── libnetlink3.java
│ ├── libpcap.java
│ ├── linux
│ │ ├── if_address.java
│ │ ├── if_arp.java
│ │ ├── if_link.java
│ │ ├── if_neighbour.java
│ │ ├── in.java
│ │ ├── ioctl.java
│ │ ├── jhash.java
│ │ ├── netlink.java
│ │ ├── pcap.java
│ │ ├── rtnetlink.java
│ │ ├── socket.java
│ │ └── time.java
│ ├── linuxutils.java
│ ├── ntp.java
│ ├── tproxy.java
│ └── tuntap.java
│ ├── net
│ ├── JVMException.java
│ ├── RawPacket.java
│ ├── SocketUtils.java
│ ├── link
│ │ ├── LinkManager.java
│ │ ├── LinkNotification.java
│ │ └── NetworkInterface.java
│ ├── netlink
│ │ ├── AddressRTAMessages.java
│ │ ├── InterfaceRTAMessages.java
│ │ ├── NetlinkMsgFactory.java
│ │ ├── NlDoneMessage.java
│ │ ├── NlErrorMessage.java
│ │ ├── NlMessage.java
│ │ ├── RTAMessage.java
│ │ ├── interfaceAddressMsg.java
│ │ ├── interfaceInfoMsg.java
│ │ ├── neighbourMsg.java
│ │ ├── neighbourRTAMessages.java
│ │ ├── routeMsg.java
│ │ └── routeRTAMessages.java
│ ├── protocols
│ │ └── IP
│ │ │ ├── GRE
│ │ │ └── GREPacket.java
│ │ │ ├── ICMP
│ │ │ └── ICMPPacket.java
│ │ │ ├── IPFactory.java
│ │ │ ├── IPIP
│ │ │ └── IPIPPacket.java
│ │ │ ├── IPv6Tunnel
│ │ │ └── IPv6TunnelPacket.java
│ │ │ ├── IpPacket.java
│ │ │ ├── TCP
│ │ │ ├── TCPOption.java
│ │ │ ├── TCPPacket.java
│ │ │ ├── TCPoptionEnd.java
│ │ │ ├── TCPoptionMSS.java
│ │ │ ├── TCPoptionNOP.java
│ │ │ ├── TCPoptionSACK.java
│ │ │ ├── TCPoptionTimeStamp.java
│ │ │ └── TCPoptionWindowScale.java
│ │ │ └── UDP
│ │ │ └── UDPPacket.java
│ ├── tproxy
│ │ ├── TProxyInterceptedSocket.java
│ │ ├── TProxyListener.java
│ │ └── TProxyServerSocket.java
│ └── tuntap
│ │ └── TunDevice.java
│ └── util
│ ├── Hexdump.java
│ ├── IndexNameMap.java
│ └── PCAPFileReader.java
├── native
├── Makefile
├── README
├── bpf_compile.c
├── java_arch.sh
├── org_it4y_jni_libnetlink3.c
├── org_it4y_jni_libpcap.c
├── org_it4y_jni_linuxutils.c
├── org_it4y_jni_ntp.c
├── org_it4y_jni_tproxy.c
├── org_it4y_jni_tuntap.c
└── testjhash.c
├── setup-test.sh
└── test
├── java
└── org
│ └── it4y
│ ├── benchmarks
│ └── TimeBenchmark.java
│ ├── integration
│ ├── IT_SystemTest.java
│ ├── IT_TProxyListenerTest.java
│ ├── jni
│ │ ├── IT_tuntapReadTest.java
│ │ ├── IT_tuntapTest.java
│ │ └── IT_tuntapWriteTest.java
│ └── utils.java
│ ├── jni
│ ├── InterfaceTest.java
│ ├── JNILoaderTest.java
│ ├── SocketOptionsTest.java
│ ├── libcTest.java
│ ├── libnetlink3Test.java
│ ├── libpcapTest.java
│ ├── linux
│ │ ├── if_addressTest.java
│ │ ├── if_arpTest.java
│ │ ├── if_linkTest.java
│ │ ├── if_neighbourTest.java
│ │ ├── jhashTest.java
│ │ └── rtnetlinkTest.java
│ ├── linuxutilsTest.java
│ ├── ntpTest.java
│ └── tunDeviceTest.java
│ ├── net
│ ├── SocketUtilsTest.java
│ ├── link
│ │ └── LinkManagerTest.java
│ ├── netlink
│ │ ├── NetlinkMsgFactoryTest.java
│ │ └── netLinkMessageTest.java
│ ├── protocols
│ │ └── IP
│ │ │ ├── GRE
│ │ │ └── grePacketTest.java
│ │ │ ├── ICMP
│ │ │ └── ICMPPacketTest.java
│ │ │ ├── IPFactoryTest.java
│ │ │ ├── IPIP
│ │ │ └── IPIPPacketTest.java
│ │ │ ├── IPv6Tunnel
│ │ │ └── IPv6TunnelPacketTest.java
│ │ │ ├── IpPacketTest.java
│ │ │ ├── TCP
│ │ │ ├── TCPPacketTest.java
│ │ │ └── TCPStreamtest.java
│ │ │ └── UDP
│ │ │ └── UDPPacketTest.java
│ └── tproxy
│ │ └── TProxyClientSocketTest.java
│ └── util
│ ├── Counter.java
│ ├── IndexNameMapTest.java
│ └── PCAPFileReaderTest.java
├── pcap
├── gre-full.pcap
├── gre-tunnel-icmp.c
├── gre.pcap
├── http-10m-random.pcap
├── http-dupack.pcap
├── https.pcapng
└── ipip-full.pcap
├── resources
└── log4j.xml
└── scripts
└── setup-test.sh
/.gitignore:
--------------------------------------------------------------------------------
1 | #Ignore following files
2 | *.so
3 | *.class
4 | .idea/*
5 | src/native/*.h
6 |
--------------------------------------------------------------------------------
/src/JavaLinuxNet.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/demo/DemoTestApp.java:
--------------------------------------------------------------------------------
1 |
2 | /*
3 | * Copyright 2014 Luc Willems (T.M.M.)
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14 | * License for the specific language governing permissions and limitations
15 | * under the License.
16 | */
17 |
18 | package org.it4y.demo;
19 |
20 | import org.it4y.net.link.LinkManager;
21 | import org.it4y.net.link.LinkNotification;
22 | import org.it4y.net.link.NetworkInterface;
23 | import org.slf4j.Logger;
24 | import org.slf4j.LoggerFactory;
25 |
26 | /**
27 | * Created by luc on 12/25/13.
28 | * run src/test/scripts/setup-test.sh before running this app. this will setup correct tun device and routing.
29 | * and than ping to 8.8.4.4
30 | */
31 | public class DemoTestApp {
32 | private final static Logger log= LoggerFactory.getLogger("Demo");
33 |
34 | public static void main(String[] args) throws Exception {
35 | TProxyListener tproxy = new TProxyListener();
36 | tproxy.start();
37 | log.info("tproxy server running");
38 | Thread.sleep(100);
39 | TunTapInterfaceListener tundev = new TunTapInterfaceListener("test", 1500);
40 | tundev.start(); //this will bring interface luc UP
41 | log.info("tun interface listener running");
42 | LinkManager lnkMng=new LinkManager();
43 | lnkMng.registerListener(LinkNotification.EventAction.All,LinkNotification.EventType.All, new LinkNotification() {
44 | @Override
45 | public void onEvent(EventAction action, EventType type, NetworkInterface network) {
46 | log.info("onEvent : "+action+" "+type+" "+network);
47 | }
48 |
49 | @Override
50 | public void onStateChanged(NetworkInterface network) {
51 | log.info("onStateChanged : "+network+" active:"+network.isActive());
52 | }
53 | });
54 | //start link manager
55 | lnkMng.start();
56 | Thread.sleep(500);
57 | log.info("ready to rock and roll");
58 | while (true) {
59 | Thread.sleep(1000);
60 | tundev.dumpSpeed();
61 | }
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/demo/TNetlinkRoutingListener.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.demo;
18 |
19 | import org.it4y.jni.libnetlink3;
20 | import org.it4y.jni.linux.netlink;
21 | import org.it4y.jni.linux.rtnetlink;
22 | import org.it4y.net.netlink.NetlinkMsgFactory;
23 | import org.it4y.net.netlink.NlMessage;
24 |
25 | import java.nio.ByteBuffer;
26 | import java.nio.ByteOrder;
27 |
28 | /**
29 | * Created by luc on 1/1/14.
30 | */
31 | public class TNetlinkRoutingListener extends TestRunner {
32 | private final libnetlink3.rtnl_handle handle;
33 | private final ByteBuffer messageBuffer = ByteBuffer.allocateDirect(8129);
34 | private int initstate;
35 |
36 |
37 | public TNetlinkRoutingListener() {
38 | super("tnetlinkrouting-listener");
39 | handle = new libnetlink3.rtnl_handle();
40 |
41 | }
42 |
43 | public void run() {
44 | //we are interested in Routing/link/address events
45 | final int groups = rtnetlink.RTMGRP_IPV4_IFADDR |
46 | rtnetlink.RTMGRP_IPV4_ROUTE |
47 | rtnetlink.RTMGRP_IPV4_MROUTE |
48 | rtnetlink.RTMGRP_LINK;
49 | //System.out.println("Groups: 0x" + Integer.toHexString(groups));
50 | libnetlink3.rtnl_open_byproto(handle, groups, netlink.NETLINK_ROUTE);
51 | //System.out.println(Hexdump.bytesToHex(handle.handle, 4));
52 | running=true;
53 | while (running) {
54 | if (initstate < 4) {
55 | //we can handle only 1 wilddump at the same time, so we have a little stepping program here
56 | switch (initstate) {
57 | case 0:
58 | //System.out.println(new Date() + " Requesting link information...");
59 | libnetlink3.rtnl_wilddump_request(handle, 0, rtnetlink.RTM_GETLINK);
60 | initstate++;
61 | break;
62 | case 1:
63 | //System.out.println(new Date() + " Requesting address information...");
64 | libnetlink3.rtnl_wilddump_request(handle, 0, rtnetlink.RTM_GETADDR);
65 | initstate++;
66 | break;
67 | case 2:
68 | //System.out.println(new Date() + " Requesting routing information...");
69 | libnetlink3.rtnl_wilddump_request(handle, 0, rtnetlink.RTM_GETROUTE);
70 | initstate++;
71 | break;
72 | default:
73 | //System.out.println("Init finished");
74 | initstate = 4; //finished
75 | }
76 | }
77 | //rtnl_listen is blocking until rtnl_accept interface returns rtl_accept_STOP.
78 | //when stop, the listen will return and thread can continue...
79 | messageBuffer.rewind();
80 | messageBuffer.order(ByteOrder.LITTLE_ENDIAN);
81 | libnetlink3.rtnl_listen(handle, messageBuffer, new libnetlink3.rtnl_accept() {
82 | public int accept(final ByteBuffer message) {
83 | //make sure ByteBuffer mar/position are set correct.
84 | message.rewind();
85 | final NlMessage msg = NetlinkMsgFactory.processRawPacket(message);
86 | if (msg != null) {
87 | //System.out.println(new Date() + " " + msg.toString());
88 | //continue or stop listening ?
89 | return msg.moreMessages() ? libnetlink3.rtl_accept_CONTINUE : libnetlink3.rtl_accept_STOP;
90 | }
91 | return libnetlink3.rtl_accept_STOP;
92 | }
93 | });
94 | }
95 | //libnetlink3.rtnl_close(handle);
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/demo/TProxyListener.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.demo;
18 |
19 | import org.it4y.jni.SocketOptions;
20 | import org.it4y.jni.linuxutils;
21 | import org.it4y.net.tproxy.TProxyInterceptedSocket;
22 | import org.it4y.net.tproxy.TProxyServerSocket;
23 | import org.slf4j.Logger;
24 | import org.slf4j.LoggerFactory;
25 |
26 | import java.net.InetAddress;
27 |
28 |
29 | /**
30 | * Created by luc on 12/28/13.
31 | */
32 | public class TProxyListener extends TestRunner {
33 |
34 | private final Logger log= LoggerFactory.getLogger(TProxyListener.class);
35 | private InetAddress listenIp;
36 | private int listenPort;
37 | private TProxyServerSocket server;
38 |
39 | public TProxyListener() {
40 | super("tproxy-listener");
41 | try {
42 | listenIp = InetAddress.getByName("127.0.0.1");
43 | listenPort = 1800;
44 | } catch (final Throwable ignore) {
45 | }
46 | }
47 |
48 | public int getFd() {
49 | return server.getFd();
50 | }
51 |
52 |
53 | public void run() {
54 | try {
55 | server = new TProxyServerSocket();
56 | server.initTProxy(listenIp, listenPort,500);
57 | running = true;
58 | while (running) {
59 | final TProxyInterceptedSocket client = server.accepProxy();
60 |
61 | //set client user transmit timeout
62 | linuxutils.setintSockOption(client.getSocket(), SocketOptions.SOL_TCP, SocketOptions.TCP_USER_TIMEOUT, 10000);
63 |
64 | log.info("TCP timout:",linuxutils.getintSockOption(client.getSocket(), SocketOptions.SOL_TCP, SocketOptions.TCP_USER_TIMEOUT));
65 | //back to the future: switch back to reno :-)
66 | linuxutils.setstringSockOption(client.getSocket(), SocketOptions.SOL_TCP, SocketOptions.TCP_CONGESTION, "reno");
67 | log.info("{} : {}",System.currentTimeMillis(),client);
68 | // TProxyInterceptedSocket lastclient = client;
69 | //do http proxy
70 | new HttpProxyThread(client).start();
71 | }
72 | } catch (final Throwable t) {
73 | log.error("ooeps:", t);
74 | }
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/demo/TestRunner.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.demo;
18 |
19 | /**
20 | * Created by luc on 12/28/13.
21 | */
22 | public abstract class TestRunner extends Thread {
23 | protected boolean running;
24 |
25 | public TestRunner() {
26 | setDaemon(true);
27 | }
28 |
29 | public TestRunner(final String name) {
30 | super(name);
31 | setDaemon(true);
32 | }
33 |
34 | public void halt() {
35 | running = false;
36 | }
37 |
38 | abstract public void run();
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/demo/TestThread.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.demo;
18 |
19 | import org.it4y.net.link.LinkManager;
20 | import org.it4y.net.link.NetworkInterface;
21 | import org.slf4j.Logger;
22 | import org.slf4j.LoggerFactory;
23 |
24 | /**
25 | * Created by luc on 1/4/14.
26 | */
27 | public class TestThread extends TestRunner {
28 | final LinkManager lnkMng;
29 | final Logger log= LoggerFactory.getLogger(TestThread.class);
30 |
31 | public TestThread(final LinkManager lnkMng) {
32 | this.lnkMng=lnkMng;
33 | }
34 |
35 | public void run() {
36 | running=true;
37 | while(running) {
38 | lnkMng.ReadLock();
39 | try {
40 | for (final String name:lnkMng.getInterfaceList()) {
41 | final NetworkInterface x=lnkMng.findByInterfaceName(name);
42 | if(!log.isTraceEnabled()) {
43 | log.trace("{}",x);
44 | }
45 | }
46 | } finally {
47 | lnkMng.ReadUnLock();
48 | }
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/jni/SocketOptions.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.jni;
18 |
19 | /**
20 | * Created by luc on 12/28/13.
21 | */
22 | /*
23 | * This a list of Linux SOCKET options not supported by JAVA
24 | */
25 | public class SocketOptions {
26 |
27 | public static final int SOL_IP = 0;
28 | public static final int SOL_TCP = 6;
29 | public static final int SOL_UDP = 17;
30 |
31 |
32 | public static final int IP_TRANSPARENT = 19;
33 |
34 | /* TCP socket options based on 3.12 kernel uapi/linux/tcp.h list*/
35 | public static final int TCP_NODELAY = 1; /* Turn off Nagle's algorithm. */
36 | public static final int TCP_MAXSEG = 2; /* Limit MSS */
37 | public static final int TCP_CORK = 3; /* Never send partially complete segments */
38 | public static final int TCP_KEEPIDLE = 4; /* Start keeplives after this period */
39 | public static final int TCI_KEEPINTVL = 5; /* Interval between keepalives */
40 | public static final int TCP_KEEPCNT = 6; /* Number of keepalives before death */
41 | public static final int TCP_SYNCNT = 7; /* Number of SYN retransmits */
42 | public static final int TCP_LINGER2 = 8; /* Life time of orphaned FIN-WAIT-2 state */
43 | public static final int TCP_DEFER_ACCEPT = 9; /* Wake up listener only when data arrive */
44 | public static final int TCP_WINDOW_CLAMP = 10; /* Bound advertised window */
45 | public static final int TCP_INFO = 11; /* Information about this connection. */
46 | public static final int TCP_QUICKACK = 12; /* Block/reenable quick acks */
47 | public static final int TCP_CONGESTION = 13; /* Congestion control algorithm */
48 | public static final int TCP_MD5SIG = 14; /* TCP MD5 Signature (RFC2385) */
49 | public static final int TCP_THIN_LINEAR_TIMEOUTS = 16; /* Use linear timeouts for thin streams*/
50 | public static final int TCP_THIN_DUPACK = 17; /* Fast retrans. after 1 dupack */
51 | public static final int TCP_USER_TIMEOUT = 18; /* How long for loss retry before timeout */
52 | public static final int TCP_REPAIR = 19; /* TCP sock is under repair right now */
53 | public static final int TCP_REPAIR_QUEUE = 20;
54 | public static final int TCP_QUEUE_SEQ = 21;
55 | public static final int TCP_REPAIR_OPTIONS = 22;
56 | public static final int TCP_FASTOPEN = 23; /* Enable FastOpen on listeners */
57 | public static final int TCP_TIMESTAMP = 24;
58 | public static final int TCP_NOTSENT_LOWAT = 25; /* limit number of unsent bytes in write queue */
59 |
60 | /* TCP socket options based on 3.12 kernel uapi/linux/udp.h list*/
61 | public static final int UDP_CORK = 1; /* Never send partially complete segments */
62 | public static final int UDP_ENCAP = 100; /* Set the socket to accept encapsulated packets */
63 |
64 | }
65 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/jni/linux/if_address.java:
--------------------------------------------------------------------------------
1 |
2 | /*
3 | * Copyright 2014 Luc Willems (T.M.M.)
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14 | * License for the specific language governing permissions and limitations
15 | * under the License.
16 | */
17 | package org.it4y.jni.linux;
18 |
19 | import org.it4y.util.IndexNameMap;
20 |
21 | import java.util.Collections;
22 | import java.util.Map;
23 |
24 | //from include
25 | public final class if_address {
26 |
27 | public static final Map IFA_NAMES =
28 | Collections.unmodifiableMap(new IndexNameMap() {
29 | {
30 | put(IFA_UNSPEC, "unspec");
31 | put(IFA_ADDRESS, "address");
32 | put(IFA_LOCAL, "local");
33 | put(IFA_LABEL, "label");
34 | put(IFA_BROADCAST,"broadcast");
35 | put(IFA_ANYCAST,"anycast");
36 | put(IFA_CACHEINFO,"cacheinfo");
37 | put(IFA_MULTICAST,"multicast");
38 | }});
39 |
40 | public static final int IFA_UNSPEC = 0;
41 | public static final int IFA_ADDRESS = 1;
42 | public static final int IFA_LOCAL = 2;
43 | public static final int IFA_LABEL = 3;
44 | public static final int IFA_BROADCAST = 4;
45 | public static final int IFA_ANYCAST = 5;
46 | public static final int IFA_CACHEINFO = 6;
47 | public static final int IFA_MULTICAST = 7;
48 | public static final int __IFA_MAX = IFA_MULTICAST;
49 | }
50 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/jni/linux/if_link.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.jni.linux;
18 |
19 | import org.it4y.util.IndexNameMap;
20 |
21 | import java.util.Collections;
22 | import java.util.Map;
23 |
24 | //from include
25 | public final class if_link {
26 | public static final Map IFLA_NAMES =
27 | Collections.unmodifiableMap(new IndexNameMap() {
28 | {
29 | put(IFLA_UNSPEC,"unspec");
30 | put(IFLA_ADDRESS, "address");
31 | put(IFLA_BROADCAST,"broadcast");
32 | put(IFLA_IFNAME,"ifname");
33 | put(IFLA_MTU,"mtu");
34 | put(IFLA_LINK,"link");
35 | put(IFLA_QDISC,"qdisc");
36 | put(IFLA_STATS,"stats");
37 | put(IFLA_COST,"cost");
38 | put(IFLA_PRIORITY,"priority");
39 | put(IFLA_MASTER,"master");
40 | put(IFLA_WIRELESS,"wireless");
41 | put(IFLA_PROTINFO,"protinfo");
42 | put(IFLA_TXQLEN,"txqlen");
43 | put(IFLA_MAP,"map");
44 | put(IFLA_WEIGHT,"weight");
45 | put(IFLA_OPERSTATE,"operstate");
46 | put(IFLA_LINKMODE,"linkmode");
47 | put(IFLA_LINKINFO,"linkinfo");
48 | put(IFLA_NET_NS_PID,"net_ns_pid");
49 | put(IFLA_IFALIAS,"ifalias");
50 | put(IFLA_NUM_VF,"num_vf");
51 | put(IFLA_VFINFO_LIST,"vfinfo_list");
52 | put(IFLA_STATS64,"stats64");
53 | put(IFLA_VF_PORTS,"vf_ports");
54 | put(IFLA_PORT_SELF,"port_self");
55 | put(IFLA_AF_SPEC,"af_spec");
56 | put(IFLA_GROUP,"group");
57 | put(IFLA_NET_NS_FD,"net_ns_fd");
58 | put(IFLA_EXT_MASK,"ext_mask");
59 | put(IFLA_PROMISCUITY,"promiscuity");
60 | put(IFLA_NUM_TX_QUEUES,"num_tx_queues");
61 | put(IFLA_NUM_RX_QUEUES,"num_rx_queues");
62 | put(IFLA_CARRIER,"carrier");
63 | }});
64 |
65 | public static final int IFLA_UNSPEC = 0;
66 | public static final int IFLA_ADDRESS = 1;
67 | public static final int IFLA_BROADCAST = 2;
68 | public static final int IFLA_IFNAME = 3;
69 | public static final int IFLA_MTU = 4;
70 | public static final int IFLA_LINK = 5;
71 | public static final int IFLA_QDISC = 6;
72 | public static final int IFLA_STATS = 7;
73 | public static final int IFLA_COST = 8;
74 | public static final int IFLA_PRIORITY = 9;
75 | public static final int IFLA_MASTER = 10;
76 | public static final int IFLA_WIRELESS = 11; /* Wireless Extension event - see wireless.h */
77 | public static final int IFLA_PROTINFO = 12; /* Protocol specific information for a link */
78 | public static final int IFLA_TXQLEN = 13;
79 | public static final int IFLA_MAP = 14;
80 | public static final int IFLA_WEIGHT = 15;
81 | public static final int IFLA_OPERSTATE = 16;
82 | public static final int IFLA_LINKMODE = 17;
83 | public static final int IFLA_LINKINFO = 18;
84 | public static final int IFLA_NET_NS_PID = 19;
85 | public static final int IFLA_IFALIAS = 20;
86 | public static final int IFLA_NUM_VF = 21; /* Number of VFs if device is SR-IOV PF */
87 | public static final int IFLA_VFINFO_LIST = 22;
88 | public static final int IFLA_STATS64 = 23;
89 | public static final int IFLA_VF_PORTS = 24;
90 | public static final int IFLA_PORT_SELF = 25;
91 | public static final int IFLA_AF_SPEC = 26;
92 | public static final int IFLA_GROUP = 27; /* Group the device belongs to */
93 | public static final int IFLA_NET_NS_FD = 28;
94 | public static final int IFLA_EXT_MASK = 29; /* Extended info mask, VFs, etc */
95 | public static final int IFLA_PROMISCUITY = 30; /* Promiscuity count: > 0 means acts PROMISC */
96 | public static final int IFLA_NUM_TX_QUEUES = 31;
97 | public static final int IFLA_NUM_RX_QUEUES = 32;
98 | public static final int IFLA_CARRIER = 33;
99 | public static final int __IFLA_MAX = IFLA_CARRIER;
100 | }
101 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/jni/linux/if_neighbour.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.jni.linux;
18 |
19 | import org.it4y.util.IndexNameMap;
20 |
21 | import java.util.Collections;
22 | import java.util.Map;
23 |
24 | /**
25 | * Created by luc on 1/4/14.
26 | */
27 | //from include
28 | public final class if_neighbour {
29 | public static final Map NDA_NAMES =
30 | Collections.unmodifiableMap(new IndexNameMap() {
31 | {
32 | put(NDA_UNSPEC,"unspec");
33 | put(NDA_DST,"dst");
34 | put(NDA_LLADDR,"lladdr");
35 | put(NDA_CACHEINFO,"cacheinfo");
36 | put(NDA_PROBES,"probes");
37 | put(NDA_VLAN,"vlan");
38 | put(NDA_PORT,"port");
39 | put(NDA_VNI,"vni");
40 | put(NDA_VNI,"ifindex");
41 | }});
42 |
43 | public static final int NDA_UNSPEC = 0;
44 | public static final int NDA_DST = 1;
45 | public static final int NDA_LLADDR = 2;
46 | public static final int NDA_CACHEINFO = 3;
47 | public static final int NDA_PROBES = 4;
48 | public static final int NDA_VLAN = 5;
49 | public static final int NDA_PORT = 6;
50 | public static final int NDA_VNI = 7;
51 | public static final int NDA_IFINDEX = 8;
52 | public static final int __NDA_MAX = NDA_IFINDEX;
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/jni/linux/ioctl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.jni.linux;
18 |
19 | /**
20 | * Created by luc on 3/29/14.
21 | */
22 | public class ioctl {
23 |
24 | public final static short IFF_UP=0x1; /* interface is up */
25 | public final static short IFF_BROADCAST=0x2; /* broadcast address valid */
26 | public final static short IFF_DEBUG=0x4; /* turn on debugging */
27 | public final static short IFF_LOOPBACK=0x8; /* is a loopback net */
28 | public final static short IFF_POINTOPOINT=0x10; /* interface is has p-p link */
29 | public final static short IFF_NOTRAILERS=0x20; /* avoid use of trailers */
30 | public final static short IFF_RUNNING=0x40; /* interface RFC2863 OPER_UP */
31 | public final static short IFF_NOARP=0x80; /* no ARP protocol */
32 | public final static short IFF_PROMISC=0x100; /* receive all packets */
33 | public final static short IFF_ALLMULTI=0x200; /* receive all multicast packets*/
34 | public final static short IFF_MASTER=0x400; /* master of a load balancer */
35 | public final static short IFF_SLAVE=0x800; /* slave of a load balancer */
36 | public final static short IFF_MULTICAST=0x1000; /* Supports multicast */
37 | public final static short IFF_PORTSEL=0x2000; /* can set media type */
38 | public final static short IF_AUTOMEDIA=0x4000; /* auto media select active */
39 | public final static short IFF_DYNAMIC=(short) 0x8000;/* dialup device with changing addresses*/
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/jni/linux/jhash.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.jni.linux;
18 |
19 | /**
20 | * Created by luc on 1/18/14.
21 | */
22 | /* jhash.h: Jenkins hash support.
23 | *
24 | * Copyright (C) 2006. Bob Jenkins (bob_jenkins@burtleburtle.net)
25 | *
26 | * http://burtleburtle.net/bob/hash/
27 | *
28 | * These are the credits from Bob's sources:
29 | *
30 | * lookup3.c, by Bob Jenkins, May 2006, Public Domain.
31 | *
32 | * These are functions for producing 32-bit hashes for hash table lookup.
33 | * hashword(), hashlittle(), hashlittle2(), hashbig(), mix(), and final()
34 | * are externally useful functions. Routines to test the hash are included
35 | * if SELF_TEST is defined. You can use this free for any purpose. It's in
36 | * the public domain. It has no warranty.
37 | *
38 | * Copyright (C) 2009-2010 Jozsef Kadlecsik (kadlec@blackhole.kfki.hu)
39 | *
40 | * I've modified Bob's hash to be useful in the Linux kernel, and
41 | * any bugs present are my fault.
42 | * Jozsef
43 | */
44 | //based on Linux include/linux/jhash.h
45 | public class jhash {
46 |
47 | public static final int JHASH_INITVAL=0xdeadbeef;
48 |
49 | /**
50 | * rol32 - rotate a 32-bit value left
51 | * @word: value to rotate
52 | * @shift: bits to roll
53 | * return (word << shift) | (word >> (32 - shift));
54 | */
55 |
56 | /* because JAVA DOESN'T UNDERSTAND unsigned integers , we need to do this shit */
57 | public static int rol32(final int x, final int shift) {
58 | return (x << shift ) |(int)(((long)x&0xffffffffL) >> (32L - shift));
59 | }
60 |
61 | public static int jhash_3words(int a, int b, int c, final int initval) {
62 | a += JHASH_INITVAL;
63 | b += JHASH_INITVAL;
64 | c += initval;
65 | /* __jhash_final(a, b, c); */
66 | /* we put C macros inline as function calls are slow... */
67 | c ^= b;
68 | c -= (b << 14 ) |(int)(((long)b&0xffffffffL) >> (32L - 14)); //rol32(b, 14);
69 | a ^= c;
70 | a -= (c << 11 ) |(int)(((long)c&0xffffffffL) >> (32L - 11)); //rol32(c, 11);
71 | b ^= a;
72 | b -= (a << 25 ) |(int)(((long)a&0xffffffffL) >> (32L - 25)); //rol32(a, 25);
73 | c ^= b;
74 | c -= (b << 16 ) |(int)(((long)b&0xffffffffL) >> (32L - 16)); //rol32(b, 16);
75 | a ^= c;
76 | a -= (c << 4 ) |(int)(((long)c&0xffffffffL) >> (32L - 4)); //rol32(c, 4);
77 | b ^= a;
78 | b -= (a << 14 ) |(int)(((long)a&0xffffffffL) >> (32L - 14)); //rol32(a, 14);
79 | c ^= b;
80 | c -= (b << 24 ) |(int)(((long)b&0xffffffffL) >> (32L - 24)); //rol32(b, 24);
81 |
82 | return c;
83 | }
84 |
85 | }
86 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/jni/linux/netlink.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.jni.linux;
18 |
19 | //based on include
20 | public final class netlink {
21 |
22 | public static final int NLMSGHDR_SIZE = 16;
23 | public static final int NETLINK_ROUTE = 0;
24 | /* Routing/device hook */
25 | public static final int NETLINK_UNUSED = 1;
26 | /* Unused number */
27 | public static final int NETLINK_USERSOCK = 2;
28 | /* Reserved for user mode socket protocols */
29 | public static final int NETLINK_FIREWALL = 3;
30 | /* Unused number, formerly ip_queue */
31 | public static final int NETLINK_SOCK_DIAG = 4;
32 | /* socket monitoring */
33 | public static final int NETLINK_NFLOG = 5;
34 | /* netfilter/iptables ULOG */
35 | public static final int NETLINK_XFRM = 6;
36 | /* ipsec */
37 | public static final int NETLINK_SELINUX = 7;
38 | /* SELinux event notifications */
39 | public static final int NETLINK_ISCSI = 8;
40 | /* Open-iSCSI */
41 | public static final int NETLINK_AUDIT = 9;
42 | /* auditing */
43 | public static final int NETLINK_FIB_LOOKUP = 10;
44 | public static final int NETLINK_CONNECTOR = 11;
45 | public static final int NETLINK_NETFILTER = 12;
46 | /* netfilter subsystem */
47 | public static final int NETLINK_IP6_FW = 13;
48 | public static final int NETLINK_DNRTMSG = 14;
49 | /* DECnet routing messages */
50 | public static final int NETLINK_KOBJECT_UEVENT = 15;
51 | /* Kernel messages to userspace */
52 | public static final int NETLINK_GENERIC = 16;
53 | /* leave room for NETLINK_DM (DM Events) */
54 | public static final int NETLINK_SCSITRANSPORT = 18;
55 | /* SCSI Transports */
56 | public static final int NETLINK_ECRYPTFS = 19;
57 | public static final int NETLINK_RDMA = 20;
58 | public static final int NETLINK_CRYPTO = 21;
59 | /* Crypto layer */
60 | public static final int NETLINK_INET_DIAG = NETLINK_SOCK_DIAG;
61 |
62 | /* Flags values */
63 | public static final int NLM_F_REQUEST = 1; /* It is request message. */
64 | public static final int NLM_F_MULTI = 2; /* Multipart message, terminated by NLMSG_DONE */
65 | public static final int NLM_F_ACK = 4; /* Reply with ack, with zero or error code */
66 | public static final int NLM_F_ECHO = 8; /* Echo this request */
67 | public static final int NLM_F_DUMP_INTR = 16; /* Dump was inconsistent due to sequence change */
68 | /* Modifiers to GET request */
69 | public static final int NLM_F_ROOT = 0x100; /* specify tree root */
70 | public static final int NLM_F_MATCH = 0x200; /* return all matching */
71 | public static final int NLM_F_ATOMIC = 0x400; /* atomic GET */
72 | public static final int NLM_F_DUMP = NLM_F_ROOT | NLM_F_MATCH;
73 | /* Modifiers to NEW request */
74 | public static final int NLM_F_REPLACE = 0x100; /* Override existing */
75 | public static final int NLM_F_EXCL = 0x200; /* Do not touch, if it exists */
76 | public static final int NLM_F_CREATE = 0x400; /* Create, if it does not exist */
77 | public static final int NLM_F_APPEND = 0x800; /* Add to end of list */
78 | public static final int NLMSG_NOOP = 0x1; /* Nothing. */
79 | public static final int NLMSG_ERROR = 0x2; /* Error */
80 | public static final int NLMSG_DONE = 0x3; /* End of a dump */
81 | public static final int NLMSG_OVERRUN = 0x4; /* Data lost */
82 | public static final int NLMSG_MIN_TYPE = 0x10; /* < 0x10: reserved control messages */
83 | }
84 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/jni/linux/pcap.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.jni.linux;
18 |
19 | /**
20 | * Created by luc on 2/18/14.
21 | */
22 | public class pcap {
23 |
24 | public final static int DLT_NULL = 0; /* BSD loopback encapsulation */
25 | public final static int DLT_EN10MB = 1; /* Ethernet (10Mb) */
26 | public final static int DLT_EN3MB = 2; /* Experimental Ethernet (3Mb) */
27 | public final static int DLT_AX25 = 3; /* Amateur Radio AX.25 */
28 | public final static int DLT_PRONET = 4; /* Proteon ProNET Token Ring */
29 | public final static int DLT_CHAOS = 5; /* Chaos */
30 | public final static int DLT_IEEE802 = 6; /* 802.5 Token Ring */
31 | public final static int DLT_ARCNET = 7; /* ARCNET, with BSD-style header */
32 | public final static int DLT_SLIP = 8; /* Serial Line IP */
33 | public final static int DLT_PPP = 9; /* Point-to-point Protocol */
34 | public final static int DLT_FDDI = 10; /* FDDI */
35 | public final static int DLT_RAW = 12; /* raw IP */
36 | public final static int DLT_IPV4 = 228; /* Raw IPv4; the packet begins with an IPv4 header. */
37 | public final static int DLT_IPV6 = 229; /* DLT_IPV6 Raw IPv6; the packet begins with an IPv6 header. */
38 |
39 | /*
40 | * Error codes for the pcap API.
41 | * These will all be negative, so you can check for the success or
42 | * failure of a call that returns these codes by checking for a
43 | * negative value.
44 | */
45 | public final static int PCAP_ERROR = -1; /* generic error code */
46 | public final static int PCAP_ERROR_BREAK = -2; /* loop terminated by pcap_breakloop */
47 | public final static int PCAP_ERROR_NOT_ACTIVATED = -3; /* the capture needs to be activated */
48 | public final static int PCAP_ERROR_ACTIVATED = -4; /* the operation can't be performed on already activated captures */
49 | public final static int PCAP_ERROR_NO_SUCH_DEVICE = -5; /* no such device exists */
50 | public final static int PCAP_ERROR_RFMON_NOTSUP = -6; /* this device doesn't support rfmon (monitor) mode */
51 | public final static int PCAP_ERROR_NOT_RFMON = -7; /* operation supported only in monitor mode */
52 | public final static int PCAP_ERROR_PERM_DENIED = -8; /* no permission to open the device */
53 | public final static int PCAP_ERROR_IFACE_NOT_UP = -9; /* interface isn't up */
54 | public final static int PCAP_ERROR_CANTSET_TSTAMP_TYPE = -10; /* this device doesn't support setting the time stamp type */
55 | public final static int PCAP_ERROR_PROMISC_PERM_DENIED = -11; /* you don't have permission to capture in promiscuous mode */
56 | public final static int PCAP_ERROR_TSTAMP_PRECISION_NOTSUP = -12; /* the requested time stamp precision is not supported */
57 |
58 | /*
59 | * Warning codes for the pcap API.
60 | * These will all be positive and non-zero, so they won't look like
61 | * errors.
62 | */
63 | public final static int PCAP_WARNING = 1; /* generic warning code */
64 | public final static int PCAP_WARNING_PROMISC_NOTSUP = 2; /* this device doesn't support promiscuous mode */
65 | public final static int PCAP_WARNING_TSTAMP_TYPE_NOTSUP = 3; /* the requested time stamp type is not supported */
66 |
67 | /*
68 | * Value to pass to pcap_compile() as the netmask if you don't know what
69 | * the netmask is.
70 | */
71 | public final static int PCAP_NETMASK_UNKNOWN = 0xffffffff;
72 |
73 | }
74 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/jni/linux/socket.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.it4y.jni.linux;
17 |
18 | /**
19 | * Created by luc on 1/10/14.
20 | */
21 | //from include
22 | public final class socket {
23 | public final static short AF_UNSPEC=0;
24 | public final static short AF_LOCAL=1;
25 | public final static short AF_UNIX=AF_LOCAL;
26 | public final static short AF_FILE=AF_LOCAL;
27 | public final static short AF_INET=2;
28 | public final static short AF_INET6=10;
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/jni/linux/time.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.jni.linux;
18 |
19 | /**
20 | * Created by luc on 5/14/14.
21 | */
22 | public class time {
23 | /* Identifier for system-wide realtime clock. */
24 | public static final int CLOCK_REALTIME=0;
25 |
26 | /* Monotonic system-wide clock. */
27 | public static final int CLOCK_MONOTONIC=1;
28 |
29 | /* High-resolution timer from the CPU. */
30 | public static final int CLOCK_PROCESS_CPUTIME_ID=2;
31 |
32 | /* Thread-specific CPU-time clock. */
33 | public static final int CLOCK_THREAD_CPUTIME_ID=3;
34 |
35 | /* Monotonic system-wide clock, not adjusted for frequency scaling. */
36 | public static final int CLOCK_MONOTONIC_RAW=4;
37 |
38 | /* Identifier for system-wide realtime clock, updated only on ticks. */
39 | public static final int CLOCK_REALTIME_COARSE=5;
40 |
41 | /* Monotonic system-wide clock, updated only on ticks. */
42 | public static final int CLOCK_MONOTONIC_COARSE=6;
43 |
44 | /* Monotonic system-wide clock that includes time spent in suspension. */
45 | public static final int CLOCK_BOOTTIME=7;
46 |
47 | /* Like CLOCK_REALTIME but also wakes suspended system. */
48 | public static final int CLOCK_REALTIME_ALARM=8;
49 |
50 | /* Like CLOCK_BOOTTIME but also wakes suspended system. */
51 | public static final int CLOCK_BOOTTIME_ALARM=9;
52 | }
53 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/jni/ntp.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.jni;
18 |
19 | /**
20 | * Created by luc on 5/19/14.
21 | */
22 | public class ntp {
23 |
24 | //some error codes from our jni methods
25 | public static final int JNI_OK = 0;
26 | public static final int JNI_ERROR = -1;
27 | public static final int JNI_ERR_FIND_CLASS_FAILED = -2;
28 | public static final int JNI_ERR_GET_METHOD_FAILED = -3;
29 | public static final int JNI_ERR_CALL_METHOD_FAILED = -4;
30 | public static final int JNI_ERR_BUFFER_TO_SMALL = -5;
31 | public static final int JNI_ERR_EXCEPTION = -6;
32 |
33 | //Load our native JNI lib
34 | static {
35 | //THIS requires libnl3 !!!!
36 | JNILoader.loadLibrary("libjnintp");
37 | final int initResult = initlib();
38 | if (initResult != JNI_OK) {
39 | throw new RuntimeException("Failed to initialize ntp jni interface : " + initResult);
40 | }
41 | }
42 |
43 | //This method should be called first before using the library
44 | //it's used to initialize internal jni structure to speedup jni lookups
45 | private static native int initlib();
46 |
47 | public static class timex {
48 | static final int STA_PLL = 0x0001; /* enable PLL updates (rw) */
49 | static final int STA_PPSFREQ = 0x0002; /* enable PPS freq discipline (rw) */
50 | static final int STA_PPSTIME = 0x0004; /* enable PPS time discipline (rw) */
51 | static final int STA_FLL = 0x0008; /* select frequency-lock mode (rw) */
52 |
53 | static final int STA_INS = 0x0010; /* insert leap (rw) */
54 | static final int STA_DEL = 0x0020; /* delete leap (rw) */
55 | static final int STA_UNSYNC = 0x0040; /* clock unsynchronized (rw) */
56 | static final int STA_FREQHOLD = 0x0080; /* hold frequency (rw) */
57 |
58 | static final int STA_PPSSIGNAL = 0x0100; /* PPS signal present (ro) */
59 | static final int STA_PPSJITTER = 0x0200; /* PPS signal jitter exceeded (ro) */
60 | static final int STA_PPSWANDER = 0x0400; /* PPS signal wander exceeded (ro) */
61 | static final int STA_PPSERROR = 0x0800; /* PPS signal calibration error (ro) */
62 |
63 | static final int STA_CLOCKERR = 0x1000; /* clock hardware fault (ro) */
64 | static final int STA_NANO = 0x2000; /* resolution (0 = us, 1 = ns) (ro) */
65 | static final int STA_MODE = 0x4000; /* mode (0 = PLL, 1 = FLL) (ro) */
66 | static final int STA_CLK = 0x8000; /* clock source (0 = A, 1 = B) (ro) */
67 |
68 | public long tv_sec;
69 | public long tv_usec;
70 | public long offset; /* time offset (usec) */
71 | public long freq; /* frequency offset (scaled ppm) */
72 |
73 | public long maxerror; /* maximum error (usec) */
74 | public long esterror; /* estimated error (usec) */
75 | public long constant; /* pll time constant */
76 | public long precision; /* clock precision (usec) (ro) */
77 | public long tolerance; /* clock frequency tolerance (ppm) (ro) */
78 | public long tick; /* (modified) usecs between clock ticks */
79 | public long ppsfreq; /* pps frequency (scaled ppm) (ro) */
80 | public long jitter; /* pps jitter (us) (ro) */
81 | public long stabil; /* pps stability (scaled ppm) (ro) */
82 | public long jitcnt; /* jitter limit exceeded (ro) */
83 | public long calcnt; /* calibration intervals (ro) */
84 | public long errcnt; /* calibration errors (ro) */
85 | public long stbcnt; /* stability limit exceeded (ro) */
86 | public int status; /* clock command/status */
87 | public int tai; /* TAI offset (ro) */
88 | public int shift; /* interval duration (s) (shift) (ro) */
89 |
90 | @Override
91 | public String toString() {
92 | final StringBuilder stringBuilder = new StringBuilder(128);
93 | stringBuilder.append("\ntv_sec: ").append(tv_sec);
94 | stringBuilder.append("\ntv_usec: ").append(tv_usec);
95 | stringBuilder.append("\nmax error: ").append(maxerror).append("usec");
96 | stringBuilder.append("\nestimated error: ").append(esterror).append(" usec");
97 | stringBuilder.append("\noffset: ").append(offset).append(" usec");
98 | stringBuilder.append("\nfreq: ").append(freq).append(" ppm");
99 | stringBuilder.append("\nconstant: ").append(constant);
100 | stringBuilder.append("\nstatus: ").append(Integer.toHexString(status));
101 | return stringBuilder.toString();
102 | }
103 | }
104 |
105 | private static native int ntp_gettime(timex time);
106 |
107 | public static timex getNtpTime() {
108 | final timex time = new timex();
109 | ntp_gettime(time);
110 | return time;
111 | }
112 |
113 | }
114 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/jni/tproxy.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.jni;
18 |
19 | public class tproxy {
20 | //Load our native JNI lib
21 | static {
22 | JNILoader.loadLibrary("libjnitproxy");
23 | }
24 |
25 | public int remoteIp;
26 | public int remotePort;
27 |
28 | public native int setIPTransparant(int fd);
29 |
30 | public native int getOriginalDestination(int fd);
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/jni/tuntap.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.jni;
18 |
19 | import org.it4y.jni.libc.ErrnoException;
20 |
21 | import java.nio.ByteBuffer;
22 |
23 | /**
24 | * Created by luc on 12/28/13.
25 | * this class encapsulate the native methods for tuntap access
26 | * DO NOT REFACTORY this class our you are scruwed
27 | */
28 |
29 | public class tuntap {
30 | /* Load libjnituntap.so */
31 | static {
32 | JNILoader.loadLibrary("libjnituntap");
33 | final int initResult=initLib();
34 | if (initResult != 0) {
35 | throw new RuntimeException("Error initialiaze libjnituntap : "+initResult);
36 | }
37 | }
38 |
39 | /*
40 | * These fields are also updated by jni code , so don't changes this
41 | */
42 | protected int fd = -1;
43 | protected String device;
44 |
45 | /***
46 | * Init JNI library
47 | * @return
48 | */
49 | private static native int initLib();
50 |
51 | /***
52 | * Open tun device on name, device must be created with ip tunnel command
53 | * @param device
54 | * @return 0 if ok
55 | */
56 | protected native int openTunDevice(String device) throws ErrnoException;
57 |
58 | /***
59 | * Open tun device, let kernel choose unique name
60 | * @return 0 if ok
61 | */
62 | protected native int openTun() throws ErrnoException;
63 |
64 | /***
65 | * close tunnel device, this will bring the interface up
66 | */
67 | public native void close();
68 |
69 | /***
70 | * Write @len bytes of @buffer data into tunnel
71 | * @param buffer
72 | * @param len
73 | */
74 | public native int writeByteBuffer(ByteBuffer buffer, int len) throws ErrnoException;
75 |
76 | /***
77 | * Read data from tunnel, incase tunnel is in nonblocking, and nonblocking =true , we will not throw exception
78 | * @param buffer
79 | * @param nonBlocking
80 | * @return size of EAGAIN in case of non blocking and no data
81 | * @throws ErrnoException
82 | */
83 | public native int readByteBuffer(ByteBuffer buffer, boolean nonBlocking) throws ErrnoException;
84 |
85 | /***
86 | * Read data from tunnel device in buffer in blocking mode
87 | * @param buffer
88 | * @return number of bytes read
89 | */
90 | public int readByteBuffer(final ByteBuffer buffer) throws ErrnoException {
91 | return readByteBuffer(buffer,false);
92 | }
93 |
94 | /***
95 | * set tun device in block/non blocking mode
96 | * @param value
97 | * @return
98 | * @throws ErrnoException
99 | */
100 | public native int setNonBlocking(boolean value) throws ErrnoException;
101 |
102 | /***
103 | * Return true/false in data is ready . timeout is in msec
104 | * @param timeout
105 | * @return
106 | */
107 | public native boolean isDataReady(int timeout);
108 |
109 | /***
110 | * enable Queue
111 | * @param timeout
112 | * @return
113 | */
114 | /* not supported until 3.12 kernel
115 | public native int enableQueue(boolean enabled);
116 | */
117 |
118 | }
119 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/net/JVMException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net;
18 |
19 | /**
20 | * Created by luc on 3/30/14.
21 | */
22 | public class JVMException extends RuntimeException {
23 |
24 | public JVMException(final Throwable cause) {
25 | super(cause);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/net/RawPacket.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net;
18 |
19 | import java.nio.ByteBuffer;
20 |
21 | public abstract class RawPacket {
22 |
23 | protected ByteBuffer rawPacket;
24 | protected int rawSize = -1;
25 | protected int rawLimit = -1;
26 |
27 | public RawPacket(final ByteBuffer bytes, final int length) {
28 | rawPacket = bytes;
29 | rawSize = length;
30 | rawLimit = bytes.limit();
31 | }
32 |
33 | public ByteBuffer getRawPacket() {
34 | return rawPacket;
35 | }
36 |
37 | public void resetBuffer() {
38 | rawPacket.clear();
39 | rawPacket.limit(rawLimit);
40 | }
41 |
42 | public int getRawSize() {
43 | return rawSize;
44 | }
45 |
46 | public abstract int getHeaderSize();
47 | public abstract int getPayLoadSize();
48 | public abstract ByteBuffer getHeader();
49 | public abstract ByteBuffer getPayLoad();
50 | public abstract int getDstRoutingHash();
51 | public abstract int getFlowHash();
52 | public abstract int getReverseFlowHash();
53 |
54 | public void release() {
55 | rawPacket=null;
56 | rawSize =-1;
57 | rawLimit =-1;
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/net/link/LinkNotification.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.link;
18 |
19 | public interface LinkNotification {
20 |
21 | /**
22 | * Event type : Link,Address,Routing. All is used for registering to ALL events
23 | */
24 | enum EventType { All,Link,Address,Routing }
25 |
26 | /**
27 | * Event Action : New, Update or Remove , All is used for registering to ALL actions, use None to skip event notification
28 | */
29 | enum EventAction { All,New,Update,Remove,None}
30 |
31 | /**
32 | * retrieve low level notification of changes on interface/link. Method is run in the netlink manager thread and must not
33 | * consume mutch time !.
34 | *
35 | * @param action : action enum (New,Update,Remove)
36 | * @param type : type of message (Link,Address,Routing)
37 | * @param network : Network interface
38 | */
39 | void onEvent(EventAction action, EventType type, NetworkInterface network);
40 |
41 | /**
42 | * retrieve high level notification when link is ready or not (see isActive). Method is run in the netlink manager thread and must
43 | * not consume much time !.
44 | *
45 | * @param network
46 | */
47 | void onStateChanged(NetworkInterface network);
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/net/netlink/AddressRTAMessages.java:
--------------------------------------------------------------------------------
1 |
2 | /*
3 | * Copyright 2014 Luc Willems (T.M.M.)
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14 | * License for the specific language governing permissions and limitations
15 | * under the License.
16 | */
17 |
18 | package org.it4y.net.netlink;
19 |
20 | import org.it4y.jni.linux.if_address;
21 |
22 | import java.nio.ByteBuffer;
23 |
24 | /**
25 | * Created by luc on 1/2/14.
26 | */
27 | public class AddressRTAMessages extends RTAMessage {
28 |
29 | public AddressRTAMessages(final int pos, final ByteBuffer buffer) {
30 | super(pos, buffer);
31 | }
32 |
33 | @Override
34 | public String getRTAName() {
35 | return if_address.IFA_NAMES.get((int)type&0xffff);
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/net/netlink/InterfaceRTAMessages.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.netlink;
18 |
19 | import org.it4y.jni.linux.if_link;
20 |
21 | import java.nio.ByteBuffer;
22 |
23 | /**
24 | * Created by luc on 1/2/14.
25 | */
26 | public class InterfaceRTAMessages extends RTAMessage {
27 |
28 | public InterfaceRTAMessages(final int pos, final ByteBuffer buffer) {
29 | super(pos, buffer);
30 | }
31 |
32 | public String getRTAName() {
33 | return if_link.IFLA_NAMES.get((int)type&0xffff);
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/net/netlink/NetlinkMsgFactory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.netlink;
18 |
19 | import org.it4y.jni.linux.netlink;
20 | import org.it4y.jni.linux.rtnetlink;
21 | import org.it4y.util.Hexdump;
22 | import org.slf4j.Logger;
23 | import org.slf4j.LoggerFactory;
24 |
25 | import java.nio.ByteBuffer;
26 |
27 | /**
28 | * Created by luc on 1/2/14.
29 | */
30 | public class NetlinkMsgFactory {
31 | private static final Logger log = LoggerFactory.getLogger(NetlinkMsgFactory.class);
32 | public static NlMessage processRawPacket(final ByteBuffer buffer) {
33 |
34 | //Read nlmsg header
35 | final int nlmsg_len = buffer.getInt(0);
36 | final short nlmsg_type = buffer.getShort(4);
37 | //to make sure position is pointed to begin of data
38 | buffer.position(0);
39 | NlMessage result = null;
40 |
41 | switch (nlmsg_type) {
42 | case rtnetlink.RTM_NEWROUTE:
43 | result = handleRoutingMsg(buffer);
44 | break;
45 | case rtnetlink.RTM_DELROUTE:
46 | result = handleRoutingMsg(buffer);
47 | break;
48 | case rtnetlink.RTM_NEWLINK:
49 | result = handleLinkMsg(buffer);
50 | break;
51 | case rtnetlink.RTM_DELLINK:
52 | result = handleLinkMsg(buffer);
53 | break;
54 | case rtnetlink.RTM_NEWADDR:
55 | result = handleAddressMsg(buffer);
56 | break;
57 | case rtnetlink.RTM_DELADDR:
58 | result = handleAddressMsg(buffer);
59 | break;
60 | //case libnetlink.linux.rtnetlink.RTM_NEWADDRLABEL: System.out.println("New Address label:"+nlmsg_type);break;
61 | //case libnetlink.linux.rtnetlink.RTM_DELADDRLABEL: System.out.println("Del Address label:"+nlmsg_type);break;
62 | case rtnetlink.RTM_NEWNEIGH:
63 | result = handleNeighbourMsg(buffer);
64 | break;
65 | case rtnetlink.RTM_DELNEIGH:
66 | result = handleNeighbourMsg(buffer);
67 | break;
68 | case rtnetlink.RTM_GETNEIGH:
69 | result = handleNeighbourMsg(buffer);
70 | break;
71 | //case libnetlink.linux.rtnetlink.RTM_NEWPREFIX: System.out.println("New prefix:"+nlmsg_type);break;
72 | //case libnetlink.linux.rtnetlink.RTM_NEWRULE: System.out.println("New route rule:"+nlmsg_type);break;
73 | //case libnetlink.linux.rtnetlink.RTM_DELRULE: System.out.println("Del route rule:"+nlmsg_type);break;
74 | //case libnetlink.linux.rtnetlink.RTM_NEWNETCONF:System.out.println("New netconf:"+nlmsg_type);break;
75 | case netlink.NLMSG_DONE:
76 | result = new NlDoneMessage(buffer);
77 | break;
78 | case netlink.NLMSG_ERROR:
79 | result = new NlErrorMessage(buffer);
80 | break;
81 | default:
82 | if (log.isDebugEnabled()) {
83 | log.debug("UNKNOWN Netlink message type: {} len:{} [{}]",nlmsg_type,nlmsg_len,Hexdump.bytesToHex(buffer, nlmsg_len));
84 | }
85 | }
86 | return result;
87 | }
88 |
89 | private static NlMessage handleRoutingMsg(final ByteBuffer buffer) {
90 | return new routeMsg(buffer);
91 | }
92 |
93 | private static NlMessage handleLinkMsg(final ByteBuffer buffer) {
94 | return new interfaceInfoMsg(buffer);
95 | }
96 |
97 | private static NlMessage handleAddressMsg(final ByteBuffer buffer) {
98 | return new interfaceAddressMsg(buffer);
99 | }
100 |
101 | private static NlMessage handleNeighbourMsg(final ByteBuffer buffer) {
102 | return new neighbourMsg(buffer);
103 | }
104 |
105 | }
106 |
107 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/net/netlink/NlDoneMessage.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.netlink;
18 |
19 | import java.nio.ByteBuffer;
20 |
21 | /**
22 | * Created by luc on 1/3/14.
23 | */
24 | public class NlDoneMessage extends NlMessage {
25 | public NlDoneMessage(final ByteBuffer msg) {
26 | super(msg);
27 | }
28 |
29 | @Override
30 | public int getRTAIndex(final String name) {
31 | return RTA_INDEX_NOTSUPPORTED;
32 | }
33 |
34 | @Override
35 | public RTAMessage createRTAMessage(final int position, final ByteBuffer msg) {
36 | return null;
37 | }
38 |
39 | @Override
40 | public boolean moreMessages() {
41 | return false;
42 | }
43 |
44 | public String toString() {
45 | final StringBuilder s = new StringBuilder(128);
46 | s.append(super.toString());
47 | s.append("netlink done");
48 | return s.toString();
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/net/netlink/NlErrorMessage.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.netlink;
18 |
19 | import java.nio.ByteBuffer;
20 |
21 | /**
22 | * Created by luc on 1/3/14.
23 | */
24 | public class NlErrorMessage extends NlMessage {
25 |
26 | public NlErrorMessage(final ByteBuffer msg) {
27 | super(msg);
28 | }
29 |
30 | @Override
31 | public int getRTAIndex(final String name) {
32 | return RTA_INDEX_NOTSUPPORTED;
33 | }
34 |
35 | @Override
36 | public RTAMessage createRTAMessage(final int position, final ByteBuffer msg) {
37 | return null;
38 | }
39 |
40 | public String toString() {
41 | final StringBuilder s = new StringBuilder(128);
42 | s.append(super.toString());
43 | s.append("netlink ERROR ");
44 | return s.toString();
45 | }
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/net/netlink/NlMessage.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.netlink;
18 |
19 | import java.nio.ByteBuffer;
20 | import java.util.HashMap;
21 |
22 | /**
23 | * Created by luc on 1/2/14.
24 | */
25 | public abstract class NlMessage {
26 |
27 | public static final int RTA_INDEX_NOTSUPPORTED=-1;
28 |
29 | //Read nlmsg header
30 | protected final int nlmsg_len;
31 | protected final short nlmsg_type;
32 | protected final short nlmsg_flags;
33 | protected final int nlmsg_seq;
34 | protected final int nlmsg_pid;
35 | protected final HashMap rtaMessages;
36 |
37 | public NlMessage(final ByteBuffer msg) {
38 | //Read nlmsg header
39 | nlmsg_len = msg.getInt();
40 | nlmsg_type = msg.getShort();
41 | nlmsg_flags = msg.getShort();
42 | nlmsg_seq = msg.getInt();
43 | nlmsg_pid = msg.getInt();
44 | rtaMessages = new HashMap(10);
45 | }
46 |
47 | public int getNlMsgLen() {
48 | return nlmsg_len;
49 | }
50 |
51 | public short getNlMsgType() {
52 | return nlmsg_type;
53 | }
54 |
55 | public short getNlmsg_flags() {
56 | return nlmsg_flags;
57 | }
58 |
59 | public int getNlMsgSequence() {
60 | return nlmsg_seq;
61 | }
62 |
63 | public int getNlMsgPID() {
64 | return nlmsg_pid;
65 | }
66 |
67 | public RTAMessage getRTAMessage(final int index) {
68 | return rtaMessages.get(index);
69 | }
70 |
71 | public boolean moreMessages() {
72 | return (nlmsg_flags & (short) 0x02) > 0;
73 | }
74 |
75 | public RTAMessage getRTAMessage(final String name) {
76 | return getRTAMessage(getRTAIndex(name));
77 | }
78 |
79 | public abstract int getRTAIndex(String name);
80 |
81 | protected abstract RTAMessage createRTAMessage(int position, ByteBuffer msg);
82 |
83 | protected void parseRTAMessages(final ByteBuffer msg) {
84 | while (msg.position() < nlmsg_len) {
85 | final int position = msg.position();
86 | final RTAMessage rta = createRTAMessage(position, msg);
87 | msg.position(position + rta.getPaddedSize());
88 | rtaMessages.put((int) rta.getType()&0xffff, rta);
89 | }
90 |
91 | }
92 |
93 | public String toString() {
94 | final StringBuilder s = new StringBuilder(128);
95 | s.append(getClass().getSimpleName()).append(' ');
96 | s.append("nlmg[size:").append(nlmsg_len).append(",type:").append(nlmsg_type).append(",flags:0x").append(Integer.toHexString(nlmsg_flags)).append("]\n");
97 | return s.toString();
98 | }
99 |
100 | }
101 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/net/netlink/RTAMessage.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.netlink;
18 |
19 | import org.it4y.jni.libc;
20 | import org.it4y.util.Hexdump;
21 |
22 | import java.net.InetAddress;
23 | import java.nio.ByteBuffer;
24 | import java.nio.ByteOrder;
25 | import java.nio.charset.Charset;
26 |
27 | /**
28 | * Created by luc on 1/2/14.
29 | */
30 | public abstract class RTAMessage {
31 | final short size;
32 | final short type;
33 | final ByteBuffer data;
34 |
35 | public RTAMessage(final int pos, final ByteBuffer buffer) {
36 | size = buffer.getShort(pos);
37 | type = buffer.getShort(pos + 2);
38 | //get size bytes from buffer for data
39 | final int old_position = buffer.position();
40 | final int old_limit = buffer.limit();
41 | buffer.position(pos + 4);
42 | buffer.limit(pos + size);
43 | data = buffer.slice();
44 | data.order(ByteOrder.LITTLE_ENDIAN);
45 | buffer.position(old_position);
46 | buffer.limit(old_limit);
47 | //mark start position
48 | data.mark();
49 | }
50 |
51 | public short getSize() {
52 | return size;
53 | }
54 |
55 | public short getType() {
56 | return type;
57 | }
58 |
59 | public int getPaddedSize() {
60 | //roundup to 4 bytes padding
61 | return (int) Math.ceil(size / 4.0) * 4;
62 | }
63 |
64 | public abstract String getRTAName();
65 |
66 | public String toString() {
67 | final StringBuilder s = new StringBuilder(128);
68 | s.append("RTA[").append(size).append('(').append(getPaddedSize()).append("):");
69 | s.append(type);
70 | try {
71 | if (getRTAName() != null) {
72 | s.append(' ').append(getRTAName());
73 | }
74 | } catch (final IndexOutOfBoundsException oeps) {
75 | s.append(' ').append("???? unknown");
76 | }
77 | s.append("] ");
78 | s.append(Hexdump.bytesToHex(data, size));
79 | return s.toString();
80 | }
81 |
82 | public byte getByte() {
83 | return data.get(0);
84 | }
85 |
86 | public short getShort() {
87 | return data.getShort(0);
88 | }
89 |
90 | public int getInt() {
91 | return data.getInt(0);
92 | }
93 |
94 | public String getString() {
95 | //Strings are always UTF-8 null terminated string so convert it that way
96 | final byte[] result = new byte[data.capacity() - 1];
97 | data.rewind();
98 | data.get(result, 0, result.length);
99 | return new String(result, Charset.forName("UTF-8"));
100 | }
101 |
102 | public String getHexString() {
103 | return Hexdump.bytesToHex(data, 6);
104 | }
105 |
106 |
107 | public InetAddress getInetAddress() {
108 | return libc.toInetAddress(libc.ntohi(data.getInt(0)));
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/net/netlink/interfaceAddressMsg.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.netlink;
18 |
19 | import org.it4y.jni.linux.if_address;
20 |
21 | import java.nio.ByteBuffer;
22 |
23 | /**
24 | * Created by luc on 1/2/14.
25 | */
26 | public class interfaceAddressMsg extends NlMessage {
27 | final byte ifa_family;
28 | final byte ifa_prefixlen; /* The prefix length */
29 | final byte ifa_flags; /* Flags */
30 | final byte ifa_scope; /* Address scope */
31 | final byte ifa_index; /* Link index */
32 |
33 | public interfaceAddressMsg(final ByteBuffer msg) {
34 | super(msg);
35 | //dummy
36 | ifa_family = msg.get();
37 | ifa_prefixlen = msg.get();
38 | ifa_flags = msg.get();
39 | ifa_scope = msg.get();
40 | ifa_index = msg.get();
41 | //padding
42 | msg.get();
43 | msg.get();
44 | msg.get();
45 | parseRTAMessages(msg);
46 | }
47 |
48 | @Override
49 | public int getRTAIndex(final String name) {
50 | for (final int key : if_address.IFA_NAMES.keySet()) {
51 | if (name.equals(if_address.IFA_NAMES.get(key))) {
52 | return key;
53 | }
54 | }
55 | return -1;
56 | }
57 |
58 | @Override
59 | public RTAMessage createRTAMessage(final int position, final ByteBuffer msg) {
60 | return new AddressRTAMessages(position, msg);
61 | }
62 |
63 | @Override
64 | public String toString() {
65 | final StringBuilder s = new StringBuilder(128);
66 | s.append(super.toString());
67 | s.append("fam: ").append(ifa_family);
68 | s.append(" flags:0x").append(Integer.toHexString((int) ifa_flags & 0xff));
69 | s.append(" idx:").append(ifa_index);
70 | s.append(" scope:0x").append(Integer.toHexString((int) ifa_scope & 0xff));
71 | s.append(" prefixlen:").append(ifa_prefixlen);
72 | s.append('\n');
73 | //dump rta messages
74 | for (final RTAMessage r : rtaMessages.values()) {
75 | if (r.getType() == if_address.IFA_LABEL) {
76 | s.append(' ').append(r.toString()).append(' ').append(r.getString()).append('\n');
77 | } else if (r.getType() == if_address.IFA_BROADCAST) {
78 | s.append(' ').append(r.toString()).append(' ').append(r.getInetAddress()).append('\n');
79 | } else if (r.getType() == if_address.IFA_ADDRESS) {
80 | s.append(' ').append(r.toString()).append(' ').append(r.getInetAddress()).append('\n');
81 | } else {
82 | s.append(' ').append(r.toString()).append('\n');
83 | }
84 | }
85 | return s.toString();
86 | }
87 |
88 | public byte getAddresFamily() {
89 | return ifa_family;
90 | }
91 |
92 | public byte getAddressPrefixlen() {
93 | return ifa_prefixlen;
94 | }
95 |
96 | public byte getAddressFlags() {
97 | return ifa_flags;
98 | }
99 |
100 | public byte getAddressScope() {
101 | return ifa_scope;
102 | }
103 |
104 | public byte getInterfaceIndex() {
105 | return ifa_index;
106 | }
107 |
108 | }
109 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/net/netlink/interfaceInfoMsg.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.netlink;
18 |
19 | import org.it4y.jni.linux.if_arp;
20 | import org.it4y.jni.linux.if_link;
21 |
22 | import java.nio.ByteBuffer;
23 |
24 | /**
25 | * Created by luc on 1/2/14.
26 | */
27 | public class interfaceInfoMsg extends NlMessage {
28 |
29 | final byte ifi_family;
30 | final short ifi_type;
31 | final int ifi_index;
32 | final int ifi_flags;
33 | final int ifi_changed;
34 |
35 | public interfaceInfoMsg(final ByteBuffer msg) {
36 | super(msg);
37 | //get ifinfomsg header
38 | msg.get(); //dummy byte
39 | ifi_family = msg.get();
40 | ifi_type = msg.getShort();
41 | ifi_index = msg.getInt();
42 | ifi_flags = msg.getInt();
43 | ifi_changed = msg.getInt();
44 | parseRTAMessages(msg);
45 | }
46 |
47 | @Override
48 | public int getRTAIndex(final String name) {
49 | for (final int i : if_link.IFLA_NAMES.keySet()) {
50 | if (name.equals(if_link.IFLA_NAMES.get(i))) {
51 | return i;
52 | }
53 | }
54 | return -1;
55 | }
56 |
57 | @Override
58 | protected RTAMessage createRTAMessage(final int position, final ByteBuffer msg) {
59 | return new InterfaceRTAMessages(position, msg);
60 | }
61 |
62 | public String toString() {
63 | final StringBuilder s = new StringBuilder(128);
64 | s.append(super.toString());
65 | s.append("fam: ").append(ifi_family);
66 | s.append(" type:").append(if_arp.ARPHDR_NAMES.get((int)ifi_type&0xffff));
67 | s.append(" idx:").append(ifi_index);
68 | s.append(" flags:0x").append(Integer.toHexString(ifi_flags));
69 | s.append(" changed:0x").append(Integer.toHexString(ifi_changed));
70 | s.append('\n');
71 | //dump rta messages
72 | for (final RTAMessage r : rtaMessages.values()) {
73 | if (r.getType() == 3 || r.getType() == 6) {
74 | s.append(' ').append(r.toString()).append(' ').append(r.getString()).append('\n');
75 | } else {
76 | s.append(' ').append(r.toString()).append('\n');
77 | }
78 | }
79 | return s.toString();
80 | }
81 |
82 | public byte getInterfaceFamily() {
83 | return ifi_family;
84 | }
85 |
86 | public short getInterfaceType() {
87 | return ifi_type;
88 | }
89 |
90 | public int getInterfaceIndex() {
91 | return ifi_index;
92 | }
93 |
94 | public int getInterfaceFlags() {
95 | return ifi_flags;
96 | }
97 |
98 | public int getInterfaceChanged() {
99 | return ifi_changed;
100 | }
101 |
102 |
103 | }
104 |
105 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/net/netlink/neighbourMsg.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.netlink;
18 |
19 | import org.it4y.jni.linux.if_neighbour;
20 |
21 | import java.nio.ByteBuffer;
22 |
23 | /**
24 | * Created by luc on 1/2/14.
25 | */
26 | public class neighbourMsg extends NlMessage {
27 | final byte ndm_family;
28 | final byte ndm_pad1;
29 | final byte ndm_pad2;
30 | final byte ndm_ifindex;
31 | final byte ndm_state;
32 | final byte ndm_flags;
33 | final byte ndm_type;
34 |
35 | public neighbourMsg(final ByteBuffer msg) {
36 | super(msg);
37 | ndm_family = msg.get();
38 | ndm_pad1 = msg.get();
39 | ndm_pad2 = msg.get();
40 | ndm_ifindex = msg.get();
41 | ndm_state = msg.get();
42 | ndm_flags = msg.get();
43 | ndm_type = msg.get();
44 | msg.get();
45 | msg.getInt();
46 | parseRTAMessages(msg);
47 | }
48 |
49 | @Override
50 | public int getRTAIndex(final String name) {
51 | for (final int i : if_neighbour.NDA_NAMES.keySet()) {
52 | if (name.equals(if_neighbour.NDA_NAMES.get(i))) {
53 | return i;
54 | }
55 | }
56 | return -1;
57 | }
58 |
59 | @Override
60 | protected RTAMessage createRTAMessage(final int position, final ByteBuffer msg) {
61 | return new neighbourRTAMessages(position, msg);
62 | }
63 |
64 | public String toString() {
65 | final StringBuilder s = new StringBuilder(128);
66 | s.append(super.toString());
67 | s.append("fam: ").append(ndm_family);
68 | s.append(" ifindex:").append(ndm_ifindex);
69 | s.append(" state:0x").append(Integer.toHexString((int) ndm_state & 0xff));
70 | s.append(" flags:0x").append(Integer.toHexString((int) ndm_state & 0xff));
71 | s.append(" type:0x").append(Integer.toHexString((int) ndm_type & 0xff));
72 | s.append('\n');
73 | //dump rta messages
74 | for (final RTAMessage r : rtaMessages.values()) {
75 | if (r.getType() == if_neighbour.NDA_DST) {
76 | s.append(' ').append(r.toString()).append(' ').append(r.getInetAddress()).append('\n');
77 | } else {
78 | s.append(' ').append(r.toString()).append('\n');
79 | }
80 | }
81 | return s.toString();
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/net/netlink/neighbourRTAMessages.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.netlink;
18 |
19 | import org.it4y.jni.linux.if_neighbour;
20 |
21 | import java.nio.ByteBuffer;
22 |
23 | /**
24 | * Created by luc on 1/2/14.
25 | */
26 | public class neighbourRTAMessages extends RTAMessage {
27 | public neighbourRTAMessages(final int pos, final ByteBuffer buffer) {
28 | super(pos, buffer);
29 | }
30 |
31 | @Override
32 | public String getRTAName() {
33 | return if_neighbour.NDA_NAMES.get((int)type&0xffff);
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/net/netlink/routeRTAMessages.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.netlink;
18 |
19 | import org.it4y.jni.linux.rtnetlink;
20 |
21 | import java.nio.ByteBuffer;
22 |
23 | /**
24 | * Created by luc on 1/2/14.
25 | */
26 | public class routeRTAMessages extends RTAMessage {
27 |
28 | public routeRTAMessages(final int pos, final ByteBuffer buffer) {
29 | super(pos, buffer);
30 | }
31 |
32 | @Override
33 | public String getRTAName() {
34 | return rtnetlink.RTA_NAMES.get((int)type&0xffff);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/net/protocols/IP/GRE/GREPacket.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.protocols.IP.GRE;
18 |
19 | import org.it4y.net.protocols.IP.IpPacket;
20 | import org.it4y.util.Hexdump;
21 |
22 | import java.nio.ByteBuffer;
23 |
24 | /**
25 | * Created by luc on 3/24/14.
26 | */
27 | public class GREPacket extends IpPacket {
28 | public static final byte PROTOCOL=47;
29 | public static final int GRE_HEADER_SIZE = 4;
30 |
31 | private static final int header_gre_flags=0;
32 | private static final int header_gre_protocol=2;
33 | private static final int header_gre_checksum=4;
34 | private static final int header_gre_reserved=6;
35 | private static final int header_gre_key=8;
36 | private static final int header_gre_seq=12;
37 |
38 | private int ip_header_offset;
39 |
40 | public GREPacket(final ByteBuffer buffer, final int size) {
41 | super(buffer, size);
42 | ip_header_offset=super.getHeaderSize();
43 | }
44 | public GREPacket(final IpPacket ip) {
45 | super(ip.getRawPacket(),ip.getRawSize());
46 | //get IP header size
47 | ip_header_offset=ip.getHeaderSize();
48 | }
49 |
50 | @Override
51 | public void initIpHeader() {
52 | super.initIpHeader();
53 | setProtocol(PROTOCOL);
54 | ip_header_offset= getIpHeaderSize();
55 | }
56 |
57 | @Override
58 | public int getHeaderSize() {
59 | int size=GRE_HEADER_SIZE;
60 | if (hasGreChecksum()) { size=size+4;}
61 | if (hasGreKeys() || hasGreSequenceNumbers() ) {size=size+8;}
62 | return size;
63 | }
64 |
65 | @Override
66 | public int getPayLoadSize() {
67 | return rawLimit - ip_header_offset - getHeaderSize();
68 | }
69 |
70 | @Override
71 | public ByteBuffer getHeader() {
72 | //get IP header size
73 | resetBuffer();
74 | rawPacket.position(ip_header_offset);
75 | rawPacket.limit(ip_header_offset + getHeaderSize());
76 | return rawPacket.slice();
77 | }
78 |
79 | @Override
80 | public ByteBuffer getPayLoad() {
81 | //get IP header size
82 | resetBuffer();
83 | rawPacket.position(ip_header_offset+getHeaderSize());
84 | rawPacket.limit(rawSize);
85 | return rawPacket.slice();
86 | }
87 |
88 | public short getGreFlags() {
89 | return rawPacket.getShort(ip_header_offset + header_gre_flags);
90 | }
91 |
92 | public boolean hasGreChecksum() {
93 | final short flags=getGreFlags();
94 | return (flags & (short)0x8000) == (short)0x8000;
95 | }
96 | public boolean hasGreKeys() {
97 | final short flags=getGreFlags();
98 | return (flags & (short)0x2000) == (short)0x2000;
99 | }
100 | public boolean hasGreSequenceNumbers() {
101 | final short flags=getGreFlags();
102 | return (flags & (short)0x1000) == (short)0x1000;
103 | }
104 |
105 | public short getGreChecksum() {
106 | return rawPacket.getShort(ip_header_offset + header_gre_checksum);
107 | }
108 |
109 | public int getGreKey() {
110 | return rawPacket.getInt(ip_header_offset + header_gre_key);
111 | }
112 | public int getGreSeqNumber() {
113 | return rawPacket.getInt(ip_header_offset + header_gre_seq);
114 | }
115 |
116 | public void setGreFlags(final short flags) {
117 | rawPacket.putShort(ip_header_offset + header_gre_flags, flags);
118 | }
119 |
120 | public short getEmbeddedProtocol() {
121 | return rawPacket.getShort(ip_header_offset + header_gre_protocol);
122 | }
123 |
124 | public void setEmbeddedProtocol(final short protocol) {
125 | rawPacket.putShort(ip_header_offset + header_gre_protocol,protocol);
126 | }
127 |
128 | @Override
129 | public String toString() {
130 | final StringBuilder s=new StringBuilder(128);
131 | s.append(super.toString()).append('[');
132 | if (hasGreChecksum()) {s.append("C,"); }
133 | if (hasGreKeys()) {s.append("K=").append(Integer.toHexString(getGreKey())).append(',');}
134 | if (hasGreSequenceNumbers()) {s.append("S=").append(Integer.toHexString(getGreSeqNumber())).append(',');}
135 | s.deleteCharAt(s.lastIndexOf(","));
136 | s.append(']');
137 | if (getPayLoadSize()>0) {
138 | s.append(Hexdump.bytesToHex(getPayLoad(), Math.min(getPayLoadSize(), 10)));
139 | }
140 | return s.toString();
141 | }
142 |
143 | }
144 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/net/protocols/IP/IPFactory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.protocols.IP;
18 |
19 | import org.it4y.net.protocols.IP.GRE.GREPacket;
20 | import org.it4y.net.protocols.IP.ICMP.ICMPPacket;
21 | import org.it4y.net.protocols.IP.IPIP.IPIPPacket;
22 | import org.it4y.net.protocols.IP.IPv6Tunnel.IPv6TunnelPacket;
23 | import org.it4y.net.protocols.IP.TCP.TCPPacket;
24 | import org.it4y.net.protocols.IP.UDP.UDPPacket;
25 |
26 | import java.nio.ByteBuffer;
27 | import java.util.Collections;
28 | import java.util.HashMap;
29 | import java.util.Map;
30 |
31 | public class IPFactory {
32 |
33 | private interface ipv4Factory {
34 | IpPacket create(ByteBuffer buffer, int size);
35 | }
36 |
37 | public static final Map ipv4FactoryMap = Collections.unmodifiableMap(new HashMap() {{
38 | put(ICMPPacket.PROTOCOL, new ipv4Factory() {
39 | public IpPacket create(final ByteBuffer buffer, final int size) {
40 | return new ICMPPacket(buffer, size);
41 | }
42 | });
43 | put(IPIPPacket.PROTOCOL, new ipv4Factory() {
44 | public IpPacket create(final ByteBuffer buffer, final int size) {
45 | return new IPIPPacket(buffer, size);
46 | }
47 | });
48 | put(TCPPacket.PROTOCOL, new ipv4Factory() {
49 | public IpPacket create(final ByteBuffer buffer, final int size) {
50 | return new TCPPacket(buffer, size);
51 | }
52 | });
53 | put(UDPPacket.PROTOCOL, new ipv4Factory() {
54 | public IpPacket create(final ByteBuffer buffer, final int size) {
55 | return new UDPPacket(buffer, size);
56 | }
57 | });
58 | put(IPv6TunnelPacket.PROTOCOL, new ipv4Factory() {
59 | public IpPacket create(final ByteBuffer buffer, final int size) {
60 | return new IPv6TunnelPacket(buffer, size);
61 | }
62 | });
63 | put(GREPacket.PROTOCOL, new ipv4Factory() {
64 | public IpPacket create(final ByteBuffer buffer, final int size) {
65 | return new GREPacket(buffer, size);
66 | }
67 | });
68 | }});
69 |
70 | public static IpPacket processRawPacket(final ByteBuffer buffer, final int size) {
71 | //check for IPv4 and protocol
72 | if (buffer != null & size >0) {
73 | final byte ipVersion = (byte) (buffer.get(IpPacket.header_version) >> 4);
74 | if (ipVersion == 4) {
75 | final byte ipProtocol=buffer.get(IpPacket.header_protocol);
76 | final ipv4Factory factory = ipv4FactoryMap.get(ipProtocol);
77 | if (factory == null) {
78 | return new IpPacket(buffer, size);
79 | } else {
80 | return factory.create(buffer, size);
81 | }
82 | }
83 | }
84 | return null;
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/net/protocols/IP/IPIP/IPIPPacket.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.protocols.IP.IPIP;
18 |
19 | import org.it4y.net.protocols.IP.IpPacket;
20 | import org.it4y.util.Hexdump;
21 |
22 | import java.nio.ByteBuffer;
23 |
24 | /**
25 | * Created by luc on 3/24/14.
26 | * bassed on RFC1853
27 | */
28 | public class IPIPPacket extends IpPacket{
29 | public static final byte PROTOCOL=4;
30 | public static final int IPIP_HEADER_SIZE = 0;
31 |
32 | private int ip_header_offset;
33 |
34 | public IPIPPacket(final ByteBuffer buffer, final int size) {
35 | super(buffer, size);
36 | ip_header_offset=super.getHeaderSize();
37 | }
38 | public IPIPPacket(final IpPacket ip) {
39 | super(ip.getRawPacket(),ip.getRawSize());
40 | //get IP header size
41 | ip_header_offset=ip.getHeaderSize();
42 | }
43 |
44 | @Override
45 | public void initIpHeader() {
46 | super.initIpHeader();
47 | setProtocol(PROTOCOL);
48 | ip_header_offset= getIpHeaderSize();
49 | }
50 |
51 | @Override
52 | public int getHeaderSize() {
53 | return IPIP_HEADER_SIZE;
54 | }
55 |
56 | @Override
57 | public int getPayLoadSize() {
58 | return rawLimit - ip_header_offset - getHeaderSize();
59 | }
60 |
61 | @Override
62 | public ByteBuffer getHeader() {
63 | //get IP header size
64 | resetBuffer();
65 | rawPacket.position(ip_header_offset);
66 | rawPacket.limit(ip_header_offset + getHeaderSize());
67 | return rawPacket.slice();
68 | }
69 |
70 | @Override
71 | public ByteBuffer getPayLoad() {
72 | //get IP header size
73 | resetBuffer();
74 | rawPacket.position(ip_header_offset+getHeaderSize());
75 | rawPacket.limit(rawSize);
76 | return rawPacket.slice();
77 | }
78 |
79 | @Override
80 | public String toString() {
81 | final StringBuilder s=new StringBuilder(128);
82 | if (getPayLoadSize()>0) {
83 | s.append(Hexdump.bytesToHex(getPayLoad(), Math.min(getPayLoadSize(), 10)));
84 | }
85 | return s.toString();
86 | }
87 |
88 | }
89 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/net/protocols/IP/IPv6Tunnel/IPv6TunnelPacket.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.protocols.IP.IPv6Tunnel;
18 |
19 | import org.it4y.net.protocols.IP.IpPacket;
20 | import org.it4y.util.Hexdump;
21 |
22 | import java.nio.ByteBuffer;
23 |
24 | /**
25 | * Created by luc on 3/24/14.
26 | */
27 | public class IPv6TunnelPacket extends IpPacket {
28 | public static final byte PROTOCOL=41;
29 | public static final int IPv6Tunnel_HEADER_SIZE = 0;
30 |
31 | private int ip_header_offset;
32 |
33 | public IPv6TunnelPacket(final ByteBuffer buffer, final int size) {
34 | super(buffer, size);
35 | ip_header_offset=super.getHeaderSize();
36 | }
37 |
38 | public IPv6TunnelPacket(final IpPacket ip) {
39 | super(ip.getRawPacket(),ip.getRawSize());
40 | //get IP header size
41 | ip_header_offset=ip.getHeaderSize();
42 | }
43 |
44 | @Override
45 | public void initIpHeader() {
46 | super.initIpHeader();
47 | setProtocol(PROTOCOL);
48 | ip_header_offset= getIpHeaderSize();
49 | }
50 |
51 | @Override
52 | public int getHeaderSize() {
53 | return IPv6Tunnel_HEADER_SIZE;
54 | }
55 |
56 | @Override
57 | public int getPayLoadSize() {
58 | return rawLimit - ip_header_offset - getHeaderSize();
59 | }
60 |
61 | @Override
62 | public ByteBuffer getHeader() {
63 | //get IP header size
64 | resetBuffer();
65 | rawPacket.position(ip_header_offset);
66 | rawPacket.limit(ip_header_offset + getHeaderSize());
67 | return rawPacket.slice();
68 | }
69 |
70 | @Override
71 | public ByteBuffer getPayLoad() {
72 | //get IP header size
73 | resetBuffer();
74 | rawPacket.position(ip_header_offset+getHeaderSize());
75 | rawPacket.limit(rawSize);
76 | return rawPacket.slice();
77 | }
78 |
79 | @Override
80 | public String toString() {
81 | final StringBuilder s=new StringBuilder(128);
82 | if (getPayLoadSize()>0) {
83 | s.append(Hexdump.bytesToHex(getPayLoad(), Math.min(getPayLoadSize(), 20)));
84 | }
85 | return s.toString();
86 | }
87 |
88 |
89 | }
90 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/net/protocols/IP/TCP/TCPOption.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.protocols.IP.TCP;
18 |
19 | public interface TCPOption {
20 |
21 | //WELL KNOW TCP options id's
22 | byte END = 0;
23 | byte NOP = 1;
24 | byte MSS = 2;
25 | byte WSCALE = 3;
26 | byte SACK_ENABLED = 4;
27 | byte SACK = 5;
28 | byte TIMESTAMP = 8;
29 |
30 | String getName();
31 |
32 | int getLength();
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/net/protocols/IP/TCP/TCPoptionEnd.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.protocols.IP.TCP;
18 |
19 | public class TCPoptionEnd implements TCPOption {
20 | public static final String name="end";
21 | public static final int length=1;
22 |
23 | public String getName() { return name; }
24 |
25 | public int getLength() {
26 | return length;
27 | }
28 |
29 | public String toString() {
30 | return name;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/net/protocols/IP/TCP/TCPoptionMSS.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.protocols.IP.TCP;
18 |
19 | public class TCPoptionMSS implements TCPOption {
20 | public static final String name="mss";
21 | public static final int length=4;
22 |
23 | private final short mss;
24 |
25 | public TCPoptionMSS(final short mss) {
26 | this.mss = mss;
27 | }
28 |
29 | public String getName() {
30 | return name;
31 | }
32 |
33 | public int getLength() {
34 | return length;
35 | }
36 |
37 | public String toString() {
38 | return "mss:" + ((int) mss & 0xffff);
39 | }
40 |
41 | public short getMss() {
42 | return mss;
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/net/protocols/IP/TCP/TCPoptionNOP.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.protocols.IP.TCP;
18 |
19 | public class TCPoptionNOP implements TCPOption {
20 | public static final String name="NOP";
21 | public static final int length=1;
22 |
23 | public String getName() {
24 | return name;
25 | }
26 |
27 | public int getLength() {
28 | return length;
29 | }
30 |
31 | public String toString() {
32 | return name;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/net/protocols/IP/TCP/TCPoptionSACK.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.protocols.IP.TCP;
18 |
19 | public class TCPoptionSACK implements TCPOption {
20 | public static final String name="SACK";
21 | public static final int length=2;
22 |
23 |
24 | public String getName() {
25 | return name;
26 | }
27 |
28 | public int getLength() {
29 | return length;
30 | }
31 |
32 | public String toString() {
33 | return name;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/net/protocols/IP/TCP/TCPoptionTimeStamp.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.protocols.IP.TCP;
18 |
19 | public class TCPoptionTimeStamp implements TCPOption {
20 | public static final String name="timestamps";
21 | public static final int length=10;
22 |
23 | private final int tsval;
24 | private final int tsecr;
25 |
26 | public TCPoptionTimeStamp(final int tsval, final int tsecr) {
27 | this.tsval = tsval;
28 | this.tsecr = tsecr;
29 | }
30 |
31 | public String getName() {return name; }
32 |
33 | public int getLength() {
34 | return length;
35 | }
36 |
37 | public String toString() {
38 | final StringBuilder s = new StringBuilder(128);
39 | s.append(name).append(":(");
40 | if (tsval != 0) {
41 | s.append((long) tsval & 0xffffffffL);
42 | }
43 | if (tsval != 0 & tsecr != 0) {
44 | s.append(',');
45 | }
46 | if (tsecr != 0) {
47 | s.append((long) tsecr & 0xffffffffL);
48 | }
49 | s.append(')');
50 | return s.toString();
51 | }
52 |
53 | public int getTsval() {
54 | return tsval;
55 | }
56 | public int getTsecr() {
57 | return tsecr;
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/net/protocols/IP/TCP/TCPoptionWindowScale.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.protocols.IP.TCP;
18 |
19 | public class TCPoptionWindowScale implements TCPOption {
20 | public static final String name="wscale";
21 | public static final int length=3;
22 |
23 | private final byte scale;
24 |
25 | public TCPoptionWindowScale(final byte scale) {
26 | this.scale = scale;
27 | }
28 |
29 | public String getName() { return name; }
30 |
31 | public int getLength() {
32 | return length;
33 | }
34 |
35 | public String toString() {
36 | return "wscale:" + ((int) (scale) & 0x00ff);
37 | }
38 |
39 | public byte getScale() {
40 | return scale;
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/net/tproxy/TProxyInterceptedSocket.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.tproxy;
18 |
19 | import org.it4y.jni.libc;
20 |
21 | import java.net.InetAddress;
22 | import java.net.InetSocketAddress;
23 | import java.net.Socket;
24 | import java.net.UnknownHostException;
25 |
26 | /**
27 | * TProxyInterceptedSocket wrappes the local and remote Socket Addresses from a TProxy intercepted TCP connection
28 | * Created by luc on 12/27/13.
29 | */
30 | public class TProxyInterceptedSocket {
31 |
32 | private final Socket socket;
33 | private final libc.sockaddr_in remote;
34 |
35 | /**
36 | * create a client proxy Socket pair
37 | * @param socket ; local part of the connection
38 | * @param remote : remote part of the connection
39 | * @throws UnknownHostException
40 | */
41 | public TProxyInterceptedSocket(final Socket socket, final libc.sockaddr_in remote) {
42 | this.socket = socket;
43 | this.remote = remote;
44 | }
45 |
46 | /**
47 | * get local part of the connection
48 | * @return
49 | */
50 | public Socket getSocket() {
51 | return socket;
52 | }
53 |
54 | /**
55 | * get Remote part of the connection a SocketAddress
56 | * @return
57 | */
58 | public InetSocketAddress getRemoteAsSocketAddress() {
59 | return remote.toInetSocketAddress();
60 | }
61 |
62 | /**
63 | * get Remote IPV4 in network notation
64 | * @return
65 | */
66 | public int getRemoteAddress() {
67 | return remote.address;
68 | }
69 |
70 | /**
71 | * get Remote IPV4 address as InetAddress
72 | * @return
73 | */
74 | public InetAddress getRemoteAddressAsInetAddress() {
75 | return remote.toInetAddress();
76 | }
77 |
78 | /**
79 | * return remote port of the connection
80 | * @return
81 | */
82 | public int getRemotePort() {
83 | return remote.port;
84 | }
85 |
86 | public String toString() {
87 | final StringBuilder s = new StringBuilder(128);
88 | s.append("local:").append(socket.getInetAddress()).append(':').append(socket.getPort()).append(' ');
89 | if (remote != null) {
90 | s.append("remote:").append(remote.toInetAddress()).append(':').append(remote.port);
91 | }
92 | return s.toString();
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/net/tproxy/TProxyServerSocket.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.tproxy;
18 |
19 | import org.it4y.jni.SocketOptions;
20 | import org.it4y.jni.libc;
21 | import org.it4y.jni.linuxutils;
22 | import org.it4y.net.JVMException;
23 | import org.it4y.net.SocketUtils;
24 |
25 | import java.io.FileDescriptor;
26 | import java.io.IOException;
27 | import java.lang.reflect.InvocationTargetException;
28 | import java.net.InetAddress;
29 | import java.net.InetSocketAddress;
30 | import java.net.ServerSocket;
31 | import java.net.Socket;
32 |
33 |
34 | /**
35 | * Created by luc on 12/27/13.
36 | * You need this on linux to run it as normal user
37 | * setcap "cap_net_raw=+eip cap_net_admin=+eip" /usr/lib/jvm/java-1.7.0/bin/java
38 | * replace java executable path with your java and use that java
39 | * Note: after upgrade/changing this file you need to repeat this
40 | */
41 | public class TProxyServerSocket extends ServerSocket {
42 |
43 | /*
44 | * This fields are manipulated by native c code so don't change it !!!
45 | */
46 | public TProxyServerSocket() throws IOException {
47 | }
48 |
49 | public FileDescriptor getFileDescriptor() throws InvocationTargetException, IllegalAccessException {
50 | return SocketUtils.getFileDescriptor(this);
51 | }
52 |
53 | public int getFd() throws JVMException {
54 | return SocketUtils.getFd(this);
55 | }
56 |
57 | public void setIPTransparentOption() throws libc.ErrnoException {
58 | linuxutils.setbooleanSockOption(this, SocketOptions.SOL_IP, SocketOptions.IP_TRANSPARENT, true);
59 | }
60 |
61 | public void initTProxy(final InetAddress address, final int port, final int backlog) throws libc.ErrnoException,IOException {
62 | setIPTransparentOption();
63 | setReuseAddress(true);
64 | //bind to localhost interface
65 | final InetSocketAddress local = new InetSocketAddress(address, port);
66 | bind(local, backlog);
67 | }
68 |
69 | public TProxyInterceptedSocket accepProxy() throws IOException,libc.ErrnoException {
70 | //final tproxy proxy = new tproxy();
71 | final Socket c = accept();
72 | //get original destination address stored in client socket structure
73 | final libc.sockaddr_in remote = linuxutils.getsockname(c);
74 | return new TProxyInterceptedSocket(c, remote);
75 | }
76 |
77 | }
78 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/net/tuntap/TunDevice.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.tuntap;
18 |
19 | import org.it4y.jni.libc;
20 | import org.it4y.jni.tuntap;
21 |
22 | public class TunDevice extends tuntap {
23 |
24 | public TunDevice() {
25 | }
26 |
27 | public TunDevice(final String device) {
28 | this.device = device;
29 | }
30 |
31 | public void open() throws libc.ErrnoException {
32 | //open on name or let kernel chouse
33 | if (device != null) {
34 | openTunDevice(device);
35 | } else {
36 | openTun();
37 | }
38 | }
39 |
40 | public String getDevice() {
41 | return device;
42 | }
43 | public int getFd() {return fd;}
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/util/Hexdump.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.it4y.util;
17 |
18 | import java.nio.ByteBuffer;
19 |
20 | public class Hexdump {
21 | final protected static char[] hexArray = "0123456789ABCDEF ".toCharArray();
22 |
23 | public static String bytesToHex(final ByteBuffer bytes, final int maxSize) {
24 | final char[] hexChars = new char[Math.min(bytes.capacity(), maxSize) * 3];
25 | int v;
26 | for (int j = 0; j < Math.min(maxSize, bytes.capacity()); j++) {
27 | v = bytes.get(j) & 0xFF;
28 | hexChars[j * 3] = hexArray[v >>> 4];
29 | hexChars[j * 3 + 1] = hexArray[v & 0x0F];
30 | hexChars[j * 3 + 2] = hexArray[0x10];
31 | }
32 | return new String(hexChars);
33 | }
34 |
35 | public static String bytesToHex(final byte[] bytes, final int maxSize) {
36 | final char[] hexChars = new char[Math.min(bytes.length, maxSize) * 3];
37 | int v;
38 | for (int j = 0; j < Math.min(maxSize, bytes.length); j++) {
39 | v = bytes[j] & 0xFF;
40 | hexChars[j * 3] = hexArray[v >>> 4];
41 | hexChars[j * 3 + 1] = hexArray[v & 0x0F];
42 | hexChars[j * 3 + 2] = hexArray[0x10];
43 | }
44 | return new String(hexChars);
45 | }
46 |
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/src/main/java/org/it4y/util/IndexNameMap.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.it4y.util;
17 |
18 | import java.util.HashMap;
19 |
20 | public class IndexNameMap extends HashMap{
21 |
22 | @SuppressWarnings("unchecked")
23 | public V get(final Object k) {
24 | final V s=super.get(k);
25 | return s==null ? (V) String.format("[%s]", k.toString()) : s;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/native/Makefile:
--------------------------------------------------------------------------------
1 | CC=gcc
2 | CFLAGS=-Wall -O3
3 | ARCH=$(shell ./java_arch.sh)
4 |
5 | #search JDK if not set
6 | ifndef JDK_HOME
7 | JDK_HOME=$(shell readlink -f `which javac` | sed "s:/bin/javac::")
8 | endif
9 |
10 | #64Bit support
11 | LBITS := $(shell getconf LONG_BIT)
12 | ifeq ($(LBITS),64)
13 | # do 64 bit stuff here, like set some CFLAGS
14 | LIBNETLINKDIR=/usr/lib64
15 | else
16 | # do 32 bit stuff here
17 | LIBNETLINKDIR=/usr/lib
18 | endif
19 |
20 |
21 | INCLUDES = -I$(JDK_HOME)/include/linux -I$(JDK_HOME)/include
22 | LFLAGS = -shared -fPIC
23 | JAVAH=javah
24 | CLASSPATH=../../target/classes
25 |
26 | all: javah build maven
27 |
28 | javah: tproxy.h tuntap.h linuxutils.h libnetlink3.h libpcap.h ntp.h
29 |
30 | tproxy.h: org_it4y_jni_tproxy.c
31 | $(JAVAH) -classpath $(CLASSPATH) org.it4y.jni.tproxy
32 |
33 | tuntap.h: org_it4y_jni_tuntap.c
34 | $(JAVAH) -classpath $(CLASSPATH) org.it4y.jni.tuntap
35 |
36 | linuxutils.h: org_it4y_jni_linuxutils.c
37 | $(JAVAH) -classpath $(CLASSPATH) org.it4y.jni.linuxutils
38 |
39 | libnetlink3.h: org_it4y_jni_libnetlink3.c
40 | $(JAVAH) -classpath $(CLASSPATH) org.it4y.jni.libnetlink3
41 |
42 | libpcap.h: org_it4y_jni_libpcap.c
43 | $(JAVAH) -classpath $(CLASSPATH) org.it4y.jni.libpcap
44 |
45 | ntp.h: org_it4y_jni_ntp.c
46 | $(JAVAH) -classpath $(CLASSPATH) org.it4y.jni.ntp
47 |
48 | libjnitproxy.so: org_it4y_jni_tproxy.c
49 | $(CC) $(CFLAGS) $(INCLUDES) $(LFLAGS) -o libjnitproxy-$(ARCH).so org_it4y_jni_tproxy.c
50 |
51 | libjnituntap.so: org_it4y_jni_tuntap.c
52 | $(CC) $(CFLAGS) $(INCLUDES) $(LFLAGS) -o libjnituntap-$(ARCH).so org_it4y_jni_tuntap.c
53 |
54 | libjnilinuxutils.so: org_it4y_jni_linuxutils.c
55 | $(CC) $(CFLAGS) $(INCLUDES) $(LFLAGS) -o libjnilinuxutils-$(ARCH).so org_it4y_jni_linuxutils.c -lrt
56 |
57 | libjninetlink3.so: org_it4y_jni_libnetlink3.c
58 | $(CC) $(CFLAGS) $(INCLUDES) `pkg-config --cflags --libs libnl-3.0` $(LFLAGS) \
59 | -o libjninetlink3-$(ARCH).so -Wl,-whole-archive $(LIBNETLINKDIR)/libnetlink.a -Wl,-no-whole-archive org_it4y_jni_libnetlink3.c
60 |
61 | libjnipcap.so: org_it4y_jni_libpcap.c
62 | $(CC) $(INCLUDES) `pcap-config --cflags ` $(LFLAGS) \
63 | org_it4y_jni_libpcap.c -lpcap -o libjnipcap-$(ARCH).so
64 |
65 | libjnintp.so: org_it4y_jni_ntp.c
66 | $(CC) $(INCLUDES) $(LFLAGS) org_it4y_jni_ntp.c -o libjnintp-$(ARCH).so
67 |
68 | testjhash: testjhash.c
69 | $(CC) $(CFLAGS) $(INCLUDES) testjhash.c -o testjhash
70 |
71 | bpf_compile: bpf_compile.c
72 | $(CC) $(CFLAGS) $(INCLUDES) `pcap-config --cflags ` bpf_compile.c -lpcap -o bpf_compile
73 |
74 | build: libjnitproxy.so libjnituntap.so libjnilinuxutils.so libjninetlink3.so libjnipcap.so libjnintp.so testjhash bpf_compile
75 |
76 | maven:
77 | cp *.so $(CLASSPATH)
78 |
79 | clean:
80 | rm -rf *.so
81 | rm -rf testjhash
82 | rm -rf bpf_compile
83 |
--------------------------------------------------------------------------------
/src/native/README:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lucwillems/JavaLinuxNet/903b9b542a6bfbc887985a3e404190241c5792ef/src/native/README
--------------------------------------------------------------------------------
/src/native/bpf_compile.c:
--------------------------------------------------------------------------------
1 | /*
2 | * BPF program compilation tool
3 | *
4 | * Generates decimal output, similar to `tcpdump -ddd ...`.
5 | * Unlike tcpdump, will generate for any given link layer type.
6 | *
7 | * Written by Willem de Bruijn (willemb@google.com)
8 | * Copyright Google, Inc. 2013
9 | * Licensed under the GNU General Public License version 2 (GPLv2)
10 | */
11 |
12 | #include
13 | #include
14 |
15 | int main(int argc, char **argv)
16 | {
17 | struct bpf_program program;
18 | struct bpf_insn *ins;
19 | int i, dlt = DLT_RAW;
20 |
21 | if (argc < 2 || argc > 3) {
22 | fprintf(stderr, "Usage: %s [link] ''\n\n"
23 | " link is a pcap linklayer type:\n"
24 | " one of EN10MB, RAW, SLIP, ...\n\n"
25 | "Examples: %s RAW 'tcp and greater 100'\n"
26 | " %s EN10MB 'ip proto 47'\n'",
27 | argv[0], argv[0], argv[0]);
28 | return 1;
29 | }
30 |
31 | if (argc == 3) {
32 | dlt = pcap_datalink_name_to_val(argv[1]);
33 | if (dlt == -1) {
34 | fprintf(stderr, "Unknown datalinktype: %s\n", argv[1]);
35 | return 1;
36 | }
37 | }
38 |
39 | if (pcap_compile_nopcap(65535, dlt, &program, argv[argc - 1], 1,
40 | PCAP_NETMASK_UNKNOWN)) {
41 | fprintf(stderr, "Compilation error\n");
42 | return 1;
43 | }
44 |
45 | //printf("%d,\n", program.bf_len);
46 | ins = program.bf_insns;
47 | printf("// %s : %s\n",argv[argc-2],argv[argc-1]);
48 | printf("byte[] bpf_bytes={\n");
49 | printf(" //size opcode:16 jt:8 jf:8 k:32 (8 bytes)\n");
50 | for (i = 0; i < program.bf_len-1; ++ins, ++i) {
51 | printf(" //%04d : 0x%x 0x%x 0x%x 0x%08x\n",
52 | i+1,
53 | ins->code,
54 | ins->jt, ins->jf,
55 | ins->k
56 | );
57 | printf(" (byte)0x%02x,(byte)0x%02x, (byte)0x%02x,(byte)0x%02x, (byte)0x%02x,(byte)0x%02x,(byte)0x%02x,(byte)0x%02x,\n",
58 | ins->code>>8, ins->code&0xff,
59 | ins->jt, ins->jf,
60 | ins->k >>24,
61 | ins->k >>16 & 0xff,
62 | ins->k >>8 &0xff,
63 | ins->k &0xff
64 | );
65 | }
66 | //last line
67 | printf(" //%04d : 0x%x 0x%x 0x%x 0x%x\n",
68 | i+1,
69 | ins->code,
70 | ins->jt, ins->jf,
71 | ins->k
72 | );
73 | printf(" (byte)0x%02x,(byte)0x%02x, (byte)0x%02x,(byte)0x%02x, (byte)0x%02x,(byte)0x%02x,(byte)0x%02x,(byte)0x%02x\n",
74 | ins->code>>8, ins->code&0xff,
75 | ins->jt, ins->jf,
76 | ins->k >>24 & 0xff,
77 | ins->k >>16 & 0xff,
78 | ins->k >>8 & 0xff,
79 | ins->k & 0xff
80 | );
81 | printf("};\n");
82 | pcap_freecode(&program);
83 | return 0;
84 | }
85 |
--------------------------------------------------------------------------------
/src/native/java_arch.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | #
3 | # seems java maps i[3..9]86 to i386
4 | # TODO : test this on amd64/ia64
5 | # the output should match java os.arch system property
6 | ARCH=`uname -m`
7 | case "$ARCH" in
8 | i[3-9]86) echo "i386"
9 | ;;
10 | x86_64) echo "amd64"
11 | ;;
12 | *) echo $ARCH
13 | ;;
14 | esac
15 |
16 |
--------------------------------------------------------------------------------
/src/native/org_it4y_jni_libpcap.c:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | #include
17 | #include
18 | //libpcap
19 | #include
20 | #include
21 | #include
22 |
23 | #include "org_it4y_jni_libpcap.h"
24 |
25 | //some errorcodes
26 | #define OK 0;
27 | #define ERR_JNI_ERROR -1;
28 | #define ERR_FIND_CLASS_FAILED -2;
29 | #define ERR_GET_METHOD_FAILED -3;
30 | #define ERR_CALL_METHOD_FAILED -4;
31 | #define ERR_BUFFER_TO_SMALL -5;
32 | #define ERR_EXCEPTION -6;
33 |
34 |
35 | // Cached Object,Field,Method ID's needed
36 | jclass bpfProgram_class;
37 | jmethodID bpfProgram_initID;
38 |
39 | /*
40 | * Class: org_it4y_jni_libpcap
41 | * Method: initlib
42 | * Signature: ()I
43 | */
44 | JNIEXPORT jint JNICALL Java_org_it4y_jni_libpcap_initlib(JNIEnv *env, jclass this) {
45 | fprintf(stderr,"libjninetlink3 init...\n");
46 |
47 | //bpfProgram class
48 | bpfProgram_class = (*env)->FindClass( env, "org/it4y/jni/libpcap$bpfPprogram");
49 | if((*env)->ExceptionOccurred(env))
50 | return ERR_FIND_CLASS_FAILED;
51 |
52 | //bpfProgram_initID method
53 | bpfProgram_initID = (*env)->GetMethodID(env,bpfProgram_class, "init", "(I)Ljava/nio/ByteBuffer;");
54 | if((*env)->ExceptionOccurred(env))
55 | return ERR_GET_METHOD_FAILED;
56 |
57 |
58 | //init ok
59 | fprintf(stderr,"libjninetlink3 ok\n");
60 | return OK;
61 |
62 | }
63 |
64 | /*
65 | * Class: org_it4y_jni_libpcap
66 | * Method: pcap_datalink_name_to_val
67 | * Signature: (Ljava/lang/String;)I
68 | */
69 | JNIEXPORT jint JNICALL Java_org_it4y_jni_libpcap_pcap_1datalink_1name_1to_1val(JNIEnv *env, jclass this, jstring device) {
70 | const char *dev;
71 |
72 | /* get device name from java */
73 | dev= (*env)->GetStringUTFChars(env,device, 0);
74 | int result=pcap_datalink_name_to_val(dev);
75 | (*env)->ReleaseStringUTFChars(env, device, dev);
76 |
77 | return result;
78 | }
79 |
80 | /*
81 | * Class: org_it4y_jni_libpcap
82 | * Method: pcap_compile_nopcap
83 | * Signature: (IILorg/it4y/jni/libpcap/bpfPprogram;Ljava/lang/String;ZI)I
84 | */
85 | JNIEXPORT jint JNICALL Java_org_it4y_jni_libpcap_pcap_1compile_1nopcap(JNIEnv *env, jclass this , jint snaplen , jint linktype , jobject bpf, jstring filter, jboolean optimize, jint mask) {
86 |
87 | struct bpf_program program;
88 | int opt=0;
89 | const char *filterexpr;
90 | jfieldID bpfProgram_bufferFieldID;
91 |
92 | if (optimize) {
93 | opt=1;
94 | }
95 | filterexpr= (*env)->GetStringUTFChars(env,filter, 0);
96 | int result=pcap_compile_nopcap(snaplen,linktype, &program, filterexpr, opt,mask);
97 | (*env)->ReleaseStringUTFChars(env, filter,filterexpr);
98 | if(result) {
99 | //#error during compile
100 | return result;
101 | }
102 |
103 | //insert data into the bpf program class
104 | //init bytebuffer
105 | jobject buffer=(*env)->CallObjectMethod(env, bpf, bpfProgram_initID, program.bf_len);
106 | if((*env)->ExceptionOccurred(env))
107 | return ERR_FIND_CLASS_FAILED;
108 |
109 | char* b = (char *)(*env)->GetDirectBufferAddress(env,(jobject)buffer);
110 | memcpy(b, program.bf_insns, program.bf_len*sizeof(struct bpf_insn));
111 |
112 | //for testing
113 | //int i;
114 | //struct bpf_insn *ins = program.bf_insns;
115 | //for (i = 0; i < program.bf_len; ++ins, ++i) {
116 | // printf(" //%04d : 0x%x 0x%x 0x%x 0x%x\n",
117 | // i,
118 | // ins->code,
119 | // ins->jt, ins->jf,
120 | // ins->k
121 | // );
122 | //}
123 | return 0;
124 | }
125 |
126 | /*
127 | * Class: org_it4y_jni_libpcap
128 | * Method: bpf_filter
129 | * Signature: ([BIILjava/nio/ByteBuffer;)I
130 | */
131 | JNIEXPORT jint JNICALL Java_org_it4y_jni_libpcap_bpf_1filter(JNIEnv *env, jclass this , jobject program, jint snaplen, jint pktlen, jobject packet) {
132 | struct pcap_pkthdr hdr;
133 | struct bpf_insn *pc;
134 | char* pkt;
135 |
136 | pc= (struct bpf_insn *)(*env)->GetDirectBufferAddress(env,(jobject)program);
137 | pkt = (char *)(*env)->GetDirectBufferAddress(env,(jobject)packet);
138 | int result=bpf_filter(pc,pkt,snaplen,pktlen);
139 | return result;
140 | }
141 |
142 | /*
143 | * Class: org_it4y_jni_libpcap
144 | * Method: bpf_validate
145 | * Signature: (Ljava/nio/ByteBuffer;I)I
146 | */
147 | JNIEXPORT jint JNICALL Java_org_it4y_jni_libpcap_bpf_1validate(JNIEnv *env, jclass this, jobject program, jint size) {
148 | struct bpf_insn *pc;
149 |
150 | if (program != NULL) {
151 | pc= (struct bpf_insn *)(*env)->GetDirectBufferAddress(env,(jobject)program);
152 | } else {
153 | return -1;
154 | }
155 | int result=bpf_validate(pc,size);
156 | return result;
157 | }
158 |
159 |
--------------------------------------------------------------------------------
/src/native/org_it4y_jni_tproxy.c:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | #include
17 | #include
18 | #include
19 | #include
20 | #include
21 | #include
22 |
23 | #include "org_it4y_jni_tproxy.h"
24 |
25 | /*
26 | * Class: org_it4y_jni_tproxy
27 | * Method: setIPTransparant
28 | * Signature: (I)I
29 | */
30 | JNIEXPORT jint JNICALL Java_org_it4y_jni_tproxy_setIPTransparant(JNIEnv *env, jobject this, jint fd) {
31 | int yes = 1;
32 | if (setsockopt(fd, SOL_IP, IP_TRANSPARENT, &yes, sizeof(yes)) != 0) {
33 | perror("setsockopt IP_TRANSPARENT");
34 | return errno;
35 | }
36 | return 0;
37 | }
38 |
39 | /*
40 | * Class: org_it4y_jni_tproxy
41 | * Method: getOriginalDestination
42 | * Signature: (I)I
43 | */
44 | JNIEXPORT jint JNICALL Java_org_it4y_jni_tproxy_getOriginalDestination(JNIEnv *env, jobject this, jint fd) {
45 |
46 | jfieldID jremoteIp, jremotePort;
47 | jclass jclass;
48 | struct sockaddr_in orig_dst;
49 | socklen_t addrlen = sizeof(orig_dst);
50 |
51 | memset(&orig_dst, 0, addrlen);
52 |
53 | //Socket is bound to original destination
54 | if(getsockname(fd, (struct sockaddr*) &orig_dst, &addrlen) < 0){
55 | perror("getsockname: ");
56 | return -1;
57 | } else {
58 | if(orig_dst.sin_family == AF_INET){
59 | uint16_t port=ntohs(orig_dst.sin_port);
60 | jclass = (*env)->GetObjectClass(env, this);
61 | jremoteIp = (*env)->GetFieldID(env, jclass, "remoteIp", "I");
62 | (*env)->SetIntField(env, this, jremoteIp ,(jint)ntohl(orig_dst.sin_addr.s_addr));
63 | jremotePort = (*env)->GetFieldID(env, jclass, "remotePort", "I");
64 | (*env)->SetIntField(env, this, jremotePort ,(jint) port);
65 | } else {
66 | fprintf(stderr," IPv6 not supported!!!\n");
67 | }
68 | }
69 | return 0;
70 | }
71 |
--------------------------------------------------------------------------------
/src/native/testjhash.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | typedef uint32_t u32;
5 | typedef uint8_t u8;
6 |
7 |
8 |
9 | /* jhash.h: Jenkins hash support.
10 | *
11 | * Copyright (C) 2006. Bob Jenkins (bob_jenkins@burtleburtle.net)
12 | *
13 | * http://burtleburtle.net/bob/hash/
14 | *
15 | * These are the credits from Bob's sources:
16 | *
17 | * lookup3.c, by Bob Jenkins, May 2006, Public Domain.
18 | *
19 | * These are functions for producing 32-bit hashes for hash table lookup.
20 | * hashword(), hashlittle(), hashlittle2(), hashbig(), mix(), and final()
21 | * are externally useful functions. Routines to test the hash are included
22 | * if SELF_TEST is defined. You can use this free for any purpose. It's in
23 | * the public domain. It has no warranty.
24 | *
25 | * Copyright (C) 2009-2010 Jozsef Kadlecsik (kadlec@blackhole.kfki.hu)
26 | *
27 | * I've modified Bob's hash to be useful in the Linux kernel, and
28 | * any bugs present are my fault.
29 | * Jozsef
30 | */
31 |
32 | /* Best hash sizes are of power of two */
33 | #define jhash_size(n) ((u32)1<<(n))
34 | /* Mask the hash value, i.e (value & jhash_mask(n)) instead of (value % n) */
35 | #define jhash_mask(n) (jhash_size(n)-1)
36 |
37 | /**
38 | * rol32 - rotate a 32-bit value left
39 | * @word: value to rotate
40 | * @shift: bits to roll
41 | */
42 | static inline u32 rol32(u32 word, unsigned int shift)
43 | {
44 | u32 a=(word << shift);
45 | u32 b=(word >> (32 - shift));
46 | u32 c=a | b;
47 | u32 x=(word << shift) | (word >> (32 - shift));
48 | fprintf(stderr,"rol32: %08x %d : %08x a=%08x b=%08x c=%08x\n",word,shift,x,a,b,c);
49 | return x;
50 | }
51 |
52 | /* __jhash_mix -- mix 3 32-bit values reversibly. */
53 | #define __jhash_mix(a, b, c) \
54 | { \
55 | a -= c; a ^= rol32(c, 4); c += b; \
56 | b -= a; b ^= rol32(a, 6); a += c; \
57 | c -= b; c ^= rol32(b, 8); b += a; \
58 | a -= c; a ^= rol32(c, 16); c += b; \
59 | b -= a; b ^= rol32(a, 19); a += c; \
60 | c -= b; c ^= rol32(b, 4); b += a; \
61 | }
62 |
63 | /* __jhash_final - final mixing of 3 32-bit values (a,b,c) into c */
64 | #define __jhash_final(a, b, c) \
65 | { \
66 | c ^= b; c -= rol32(b, 14); \
67 | a ^= c; a -= rol32(c, 11); \
68 | b ^= a; b -= rol32(a, 25); \
69 | c ^= b; c -= rol32(b, 16); \
70 | a ^= c; a -= rol32(c, 4); \
71 | b ^= a; b -= rol32(a, 14); \
72 | c ^= b; c -= rol32(b, 24); \
73 | }
74 |
75 | /* An arbitrary initial parameter */
76 | #define JHASH_INITVAL 0xdeadbeef
77 |
78 |
79 | /* jhash_3words - hash exactly 3, 2 or 1 word(s) */
80 | static inline u32 jhash_3words(u32 a, u32 b, u32 c, u32 initval)
81 | {
82 | a += JHASH_INITVAL;
83 | b += JHASH_INITVAL;
84 | c += initval;
85 |
86 | fprintf(stderr,"1 a: %08x b: %08x c: %08x\n",a,b,c);
87 |
88 |
89 | c ^= b;
90 | fprintf(stderr,"2 a: %08x b: %08x c: %08x\n",a,b,c);
91 | c -= rol32(b, 14);
92 | fprintf(stderr,"3 a: %08x b: %08x c: %08x\n",a,b,c);
93 |
94 | a ^= c;
95 | fprintf(stderr,"4 a: %08x b: %08x c: %08x\n",a,b,c);
96 | a -= rol32(c, 11);
97 | fprintf(stderr,"5 a: %08x b: %08x c: %08x\n",a,b,c);
98 | b ^= a;
99 | fprintf(stderr,"6 a: %08x b: %08x c: %08x\n",a,b,c);
100 | b -= rol32(a, 25);
101 | fprintf(stderr,"7 a: %08x b: %08x c: %08x\n",a,b,c);
102 | c ^= b;
103 | fprintf(stderr,"8 a: %08x b: %08x c: %08x\n",a,b,c);
104 | c -= rol32(b, 16);
105 | fprintf(stderr,"9 a: %08x b: %08x c: %08x\n",a,b,c);
106 | a ^= c;
107 | fprintf(stderr,"10 a: %08x b: %08x c: %08x\n",a,b,c);
108 | a -= rol32(c, 4);
109 | fprintf(stderr,"11 a: %08x b: %08x c: %08x\n",a,b,c);
110 | b ^= a;
111 | fprintf(stderr,"12 a: %08x b: %08x c: %08x\n",a,b,c);
112 | b -= rol32(a, 14);
113 | fprintf(stderr,"13 a: %08x b: %08x c: %08x\n",a,b,c);
114 | c ^= b;
115 | fprintf(stderr,"14 a: %08x b: %08x c: %08x\n",a,b,c);
116 | c -= rol32(b, 24);
117 | fprintf(stderr,"15 a: %08x b: %08x c: %08x\n",a,b,c);
118 |
119 |
120 | fprintf(stderr,"x a: %08x b: %08x c: %08x\n",a,b,c);
121 | //__jhash_final(a, b, c);
122 |
123 | return c;
124 | }
125 |
126 | static inline u32 jhash_2words(u32 a, u32 b, u32 initval)
127 | {
128 | return jhash_3words(a, b, 0, initval);
129 | }
130 |
131 | static inline u32 jhash_1word(u32 a, u32 initval)
132 | {
133 | return jhash_3words(a, 0, 0, initval);
134 | }
135 |
136 |
137 | int main()
138 | {
139 |
140 | fprintf(stderr,"0xffffffff,0xeeeeeeee,0xdddddddd,0x00000000 : %08x\n",jhash_3words(0xffffffff,0xeeeeeeee,0xdddddddd,0x00000000));
141 | fprintf(stderr,"0x11223344,0x44332211,0x01020304,0x12345678 : %08x\n",jhash_3words(0x11223344,0x44332211,0x01020304,0x12345678));
142 | fprintf(stderr,"0x00000000,0x00000000,0x00000000,0x00000000 : %08x\n",jhash_3words(0x00000000,0x00000000,0x00000000,0x00000000));
143 | return 0;
144 | }
145 |
--------------------------------------------------------------------------------
/src/setup-test.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | #
3 | # Note we abuse 8.8.4.4 as test IP
4 | TESTIP=8.8.4.4
5 |
6 | ip tuntap del dev luc mode tun
7 | ip tuntap add dev luc mode tun user luc group users
8 | ip addr add 127.0.0.2/32 dev luc
9 | ip link set dev luc up
10 | ip route add $TESTIP dev luc
11 |
12 | #route all redirected traffic to lo
13 | ip rule del priority 2000
14 | ip rule add priority 2000 fwmark 1 lookup 100
15 | ip route flush table 100
16 | ip -f inet route add local 0.0.0.0/0 dev lo table 100
17 |
18 | iptables -F
19 | iptables -t mangle -F
20 | iptables -t mangle -N DIVERT
21 | iptables -t mangle -A DIVERT -j MARK --set-mark 1
22 | iptables -t mangle -A DIVERT -j ACCEPT
23 |
24 | #for forwarding traffic
25 | iptables -t mangle -A PREROUTING -p tcp -m socket -j DIVERT
26 | iptables -t mangle -A PREROUTING -p tcp -m tcp --destination $TESTIP --dport 80 -j TPROXY --on-port 1800 --on-ip 0.0.0.0 --tproxy-mark 0x01/0x01
27 |
28 | #for local traffic
29 | iptables -t mangle -A OUTPUT -p tcp -m tcp --destination $TESTIP --dport 80 -j MARK --set-mark 0x01
30 |
--------------------------------------------------------------------------------
/src/test/java/org/it4y/benchmarks/TimeBenchmark.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.benchmarks;
18 |
19 | import org.it4y.jni.linux.time;
20 | import org.it4y.jni.linuxutils;
21 | import org.openjdk.jmh.annotations.*;
22 |
23 | import java.util.concurrent.TimeUnit;
24 |
25 | /**
26 | * Created by luc on 11/16/14.
27 | */
28 |
29 | @Warmup(iterations = 10)
30 | @Fork(1)
31 | @Threads(4)
32 | @BenchmarkMode(Mode.AverageTime)
33 | @OutputTimeUnit(TimeUnit.NANOSECONDS)
34 | @Measurement(time = 1000,timeUnit = TimeUnit.MILLISECONDS)
35 |
36 | public class TimeBenchmark {
37 |
38 | @Benchmark
39 | public void benchmarkMonotonicCoarse() {
40 | linuxutils.clock_getTime(time.CLOCK_MONOTONIC_COARSE);
41 | }
42 | @Benchmark
43 | public void benchmarkMonotonicRaw() {
44 | linuxutils.clock_getTime(time.CLOCK_MONOTONIC_RAW);
45 | }
46 | @Benchmark
47 | public void benchmarkClockMonotonicCoarse() {
48 | linuxutils.clock_getTime(time.CLOCK_MONOTONIC_COARSE);
49 | }
50 |
51 | @Benchmark
52 | public void benchmarkUsecTime() {
53 | linuxutils.usecTime();
54 | }
55 | @Benchmark
56 | public void benchmarkUsecTimeBaseOnCLOCKMONOTONICCOARSE() {
57 | linuxutils.usecTime(time.CLOCK_MONOTONIC_COARSE);
58 | }
59 |
60 | @Benchmark
61 | public void benchmarknanoTime() {
62 | System.nanoTime();
63 | }
64 |
65 | @Benchmark
66 | public void benchmarkusecCLOCK_MONOTONIC_COARSE_TimeAccurancy() {
67 | long t=0;
68 | while(linuxutils.usecTime(time.CLOCK_MONOTONIC_COARSE)==t && t !=0) {}
69 | }
70 |
71 | @Benchmark
72 | public void benchmarkgetTimeCLOCK_MONOTONIC_COARSE_TimeAccurancy() {
73 | long t=0;
74 | while(linuxutils.clock_getTime(time.CLOCK_MONOTONIC_COARSE)==t && t!=0) {}
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/src/test/java/org/it4y/integration/IT_SystemTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.integration;
18 |
19 | import org.junit.Test;
20 | import org.slf4j.Logger;
21 | import org.slf4j.LoggerFactory;
22 |
23 | import java.io.File;
24 | import java.io.FileInputStream;
25 | import java.util.Scanner;
26 |
27 | /**
28 | * Created by luc on 3/21/14.
29 | */
30 | public class IT_SystemTest {
31 | Logger log= LoggerFactory.getLogger(IT_SystemTest.class);
32 | @Test
33 | public void testDumpSystemInfo() throws Exception {
34 | //Just dump system information
35 | for (Object key:System.getProperties().keySet()) {
36 | log.info(" property {}: {}",key,System.getProperty(key.toString()));
37 | }
38 |
39 | //Read our environment
40 | //Just dump system information
41 | for (Object key:System.getenv().keySet()) {
42 | log.info("env {}: {}",key,System.getenv(key.toString()));
43 | }
44 |
45 | //Read how we are executed
46 | //read 0 terminated string
47 | Scanner scanner = new Scanner(new FileInputStream(new File("/proc/self/cmdline")),"UTF-8");
48 | scanner.useDelimiter("\u0000");
49 | StringBuilder cmdline=new StringBuilder();
50 | while (scanner.hasNext()) {
51 | cmdline.append(scanner.next()).append(" ");
52 | }
53 | log.info("Cmd line: {}",cmdline.toString());
54 |
55 | }
56 |
57 | }
58 |
--------------------------------------------------------------------------------
/src/test/java/org/it4y/integration/jni/IT_tuntapTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.integration.jni;
18 |
19 | import junit.framework.Assert;
20 | import org.it4y.jni.libc;
21 | import org.it4y.net.tuntap.TunDevice;
22 | import org.junit.Test;
23 | import org.slf4j.Logger;
24 | import org.slf4j.LoggerFactory;
25 |
26 | /**
27 | * Created by luc on 1/17/14.
28 | * Please run setup-test.sh before running this test
29 | * This can only be run on linux
30 | */
31 | public class IT_tuntapTest {
32 | Logger log= LoggerFactory.getLogger(IT_tuntapTest.class);
33 |
34 | /* create and open a tunnel device */
35 | private TunDevice openTun(String device) throws libc.ErrnoException {
36 | TunDevice tun=null;
37 | if (device != null) {
38 | tun=new TunDevice(device);
39 | } else {
40 | tun=new TunDevice();
41 | }
42 | Assert.assertNotNull(tun);
43 | log.info("tun: {}",tun);
44 | return tun;
45 | }
46 |
47 | @Test
48 | public void testAnonymousTunDevice() throws Exception {
49 | TunDevice tun=null;
50 | log.info("test anonymous tunnel device");
51 | try {
52 | tun=openTun(null);
53 | tun.open();
54 | Assert.assertTrue(tun.getFd() > 0);
55 | log.info("device: {} fd: {}",tun.getDevice(),tun.getFd());
56 | Assert.assertTrue(tun.getDevice().startsWith("tun"));
57 | } finally {
58 | if (tun != null) {
59 | tun.close();
60 | Assert.assertEquals(0,tun.getFd());
61 | }
62 | }
63 | }
64 |
65 | @Test
66 | public void testNamedTunDeviceOnName() throws Exception{
67 | TunDevice tun=null;
68 | log.info("test named tunnel device");
69 | try {
70 | tun=openTun("test");
71 | tun.open();
72 | Assert.assertTrue(tun.getFd() > 0);
73 | log.info("device: {} fd: {}",tun.getDevice(),tun.getFd());
74 | Assert.assertEquals("test",tun.getDevice());
75 | } finally {
76 | if (tun != null) {
77 | tun.close();
78 | Assert.assertEquals(0, tun.getFd());
79 | }
80 | }
81 | }
82 |
83 | @Test
84 | public void testTunDeviceDoubleOpen() throws Exception{
85 | boolean thrownexception=false;
86 | log.info("test double open");
87 | TunDevice tun=null;
88 | try {
89 | tun=openTun("test");
90 | //this will cause exception
91 | tun.open();
92 | Assert.assertTrue(tun.getFd() > 0);
93 | log.info("device: {} fd: {}",tun.getDevice(),tun.getFd());
94 | tun.open();
95 | } catch (libc.ErrnoException errno) {
96 | log.info("got exception (OK): {}",errno.getMessage());
97 | thrownexception=true;
98 | Assert.assertEquals(16,errno.getErrno());
99 | //Assert.assertEquals("Device or resource busy",errno.getMessage());
100 | } finally {
101 | if (tun != null) {
102 | tun.close();
103 | Assert.assertEquals(0, tun.getFd());
104 | Assert.assertTrue(thrownexception);
105 | }
106 | }
107 | }
108 |
109 | }
--------------------------------------------------------------------------------
/src/test/java/org/it4y/integration/jni/IT_tuntapWriteTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.integration.jni;
18 |
19 | import junit.framework.Assert;
20 | import org.it4y.integration.utils;
21 | import org.it4y.jni.libc;
22 | import org.it4y.net.protocols.IP.ICMP.ICMPPacket;
23 | import org.it4y.net.protocols.IP.IpPacket;
24 | import org.it4y.net.tuntap.TunDevice;
25 | import org.junit.Test;
26 | import org.slf4j.Logger;
27 | import org.slf4j.LoggerFactory;
28 |
29 | import java.nio.ByteBuffer;
30 |
31 | /**
32 | * Created by luc on 3/21/14.
33 | */
34 | public class IT_tuntapWriteTest {
35 | Logger log= LoggerFactory.getLogger(IT_tuntapWriteTest.class);
36 |
37 | /* create and open a tunnel device */
38 | private TunDevice openTun(String device) throws libc.ErrnoException {
39 | TunDevice tun=null;
40 | if (device != null) {
41 | tun=new TunDevice(device);
42 | } else {
43 | tun=new TunDevice();
44 | }
45 | Assert.assertNotNull(tun);
46 | log.info("tun: {}",tun);
47 | return tun;
48 | }
49 |
50 |
51 | @Test
52 | public void testTunWrite() throws Exception{
53 | boolean thrownexception=false;
54 | TunDevice tun=null;
55 | log.info("test tunnel write");
56 | try {
57 | tun=openTun("test");
58 | tun.open();
59 | Assert.assertTrue(tun.getFd() > 0);
60 | log.info("device: {} fd: {}",tun.getDevice(),tun.getFd());
61 | //we need to write some bytes to tun device
62 | ByteBuffer buf=ByteBuffer.allocateDirect(60);
63 | //create dummy ICMP packet,
64 | buf.clear();
65 | buf.put((byte) 0x45); //IPv4 + header size
66 | buf.put((byte) 0x00); //dscp
67 | buf.put((byte)60); //size
68 | buf.putShort((byte) 0x00);
69 | buf.putShort((byte) 0x00);
70 | buf.put((byte) 0x40); //TTL
71 | buf.put((byte)0x01); //protocol
72 | int x=tun.writeByteBuffer(buf,60);
73 | Assert.assertEquals(60,x);
74 | } finally {
75 | if (tun != null) {
76 | tun.close();
77 | Assert.assertEquals(0, tun.getFd());
78 | }
79 | }
80 | }
81 |
82 | @Test
83 | public void testTunWriteInvalidIP() throws Exception{
84 | boolean thrownexception=false;
85 | TunDevice tun=null;
86 | log.info("test tunnel write invalid IP");
87 | try {
88 | tun=openTun("test");
89 | tun.open();
90 | Assert.assertTrue(tun.getFd() > 0);
91 | log.info("device: {} fd: {}",tun.getDevice(),tun.getFd());
92 |
93 | int size=1000;
94 | ByteBuffer ipPacket= utils.getBadIpPacket(ICMPPacket.PROTOCOL, size);
95 | tun.writeByteBuffer(ipPacket,size);
96 | } catch (libc.ErrnoException errno) {
97 | //invalid argument
98 | log.info("got exeception (OK) : {}",errno.getMessage());
99 | Assert.assertEquals(22,errno.getErrno());
100 | thrownexception=true;
101 | } finally {
102 | if (tun != null) {
103 | tun.close();
104 | Assert.assertEquals(0, tun.getFd());
105 | Assert.assertTrue(thrownexception);
106 | }
107 | }
108 | }
109 |
110 | }
111 |
--------------------------------------------------------------------------------
/src/test/java/org/it4y/integration/utils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.integration;
18 |
19 | import org.it4y.net.protocols.IP.ICMP.ICMPPacket;
20 |
21 | import java.io.IOException;
22 | import java.net.DatagramPacket;
23 | import java.net.DatagramSocket;
24 | import java.net.InetAddress;
25 | import java.nio.ByteBuffer;
26 |
27 | /**
28 | * Created by luc on 1/18/14.
29 | */
30 | public class utils {
31 |
32 | //See setup-test.sh script
33 | public static String TESTIP="8.8.4.4";
34 | public static int TESTPORT=1024;
35 |
36 | public static void sendTestUDP(int size) throws IOException {
37 | byte[] buffer = new byte[size];
38 | InetAddress address = InetAddress.getByName(TESTIP);
39 | DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, TESTPORT);
40 | DatagramSocket socket = new DatagramSocket();
41 | socket.send(packet);
42 | }
43 |
44 | public static ByteBuffer getBadIpPacket(byte ipProtocol, int size) {
45 | //we need to write some bytes to tun device
46 | ByteBuffer buf=ByteBuffer.allocateDirect(size);
47 | //create dummy ICMP packet,
48 | buf.clear();
49 | buf.put((byte) 0x55); //IPv5 + header size , this doesn't exist ofcourse
50 | buf.put((byte) 0x00); //dscp
51 | buf.put((byte)60); //size
52 | buf.putShort((byte) 0x00);
53 | buf.putShort((byte) 0x00);
54 | buf.put((byte) 0x40); //TTL
55 | buf.put(ipProtocol); //protocol
56 | return buf;
57 | }
58 |
59 | public static ICMPPacket getIcmpPing(int size) {
60 | //we need to write some bytes to tun device
61 | ByteBuffer buf=ByteBuffer.allocateDirect(size+28);
62 | //create dummy ICMP packet,
63 | ICMPPacket icmp=new ICMPPacket(buf,size);
64 | icmp.initIpHeader();
65 | icmp.setType(ICMPPacket.ECHO_REQUEST);
66 | icmp.setSourceAddress(0x7f000002);
67 | icmp.setDestinationAddress(0x7f000001);
68 | icmp.updateChecksum();
69 | return icmp;
70 | }
71 |
72 | }
73 |
--------------------------------------------------------------------------------
/src/test/java/org/it4y/jni/JNILoaderTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.jni;
18 |
19 | import org.junit.Assert;
20 | import org.junit.Before;
21 | import org.junit.Test;
22 | import org.slf4j.Logger;
23 | import org.slf4j.LoggerFactory;
24 |
25 | import java.io.File;
26 |
27 | /**
28 | * Created by luc on 3/24/14.
29 | */
30 | public class JNILoaderTest {
31 | Logger logger = LoggerFactory.getLogger(JNILoader.class);
32 | private File tmpDir;
33 |
34 | @Before
35 | public void initTest() {
36 | //Setup System properties for this test.
37 | //As we could run both test into 1 VM, we should "try" to cleanup before test
38 | tmpDir=new File("/tmp/luc/test");
39 | //Setup System properties
40 | System.getProperties().remove(JNILoader.customPathKEY); //remove any "old" stuff
41 | System.setProperty(JNILoader.customPathKEY,tmpDir.getAbsolutePath());
42 | }
43 |
44 | @Test
45 | public void testJNILoaderWithCustomPath() {
46 | JNILoader.loadLibrary("libjnituntap");
47 | //Directory must exist
48 | Assert.assertTrue(tmpDir.exists());
49 | File soFile=new File(tmpDir,JNILoader.libraryArchFileName("libjnituntap"));
50 | Assert.assertTrue(soFile.exists());
51 | Assert.assertTrue(soFile.length()>0);
52 | }
53 |
54 | @Test
55 | public void testJNILoaderLoadNonExisting() {
56 | try {
57 | JNILoader.loadLibrary("shithappens");
58 | } catch (RuntimeException re) {
59 | logger.info("Got RuntimeException (OK): {}",re.getMessage());
60 | return;
61 | }
62 | Assert.assertTrue("We must have RuntimeException",false);
63 | }
64 |
65 | }
66 |
--------------------------------------------------------------------------------
/src/test/java/org/it4y/jni/SocketOptionsTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.jni;
18 |
19 | import org.junit.Assert;
20 | import org.junit.Test;
21 |
22 | /**
23 | * Created by luc on 3/23/14.
24 | */
25 | public class SocketOptionsTest {
26 |
27 | @Test
28 | public void testSocketOptions() {
29 | //nothing really usefull ?
30 | Assert.assertEquals(0,SocketOptions.SOL_IP);
31 | Assert.assertEquals(6,SocketOptions.SOL_TCP);
32 | Assert.assertEquals(17,SocketOptions.SOL_UDP);
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/test/java/org/it4y/jni/libnetlink3Test.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.jni;
18 |
19 | import junit.framework.Assert;
20 | import org.it4y.jni.linux.netlink;
21 | import org.it4y.jni.linux.rtnetlink;
22 | import org.it4y.util.Counter;
23 | import org.junit.Test;
24 | import org.slf4j.Logger;
25 | import org.slf4j.LoggerFactory;
26 |
27 | import java.nio.ByteBuffer;
28 |
29 | import static org.it4y.jni.libnetlink3.rtnl_accept;
30 |
31 | /**
32 | * Created by luc on 1/9/14.
33 | */
34 | public class libnetlink3Test {
35 |
36 | private Logger logger = LoggerFactory.getLogger(libnetlink3Test.class);
37 | private ByteBuffer messageBuffer = ByteBuffer.allocateDirect(8129);
38 |
39 | @Test
40 | public void testRtnlOpenClose() throws Exception {
41 |
42 | logger.info("rtnl open/close");
43 | libnetlink3.rtnl_handle handle;
44 | ByteBuffer buffer;
45 |
46 | handle=new libnetlink3.rtnl_handle();
47 | Assert.assertNotNull(handle);
48 |
49 | //open netlink3 socket
50 | int result=libnetlink3.rtnl_open(handle,(short)0xffff) ;
51 | Assert.assertTrue(result==0);
52 | logger.info("rtnl fd: {}",handle.getFd());
53 | logger.info("rtnl seq: {}",handle.getSeq());
54 |
55 | //Check the rtnl handle structure , from netlink c code:
56 | //struct rtnl_handle
57 | //{
58 | // int fd;
59 | // struct sockaddr_nl local;
60 | // struct sockaddr_nl peer;
61 | // uint32_t seq;
62 | // uint32_t dump;
63 | //};
64 | buffer=ByteBuffer.wrap(handle.handle);
65 | Assert.assertNotNull(buffer);
66 | Assert.assertTrue(buffer.getShort() != 0); //fd field
67 | Assert.assertTrue(buffer.getInt() != 0); //local
68 | Assert.assertTrue(buffer.getInt() !=0); //peer
69 |
70 | libnetlink3.rtnl_close(handle);
71 | }
72 |
73 | @Test
74 | public void testRtnlListen() throws Exception {
75 |
76 | libnetlink3.rtnl_handle handle;
77 | ByteBuffer buffer;
78 | int result=0;
79 | final Counter cnt=new Counter();
80 |
81 | logger.info("rtnl listen...");
82 | //open netlink3 socket
83 | handle=new libnetlink3.rtnl_handle();
84 | int groups = rtnetlink.RTMGRP_IPV4_IFADDR |
85 | rtnetlink.RTMGRP_IPV4_ROUTE |
86 | rtnetlink.RTMGRP_IPV4_MROUTE |
87 | rtnetlink.RTMGRP_LINK;
88 | result=libnetlink3.rtnl_open_byproto(handle, groups,netlink.NETLINK_ROUTE);
89 | Assert.assertTrue(result == 0);
90 | //Request addres information
91 | logger.info("rtnl dump request");
92 | result=libnetlink3.rtnl_wilddump_request(handle, 0, rtnetlink.RTM_GETADDR);
93 | int retry=0;
94 | //this runs async so retry 10 times
95 | while(cnt.getCount()==0 & retry<10) {
96 | result=libnetlink3.rtnl_listen(handle, messageBuffer, new rtnl_accept() {
97 | @Override
98 | public int accept(ByteBuffer message) {
99 | logger.info("rtnl got message, stopping");
100 | cnt.inc();
101 | return libnetlink3.rtl_accept_STOP;
102 | }
103 | });
104 | Thread.sleep(100);
105 | retry++;
106 | }
107 | //we recieved a message ?
108 | Assert.assertTrue(cnt.getCount()==1);
109 | //close it
110 | libnetlink3.rtnl_close(handle);
111 | }
112 |
113 | @Test
114 | public void testLibnetlink3Utils() {
115 | org.junit.Assert.assertEquals(0,libnetlink3.utils.nl_mgrp(0));
116 | org.junit.Assert.assertEquals(1,libnetlink3.utils.nl_mgrp(1));
117 | org.junit.Assert.assertEquals(2,libnetlink3.utils.nl_mgrp(2));
118 | org.junit.Assert.assertEquals(4,libnetlink3.utils.nl_mgrp(3));
119 | org.junit.Assert.assertEquals(8,libnetlink3.utils.nl_mgrp(4));
120 | org.junit.Assert.assertEquals(16,libnetlink3.utils.nl_mgrp(5));
121 | org.junit.Assert.assertEquals(0x40000000,libnetlink3.utils.nl_mgrp(31));
122 | }
123 |
124 | public void testRTNL_Handle(){
125 | libnetlink3.rtnl_handle handle = new libnetlink3.rtnl_handle();
126 | org.junit.Assert.assertNotNull(handle);
127 |
128 | }
129 | }
--------------------------------------------------------------------------------
/src/test/java/org/it4y/jni/linux/if_addressTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.jni.linux;
18 |
19 | import org.junit.Assert;
20 | import org.junit.Test;
21 |
22 | /**
23 | * Created by luc on 1/8/14.
24 | */
25 | public class if_addressTest {
26 |
27 | @Test
28 | public void ifAddressNamesTest() {
29 | Assert.assertNotNull(if_address.IFA_NAMES.get(Integer.MAX_VALUE));
30 | Assert.assertEquals("[" + Integer.MAX_VALUE + "]", if_address.IFA_NAMES.get(Integer.MAX_VALUE));
31 | Assert.assertEquals("address",if_address.IFA_NAMES.get(if_address.IFA_ADDRESS));
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/test/java/org/it4y/jni/linux/if_arpTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.jni.linux;
18 |
19 | import org.junit.Assert;
20 | import org.junit.Test;
21 |
22 | /**
23 | * Created by luc on 1/8/14.
24 | */
25 | public class if_arpTest {
26 | @Test
27 | public void ifarpNamesTest() {
28 | Assert.assertNotNull(if_arp.ARPHDR_NAMES.get(Integer.MAX_VALUE));
29 | Assert.assertEquals("[" + Integer.MAX_VALUE + "]", if_arp.ARPHDR_NAMES.get(Integer.MAX_VALUE));
30 | Assert.assertEquals("appletalk",if_arp.ARPHDR_NAMES.get(if_arp.ARPHRD_APPLETLK));
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/src/test/java/org/it4y/jni/linux/if_linkTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.jni.linux;
18 |
19 | import org.junit.Assert;
20 | import org.junit.Test;
21 |
22 | /**
23 | * Created by luc on 1/9/14.
24 | */
25 | public class if_linkTest {
26 | @Test
27 | public void iflinkNamesTest() {
28 | Assert.assertNotNull(if_link.IFLA_NAMES.get(Integer.MAX_VALUE));
29 | Assert.assertEquals("[" + Integer.MAX_VALUE + "]", if_link.IFLA_NAMES.get(Integer.MAX_VALUE));
30 | Assert.assertEquals("address",if_link.IFLA_NAMES.get(if_link.IFLA_ADDRESS));
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/src/test/java/org/it4y/jni/linux/if_neighbourTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.jni.linux;
18 |
19 | import org.junit.Assert;
20 | import org.junit.Test;
21 |
22 | /**
23 | * Created by luc on 1/9/14.
24 | */
25 | public class if_neighbourTest {
26 |
27 | @Test
28 | public void iflinkNamesTest() {
29 | Assert.assertNotNull(if_neighbour.NDA_NAMES.get(Integer.MAX_VALUE));
30 | Assert.assertEquals("[" + Integer.MAX_VALUE + "]", if_neighbour.NDA_NAMES.get(Integer.MAX_VALUE));
31 | Assert.assertEquals("port",if_neighbour.NDA_NAMES.get(if_neighbour.NDA_PORT));
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/src/test/java/org/it4y/jni/linux/jhashTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.jni.linux;
18 |
19 | import org.junit.Assert;
20 | import org.junit.Test;
21 |
22 | /**
23 | * Created by luc on 1/20/14.
24 | */
25 | public class jhashTest {
26 |
27 | /* we use src/native/testjhash.c for verification */
28 | @Test
29 | public void rol32Test() {
30 | //0xffffffff,0xeeeeeeee,0xdddddddd,0x00000000 : 44ca8698
31 | int a,shift;
32 |
33 | a=0xcd9caddd;
34 | shift=14;
35 | Assert.assertEquals(0x2b777367,jhash.rol32(a,shift));
36 |
37 | a=0xe4c9fc99;
38 | shift=11;
39 | Assert.assertEquals(0x4fe4cf26,jhash.rol32(a,shift));
40 |
41 | a=0xea7f7351;
42 | shift=25;
43 | Assert.assertEquals(0xa3d4fee6,jhash.rol32(a,shift));
44 |
45 | a=0x840edfa6;
46 | shift=16;
47 | Assert.assertEquals(0xdfa6840e, jhash.rol32(a, shift));
48 |
49 | a=0x81209f31;
50 | shift=4;
51 | Assert.assertEquals(0x1209f318,jhash.rol32(a,shift));
52 |
53 | a=0x5955f948;
54 | shift=14;
55 | Assert.assertEquals(0x7e521655,jhash.rol32(a,shift));
56 |
57 | a=0x5f091099;
58 | shift=24;
59 | Assert.assertEquals(0x995f0910,jhash.rol32(a,shift));
60 | }
61 |
62 |
63 | @Test
64 | public void jhash3wordsTest() {
65 | int a,b,c,initval;
66 |
67 | //0xffffffff,0xeeeeeeee,0xdddddddd,0x00000000 : 44ca8698
68 | a=0xffffffff;
69 | b=0xeeeeeeee;
70 | c=0xdddddddd;
71 | initval=0x00000000;
72 | Assert.assertEquals(0x44ca8698,jhash.jhash_3words(a,b,c,initval));
73 |
74 | //0x11223344,0x44332211,0x01020304,0x12345678 : 0bb15e12
75 | a=0x11223344;
76 | b=0x44332211;
77 | c=0x01020304;
78 | initval=0x12345678;
79 | Assert.assertEquals(0x0bb15e12,jhash.jhash_3words(a,b,c,initval));
80 |
81 | //0x00000000,0x00000000,0x00000000,0x00000000 : 0bb15e12
82 | a=0x00000000;
83 | b=0x00000000;
84 | c=0x00000000;
85 | initval=0x00000000;
86 | Assert.assertEquals(0xc0b0a2c2,jhash.jhash_3words(a,b,c,initval));
87 |
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/src/test/java/org/it4y/jni/linux/rtnetlinkTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.jni.linux;
18 |
19 | import org.junit.Assert;
20 | import org.junit.Test;
21 |
22 | /**
23 | * Created by luc on 1/9/14.
24 | */
25 | public class rtnetlinkTest {
26 |
27 | @Test
28 | public void ifrtnetlinkRTANamesTest() {
29 | Assert.assertNotNull(rtnetlink.RTA_NAMES.get(Integer.MAX_VALUE));
30 | Assert.assertEquals("[" + Integer.MAX_VALUE + "]", rtnetlink.RTA_NAMES.get(Integer.MAX_VALUE));
31 | Assert.assertEquals("dst",rtnetlink.RTA_NAMES.get(rtnetlink.RTA_DST));
32 | }
33 |
34 | @Test
35 | public void ifrtnetlinkRTNNamesTest() {
36 | Assert.assertNotNull(rtnetlink.RTN_NAMES.get(Integer.MAX_VALUE));
37 | Assert.assertEquals("[" + Integer.MAX_VALUE + "]", rtnetlink.RTN_NAMES.get(Integer.MAX_VALUE));
38 | Assert.assertEquals("anycast",rtnetlink.RTN_NAMES.get(rtnetlink.RTN_ANYCAST));
39 | }
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/src/test/java/org/it4y/jni/linuxutilsTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.jni;
18 |
19 | import org.junit.Assert;
20 | import org.junit.Test;
21 | import org.slf4j.Logger;
22 | import org.slf4j.LoggerFactory;
23 |
24 | /**
25 | * Created by luc on 5/14/14.
26 | */
27 | public class linuxutilsTest {
28 | Logger logger= LoggerFactory.getLogger(linuxutilsTest.class);
29 |
30 | @Test
31 | public void testClockgetTime() {
32 | long time=linuxutils.clock_getTime(org.it4y.jni.linux.time.CLOCK_REALTIME);
33 | logger.info("Real time: {} nsec",time);
34 | Assert.assertTrue(time>0);
35 | time=linuxutils.clock_getTime(org.it4y.jni.linux.time.CLOCK_MONOTONIC);
36 | logger.info("monotonic time: {} nsec",time);
37 | Assert.assertTrue(time>0);
38 | time=linuxutils.clock_getTime(org.it4y.jni.linux.time.CLOCK_PROCESS_CPUTIME_ID);
39 | logger.info("process time: {} nsec",time);
40 | Assert.assertTrue(time > 0);
41 | time=linuxutils.clock_getTime(org.it4y.jni.linux.time.CLOCK_THREAD_CPUTIME_ID);
42 | logger.info("thread time: {} nsec",time);
43 | Assert.assertTrue(time > 0);
44 | time=linuxutils.clock_getTime(org.it4y.jni.linux.time.CLOCK_MONOTONIC_RAW);
45 | logger.info("monotonic raw time: {} nsec",time);
46 | Assert.assertTrue(time > 0);
47 | time=linuxutils.clock_getTime(org.it4y.jni.linux.time.CLOCK_REALTIME_COARSE);
48 | logger.info("realtime coarse time: {} nsec",time);
49 | Assert.assertTrue(time > 0);
50 | time=linuxutils.clock_getTime(org.it4y.jni.linux.time.CLOCK_MONOTONIC_COARSE);
51 | logger.info("monotonic coarse time: {} nsec",time);
52 | Assert.assertTrue(time > 0);
53 | time=linuxutils.clock_getTime(org.it4y.jni.linux.time.CLOCK_BOOTTIME);
54 | logger.info("boot time: {} nsec",time);
55 | Assert.assertTrue(time > 0);
56 | time=linuxutils.clock_getTime(org.it4y.jni.linux.time.CLOCK_REALTIME_ALARM);
57 | logger.info("realtime alarm time: {} nsec",time);
58 | Assert.assertTrue(time > 0);
59 | time=linuxutils.clock_getTime(org.it4y.jni.linux.time.CLOCK_BOOTTIME_ALARM);
60 | logger.info("boottime alarm time: {} nsec",time);
61 | Assert.assertTrue(time > 0);
62 |
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/src/test/java/org/it4y/jni/ntpTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.jni;
18 |
19 | import org.junit.Ignore;
20 | import org.junit.Test;
21 | import org.slf4j.Logger;
22 | import org.slf4j.LoggerFactory;
23 |
24 | /**
25 | * Created by luc on 5/19/14.
26 | */
27 | public class ntpTest {
28 | private Logger logger= LoggerFactory.getLogger(ntpTest.class);
29 |
30 | @Ignore
31 | @Test
32 | public void testNtptime2() throws InterruptedException {
33 | while(true) {
34 | ntp.timex time = ntp.getNtpTime();
35 | logger.info("time: {}", time);
36 | Thread.sleep(1000);
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/test/java/org/it4y/jni/tunDeviceTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.jni;
18 |
19 | import junit.framework.Assert;
20 | import org.it4y.net.tuntap.TunDevice;
21 | import org.junit.Test;
22 |
23 | /**
24 | * Created by luc on 1/18/14.
25 | * This test can not do mutch when no admin rights have been given.
26 | * It willhow ever :
27 | * - load / call jni stuff and make sure this is ok
28 | * - check security in case it is run with security not active
29 | * - incase setcap is used, we can test jni calls
30 | *
31 | * the integration test is more pratical, but needs additional setup .
32 | */
33 |
34 | public class tunDeviceTest {
35 |
36 | /* create and open a tunnel device */
37 | private TunDevice openTun(final String device) throws libc.ErrnoException {
38 | final TunDevice tun;
39 | if (device != null) {
40 | tun=new TunDevice(device);
41 | } else {
42 | tun=new TunDevice();
43 | }
44 | Assert.assertNotNull(tun);
45 | return tun;
46 | }
47 |
48 | @Test
49 | public void testOpenTunDevice() throws Exception {
50 | TunDevice tun=null;
51 | try {
52 | tun=openTun("test");
53 | try {
54 | tun.open();
55 | } catch (final libc.ErrnoException errno) {
56 | //must be "Operation not permitted
57 | Assert.assertEquals(1,errno.getErrno());
58 | }
59 | } finally {
60 | if (tun != null) {
61 | tun.close();
62 | Assert.assertEquals(0,tun.getFd());
63 | }
64 | }
65 | }
66 |
67 | @Test
68 | public void testOpenTun() throws Exception {
69 | TunDevice tun=null;
70 | try {
71 | tun=openTun(null);
72 | try {
73 | tun.open();
74 | } catch (final libc.ErrnoException errno) {
75 | //must be "Operation not permitted
76 | Assert.assertEquals(1,errno.getErrno());
77 | }
78 | } finally {
79 | if (tun != null) {
80 | tun.close();
81 | Assert.assertEquals(0,tun.getFd());
82 | }
83 | }
84 | }
85 |
86 |
87 | @Test
88 | public void testSetNonBlocking() throws Exception {
89 | TunDevice tun=null;
90 | try {
91 | tun=openTun(null);
92 | try {
93 | tun.open();
94 | tun.setNonBlocking(true);
95 | } catch (final libc.ErrnoException errno) {
96 | //must be "Operation not permitted
97 | Assert.assertEquals(1,errno.getErrno());
98 | }
99 | } finally {
100 | if (tun != null) {
101 | tun.close();
102 | Assert.assertEquals(0,tun.getFd());
103 | }
104 | }
105 |
106 | }
107 |
108 | @Test
109 | public void testIsDataReady() throws Exception {
110 | TunDevice tun=null;
111 | try {
112 | tun=openTun(null);
113 | try {
114 | tun.open();
115 | tun.isDataReady(100);
116 | } catch (final libc.ErrnoException errno) {
117 | //must be "Operation not permitted
118 | Assert.assertEquals(1,errno.getErrno());
119 | }
120 | } finally {
121 | if (tun != null) {
122 | tun.close();
123 | Assert.assertEquals(0,tun.getFd());
124 | }
125 | }
126 | }
127 |
128 | }
129 |
--------------------------------------------------------------------------------
/src/test/java/org/it4y/net/SocketUtilsTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net;
18 |
19 | import junit.framework.Assert;
20 | import org.junit.Test;
21 | import org.slf4j.Logger;
22 | import org.slf4j.LoggerFactory;
23 |
24 | import javax.net.ServerSocketFactory;
25 | import javax.net.SocketFactory;
26 | import java.io.FileInputStream;
27 | import java.io.FileOutputStream;
28 | import java.io.RandomAccessFile;
29 | import java.net.ServerSocket;
30 | import java.net.Socket;
31 |
32 | /**
33 | * Created by luc on 1/8/14.
34 | */
35 |
36 | public class SocketUtilsTest {
37 | private Logger log= LoggerFactory.getLogger(SocketUtilsTest.class);
38 | @Test
39 | public void testSocketFd() throws Exception {
40 | //create client socket and get access to fd
41 | Socket s= SocketFactory.getDefault().createSocket();
42 | int fd=SocketUtils.getFd(s);
43 | log.info("fd client socket: {}",fd);
44 | Assert.assertTrue("FD must be > 0",fd>0);
45 | s.close();
46 | }
47 |
48 | @Test
49 | public void testServerSocketFd() throws Exception {
50 | //create Server socket and get access to fd
51 | ServerSocket s= ServerSocketFactory.getDefault().createServerSocket();
52 | int fd=SocketUtils.getFd(s);
53 | log.info("fd server socket: {}",fd);
54 | Assert.assertTrue("FD must be > 0", fd > 0);
55 | s.close();
56 | }
57 |
58 | @Test
59 | public void testFileOutputStreamFd() throws Exception {
60 | FileOutputStream fo=new FileOutputStream("/tmp/DemoTestApp");
61 | int fd=SocketUtils.getFd(fo);
62 | log.info("fd file outputstream: {}",fd);
63 | Assert.assertTrue("FD must be > 0", fd > 0);
64 | fo.close();
65 |
66 | }
67 | @Test
68 | public void testFileInputStreamFd() throws Exception {
69 | FileInputStream fi=new FileInputStream("/proc/sys/net/ipv4/ip_forward");
70 | int fd=SocketUtils.getFd(fi);
71 | log.info("fd file inputstream: {}",fd);
72 | Assert.assertTrue("FD must be > 0", fd > 0);
73 | fi.close();
74 |
75 | }
76 | @Test
77 | public void testRandomAccessFileFd() throws Exception {
78 | RandomAccessFile random=new RandomAccessFile("/proc/sys/net/ipv4/ip_forward","r");
79 | int fd=SocketUtils.getFd(random);
80 | log.info("fd random access file: {}",fd);
81 | Assert.assertTrue("FD must be > 0", fd > 0);
82 | random.close();
83 |
84 | }
85 |
86 | }
87 |
--------------------------------------------------------------------------------
/src/test/java/org/it4y/net/netlink/NetlinkMsgFactoryTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.netlink;
18 |
19 | import org.junit.Assert;
20 | import org.junit.Test;
21 |
22 | import java.nio.ByteBuffer;
23 |
24 | /**
25 | * Created by luc on 3/23/14.
26 | */
27 | public class NetlinkMsgFactoryTest {
28 |
29 | @Test
30 | public void testNetLinkMsgFactory() {
31 | ByteBuffer rawData=ByteBuffer.allocate(16);
32 | NlMessage msg=NetlinkMsgFactory.processRawPacket(rawData);
33 | //invalid message
34 | Assert.assertNull(msg);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/test/java/org/it4y/net/netlink/netLinkMessageTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.netlink;
18 |
19 | import org.junit.Assert;
20 | import org.junit.Test;
21 | import org.slf4j.Logger;
22 | import org.slf4j.LoggerFactory;
23 |
24 | import java.nio.ByteBuffer;
25 |
26 | /**
27 | * Created by luc on 3/23/14.
28 | */
29 | public class netLinkMessageTest {
30 | private Logger logger= LoggerFactory.getLogger(netLinkMessageTest.class);
31 |
32 | @Test
33 | public void testNlErrorMessage() throws Exception {
34 | logger.info("NlErrorMessage...");
35 | ByteBuffer rawData=ByteBuffer.allocate(16);
36 | NlErrorMessage msg=new NlErrorMessage(rawData);
37 | Assert.assertNotNull(msg);
38 | Assert.assertEquals(0, msg.getNlMsgType());
39 | Assert.assertEquals(0, msg.getNlMsgLen());
40 | Assert.assertEquals(0, msg.getNlMsgPID());
41 | Assert.assertEquals(0,msg.getNlMsgSequence());
42 | Assert.assertEquals(0,msg.getNlmsg_flags());
43 | Assert.assertEquals(-1,msg.getRTAIndex(""));
44 | Assert.assertNull(msg.createRTAMessage(0, rawData));
45 | Assert.assertNotNull(msg.toString());
46 | logger.info("NlErrorMessage : {}",msg.toString());
47 | }
48 | @Test
49 | public void testNlDoneMessage() throws Exception {
50 | logger.info("NlDoneMessage...");
51 | ByteBuffer rawData=ByteBuffer.allocate(16);
52 | NlDoneMessage msg=new NlDoneMessage(rawData);
53 | Assert.assertNotNull(msg);
54 | Assert.assertEquals(0, msg.getNlMsgType());
55 | Assert.assertEquals(0, msg.getNlMsgLen());
56 | Assert.assertEquals(0, msg.getNlMsgPID());
57 | Assert.assertEquals(0,msg.getNlMsgSequence());
58 | Assert.assertEquals(0,msg.getNlmsg_flags());
59 | Assert.assertEquals(-1,msg.getRTAIndex(""));
60 | Assert.assertNull(msg.createRTAMessage(0,rawData));
61 | Assert.assertNotNull(msg.toString());
62 | logger.info("NlErrorMessage : {}",msg.toString());
63 | }
64 |
65 | @Test
66 | public void testneighbourMessage() throws Exception {
67 | logger.info("neighbourMessage...");
68 | ByteBuffer rawData=ByteBuffer.allocate(16+12);
69 | neighbourMsg msg=new neighbourMsg(rawData);
70 | Assert.assertNotNull(msg);
71 | Assert.assertEquals(0, msg.getNlMsgType());
72 | Assert.assertEquals(0, msg.getNlMsgLen());
73 | Assert.assertEquals(0, msg.getNlMsgPID());
74 | Assert.assertEquals(0,msg.getNlMsgSequence());
75 | Assert.assertEquals(0,msg.getNlmsg_flags());
76 | Assert.assertEquals(-1, msg.getRTAIndex(""));
77 | Assert.assertNotNull(msg.toString());
78 | logger.info("neighbourMessage : {}",msg.toString());
79 | }
80 |
81 | @Test
82 | public void testRouteMessage() throws Exception {
83 | logger.info("routeMessage...");
84 | ByteBuffer rawData=ByteBuffer.allocate(16+12);
85 | routeMsg msg=new routeMsg(rawData);
86 | Assert.assertNotNull(msg);
87 | Assert.assertEquals(0, msg.getNlMsgType());
88 | Assert.assertEquals(0, msg.getNlMsgLen());
89 | Assert.assertEquals(0, msg.getNlMsgPID());
90 | Assert.assertEquals(0,msg.getNlMsgSequence());
91 | Assert.assertEquals(0,msg.getNlmsg_flags());
92 | Assert.assertEquals(-1, msg.getRTAIndex(""));
93 | Assert.assertNotNull(msg.toString());
94 | logger.info("routeMessage : {}",msg.toString());
95 | }
96 |
97 | }
98 |
--------------------------------------------------------------------------------
/src/test/java/org/it4y/net/protocols/IP/IPIP/IPIPPacketTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.protocols.IP.IPIP;
18 |
19 | import junit.framework.Assert;
20 | import org.it4y.net.protocols.IP.GRE.GREPacket;
21 | import org.it4y.net.protocols.IP.ICMP.ICMPPacket;
22 | import org.it4y.net.protocols.IP.IPFactory;
23 | import org.it4y.net.protocols.IP.IpPacket;
24 | import org.junit.Test;
25 | import org.slf4j.Logger;
26 | import org.slf4j.LoggerFactory;
27 |
28 | import java.nio.ByteBuffer;
29 |
30 | /**
31 | * Created by luc on 3/24/14.
32 | */
33 | public class IPIPPacketTest {
34 | private Logger logger = LoggerFactory.getLogger(IPIPPacketTest.class);
35 |
36 | //IPIP tunnel as in RFC1853
37 | static final byte[] ipip_1 = {
38 | (byte)0x45, (byte)0x00, (byte)0x00, (byte)0x68, (byte)0xe6, (byte)0xe4, (byte)0x40, (byte)0x00, /* E..h..@. */
39 | (byte)0x40, (byte)0x04, (byte)0xd6, (byte)0x5f, (byte)0xac, (byte)0x10, (byte)0x12, (byte)0x96, /* @.._.... */
40 | (byte)0xac, (byte)0x10, (byte)0x12, (byte)0x97, (byte)0x45, (byte)0x00, (byte)0x00, (byte)0x54, /* ....E..T */
41 | (byte)0x77, (byte)0xff, (byte)0x40, (byte)0x00, (byte)0x40, (byte)0x01, (byte)0x1c, (byte)0xa6, /* w.@.@... */
42 | (byte)0x0a, (byte)0x00, (byte)0xc9, (byte)0x02, (byte)0x0a, (byte)0x00, (byte)0xc9, (byte)0x01, /* ........ */
43 | (byte)0x08, (byte)0x00, (byte)0xa6, (byte)0x3b, (byte)0x0b, (byte)0x7a, (byte)0x00, (byte)0x0d, /* ...;.z.. */
44 | (byte)0x02, (byte)0x1e, (byte)0x30, (byte)0x53, (byte)0x24, (byte)0xc9, (byte)0x04, (byte)0x00, /* ..0S$... */
45 | (byte)0x08, (byte)0x09, (byte)0x0a, (byte)0x0b, (byte)0x0c, (byte)0x0d, (byte)0x0e, (byte)0x0f, /* ........ */
46 | (byte)0x10, (byte)0x11, (byte)0x12, (byte)0x13, (byte)0x14, (byte)0x15, (byte)0x16, (byte)0x17, /* ........ */
47 | (byte)0x18, (byte)0x19, (byte)0x1a, (byte)0x1b, (byte)0x1c, (byte)0x1d, (byte)0x1e, (byte)0x1f, /* ........ */
48 | (byte)0x20, (byte)0x21, (byte)0x22, (byte)0x23, (byte)0x24, (byte)0x25, (byte)0x26, (byte)0x27, /* !"#$%&' */
49 | (byte)0x28, (byte)0x29, (byte)0x2a, (byte)0x2b, (byte)0x2c, (byte)0x2d, (byte)0x2e, (byte)0x2f, /* ()*+,-./ */
50 | (byte)0x30, (byte)0x31, (byte)0x32, (byte)0x33, (byte)0x34, (byte)0x35, (byte)0x36, (byte)0x37 /* 01234567 */
51 | };
52 |
53 | static final byte[] ipip_2 = {
54 | (byte)0x45, (byte)0x00, (byte)0x00, (byte)0x68, (byte)0xc8, (byte)0x9e, (byte)0x40, (byte)0x00, /* E..h..@. */
55 | (byte)0x40, (byte)0x04, (byte)0xf4, (byte)0xa5, (byte)0xac, (byte)0x10, (byte)0x12, (byte)0x97, /* @....... */
56 | (byte)0xac, (byte)0x10, (byte)0x12, (byte)0x96, (byte)0x45, (byte)0x00, (byte)0x00, (byte)0x54, /* ....E..T */
57 | (byte)0xec, (byte)0x91, (byte)0x00, (byte)0x00, (byte)0x40, (byte)0x01, (byte)0xe8, (byte)0x13, /* ....@... */
58 | (byte)0x0a, (byte)0x00, (byte)0xc9, (byte)0x01, (byte)0x0a, (byte)0x00, (byte)0xc9, (byte)0x02, /* ........ */
59 | (byte)0x00, (byte)0x00, (byte)0xae, (byte)0x3b, (byte)0x0b, (byte)0x7a, (byte)0x00, (byte)0x0d, /* ...;.z.. */
60 | (byte)0x02, (byte)0x1e, (byte)0x30, (byte)0x53, (byte)0x24, (byte)0xc9, (byte)0x04, (byte)0x00, /* ..0S$... */
61 | (byte)0x08, (byte)0x09, (byte)0x0a, (byte)0x0b, (byte)0x0c, (byte)0x0d, (byte)0x0e, (byte)0x0f, /* ........ */
62 | (byte)0x10, (byte)0x11, (byte)0x12, (byte)0x13, (byte)0x14, (byte)0x15, (byte)0x16, (byte)0x17, /* ........ */
63 | (byte)0x18, (byte)0x19, (byte)0x1a, (byte)0x1b, (byte)0x1c, (byte)0x1d, (byte)0x1e, (byte)0x1f, /* ........ */
64 | (byte)0x20, (byte)0x21, (byte)0x22, (byte)0x23, (byte)0x24, (byte)0x25, (byte)0x26, (byte)0x27, /* !"#$%&' */
65 | (byte)0x28, (byte)0x29, (byte)0x2a, (byte)0x2b, (byte)0x2c, (byte)0x2d, (byte)0x2e, (byte)0x2f, /* ()*+,-./ */
66 | (byte)0x30, (byte)0x31, (byte)0x32, (byte)0x33, (byte)0x34, (byte)0x35, (byte)0x36, (byte)0x37 /* 01234567 */
67 | };
68 |
69 | @Test
70 | public void testIPIPPacket() {
71 | ByteBuffer rawData=ByteBuffer.allocate(ipip_1.length);
72 | rawData.put(ipip_1);
73 | rawData.flip();
74 | IpPacket packet = IPFactory.processRawPacket(rawData, (byte) rawData.limit());
75 | Assert.assertNotNull(packet);
76 | logger.info("IPIP packet: {}", packet.toString());
77 | ByteBuffer payload=packet.getPayLoad();
78 | //payload is ICMP packet so lets see if this works
79 | ICMPPacket icmpPacket = (ICMPPacket) IPFactory.processRawPacket(payload,payload.limit());
80 | Assert.assertNotNull(icmpPacket);
81 | logger.info(" IPIP payload: {}", icmpPacket.toString());
82 | Assert.assertEquals(ICMPPacket.ECHO_REQUEST, icmpPacket.getType());
83 |
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/src/test/java/org/it4y/net/protocols/IP/IPv6Tunnel/IPv6TunnelPacketTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.protocols.IP.IPv6Tunnel;
18 |
19 | import junit.framework.Assert;
20 | import org.it4y.net.protocols.IP.IPFactory;
21 | import org.it4y.net.protocols.IP.IpPacket;
22 | import org.junit.Test;
23 | import org.slf4j.Logger;
24 | import org.slf4j.LoggerFactory;
25 |
26 | import java.nio.ByteBuffer;
27 |
28 | /**
29 | * Created by luc on 3/24/14.
30 | */
31 | public class IPv6TunnelPacketTest {
32 |
33 | private Logger logger = LoggerFactory.getLogger(IPv6TunnelPacket.class);
34 |
35 | //actually this is not real uipv6 in ipv4 , only ipv4 header is ok ,and first nibble of ipv6=6
36 | static final byte[] ipv6Tunnel_1 = {
37 | (byte)0x45, (byte)0x00, (byte)0x00, (byte)0x68, (byte)0xe6, (byte)0xe4, (byte)0x40, (byte)0x00, /* E..h..@. */
38 | (byte)0x40, (byte)0x29, (byte)0xd6, (byte)0x5f, (byte)0xac, (byte)0x10, (byte)0x12, (byte)0x96, /* @.._.... */
39 | (byte)0xac, (byte)0x10, (byte)0x12, (byte)0x97, (byte)0x65, (byte)0x00, (byte)0x00, (byte)0x54, /* ....E..T */
40 | (byte)0x77, (byte)0xff, (byte)0x40, (byte)0x00, (byte)0x40, (byte)0x01, (byte)0x1c, (byte)0xa6, /* w.@.@... */
41 | (byte)0x0a, (byte)0x00, (byte)0xc9, (byte)0x02, (byte)0x0a, (byte)0x00, (byte)0xc9, (byte)0x01, /* ........ */
42 | (byte)0x08, (byte)0x00, (byte)0xa6, (byte)0x3b, (byte)0x0b, (byte)0x7a, (byte)0x00, (byte)0x0d, /* ...;.z.. */
43 | (byte)0x02, (byte)0x1e, (byte)0x30, (byte)0x53, (byte)0x24, (byte)0xc9, (byte)0x04, (byte)0x00, /* ..0S$... */
44 | (byte)0x08, (byte)0x09, (byte)0x0a, (byte)0x0b, (byte)0x0c, (byte)0x0d, (byte)0x0e, (byte)0x0f, /* ........ */
45 | (byte)0x10, (byte)0x11, (byte)0x12, (byte)0x13, (byte)0x14, (byte)0x15, (byte)0x16, (byte)0x17, /* ........ */
46 | (byte)0x18, (byte)0x19, (byte)0x1a, (byte)0x1b, (byte)0x1c, (byte)0x1d, (byte)0x1e, (byte)0x1f, /* ........ */
47 | (byte)0x20, (byte)0x21, (byte)0x22, (byte)0x23, (byte)0x24, (byte)0x25, (byte)0x26, (byte)0x27, /* !"#$%&' */
48 | (byte)0x28, (byte)0x29, (byte)0x2a, (byte)0x2b, (byte)0x2c, (byte)0x2d, (byte)0x2e, (byte)0x2f, /* ()*+,-./ */
49 | (byte)0x30, (byte)0x31, (byte)0x32, (byte)0x33, (byte)0x34, (byte)0x35, (byte)0x36, (byte)0x37 /* 01234567 */
50 | };
51 |
52 | @Test
53 | public void testIPv6TunnelPacket() {
54 | ByteBuffer rawData = ByteBuffer.allocate(ipv6Tunnel_1.length);
55 | rawData.put(ipv6Tunnel_1);
56 | rawData.flip();
57 | IpPacket packet = IPFactory.processRawPacket(rawData, (byte) rawData.limit());
58 | Assert.assertNotNull(packet);
59 | logger.info("IPv6Tunnel packet: {}", packet.toString());
60 | IPv6TunnelPacket ipv6 = (IPv6TunnelPacket) packet;
61 | ByteBuffer payload = ipv6.getPayLoad();
62 | Assert.assertNotNull(ipv6.getHeader());
63 | Assert.assertEquals(0, ipv6.getHeaderSize());
64 | Assert.assertEquals(84, ipv6.getPayLoadSize());
65 | }
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/src/test/java/org/it4y/net/protocols/IP/IpPacketTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.protocols.IP;
18 |
19 | import org.it4y.net.protocols.IP.UDP.UDPPacket;
20 | import org.junit.Assert;
21 | import org.junit.Test;
22 |
23 | import java.nio.ByteBuffer;
24 |
25 | /**
26 | * Created by luc on 3/21/14.
27 | */
28 | public class IpPacketTest {
29 |
30 | @Test
31 | public void testIpPacket() {
32 | ByteBuffer rawBytes=ByteBuffer.allocate(60);
33 | IpPacket ipPacket = new IpPacket(rawBytes,60);
34 |
35 | Assert.assertNotNull(ipPacket);
36 | ipPacket.initIpHeader();
37 | ipPacket.updateChecksum();
38 | Assert.assertEquals(20, ipPacket.getHeaderSize());
39 | Assert.assertEquals(0, ipPacket.getTOS());
40 | Assert.assertEquals(64, ipPacket.getTTL());
41 | Assert.assertEquals(64, ipPacket.getTTL());
42 | Assert.assertEquals(20, ipPacket.getHeaderSize());
43 | Assert.assertEquals(40, ipPacket.getPayLoadSize());
44 | Assert.assertEquals(60, ipPacket.getRawSize());
45 | Assert.assertEquals(0, ipPacket.getIdentification());
46 | Assert.assertEquals(0, ipPacket.getFlags());
47 | Assert.assertEquals(0,ipPacket.getFragmentOffset());
48 | Assert.assertNotNull(ipPacket.getRawPacket());
49 | ipPacket.getDstRoutingHash();
50 | ipPacket.getFlowHash();
51 | Assert.assertNotNull(ipPacket.toString());
52 | Assert.assertFalse(ipPacket.hasOptions());
53 | Assert.assertNotNull(ipPacket.getHeader());
54 | Assert.assertNotNull(ipPacket.getIpHeader());
55 | Assert.assertNotNull(ipPacket.getPayLoad());
56 | Assert.assertNotNull(ipPacket.getIpPayLoad());
57 | ipPacket.release();
58 | Assert.assertNull(ipPacket.getRawPacket());
59 | }
60 |
61 | @Test
62 | public void testWordBoundRfc1071Checksum() {
63 | ByteBuffer rawBytes=ByteBuffer.allocate(8);
64 | //this is based on rfc1071 examples
65 | rawBytes.put((byte)0x00);
66 | rawBytes.put((byte)0x01);
67 | rawBytes.put((byte)0xf2);
68 | rawBytes.put((byte)0x03);
69 | rawBytes.put((byte)0xf4);
70 | rawBytes.put((byte)0xf5);
71 | rawBytes.put((byte) 0xf6);
72 | rawBytes.put((byte)0xf7);
73 | IpPacket packet = new IpPacket(rawBytes,rawBytes.limit());
74 | Assert.assertEquals((short)0x220d,packet.rfc1071Checksum(0,8));
75 |
76 | }
77 |
78 | @Test
79 | public void testNotWordBoundRfc1071Checksum() {
80 | ByteBuffer rawBytes=ByteBuffer.allocate(3);
81 | //this is based on rfc1071 examples
82 | rawBytes.put((byte)0x00);
83 | rawBytes.put((byte)0x01);
84 | rawBytes.put((byte)0xf2);
85 | IpPacket packet = new IpPacket(rawBytes,rawBytes.limit());
86 | Assert.assertEquals((short)0xFF0C,packet.rfc1071Checksum(0,3));
87 | }
88 |
89 | @Test
90 | public void testCreateRawIp(){
91 | ByteBuffer rawBytes=ByteBuffer.allocate(60);
92 | IpPacket packet = new IpPacket(rawBytes,60);
93 | Assert.assertNotNull(packet);
94 | packet.resetBuffer();
95 | packet.initIpHeader();
96 | packet.setSourceAddress(0x08080808);
97 | packet.setDestinationAddress(0x08080404);
98 | packet.setTOS((byte)0x01);
99 | packet.setTTL((byte)0x02);
100 | packet.setProtocol(UDPPacket.PROTOCOL);
101 | packet.setFragmentOffset((short)0x1fff);
102 | packet.setIdentification((short)0x04);
103 | //set some flags
104 | Assert.assertFalse(packet.isDF());
105 | Assert.assertFalse(packet.isMF());
106 | packet.setDF(true);
107 | Assert.assertTrue(packet.isDF());
108 | Assert.assertFalse(packet.isMF());
109 | packet.setMF(true);
110 | Assert.assertTrue(packet.isDF());
111 | Assert.assertTrue(packet.isMF());
112 | packet.updateChecksum();
113 | //validate
114 | Assert.assertEquals(0x08080808,packet.getSourceAddress());
115 | Assert.assertEquals(0x08080404,packet.getDestinationAddress());
116 | Assert.assertEquals(0x01,packet.getTOS());
117 | Assert.assertEquals(0x02,packet.getTTL());
118 | Assert.assertEquals(UDPPacket.PROTOCOL,packet.getProtocol());
119 | Assert.assertEquals(0x1fff,packet.getFragmentOffset());
120 | Assert.assertEquals(0x04,packet.getIdentification());
121 |
122 | packet.setDF(false);
123 | packet.setMF(false);
124 | Assert.assertEquals(0x1fff,packet.getFragmentOffset());
125 | Assert.assertFalse(packet.isDF());
126 | Assert.assertFalse(packet.isMF());
127 | packet.setFragmentOffset((short)0x1234);
128 | Assert.assertEquals((short)0x1234,packet.getFragmentOffset());
129 | }
130 | }
131 |
--------------------------------------------------------------------------------
/src/test/java/org/it4y/net/protocols/IP/TCP/TCPStreamtest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.protocols.IP.TCP;
18 |
19 | import org.it4y.net.protocols.IP.IpPacket;
20 | import org.it4y.util.PCAPFileReader;
21 | import org.junit.Test;
22 | import org.slf4j.Logger;
23 | import org.slf4j.LoggerFactory;
24 |
25 | import java.io.IOException;
26 |
27 | /**
28 | * Created by luc on 4/13/14.
29 | */
30 | public class TCPStreamtest {
31 | private Logger logger= LoggerFactory.getLogger(TCPStreamtest.class);
32 |
33 | @Test
34 | public void testTCPStream() throws IOException {
35 | long firstAck=0;
36 | long firstSeqNr=0;
37 | long lastAck=0;
38 | long dupAckcount=0;
39 | PCAPFileReader reader = new PCAPFileReader("src/test/pcap/http-10m-random.pcap");
40 | IpPacket ipPacket;
41 | while((ipPacket=reader.readPacket())!=null) {
42 | TCPPacket tcpPacket = (TCPPacket)ipPacket;
43 | long ack=((long)tcpPacket.getAckNumber()) & 0xffffffff;
44 | long seqnr=((long)tcpPacket.getSequenceNumber()) & 0xffffffff;
45 | if (tcpPacket.isSYN() & tcpPacket.isACK()) {
46 | firstSeqNr=ack;
47 | firstAck=seqnr;
48 | lastAck=seqnr;
49 | logger.info("First SYNC ACK {} {}",firstAck,firstSeqNr);
50 | }
51 | if (tcpPacket.getDestinationPort()==80) {
52 | if (lastAck == ack) {
53 | dupAckcount++;
54 | if (dupAckcount > 1) {
55 | logger.info("dup ack : {} cnt={}", ack, dupAckcount);
56 | }
57 | } else {
58 | dupAckcount = 0;
59 | lastAck = ack;
60 | }
61 | logger.info("{} {} {} {} {} {} {}",(seqnr-firstSeqNr),(ack-firstAck),tcpPacket.getRawSize(),tcpPacket.getPayLoadSize(),((TCPPacket) ipPacket).isSYN(),((TCPPacket) ipPacket).isACK(),((TCPPacket) ipPacket).isFIN());
62 | }
63 | }
64 | }
65 |
66 | @Test
67 | public void testTCPStreamWithDupAck() throws IOException {
68 | long firstAck=0;
69 | long firstSeqNr=0;
70 | long lastAck=0;
71 | long dupAckcount=0;
72 | int port=0;
73 | PCAPFileReader reader = new PCAPFileReader("src/test/pcap/http-dupack.pcap");
74 | IpPacket ipPacket;
75 | while((ipPacket=reader.readPacket())!=null) {
76 | TCPPacket tcpPacket = (TCPPacket)ipPacket;
77 | long ack=((long)tcpPacket.getAckNumber()) & 0xffffffff;
78 | long seqnr=((long)tcpPacket.getSequenceNumber()) & 0xffffffff;
79 | if (tcpPacket.isSYN() & !tcpPacket.isACK()) {
80 | port=tcpPacket.getDestinationPort();
81 | }
82 | if (tcpPacket.isSYN() & tcpPacket.isACK()) {
83 | firstSeqNr=ack;
84 | firstAck=seqnr;
85 | lastAck=seqnr;
86 | logger.info("First SYNC ACK {} {}",firstAck,firstSeqNr);
87 | }
88 | if (tcpPacket.getDestinationPort()==port) {
89 | if (lastAck == ack) {
90 | dupAckcount++;
91 | if (dupAckcount > 1) {
92 | logger.info("dup ack : {} cnt={}", ack, dupAckcount);
93 | }
94 | } else {
95 | dupAckcount = 0;
96 | lastAck = ack;
97 | }
98 | double ratio=1;
99 | if (seqnr!=firstSeqNr && ack != firstAck) {
100 | ratio=(ack-firstAck)/(seqnr-firstSeqNr);
101 | }
102 | logger.info("{} {} {} {} {} {} {} {}",ratio,(seqnr-firstSeqNr),(ack-firstAck),tcpPacket.getRawSize(),tcpPacket.getPayLoadSize(),((TCPPacket) ipPacket).isSYN(),((TCPPacket) ipPacket).isACK(),((TCPPacket) ipPacket).isFIN());
103 | }
104 | }
105 | }
106 | }
--------------------------------------------------------------------------------
/src/test/java/org/it4y/net/tproxy/TProxyClientSocketTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.net.tproxy;
18 |
19 | import junit.framework.Assert;
20 | import org.it4y.jni.libc;
21 | import org.it4y.jni.linux.socket;
22 | import org.junit.Test;
23 |
24 | import java.net.InetAddress;
25 | import java.net.Socket;
26 | import java.net.SocketAddress;
27 |
28 | /**
29 | * Created by luc on 1/10/14.
30 | */
31 | public class TProxyClientSocketTest {
32 |
33 | @Test
34 | public void testTPRoxyClientSocket() throws Exception {
35 | Socket client=new Socket();
36 | libc.sockaddr_in remote=new libc.sockaddr_in(0x01020304,(short)0x1234, socket.AF_INET);
37 | TProxyInterceptedSocket tps=new TProxyInterceptedSocket(client,remote);
38 | Assert.assertNotNull(tps);
39 | Assert.assertEquals(client, tps.getSocket());
40 | Assert.assertEquals(0x01020304, tps.getRemoteAddress());
41 | Assert.assertEquals(0x1234,tps.getRemotePort());
42 | InetAddress ia=tps.getRemoteAddressAsInetAddress();
43 | Assert.assertEquals("/1.2.3.4",ia.toString());
44 | Assert.assertEquals("local:null:0 remote:/1.2.3.4:4660",tps.toString());
45 | SocketAddress sa=tps.getRemoteAsSocketAddress();
46 | Assert.assertEquals("/1.2.3.4:4660",sa.toString());
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/test/java/org/it4y/util/Counter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.util;
18 |
19 | import java.util.concurrent.atomic.AtomicInteger;
20 | import java.util.concurrent.atomic.AtomicLong;
21 |
22 | /**
23 | * Created by luc on 1/9/14.
24 | */
25 | public class Counter {
26 | //workaround around final/inner class access
27 | private AtomicInteger cnt=new AtomicInteger(0);
28 | public void inc() {
29 | cnt.incrementAndGet();
30 | }
31 | public void dec() {
32 | cnt.decrementAndGet();
33 | }
34 |
35 | public int getCount() {
36 | return cnt.intValue();
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/src/test/java/org/it4y/util/IndexNameMapTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Luc Willems (T.M.M.)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.it4y.util;
18 |
19 | import org.junit.After;
20 | import org.junit.Assert;
21 | import org.junit.Before;
22 | import org.junit.Test;
23 |
24 | /**
25 | * Created by luc on 1/7/14.
26 | */
27 | public class IndexNameMapTest {
28 | @Before
29 | public void setUp() throws Exception {
30 |
31 | }
32 |
33 | @After
34 | public void tearDown() throws Exception {
35 |
36 | }
37 |
38 | @Test
39 | public void testIntegerKey() throws Exception {
40 | IndexNameMap test=new IndexNameMap();
41 | Assert.assertNotNull(test);
42 | //get a index not existing should return the text with [ test=new IndexNameMap();
53 | Assert.assertNotNull(test);
54 | String index="hello";
55 | //get a index not existing should return the text with [ 0);
38 | Assert.assertTrue(reader.getSnaplength()>0);
39 | try {
40 | IpPacket ip;
41 | while ((ip = reader.readPacket()) != null) {
42 | logger.info("{}", ip);
43 | ip.release();
44 | }
45 | } finally {
46 | reader.close();
47 | }
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/test/pcap/gre-full.pcap:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lucwillems/JavaLinuxNet/903b9b542a6bfbc887985a3e404190241c5792ef/src/test/pcap/gre-full.pcap
--------------------------------------------------------------------------------
/src/test/pcap/gre.pcap:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lucwillems/JavaLinuxNet/903b9b542a6bfbc887985a3e404190241c5792ef/src/test/pcap/gre.pcap
--------------------------------------------------------------------------------
/src/test/pcap/http-10m-random.pcap:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lucwillems/JavaLinuxNet/903b9b542a6bfbc887985a3e404190241c5792ef/src/test/pcap/http-10m-random.pcap
--------------------------------------------------------------------------------
/src/test/pcap/http-dupack.pcap:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lucwillems/JavaLinuxNet/903b9b542a6bfbc887985a3e404190241c5792ef/src/test/pcap/http-dupack.pcap
--------------------------------------------------------------------------------
/src/test/pcap/https.pcapng:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lucwillems/JavaLinuxNet/903b9b542a6bfbc887985a3e404190241c5792ef/src/test/pcap/https.pcapng
--------------------------------------------------------------------------------
/src/test/pcap/ipip-full.pcap:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lucwillems/JavaLinuxNet/903b9b542a6bfbc887985a3e404190241c5792ef/src/test/pcap/ipip-full.pcap
--------------------------------------------------------------------------------
/src/test/resources/log4j.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/src/test/scripts/setup-test.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # run this script to setup lowlevel linux environment for testing
3 | #
4 | if [ -z "$SUDO_USER" ];then
5 | echo "Please use sudo $0"
6 | exit 0
7 | fi
8 |
9 | #get user & primary group
10 | TUN_USER=$SUDO_USER
11 | TUN_GROUP=`groups $SUDO_USER | awk '{print $3}'`
12 |
13 | # Note we abuse 8.8.4.4 as test IP
14 | TESTIP=8.8.4.4
15 | TESTNET=8.8.4.0/24
16 | TUNDEV=test
17 | USER=$TUN_USER
18 | GROUP=$TUN_GROUP
19 | TUNDEV2=testnotused
20 | USER=$TUN_USER
21 | GROUP=$TUN_GROUP
22 |
23 | ip tuntap del dev $TUNDEV mode tun
24 | ip tuntap add dev $TUNDEV mode tun user $USER group $GROUP
25 | ip addr add 127.0.0.2/32 dev $TUNDEV
26 | ip link set dev $TUNDEV up
27 | ip route add $TESTNET dev $TUNDEV
28 | echo "1" > /proc/sys/net/ipv4/conf/$TUNDEV/log_martians
29 | echo "0" > /proc/sys/net/ipv4/conf/$TUNDEV/rp_filter
30 |
31 |
32 | ip tuntap del dev $TUNDEV2 mode tun
33 | ip tuntap add dev $TUNDEV2 mode tun user $USER group $GROUP
34 | ip addr add 127.0.0.3/32 dev $TUNDEV2
35 | ip link set dev $TUNDEV2 up
36 |
37 | #route all redirected traffic to lo
38 | ip rule del priority 2000
39 | ip rule add priority 2000 fwmark 1 lookup 100
40 | ip route flush table 100
41 | ip -f inet route add local 0.0.0.0/0 dev lo table 100
42 |
43 | iptables -F
44 | iptables -t mangle -F
45 | iptables -t mangle -N DIVERT
46 | iptables -t mangle -A DIVERT -j MARK --set-mark 1
47 | iptables -t mangle -A DIVERT -j ACCEPT
48 |
49 | #for forwarding traffic
50 | iptables -t mangle -A PREROUTING -p tcp -m socket -j DIVERT
51 | iptables -t mangle -A PREROUTING -p tcp -m tcp --destination $TESTIP --dport 80 -j TPROXY --on-port 1800 --on-ip 0.0.0.0 --tproxy-mark 0x01/0x01
52 |
53 | #for local traffic
54 | iptables -t mangle -A OUTPUT -p tcp -m tcp --destination $TESTIP --dport 80 -j MARK --set-mark 0x01
55 |
56 | #get some packet loss and delay
57 | #tc qdisc del dev lo root netem
58 | #tc qdisc add dev lo root netem loss 1% delay 100ms 20ms
59 |
60 |
--------------------------------------------------------------------------------