Compare commits

..

125 Commits

Author SHA1 Message Date
wangyu
6c1446036b huge_buf_len and huge_data_len fix for mp 2020-07-15 04:35:09 -04:00
wangyu
4e5b3f2baa sync 79bb28 2020-07-15 04:11:38 -04:00
wangyu
ae8356504c do not drop truncated packet for pcap when fix_gro enabled 2020-07-15 03:01:20 -04:00
wangyu
f7f6c6bbe6 update 2020-07-15 01:57:51 -04:00
wangyu
4530606246 aes128cfb_0 2020-07-15 01:38:24 -04:00
wangyu
1b8125003d update 2020-07-14 14:48:03 -04:00
wangyu
769affb1aa change gro scheme 2020-07-14 14:30:54 -04:00
wangyu
bbd49ca82c fix last commit 2020-07-14 12:30:20 -04:00
wangyu
ca4a5d3417 modify scheme of cfb 2020-07-14 11:41:21 -04:00
wangyu
1031f9d760 add wepoll target 2020-07-14 10:08:51 -04:00
wangyu
1c7c9e8a7f merge up to 5cc304 2020-07-14 08:36:46 -04:00
wangyu
87a362109d rm sha1.cpp 2020-07-14 08:26:03 -04:00
wangyu
6681f3a4e6 merge up to f68c6e2 2020-07-14 08:01:48 -04:00
wangyu
fe9e73decc merge ee787e0 2020-07-14 07:21:03 -04:00
U-DESKTOP-T772REH\wangyu
6074dc3a50 get_current_time_us() never goes back now 2019-04-07 18:21:30 +08:00
U-DESKTOP-T772REH\wangyu
07ad00f54d fixed get_sock_error() format on windows 2018-11-13 20:29:37 +08:00
wangyu-
7544fbe9d7 fix \n in log 2018-11-13 05:58:22 -06:00
wangyu-
5ff768b165 changed a few log levels 2018-11-13 05:48:25 -06:00
wangyu-
bb7fe5c0d4 fix typo in code 2018-11-13 03:14:44 -06:00
wangyu-
9c8316e957 fix bug in random port bind 2018-11-13 02:35:42 -06:00
wangyu-
b59b13ab9d update help page 2018-11-13 02:11:48 -06:00
wangyu-
a3bd8b8030 Merge pull request #12 from hughgr/patch-1
update text instruction
2018-11-13 16:09:53 +08:00
wangyu-
003f31bfef new option --no-pcap-mutex 2018-11-13 02:08:32 -06:00
wangyu-
7980103bd5 a lot of trival changes 2018-11-13 01:33:46 -06:00
wangyu-
7df9c7f38b update pcap wrapper 2018-11-13 00:05:24 -06:00
wangyu-
d24c96a400 use pcap_breakloop() 2018-11-13 00:03:35 -06:00
wangyu-
001c42be56 protect pcap functions with mutex 2018-11-12 22:56:21 -06:00
老舍
98eba2f2bd update text instruction 2018-11-02 15:46:45 +08:00
wangyu-
175a28d7f4 fixed incorrect text in misc.cpp 2018-10-21 14:13:36 +08:00
U-DESKTOP-T772REH\wangyu
d6c31f00ac turn down log level 2018-09-05 23:53:13 +08:00
U-DESKTOP-T772REH\wangyu
ccdaf886d2 bug fix 2018-09-05 18:46:36 +08:00
wangyu-
3a1050fa26 trival 2018-08-31 12:52:49 -05:00
wangyu-
4bfbe976f1 add warning 2018-08-31 12:47:26 -05:00
root
4e3305bd80 fixed a core 2018-08-31 12:21:46 -05:00
wangyu
349bcf17f1 fix mac compile 2018-08-29 18:08:42 -07:00
wangyu-
ca22a3cf3b reduce diff 2018-08-29 20:03:04 -05:00
U-DESKTOP-T772REH\wangyu
a9bb76d6e8 fix compile on windows again 2018-08-30 08:51:49 +08:00
wangyu-
4e4a77ce16 fix windows compile 2018-08-29 19:37:16 -05:00
wangyu-
ff39a562a6 fix compile 2018-08-29 19:30:26 -05:00
wangyu-
1679c324b3 fixed dev detection and -g 2018-08-29 19:16:42 -05:00
wangyu-
e0aaa65347 reduce diff 2018-08-29 17:07:50 -05:00
wangyu-
61fd35244d added fixthis 2018-08-29 16:10:39 -05:00
wangyu-
314e982570 fix ipv6 of libnet 2018-08-29 15:55:54 -05:00
wangyu-
00776c3423 added ipv6 support,reduce diff with non-mp version 2018-08-29 15:42:45 -05:00
wangyu-
077d1023a7 split main.cpp into main.cpp and client.cpp 2018-08-29 02:10:46 -05:00
wangyu-
2072cfed8d reduce diff with non-mp version 2018-08-29 01:19:15 -05:00
wangyu-
2fc52806fd reduce diff with non-mp version, its only compiles, function is broken 2018-08-28 17:06:04 -05:00
wangyu-
5f29a46aae reduce diff with non-mp version 2018-08-28 16:42:40 -05:00
wangyu-
a130936947 reduce diff with no-mp version 2018-08-28 16:20:11 -05:00
wangyu-
57af53afa8 deleted unused codes,reduce diff with non-mp version 2018-08-28 15:51:53 -05:00
U-DESKTOP-T772REH\wangyu
ae9db0eecf syn update of linux version. for aes128cfb and hmac_sha1 2018-07-24 19:05:21 +08:00
wangyu-
626926e25c changed a typo 2018-07-21 20:51:13 +08:00
U-DESKTOP-T772REH\wangyu
d639adfbbe fix log format 2018-07-05 16:44:51 +08:00
U-DESKTOP-T772REH\wangyu
f1e18d4583 support npcap non-compatiable mode 2018-07-01 11:13:50 +08:00
root
f7166bfde3 fix a core in dev detection 2018-06-30 18:10:59 +00:00
root
7f848553f5 support linux cooked mode 2018-06-29 17:54:31 +00:00
wangyu-
7c1b34d5df trival 2018-06-24 08:30:00 -05:00
wangyu-
44d670d113 sync updates from linux version 2018-06-24 08:27:25 -05:00
wangyu-
d0bd53f087 move images 2018-06-23 17:26:25 -05:00
U-DESKTOP-T772REH\wangyu
2944e73410 supress compile warning 2018-06-24 06:19:38 +08:00
wangyu-
fe64630b30 add missing files 2018-06-23 17:13:26 -05:00
wangyu-
62453eaa39 sync update from linux version 2018-06-23 17:12:04 -05:00
U-DESKTOP-T772REH\wangyu
d43b9ae98c add .gitattributes 2018-06-23 15:55:37 +08:00
U-DESKTOP-T772REH\wangyu
0201d9efe1 trival 2018-06-23 12:34:12 +08:00
U-DESKTOP-T772REH\wangyu
be20e2250d improve makefile 2018-06-23 12:32:20 +08:00
wangyu-
551dc034da fix compile error 2018-06-22 23:14:40 -05:00
U-DESKTOP-T772REH\wangyu
4ce3661b01 change assert to log fatal 2018-06-23 12:08:28 +08:00
wangyu-
0a53d256b6 Update README.md 2018-06-21 18:25:17 +08:00
U-DESKTOP-T772REH\wangyu
955093d26e Merge branch 'portable' of https://github.com/wangyu-/udp2raw-tunnel into portable 2018-06-20 21:07:02 +08:00
U-DESKTOP-T772REH\wangyu
46314022b9 add a log 2018-06-20 21:06:31 +08:00
wangyu
01a793e218 fix print format 2018-06-20 03:45:36 -07:00
U-DESKTOP-T772REH\wangyu
5aafe04f6d --enable-color, fix a segment fault 2018-06-20 00:41:13 +08:00
U-DESKTOP-T772REH\wangyu
17910bb9f4 trival 2018-06-19 17:19:56 +08:00
U-DESKTOP-T772REH\wangyu
d5024a619c fix -g option 2018-06-19 15:40:55 +08:00
U-DESKTOP-T772REH\wangyu
086cba4b1d trival 2018-06-19 14:04:57 +08:00
U-DESKTOP-T772REH\wangyu
db7b43001a simplify pcap_wrapper code 2018-06-19 11:40:22 +08:00
U-DESKTOP-T772REH\wangyu
e110f759eb fix invalid filter expression 2018-06-19 02:21:31 +08:00
U-DESKTOP-T772REH\wangyu
d85bb78139 fix broken random device on mingw 2018-06-19 00:48:09 +08:00
U-DESKTOP-T772REH\wangyu
a1dae3b22e mingw works 2018-06-19 00:36:53 +08:00
U-DESKTOP-T772REH\wangyu
dfcc799876 debug code 2018-06-19 00:15:58 +08:00
U-DESKTOP-T772REH\wangyu
8a5ae7727a delete useless extern c 2018-06-18 22:44:37 +08:00
U-DESKTOP-T772REH\wangyu
56727f76b6 fix cygwin compile 2018-06-18 22:32:43 +08:00
U-DESKTOP-T772REH\wangyu
f75eb798dc mingw compiles but not work yet 2018-06-18 21:50:57 +08:00
U-DESKTOP-T772REH\wangyu
26b356866f Merge branch 'portable' of https://github.com/wangyu-/udp2raw-tunnel into portable 2018-06-17 19:54:03 +08:00
U-DESKTOP-T772REH\wangyu
570e7173d3 trival 2018-06-17 19:53:53 +08:00
wangyu-
0d6df51ebe remove useless headers 2018-06-17 06:50:24 -05:00
U-DESKTOP-T772REH\wangyu
c03e60be51 packet header print fix 2018-06-17 17:52:33 +08:00
wangyu-
e630f81c6e trival 2018-06-17 04:21:51 -05:00
wangyu-
8e7aec7b50 Merge branch 'portable' of https://github.com/wangyu-/udp2raw-tunnel into portable 2018-06-17 04:18:46 -05:00
wangyu-
f43598b423 auto detect device 2018-06-17 04:18:33 -05:00
Charlie Root
80bcf91712 fix freebsd compile 2018-06-16 17:09:16 +00:00
wangyu
d1f40f334d fix mac compile 2018-06-16 09:53:45 -07:00
wangyu-
62e78999de fix linux compile 2018-06-16 11:44:14 -05:00
U-DESKTOP-T772REH\wangyu
fc82fe45c7 add missing file for windows 2018-06-17 00:35:54 +08:00
U-DESKTOP-T772REH\wangyu
970cd8bac5 windows works 2018-06-17 00:35:31 +08:00
wangyu-
a75afc94bb trival 2018-06-16 05:53:44 -05:00
wangyu-
976e0495e5 allow to compile without libnet 2018-06-15 23:05:32 -05:00
wangyu-
33d96331fe implement dummy socket 2018-06-15 11:47:57 -05:00
wangyu-
ba6d5e8895 use tcp for detection 2018-06-15 10:06:34 -05:00
wangyu-
63950e2b22 new option pcap-send 2018-06-15 06:47:39 -05:00
wangyu-
4b8776c67a changed pcap_next_ex to pcap_loop 2018-06-15 02:48:52 -05:00
wangyu-
ddf6b40f3a Merge branch 'portable' of https://github.com/wangyu-/udp2raw-tunnel into portable 2018-06-15 02:25:26 -05:00
wangyu-
55f77463e7 fix pcap latency 2018-06-15 02:25:14 -05:00
Charlie Root
5926e9bd49 fix endian detection on freebsd 2018-06-15 06:07:14 +00:00
wangyu-
b9af389168 renamed id_t to avoid conflict on bsd 2018-06-15 00:50:47 -05:00
wangyu-
23df5160d1 avoid using libnet_clear_packet() 2018-06-15 00:04:41 -05:00
root
af3d7e6c23 add log 2018-06-15 04:53:23 +00:00
wangyu-
781f3d1b44 improve endian detection 2018-06-14 22:31:52 -05:00
root
eba3e2e8cd fix endian problem 2018-06-15 03:23:23 +00:00
root
11b49c72d5 fix an assertion 2018-06-15 03:03:33 +00:00
wangyu
2ab846a9ca endianness macro, fix mac warning 2018-06-14 08:46:37 -07:00
wangyu
0b44f74d9b Merge branch 'portable' of https://github.com/wangyu-/udp2raw-tunnel into portable 2018-06-14 07:55:55 -07:00
wangyu
2198e23026 remove non-portable code on mac 2018-06-14 07:55:50 -07:00
wangyu-
e5524d9edf fix iphdr tcphdr udphdr 2018-06-14 09:54:33 -05:00
wangyu-
5d4ea64d00 remove non-portable code 2018-06-14 09:25:02 -05:00
wangyu
00f37c0d2f remove non-portable headers 2018-06-14 06:46:43 -07:00
wangyu-
1a4c494978 filter expression works 2018-06-14 08:18:26 -05:00
wangyu-
fed5bdc700 libpcap roughly works 2018-06-14 08:01:03 -05:00
wangyu-
83e13ebc5f libnet roughly works 2018-06-12 10:08:41 -05:00
wangyu-
8a1d5b58b1 add libnet and libpcap 2018-06-09 09:04:00 -05:00
wangyu-
ae2fbd4b19 libev works 2018-06-07 06:24:31 -05:00
wangyu-
b5e61ed87d remove useless comments 2018-06-06 21:12:28 -05:00
wangyu-
b449efc6c8 add libev 2018-06-06 20:53:35 -05:00
wangyu-
499599417a removed --lower-level 2018-06-06 20:53:02 -05:00
wangyu-
f44003b801 removed server mode 2018-06-06 19:50:42 -05:00
31 changed files with 1964 additions and 1467 deletions

2
.gitattributes vendored
View File

@@ -1 +1 @@
lib/aes_acc/asm/* linguist-vendored
libev/* linguist-vendored

281
README.md
View File

@@ -1,282 +1,11 @@
# Udp2raw-tunnel
A Tunnel which turns UDP Traffic into Encrypted FakeTCP/UDP/ICMP Traffic by using Raw Socket, helps you Bypass UDP FireWalls(or Unstable UDP Environment). It can defend Replay-Attack and supports Multiplexing. It also acts as a Connection Stabilizer.
# udp2raw-multiplatform
![image0](images/image0.PNG)
When used alone,udp2raw tunnels only UDP traffic. Nevertheless,if you used udp2raw + any UDP-based VPN together,you can tunnel any traffic(include TCP/UDP/ICMP),currently OpenVPN/L2TP/ShadowVPN and [tinyfecVPN](https://github.com/wangyu-/tinyfecVPN) are confirmed to be supported.
multi-platform(cross-platform) version of [udp2raw](https://github.com/wangyu-/udp2raw-tunnel), which supports Windows/Mac/BSD natively.
![image_vpn](images/udp2rawopenvpn.PNG)
udp2raw的跨平台版协议兼容[linux版的udpraw](https://github.com/wangyu-/udp2raw-tunnel)可以直接运行在Windows、Mac、BSD上。
[简体中文](/doc/README.zh-cn.md)(内容更丰富)
Check [Wiki](https://github.com/wangyu-/udp2raw-multiplatform/wiki) for details.
[udp2raw wiki](https://github.com/wangyu-/udp2raw-tunnel/wiki)
# Support Platforms
Linux host (including desktop Linux,Android phone/tablet,OpenWRT router,or Raspberry PI) with root access.
For Windows and MacOS users, use the udp2raw in [this repo](https://github.com/wangyu-/udp2raw-multiplatform).
<del>For Windows and MacOS You can run udp2raw inside [this](https://github.com/wangyu-/udp2raw-tunnel/releases/download/20171108.0/lede-17.01.2-x86_virtual_machine_image.zip) 7.5mb virtual machine image(make sure network adapter runs at bridged mode).</del>
# Features
### Send/Receive UDP Packets with ICMP/FakeTCP/UDP headers
ICMP/FakeTCP headers help you bypass UDP blocking, UDP QOS or improper UDP NAT behavior on some ISPs. In ICMP header mode,udp2raw works like an ICMP tunnel.
UDP headers are also supported. In UDP header mode, it behaves just like a normal UDP tunnel, and you can just make use of the other features (such as encrytion, anti-replay, or connection stalization).
### Simulated TCP with Real-time/Out-of-Order Delivery
In FakeTCP header mode,udp2raw simulates 3-way handshake while establishing a connection,simulates seq and ack_seq while data transferring. It also simulates following TCP options: `MSS`, `sackOk`, `TS`, `TS_ack`, `wscale`.Firewalls will regard FakeTCP as a TCP connection, but its essentially UDP: it supports real-time/out-of-order delivery(just as normal UDP does), no congrestion control or re-transmission. So there wont be any TCP over TCP problem when using OpenVPN.
### Encrpytion, Anti-Replay
* Encrypt your traffic with AES-128-CBC.
* Protect data integrity by HMAC-SHA1 (or weaker MD5/CRC32).
* Defense replay attack with an anti-replay window, smiliar to IPSec and OpenVPN.
### Failure Dectection & Stablization (Connection Recovery)
Conection failures are detected by heartbeats. If timed-out, client will automatically change port number and reconnect. If reconnection is successful, the previous connection will be recovered, and all existing UDP conversations will stay vaild.
For example, if you use udp2raw + OpenVPN, OpenVPN won't lose connection after any reconnect, **even if network cable is re-plugged or WiFi access point is changed**.
### Other Features
* **Multiplexing** One client can handle multiple UDP connections, all of which share the same raw connection.
* **Multiple Clients** One server can have multiple clients.
* **NAT Support** All of the 3 modes work in NAT environments.
* **OpenVZ Support** Tested on BandwagonHost VPS.
* **Easy to Build** No dependencies.To cross-compile udp2raw,all you need to do is just to download a toolchain,modify makefile to point at the toolchain,run `make cross` then everything is done.(Note:Pre-compiled binaries for Desktop,RaspberryPi,Android,some Openwrt Routers are already included in [Releases](https://github.com/wangyu-/udp2raw-tunnel/releases))
### Keywords
`Bypass UDP QoS` `Bypass UDP Blocking` `Bypass OpenVPN TCP over TCP problem` `OpenVPN over ICMP` `UDP to ICMP tunnel` `UDP to TCP tunnel` `UDP over ICMP` `UDP over TCP`
# Getting Started
### Installing
Download binary release from https://github.com/wangyu-/udp2raw-tunnel/releases
### Running
Assume your UDP is blocked or being QOS-ed or just poorly supported. Assume your server ip is 44.55.66.77, you have a service listening on udp port 7777.
```bash
# Run at server side:
./udp2raw_amd64 -s -l0.0.0.0:4096 -r 127.0.0.1:7777 -k "passwd" --raw-mode faketcp -a
# Run at client side
./udp2raw_amd64 -c -l0.0.0.0:3333 -r44.55.66.77:4096 -k "passwd" --raw-mode faketcp -a
```
(The above commands need to be run as root. For better security, with some extra steps, you can run udp2raw as non-root. Check [this link](https://github.com/wangyu-/udp2raw-tunnel/wiki/run-udp2raw-as-non-root) for more info )
###### Server Output:
![](images/output_server.PNG)
###### Client Output:
![](images/output_client.PNG)
Now,an encrypted raw tunnel has been established between client and server through TCP port 4096. Connecting to UDP port 3333 at the client side is equivalent to connecting to port 7777 at the server side. No UDP traffic will be exposed.
### Note
To run on Android, check [Android_Guide](/doc/android_guide.md)
`-a` option automatically adds an iptables rule (or a few iptables rules) for you, udp2raw relys on this iptables rule to work stably. Be aware you dont forget `-a` (its a common mistake). If you dont want udp2raw to add iptables rule automatically, you can add it manually(take a look at `-g` option) and omit `-a`.
# Advanced Topic
### Usage
```
udp2raw-tunnel
git version:6e1df4b39f build date:Oct 24 2017 09:21:15
repository: https://github.com/wangyu-/udp2raw-tunnel
usage:
run as client : ./this_program -c -l local_listen_ip:local_port -r server_address:server_port [options]
run as server : ./this_program -s -l server_listen_ip:server_port -r remote_address:remote_port [options]
common options,these options must be same on both side:
--raw-mode <string> avaliable values:faketcp(default),udp,icmp
-k,--key <string> password to gen symetric key,default:"secret key"
--cipher-mode <string> avaliable values:aes128cbc(default),xor,none
--auth-mode <string> avaliable values:hmac_sha1,md5(default),crc32,simple,none
-a,--auto-rule auto add (and delete) iptables rule
-g,--gen-rule generate iptables rule then exit,so that you can copy and
add it manually.overrides -a
--disable-anti-replay disable anti-replay,not suggested
client options:
--source-ip <ip> force source-ip for raw socket
--source-port <port> force source-port for raw socket,tcp/udp only
this option disables port changing while re-connecting
other options:
--conf-file <string> read options from a configuration file instead of command line.
check example.conf in repo for format
--fifo <string> use a fifo(named pipe) for sending commands to the running program,
check readme.md in repository for supported commands.
--log-level <number> 0:never 1:fatal 2:error 3:warn
4:info (default) 5:debug 6:trace
--log-position enable file name,function name,line number in log
--disable-color disable log color
--disable-bpf disable the kernel space filter,most time its not necessary
unless you suspect there is a bug
--sock-buf <number> buf size for socket,>=10 and <=10240,unit:kbyte,default:1024
--force-sock-buf bypass system limitation while setting sock-buf
--seq-mode <number> seq increase mode for faketcp:
0:static header,do not increase seq and ack_seq
1:increase seq for every packet,simply ack last seq
2:increase seq randomly, about every 3 packets,simply ack last seq
3:simulate an almost real seq/ack procedure(default)
4:similiar to 3,but do not consider TCP Option Window_Scale,
maybe useful when firewall doesnt support TCP Option
--lower-level <string> send packets at OSI level 2, format:'if_name#dest_mac_adress'
ie:'eth0#00:23:45:67:89:b9'.or try '--lower-level auto' to obtain
the parameter automatically,specify it manually if 'auto' failed
--gen-add generate iptables rule and add it permanently,then exit.overrides -g
--keep-rule monitor iptables and auto re-add if necessary.implys -a
--clear clear any iptables rules added by this program.overrides everything
-h,--help print this help message
```
### Iptables rules,`-a` and `-g`
This program sends packets via raw socket. In FakeTCP mode, Linux kernel TCP packet processing has to be blocked by a iptables rule on both sides, otherwise the kernel will automatically send RST for an unrecongized TCP packet and you will sustain from stability / peformance problems. You can use `-a` option to let the program automatically add / delete iptables rule on start / exit. You can also use the `-g` option to generate iptables rule and add it manually.
### `--cipher-mode` and `--auth-mode`
It is suggested to use `aes128cbc` + `hmac_sha1` to obtain maximum security. If you want to run the program on a router, you can try `xor` + `simple`, which can fool packet inspection by firewalls the most of time, but it cannot protect you from serious attacks. Mode none is only for debugging purpose. It is not recommended to set the cipher-mode or auth-mode to none.
### `--seq-mode`
The FakeTCP mode does not behave 100% like a real tcp connection. ISPs may be able to distinguish the simulated tcp traffic from the real TCP traffic (though it's costly). seq-mode can help you change the seq increase behavior slightly. If you experience connection problems, try to change the value.
### `--lower-level`
`--lower-level` allows you to send packet at OSI level 2(link level),so that you can bypass any local iptables rules. If you have a complicated iptables rules which conflicts with udp2raw and you cant(or too lazy to) edit the iptables rules,`--lower-level` can be very useful. Try `--lower-level auto` to auto detect the parameters,you can specify it manually if `auto` fails.
Manual format `if_name#dest_mac_adress`,ie:`eth0#00:23:45:67:89:b9`.
### `--keep-rule`
Monitor iptables and auto re-add iptables rules(for blocking kernel tcp processing) if necessary.Especially useful when iptables rules may be cleared by other programs(for example,if you are using openwrt,everytime you changed and commited a setting,iptables rule may be cleared and re-constructed).
### `--conf-file`
You can also load options from a configuration file in order to keep secrets away from `ps` command.
For example, rewrite the options for the above `server` example (in Getting Started section) into configuration file:
`server.conf`
```
-s
# You can add comments like this
# Comments MUST occupy an entire line
# Or they will not work as expected
# Listen address
-l 0.0.0.0:4096
# Remote address
-r 127.0.0.1:7777
-a
-k passwd
--raw-mode faketcp
```
Pay attention to the `-k` parameter: In command line mode the quotes around the password will be removed by shell. In configuration files we do not remove quotes.
Then start the server with
```bash
./udp2raw_amd64 --conf-file server.conf
```
### `--fifo`
Use a fifo(named pipe) for sending commands to the running program. For example `--fifo fifo.file`.
At client side,you can use `echo reconnect >fifo.file` to force client to reconnect.Currently no command has been implemented for server.
# Peformance Test
#### Test method:
iperf3 TCP via OpenVPN + udp2raw
(iperf3 UDP mode is not used because of a bug mentioned in this issue: https://github.com/esnet/iperf/issues/296 . Instead, we package the TCP traffic into UDP by OpenVPN to test the performance. Read [Application](https://github.com/wangyu-/udp2raw-tunnel#application) for details.
#### iperf3 command:
```
iperf3 -c 10.222.2.1 -P40
iperf3 -c 10.222.2.1 -P40 -R
```
#### Environments
* **Client** Vultr $2.5/monthly plan (single core 2.4GHz cpu, 512MB RAM, Tokyo, Japan)
* **Server** BandwagonHost $3.99/annually plan (single core 2.0GHz cpu, 128MB RAM, Los Angeles, USA)
### Test1
raw_mode: faketcp cipher_mode: xor  auth_mode: simple
![image4](images/image4.PNG)
(reverse speed was simliar and not uploaded)
### Test2
raw_mode: faketcp cipher_mode: aes128cbc  auth_mode: md5
![image5](images/image5.PNG)
(reverse speed was simliar and not uploaded)
# Application
## Tunneling any traffic via raw traffic by using udp2raw +openvpn
![image_vpn](images/udp2rawopenvpn.PNG)
1. Bypasses UDP block/UDP QOS
2. No TCP over TCP problem (TCP over TCP problem http://sites.inka.de/bigred/devel/tcp-tcp.html ,https://community.openvpn.net/openvpn/ticket/2 )
3. OpenVpn over ICMP also becomes a choice
4. Supports almost any UDP-based VPN
More details at [openvpn+udp2raw_guide](https://github.com/wangyu-/udp2raw-tunnel/wiki/udp2raw-openvpn-config-guide)
## Speed-up tcp connection via raw traffic by using udp2raw+kcptun
kcptun is a tcp connection speed-up program,it speeds-up tcp connection by using kcp protocol on-top of udp.by using udp2raw,you can use kcptun while udp is QoSed or blocked.
(kcptun, https://github.com/xtaci/kcptun)
## Speed-up tcp connection via raw traffic by using udp2raw+finalspeed
finalspeed is a tcp connection speed-up program similiar to kcptun,it speeds-up tcp connection by using kcp protocol on-top of udp or tcp.but its tcp mode doesnt support openvz,you can bypass this problem if you use udp2raw+finalspeed together,and icmp mode also becomes avaliable.
# How to build
read [build_guide](/doc/build_guide.md)
# Other
### Easier installation on ArchLinux
```
yaourt -S udp2raw-tunnel # or
pacaur -S udp2raw-tunnel
```
# Related work
### kcptun-raw
udp2raw was inspired by kcptun-raw,which modified kcptun to support tcp mode.
https://github.com/Chion82/kcptun-raw
### relayRawSocket
kcptun-raw was inspired by relayRawSocket. A simple udp to raw tunnel,wrote in python
https://github.com/linhua55/some_kcptun_tools/tree/master/relayRawSocket
### kcpraw
another project of kcptun with tcp mode
https://github.com/ccsexyz/kcpraw
### icmptunnel
Transparently tunnel your IP traffic through ICMP echo and reply packets.
https://github.com/DhavalKapil/icmptunnel
### Tcp Minion
Tcp Minion is a project which modifid the code of tcp stack in kernel,and implemented real-time out-order udp packet delivery through this modified tcp stack.I failed to find the implementation,but there are some papers avaliable:
https://arxiv.org/abs/1103.0463
http://korz.cs.yale.edu/2009/tng/papers/pfldnet10.pdf
https://pdfs.semanticscholar.org/9e6f/e2306f4385b4eb5416d1fcab16e9361d6ba3.pdf
# wiki
Check wiki for more info:
https://github.com/wangyu-/udp2raw-tunnel/wiki
更多信息,见 [Wiki](https://github.com/wangyu-/udp2raw-multiplatform/wiki)

View File

@@ -8,6 +8,17 @@
#include "fd_manager.h"
u32_t detect_interval=1500;
u64_t laste_detect_time=0;
int use_udp_for_detection=0;
int use_tcp_for_detection=1;
extern pcap_t *pcap_handle;
extern int pcap_captured_full_len;
int client_on_timer(conn_info_t &conn_info) //for client. called when a timer is ready in epoll
{
packet_info_t &send_info=conn_info.raw_info.send_info;
@@ -20,6 +31,75 @@ int client_on_timer(conn_info_t &conn_info) //for client. called when a timer is
mylog(log_trace,"<client_on_timer,send_info.ts_ack= %u>\n",send_info.ts_ack);
//mylog(log_debug,"pcap cnt :%d\n",pcap_cnt);
if(send_with_pcap&&!pcap_header_captured)
{
if(get_current_time()-laste_detect_time>detect_interval)
{
laste_detect_time=get_current_time();
}
else
{
return 0;
}
/*
struct sockaddr_in remote_addr_in={0};
socklen_t slen = sizeof(sockaddr_in);
int port=get_true_random_number()%65534+1;
remote_addr_in.sin_family = AF_INET;
remote_addr_in.sin_port = htons(port);
remote_addr_in.sin_addr.s_addr = remote_ip_uint32;*/
int port=get_true_random_number()%65534+1;
address_t tmp_addr=remote_addr;
tmp_addr.set_port(port);
if(use_udp_for_detection)
{
int new_udp_fd=socket(tmp_addr.get_type(), SOCK_DGRAM, IPPROTO_UDP);
if(new_udp_fd<0)
{
mylog(log_warn,"create new_udp_fd error\n");
return -1;
}
setnonblocking(new_udp_fd);
u64_t tmp=get_true_random_number();
int ret=sendto(new_udp_fd,(char*)(&tmp),sizeof(tmp),0,(struct sockaddr *)&tmp_addr.inner,tmp_addr.get_len());
if(ret==-1)
{
mylog(log_warn,"sendto() failed\n");
}
sock_close(new_udp_fd);
}
if(use_tcp_for_detection)
{
static int last_tcp_fd=-1;
int new_tcp_fd=socket(tmp_addr.get_type(), SOCK_STREAM, IPPROTO_TCP);
if(new_tcp_fd<0)
{
mylog(log_warn,"create new_tcp_fd error\n");
return -1;
}
setnonblocking(new_tcp_fd);
connect(new_tcp_fd,(struct sockaddr *)&tmp_addr.inner,tmp_addr.get_len());
if(last_tcp_fd!=-1)
sock_close(last_tcp_fd);
last_tcp_fd=new_tcp_fd;
//close(new_tcp_fd);
}
mylog(log_info,"waiting for a use-able packet to be captured\n");
return 0;
}
if(raw_info.disabled)
{
conn_info.state.client_current_state=client_idle;
@@ -105,7 +185,8 @@ int client_on_timer(conn_info_t &conn_info) //for client. called when a timer is
{
setnonblocking(bind_fd);
int ret=connect(bind_fd,(struct sockaddr *)&remote_addr.inner,remote_addr.get_len());
mylog(log_info,"ret=%d,errno=%s,%d %s\n",ret,get_sock_error(),bind_fd,remote_addr.get_str());
mylog(log_debug,"ret=%d,errno=%s, %d %s\n",ret,get_sock_error(),bind_fd,remote_addr.get_str());
//mylog(log_info,"ret=%d,errno=,%d %s\n",ret,bind_fd,remote_addr.get_str());
conn_info.state.client_current_state=client_tcp_handshake_dummy;
mylog(log_info,"state changed from client_idle to client_tcp_handshake_dummy\n");
}
@@ -306,6 +387,77 @@ int client_on_timer(conn_info_t &conn_info) //for client. called when a timer is
}
return 0;
}
int client_on_raw_recv_hs2_or_ready(conn_info_t &conn_info,char type,char *data,int data_len)
{
packet_info_t &send_info=conn_info.raw_info.send_info;
packet_info_t &recv_info=conn_info.raw_info.recv_info;
if(!recv_info.new_src_ip.equal(send_info.new_dst_ip)||recv_info.src_port!=send_info.dst_port)
{
mylog(log_warn,"unexpected adress %s %s %d %d,this shouldnt happen.\n",recv_info.new_src_ip.get_str1(),send_info.new_dst_ip.get_str2(),recv_info.src_port,send_info.dst_port);
return -1;
}
if(conn_info.state.client_current_state==client_handshake2)
{
mylog(log_info,"changed state from to client_handshake2 to client_ready\n");
conn_info.state.client_current_state=client_ready;
conn_info.last_hb_sent_time=0;
conn_info.last_hb_recv_time=get_current_time();
conn_info.last_oppsite_roller_time=conn_info.last_hb_recv_time;
client_on_timer(conn_info);
}
if(data_len>=0&&type=='h')
{
mylog(log_debug,"[hb]heart beat received,oppsite_roller=%d\n",int(conn_info.oppsite_roller));
conn_info.last_hb_recv_time=get_current_time();
return 0;
}
else if(data_len>= int( sizeof(u32_t))&&type=='d')
{
mylog(log_trace,"received a data from fake tcp,len:%d\n",data_len);
if(hb_mode==0)
conn_info.last_hb_recv_time=get_current_time();
u32_t tmp_conv_id;
memcpy(&tmp_conv_id,&data[0],sizeof(tmp_conv_id));
tmp_conv_id=ntohl(tmp_conv_id);
if(!conn_info.blob->conv_manager.c.is_conv_used(tmp_conv_id))
{
mylog(log_info,"unknow conv %d,ignore\n",tmp_conv_id);
return 0;
}
conn_info.blob->conv_manager.c.update_active_time(tmp_conv_id);
//u64_t u64=conn_info.blob->conv_manager.c.find_data_by_conv(tmp_conv_id);
address_t tmp_addr=conn_info.blob->conv_manager.c.find_data_by_conv(tmp_conv_id);
//sockaddr_in tmp_sockaddr={0};
//tmp_sockaddr.sin_family = AF_INET;
//tmp_sockaddr.sin_addr.s_addr=(u64>>32u);
//tmp_sockaddr.sin_port= htons(uint16_t((u64<<32u)>>32u));
int ret=sendto(udp_fd,data+sizeof(u32_t),data_len -(sizeof(u32_t)),0,(struct sockaddr *)&tmp_addr.inner,tmp_addr.get_len());
if(ret<0)
{
mylog(log_warn,"sento returned %d,%s,%02x,%s\n",ret,get_sock_error(),int(tmp_addr.get_type()),tmp_addr.get_str());
//perror("ret<0");
}
}
else
{
mylog(log_warn,"unknown packet,this shouldnt happen.\n");
return -1;
}
return 0;
}
int client_on_raw_recv(conn_info_t &conn_info) //called when raw fd received a packet.
{
char* data;int data_len;
@@ -315,7 +467,8 @@ int client_on_raw_recv(conn_info_t &conn_info) //called when raw fd received a p
raw_info_t &raw_info=conn_info.raw_info;
mylog(log_trace,"<client_on_raw_recv,send_info.ts_ack= %u>\n",send_info.ts_ack);
if(pre_recv_raw_packet()<0) return -1;
//if(pre_recv_raw_packet()<0) return -1;
//no pre_recv_raw_packet() in mp version
if(conn_info.state.client_current_state==client_idle )
{
@@ -426,75 +579,22 @@ int client_on_raw_recv(conn_info_t &conn_info) //called when raw fd received a p
}
else if(conn_info.state.client_current_state==client_handshake2||conn_info.state.client_current_state==client_ready)//received heartbeat or data
{
char type;
if(recv_safer(conn_info,type,data,data_len)!=0)
vector<char> type_vec;
vector<string> data_vec;
recv_safer_multi(conn_info,type_vec,data_vec);
if(data_vec.empty())
{
mylog(log_debug,"recv_safer failed!\n");
return -1;
}
if(!recv_info.new_src_ip.equal(send_info.new_dst_ip)||recv_info.src_port!=send_info.dst_port)
{
mylog(log_warn,"unexpected adress %s %s %d %d,this shouldnt happen.\n",recv_info.new_src_ip.get_str1(),send_info.new_dst_ip.get_str2(),recv_info.src_port,send_info.dst_port);
return -1;
}
if(conn_info.state.client_current_state==client_handshake2)
{
mylog(log_info,"changed state from to client_handshake2 to client_ready\n");
conn_info.state.client_current_state=client_ready;
conn_info.last_hb_sent_time=0;
conn_info.last_hb_recv_time=get_current_time();
conn_info.last_oppsite_roller_time=conn_info.last_hb_recv_time;
client_on_timer(conn_info);
}
if(data_len>=0&&type=='h')
{
mylog(log_debug,"[hb]heart beat received,oppsite_roller=%d\n",int(conn_info.oppsite_roller));
conn_info.last_hb_recv_time=get_current_time();
return 0;
}
else if(data_len>= int( sizeof(u32_t))&&type=='d')
{
mylog(log_trace,"received a data from fake tcp,len:%d\n",data_len);
if(hb_mode==0)
conn_info.last_hb_recv_time=get_current_time();
u32_t tmp_conv_id;
memcpy(&tmp_conv_id,&data[0],sizeof(tmp_conv_id));
tmp_conv_id=ntohl(tmp_conv_id);
if(!conn_info.blob->conv_manager.c.is_conv_used(tmp_conv_id))
{
mylog(log_info,"unknow conv %d,ignore\n",tmp_conv_id);
return 0;
}
conn_info.blob->conv_manager.c.update_active_time(tmp_conv_id);
//u64_t u64=conn_info.blob->conv_manager.c.find_data_by_conv(tmp_conv_id);
address_t tmp_addr=conn_info.blob->conv_manager.c.find_data_by_conv(tmp_conv_id);
//sockaddr_in tmp_sockaddr={0};
//tmp_sockaddr.sin_family = AF_INET;
//tmp_sockaddr.sin_addr.s_addr=(u64>>32u);
//tmp_sockaddr.sin_port= htons(uint16_t((u64<<32u)>>32u));
int ret=sendto(udp_fd,data+sizeof(u32_t),data_len -(sizeof(u32_t)),0,(struct sockaddr *)&tmp_addr.inner,tmp_addr.get_len());
if(ret<0)
{
mylog(log_warn,"sento returned %d,%s,%02x,%s\n",ret,get_sock_error(),int(tmp_addr.get_type()),tmp_addr.get_str());
//perror("ret<0");
}
}
else
{
mylog(log_warn,"unknown packet,this shouldnt happen.\n");
return -1;
}
for(int i=0;i<(int)type_vec.size();i++)
{
char type=type_vec[i];
char *data=(char *)data_vec[i].c_str(); //be careful, do not append data to it
int data_len=data_vec[i].length();
client_on_raw_recv_hs2_or_ready(conn_info, type, data,data_len);
}
return 0;
}
@@ -564,10 +664,69 @@ void udp_accept_cb(struct ev_loop *loop, struct ev_io *watcher, int revents)
}
void raw_recv_cb(struct ev_loop *loop, struct ev_io *watcher, int revents)
{
//assert(0==1);
assert(0==1);
conn_info_t & conn_info= *((conn_info_t*)watcher->data);
client_on_raw_recv(conn_info);
}
void async_cb(struct ev_loop *loop, struct ev_async *watcher, int revents)
{
conn_info_t & conn_info= *((conn_info_t*)watcher->data);
if(send_with_pcap&&!pcap_header_captured)
{
int empty=0;char *p;int len;
pthread_mutex_lock(&queue_mutex);
empty=my_queue.empty();
if(!empty)
{
my_queue.peek_front(p,len);
my_queue.pop_front();
}
pthread_mutex_unlock(&queue_mutex);
if(empty) return;
pcap_header_captured=1;
assert(pcap_link_header_len!=-1);
memcpy(pcap_header_buf,p,max_data_len);
log_bare(log_info,"link level header captured:\n");
unsigned char *tmp=(unsigned char*)pcap_header_buf;
pcap_captured_full_len=len;
for(int i=0;i<pcap_link_header_len;i++)
log_bare(log_info,"<%x>",(u32_t)tmp[i]);
log_bare(log_info,"\n");
return ;
}
//mylog(log_info,"async_cb called\n");
while(1)
{
int empty=0;char *p;int len;
pthread_mutex_lock(&queue_mutex);
empty=my_queue.empty();
if(!empty)
{
my_queue.peek_front(p,len);
my_queue.pop_front();
}
pthread_mutex_unlock(&queue_mutex);
if(empty) break;
if(g_fix_gro==0&&len>max_data_len)
{
mylog(log_warn,"huge packet %d > %d, dropped\n",len,max_data_len);
break;
}
int new_len=len-pcap_link_header_len;
memcpy(g_packet_buf,p+pcap_link_header_len,new_len);
g_packet_buf_len=new_len;
assert(g_packet_buf_cnt==0);
g_packet_buf_cnt++;
client_on_raw_recv(conn_info);
}
}
void clear_timer_cb(struct ev_loop *loop, struct ev_timer *watcher, int revents)
{
conn_info_t & conn_info= *((conn_info_t*)watcher->data);
@@ -613,6 +772,7 @@ int client_event_loop()
packet_info_t &send_info=conn_info.raw_info.send_info;
packet_info_t &recv_info=conn_info.raw_info.recv_info;
/*
if(lower_level)
{
if(lower_level_manual)
@@ -688,6 +848,113 @@ int client_event_loop()
}
}
*/
address_t tmp_addr;
if(get_src_adress2(tmp_addr,remote_addr)!=0)
{
mylog(log_error,"get_src_adress() failed\n");
myexit(-1);
}
if(strcmp(dev,"")==0)
{
mylog(log_info,"--dev have not been set, trying to detect automatically, avaliable deives:\n");
mylog(log_info,"avaliable deives(device name: ip address ; description):\n");
char errbuf[PCAP_ERRBUF_SIZE];
int found=0;
pcap_if_t *interfaces,*d;
if(pcap_findalldevs(&interfaces,errbuf)==-1)
{
mylog(log_fatal,"error in pcap_findalldevs(),%s\n",errbuf);
myexit(-1);
}
for(pcap_if_t *d=interfaces; d!=NULL; d=d->next) {
log_bare(log_warn,"%s:", d->name);
int cnt=0;
for(pcap_addr_t *a=d->addresses; a!=NULL; a=a->next) {
if(a->addr==NULL)
{
log_bare(log_debug," [a->addr==NULL]");
continue;
}
if(a->addr->sa_family == AF_INET||a->addr->sa_family == AF_INET6)
{
cnt++;
if(a->addr->sa_family ==AF_INET)
{
char s[max_addr_len];
inet_ntop(AF_INET, &((struct sockaddr_in*)a->addr)->sin_addr, s,max_addr_len);
log_bare(log_warn," [%s]", s);
if(a->addr->sa_family==raw_ip_version)
{
if(((struct sockaddr_in*)a->addr)->sin_addr.s_addr ==tmp_addr.inner.ipv4.sin_addr.s_addr)
{
found++;
strcpy(dev,d->name);
}
}
}
else
{
assert(a->addr->sa_family ==AF_INET6);
char s[max_addr_len];
inet_ntop(AF_INET6, &((struct sockaddr_in6*)a->addr)->sin6_addr, s,max_addr_len);
log_bare(log_warn," [%s]", s);
if(a->addr->sa_family==raw_ip_version)
{
if( memcmp( &((struct sockaddr_in6*)a->addr)->sin6_addr,&tmp_addr.inner.ipv6.sin6_addr,sizeof(struct in6_addr))==0 )
{
found++;
strcpy(dev,d->name);
}
}
}
}
else
{
log_bare(log_debug," [unknow:%d]",int(a->addr->sa_family));
}
}
if(cnt==0) log_bare(log_warn," [no ip found]");
if(d->description==0)
{
log_bare(log_warn,"; (no description avaliable)");
}
else
{
log_bare(log_warn,"; %s", d->description);
}
log_bare(log_warn,"\n");
}
if(found==0)
{
mylog(log_fatal,"no matched device found for ip: [%s]\n",tmp_addr.get_ip());
myexit(-1);
}
else if(found==1)
{
mylog(log_info,"using device:[%s], ip: [%s]\n",dev,tmp_addr.get_ip());
}
else
{
mylog(log_fatal,"more than one devices found for ip: [%s] , you need to use --dev manually\n",tmp_addr.get_ip());
myexit(-1);
}
}
else
{
mylog(log_info,"--dev has been manually set, using device:[%s]\n",dev);
}
send_info.src_port=0;
memset(&send_info.new_src_ip,0,sizeof(send_info.new_src_ip));
@@ -747,11 +1014,20 @@ int client_event_loop()
// myexit(-1);
//}
/*
struct ev_io raw_recv_watcher;
raw_recv_watcher.data=&conn_info;
ev_io_init(&raw_recv_watcher, raw_recv_cb, raw_recv_fd, EV_READ);
ev_io_start(loop, &raw_recv_watcher);
*/
g_default_loop=loop;
async_watcher.data=&conn_info;
ev_async_init(&async_watcher,async_cb);
ev_async_start(loop,&async_watcher);
init_raw_socket();//must be put after dev detection
//set_timer(epollfd,timer_fd);
struct ev_timer clear_timer;

View File

@@ -346,6 +346,54 @@ int my_ip_t::from_str(char * str)
return 0;
}*/
int init_ws()
{
#if defined(__MINGW32__)
WORD wVersionRequested;
WSADATA wsaData;
int err;
/* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */
wVersionRequested = MAKEWORD(2, 2);
err = WSAStartup(wVersionRequested, &wsaData);
if (err != 0) {
/* Tell the user that we could not find a usable */
/* Winsock DLL. */
printf("WSAStartup failed with error: %d\n", err);
exit(-1);
}
/* Confirm that the WinSock DLL supports 2.2.*/
/* Note that if the DLL supports versions greater */
/* than 2.2 in addition to 2.2, it will still return */
/* 2.2 in wVersion since that is the version we */
/* requested. */
if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) {
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
printf("Could not find a usable version of Winsock.dll\n");
WSACleanup();
exit(-1);
}
else
{
printf("The Winsock 2.2 dll was found okay");
}
int tmp[]={0,100,200,300,500,800,1000,2000,3000,4000,-1};
int succ=0;
for(int i=1;tmp[i]!=-1;i++)
{
if(_setmaxstdio(100)==-1) break;
else succ=i;
}
printf(", _setmaxstdio() was set to %d\n",tmp[succ]);
#endif
return 0;
}
#if defined(__MINGW32__)
int inet_pton(int af, const char *src, void *dst)
{
@@ -404,7 +452,11 @@ char *get_sock_error()
(LPWSTR)&s, 0, NULL);
sprintf(buf, "%d:%S", e,s);
int len=strlen(buf);
if(len>0&&buf[len-1]=='\n') buf[len-1]=0;
while(len>0 && (buf[len-1]=='\r'||buf[len-1]=='\n' ))
{
len--;
buf[len]=0;
}
LocalFree(s);
return buf;
}
@@ -426,13 +478,31 @@ int get_sock_errno()
#endif
u64_t get_current_time_us()
{
static u64_t value_fix=0;
static u64_t largest_value=0;
u64_t raw_value=(u64_t)(ev_time()*1000*1000);
u64_t fixed_value=raw_value+value_fix;
if(fixed_value< largest_value)
{
value_fix+= largest_value- fixed_value;
}
else
{
largest_value=fixed_value;
}
//printf("<%lld,%lld,%lld>\n",raw_value,value_fix,raw_value + value_fix);
return raw_value + value_fix; //new fixed value
}
u64_t get_current_time()
{
timespec tmp_time;
clock_gettime(CLOCK_MONOTONIC, &tmp_time);
return ((u64_t)tmp_time.tv_sec)*1000llu+((u64_t)tmp_time.tv_nsec)/(1000*1000llu);
//return (u64_t)(ev_time()*1000); //todo change to this later
return get_current_time_us()/1000;
}
u64_t pack_u64(u32_t a,u32_t b)
@@ -470,6 +540,8 @@ void init_random_number_fd()
}
setnonblocking(random_number_fd);
}*/
#if !defined(__MINGW32__)
struct random_fd_t
{
int random_number_fd;
@@ -489,8 +561,60 @@ struct random_fd_t
return random_number_fd;
}
}random_fd;
#else
struct my_random_t
{
std::random_device rd;
std::mt19937 gen;
std::uniform_int_distribution<u64_t> dis64;
std::uniform_int_distribution<u32_t> dis32;
std::uniform_int_distribution<unsigned char> dis8;
my_random_t()
{
//std::mt19937 gen_tmp(rd()); //random device is broken on mingw
timespec tmp_time;
clock_gettime(CLOCK_MONOTONIC, &tmp_time);
long long a=((u64_t)tmp_time.tv_sec)*1000000000llu+((u64_t)tmp_time.tv_nsec);
std::mt19937 gen_tmp(a);
gen=gen_tmp;
gen.discard(700000); //magic
}
u64_t gen64()
{
return dis64(gen);
}
u32_t gen32()
{
return dis32(gen);
}
unsigned char gen8()
{
return dis8(gen);
}
/*int random_number_fd;
random_fd_t()
{
random_number_fd=open("/dev/urandom",O_RDONLY);
if(random_number_fd==-1)
{
mylog(log_fatal,"error open /dev/urandom\n");
myexit(-1);
}
setnonblocking(random_number_fd);
}
int get_fd()
{
return random_number_fd;
}*/
}my_random;
#endif
u64_t get_true_random_number_64()
{
#if !defined(__MINGW32__)
u64_t ret;
int size=read(random_fd.get_fd(),&ret,sizeof(ret));
if(size!=sizeof(ret))
@@ -499,9 +623,13 @@ u64_t get_true_random_number_64()
myexit(-1);
}
return ret;
#else
return my_random.gen64(); //fake random number
#endif
}
u32_t get_true_random_number()
{
#if !defined(__MINGW32__)
u32_t ret;
int size=read(random_fd.get_fd(),&ret,sizeof(ret));
if(size!=sizeof(ret))
@@ -510,6 +638,9 @@ u32_t get_true_random_number()
myexit(-1);
}
return ret;
#else
return my_random.gen32(); //fake random number
#endif
}
u32_t get_true_random_number_nz() //nz for non-zero
{
@@ -672,6 +803,10 @@ int set_buf_size(int fd,int socket_buf_size)
{
if(force_socket_buf)
{
mylog(log_fatal,"force_socket_buf not supported in this verion\n");
myexit(-1);
//assert(0==1);
#if 0
if(setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &socket_buf_size, sizeof(socket_buf_size))<0)
{
mylog(log_fatal,"SO_SNDBUFFORCE fail socket_buf_size=%d errno=%s\n",socket_buf_size,strerror(errno));
@@ -682,6 +817,8 @@ int set_buf_size(int fd,int socket_buf_size)
mylog(log_fatal,"SO_RCVBUFFORCE fail socket_buf_size=%d errno=%s\n",socket_buf_size,strerror(errno));
myexit(1);
}
#endif
}
else
{
@@ -817,13 +954,15 @@ bool larger_than_u16(uint16_t a,uint16_t b)
{
return 1;
}
}*/
}
*/
}
void myexit(int a)
{
if(enable_log_color)
printf("%s\n",RESET);
/*
if(keep_thread_running)
{
if(pthread_cancel(keep_thread))
@@ -836,6 +975,7 @@ void myexit(int a)
}
}
clear_iptables_rule();
*/
exit(a);
}
@@ -905,6 +1045,9 @@ int read_file(const char * file,string &output)
return 0;
}
int run_command(string command0,char * &output,int flag) {
mylog(log_fatal,"run_command not supported in this version\n");
myexit(-1);
#if 0
FILE *in;
@@ -958,6 +1101,7 @@ int run_command(string command0,char * &output,int flag) {
return -4;
}
#endif
return 0;
}
@@ -1078,6 +1222,7 @@ vector<string> parse_conf_line(const string& s0)
int create_fifo(char * file)
{
#if !defined(__MINGW32__)
if(mkfifo (file, 0666)!=0)
{
if(errno==EEXIST)
@@ -1111,9 +1256,13 @@ int create_fifo(char * file)
setnonblocking(fifo_fd);
return fifo_fd;
#else
mylog(log_fatal,"--fifo not supported in this version\n");
myexit(-1);
return 0;
#endif
}
/*
void ip_port_t::from_u64(u64_t u64)
{
ip=get_u64_h(u64);
@@ -1128,7 +1277,7 @@ char * ip_port_t::to_s()
static char res[40];
sprintf(res,"%s:%d",my_ntoa(ip),port);
return res;
}*/
}

View File

@@ -27,8 +27,6 @@
#include <assert.h>
#include <pthread.h>
#if defined(UDP2RAW_MP)
#if !defined(__CYGWIN__) && !defined(__MINGW32__)
#include <pcap.h>
#else
@@ -40,20 +38,11 @@
#include <libnet.h>
#endif
#else
//#include <linux/if_ether.h>
#include <linux/filter.h>
#include <linux/if_packet.h>
#include <sys/epoll.h>
//#include <sys/wait.h> //signal
#include <netinet/if_ether.h>
#include <net/if.h>
#include <sys/timerfd.h>
#endif
#if !defined(NO_LIBEV_EMBED)
#include <my_ev.h>
#else
#include "ev.h"
#endif
#if defined(__MINGW32__)
#include <winsock2.h>
@@ -159,7 +148,7 @@ const int max_addr_len=100;
extern int force_socket_buf;
/*
extern int g_fix_gro;
struct ip_port_t
{
u32_t ip;
@@ -167,7 +156,8 @@ struct ip_port_t
void from_u64(u64_t u64);
u64_t to_u64();
char * to_s();
};*/
};
typedef u64_t fd64_t;
@@ -345,12 +335,59 @@ struct not_copy_able_t
}
};
const int huge_data_len=65535+100; //a packet with link level header might be larger than 65535
const int huge_buf_len=huge_data_len+100;
const int max_data_len=1800;
const int buf_len=max_data_len+400;
//const int max_address_len=512;
const int queue_len=200;
struct queue_t
{
char data[queue_len][huge_buf_len];
int data_len[queue_len];
int head=0;
int tail=0;
void clear()
{
head=tail=0;
}
int empty()
{
if(head==tail) return 1;
else return 0;
}
int full()
{
if( (tail+1)%queue_len==head ) return 1;
else return 0;
}
void peek_front(char * & p,int &len)
{
assert(!empty());
p=data[head];
len=data_len[head];
}
void pop_front()
{
assert(!empty());
head++;head%=queue_len;
}
void push_back(char * p,int len)
{
assert(!full());
memcpy(data[tail],p,len);
data_len[tail]=len;
tail++;tail%=queue_len;
}
};
int init_ws();
u64_t get_current_time();
u64_t pack_u64(u32_t a,u32_t b);

View File

@@ -11,8 +11,6 @@
int disable_anti_replay=0;//if anti_replay windows is diabled
const int disable_conn_clear=0;//a raw connection is called conn.
conn_manager_t conn_manager;
@@ -462,12 +460,9 @@ int send_safer(conn_info_t &conn_info,char type,const char* data,int len) //saf
}
char send_data_buf[buf_len]; //buf for send data and send hb
char send_data_buf2[buf_len];
my_id_t n_tmp_id=htonl(conn_info.my_id);
memcpy(send_data_buf,&n_tmp_id,sizeof(n_tmp_id));
@@ -488,10 +483,32 @@ int send_safer(conn_info_t &conn_info,char type,const char* data,int len) //saf
int new_len=len+sizeof(n_seq)+sizeof(n_tmp_id)*2+2;
if(my_encrypt(send_data_buf,send_data_buf2,new_len)!=0)
if(g_fix_gro==0)
{
if (my_encrypt(send_data_buf, send_data_buf2, new_len) != 0)
{
return -1;
}
}
else
{
if (my_encrypt(send_data_buf, send_data_buf2+2, new_len) != 0)
{
return -1;
}
write_u16(send_data_buf2,new_len);
new_len+=2;
if(cipher_mode==cipher_xor)
{
return -1;
send_data_buf2[0]^=gro_xor[0];
send_data_buf2[1]^=gro_xor[1];
}
else if(cipher_mode==cipher_aes128cbc||cipher_mode==cipher_aes128cbc)
{
aes_ecb_encrypt1(send_data_buf2);
}
}
if(send_raw0(conn_info.raw_info,send_data_buf2,new_len)!=0) return -1;
@@ -602,19 +619,101 @@ int reserved_parse_safer(conn_info_t &conn_info,const char * input,int input_len
return 0;
}
int recv_safer(conn_info_t &conn_info,char &type,char* &data,int &len)///safer transfer function with anti-replay,when mutually verification is done.
int recv_safer_notused(conn_info_t &conn_info,char &type,char* &data,int &len)///safer transfer function with anti-replay,when mutually verification is done.
{
packet_info_t &send_info=conn_info.raw_info.send_info;
packet_info_t &recv_info=conn_info.raw_info.recv_info;
char * recv_data;int recv_len;
static char recv_data_buf[buf_len];
//static char recv_data_buf[buf_len];
if(recv_raw0(conn_info.raw_info,recv_data,recv_len)!=0) return -1;
return reserved_parse_safer(conn_info,recv_data,recv_len,type,data,len);
}
int recv_safer_multi(conn_info_t &conn_info,vector<char> &type_arr,vector<string> &data_arr)///safer transfer function with anti-replay,when mutually verification is done.
{
packet_info_t &send_info=conn_info.raw_info.send_info;
packet_info_t &recv_info=conn_info.raw_info.recv_info;
char * recv_data;int recv_len;
assert(type_arr.empty());
assert(data_arr.empty());
if(recv_raw0(conn_info.raw_info,recv_data,recv_len)!=0) return -1;
char type;
char *data;
int len;
if(g_fix_gro==0)
{
int ret = reserved_parse_safer(conn_info, recv_data, recv_len, type, data, len);
if(ret==0)
{
type_arr.push_back(type);
data_arr.emplace_back(data,data+len);
//std::copy(data,data+len,data_arr[0]);
}
return 0;
} else
{
char *ori_recv_data=recv_data;
int ori_recv_len=recv_len;
//mylog(log_debug,"recv_len:%d\n",recv_len);
int cnt=0;
while(recv_len>=16)
{
cnt++;
int single_len_no_xor;
single_len_no_xor=read_u16(recv_data);
int single_len;
if(cipher_mode==cipher_xor)
{
recv_data[0]^=gro_xor[0];
recv_data[1]^=gro_xor[1];
}
else if(cipher_mode==cipher_aes128cbc||cipher_mode==cipher_aes128cbc)
{
aes_ecb_decrypt1(recv_data);
}
single_len=read_u16(recv_data);
recv_len-=2;
recv_data+=2;
if(single_len > recv_len)
{
mylog(log_debug,"illegal single_len %d(%d), recv_len %d left,dropped\n",single_len,single_len_no_xor,recv_len);
break;
}
if(single_len> max_data_len )
{
mylog(log_warn,"single_len %d(%d) > %d, maybe you need to turn down mtu at upper level\n",single_len,single_len_no_xor,max_data_len);
break;
}
int ret = reserved_parse_safer(conn_info, recv_data, single_len, type, data, len);
if(ret!=0)
{
mylog(log_debug,"parse failed, offset= %d,single_len=%d(%d)\n",(int)(recv_data-ori_recv_data),single_len,single_len_no_xor);
} else{
type_arr.push_back(type);
data_arr.emplace_back(data,data+len);
//std::copy(data,data+len,data_arr[data_arr.size()-1]);
}
recv_data+=single_len;
recv_len-=single_len;
}
if(cnt>1)
{
mylog(log_debug,"got a suspected gro packet, %d packets recovered, recv_len=%d, loop_cnt=%d\n",(int)data_arr.size(),ori_recv_len,cnt);
}
return 0;
}
}
void server_clear_function(u64_t u64)//used in conv_manager in server mode.for server we have to use one udp fd for one conv(udp connection),
//so we have to close the fd when conv expires
{

View File

@@ -19,7 +19,6 @@ extern int disable_anti_replay;
const int disable_conv_clear=0;//a udp connection in the multiplexer is called conversation in this program,conv for short.
struct anti_replay_t //its for anti replay attack,similar to openvpn/ipsec 's anti replay window
{
u64_t max_packet_received;
@@ -283,7 +282,6 @@ struct conn_info_t //stores info for a raw connection.for client ,there is o
/*
const uint32_t &ip=raw_info.recv_info.src_ip;
const uint16_t &port=raw_info.recv_info.src_port;
*/
void recover(const conn_info_t &conn_info);
void re_init();
@@ -346,5 +344,8 @@ int send_handshake(raw_info_t &raw_info,my_id_t id1,my_id_t id2,my_id_t id3);//
int send_safer(conn_info_t &conn_info,char type,const char* data,int len); //safer transfer function with anti-replay,when mutually verification is done.
int send_data_safer(conn_info_t &conn_info,const char* data,int len,u32_t conv_num);//a wrap for send_safer for transfer data.
//int reserved_parse_safer(conn_info_t &conn_info,const char * input,int input_len,char &type,char* &data,int &len);//subfunction for recv_safer,allow overlap
int recv_safer(conn_info_t &conn_info,char &type,char* &data,int &len);///safer transfer function with anti-replay,when mutually verification is done.
//int recv_safer(conn_info_t &conn_info,char &type,char* &data,int &len);///safer transfer function with anti-replay,when mutually verification is done.
int recv_safer_multi(conn_info_t &conn_info,vector<char> &type_arr,vector<string> &data_arr);//new api for handle gro
#endif /* CONNECTION_H_ */

View File

@@ -26,9 +26,11 @@ Release中提供了`amd64`、`x86`、`arm`、`mips_be`、`mips_le`的预编译bi
##### 对于windows和mac用户
可以用[这个repo](https://github.com/wangyu-/udp2raw-multiplatform)里的udp2raw原生运行
可以把udp2raw运行在虚拟机上(网络必须是桥接模式)
<del>可以把udp2raw运行在虚拟机上(网络必须是桥接模式)。可以参考: https://github.com/wangyu-/udp2raw-tunnel/wiki/在windows-mac上运行udp2raw客户端带图形界面 </del>
另外可以参考:
https://github.com/wangyu-/udp2raw-tunnel/wiki/在windows-mac上运行udp2raw客户端带图形界面
##### 对于ios和游戏主机用户
@@ -41,11 +43,15 @@ Release中提供了`amd64`、`x86`、`arm`、`mips_be`、`mips_le`的预编译bi
### 模拟TCP3次握手
模拟TCP3次握手模拟seq ack过程。另外还模拟了一些tcp optionMSS,sackOk,TS,TS_ack,wscale用来使流量看起来更像是由普通的linux tcp协议栈发送的。
### 心跳保活、自动重连,连接恢复
### 心跳保活、自动重连,连接快速恢复,单向链路失效检测
心跳保活、自动重连udp2raw重连可以恢复上次的连接重连后上层连接继续有效底层掉线上层不掉线。有效解决上层连接断开的问题。 (功能借鉴自[kcptun-raw](https://github.com/Chion82/kcptun-raw)**就算你拔掉网线重插或者重新拨号获得新ip上层应用也不会断线**
Client能用单倍的超时时间检测到单向链路的失效不管是上行还是下行只要有一个方向失效就能被client检测到。重连只需要client发起就可以立即被server处理不需要等到server端的连接超时后。
对于有大量client的情况对于不同client,server发送的心跳是错开时间发送的不会因为短时间发送大量的心跳而造成拥塞和延迟抖动。
### 加密 防重放攻击
用aes128cbc加密(或更弱的xor)hmac-sha1(或更弱的md5/crc32/simple)做数据完整校验。用类似ipsec/openvpn的replay window机制来防止重放攻击。
用aes128cbc加密md5/crc32做数据完整校验。用类似ipsec/openvpn的 replay window机制来防止重放攻击。
设计目标是即使攻击者可以监听到tunnel的所有包可以选择性丢弃tunnel的任意包可以重放任意包攻击者也没办法获得tunnel承载的任何数据也没办法向tunnel的数据流中通过包构造/包重放插入任何数据。
@@ -60,6 +66,8 @@ NAT 穿透 tcp icmp udp模式都支持nat穿透。
支持Openwrt没有编译依赖容易编译到任何平台上。
epoll实现高并发除了回收过期连接外所有操作的时间复杂度都跟连接数无关。回收过期连接的操做也是柔和进行的不会因为消耗太多cpu时间造成延迟抖动。
### 关键词
突破udp qos,突破udp屏蔽openvpn tcp over tcp problem,openvpn over icmp,udp to icmp tunnel,udp to tcp tunnel,udp via icmp,udp via tcp
@@ -75,10 +83,10 @@ https://github.com/wangyu-/udp2raw-tunnel/releases
```
在server端运行:
./udp2raw_amd64 -s -l0.0.0.0:4096 -r127.0.0.1:7777 -k "passwd" --raw-mode faketcp --cipher-mode xor -a
./udp2raw_amd64 -s -l0.0.0.0:4096 -r127.0.0.1:7777 -a -k "passwd" --raw-mode faketcp --cipher-mode xor
在client端运行:
./udp2raw_amd64 -c -l0.0.0.0:3333 -r44.55.66.77:4096 -k "passwd" --raw-mode faketcp --cipher-mode xor -a
./udp2raw_amd64 -c -l0.0.0.0:3333 -r44.55.66.77:4096 -a -k "passwd" --raw-mode faketcp --cipher-mode xor
```
(以上例子需要用root账号运行。 用非root运行udp2raw需要一些额外的步骤具体方法请看 [这个](https://github.com/wangyu-/udp2raw-tunnel/wiki/run-udp2raw-as-non-root) 链接。用非root运行更安全)
@@ -98,7 +106,9 @@ https://github.com/wangyu-/udp2raw-tunnel/releases
如果要在anroid上运行请看[Android简明教程](/doc/android_guide.md)
`-a`选项会自动添加一条/几条iptables规则udp2raw必须和相应的iptables规则配合才能稳定工作一定要注意不要忘了`-a`(这是个常见错误)。 如果你不想让udp2raw自动添加iptables规则可以自己手动添加相应的iptables规则(看一下`-g`选项),然后以不带`-a`的方式运行udp2raw。
如果要在梅林固件的路由器上使用,添加`--lower-level auto` `--keep-rule`
如果client和server无法连接或者连接经常断开请看一下`--seq-mode`的用法尝试不同的seq-mode。
# 进阶操作说明
@@ -109,14 +119,14 @@ git version:6e1df4b39f build date:Oct 24 2017 09:21:15
repository: https://github.com/wangyu-/udp2raw-tunnel
usage:
run as client : ./this_program -c -l local_listen_ip:local_port -r server_address:server_port [options]
run as server : ./this_program -s -l server_listen_ip:server_port -r remote_address:remote_port [options]
run as client : ./this_program -c -l local_listen_ip:local_port -r server_address:server_port [options]
run as server : ./this_program -s -l server_listen_ip:server_port -r remote_address:remote_port [options]
common options,these options must be same on both side:
--raw-mode <string> avaliable values:faketcp(default),udp,icmp
-k,--key <string> password to gen symetric key,default:"secret key"
--cipher-mode <string> avaliable values:aes128cbc(default),xor,none
--auth-mode <string> avaliable values:hmac_sha1,md5(default),crc32,simple,none
--auth-mode <string> avaliable values:md5(default),crc32,simple,none
-a,--auto-rule auto add (and delete) iptables rule
-g,--gen-rule generate iptables rule then exit,so that you can copy and
add it manually.overrides -a
@@ -160,7 +170,7 @@ other options:
用raw收发udp包也类似只是内核回复的是icmp unreachable。而用raw 收发icmp内核会自动回复icmp echo。都需要相应的iptables规则。
### `--cipher-mode` 和 `--auth-mode`
如果要最大的安全性建议用aes128cbc+hmac_sha1。如果要运行在路由器上建议用xor+simple可以节省CPU。但是注意xor+simple只能骗过防火墙的包检测不能防止真正的攻击者。
如果要最大的安全性建议用aes128cbc+md5。如果要运行在路由器上建议用xor+simple可以节省CPU。但是注意xor+simple只能骗过防火墙的包检测不能防止真正的攻击者。
### `--seq-mode`
facktcp模式并没有模拟tcp的全部。所以理论上有办法把faketcp和真正的tcp流量区分开来虽然大部分ISP不太可能做这种程度的包检测。seq-mode可以改变一些seq ack的行为。如果遇到了连接问题可以尝试更改。在我这边的移动线路用3种模式都没问题。

View File

@@ -26,6 +26,8 @@ unsigned char hmac_key_decrypt[hmac_key_len + 100]; //key for hmac
unsigned char cipher_key_encrypt[cipher_key_len + 100]; //key for aes etc.
unsigned char cipher_key_decrypt[cipher_key_len + 100]; //key for aes etc.
char gro_xor[256+100];//dirty fix for gro
unordered_map<int, const char *> auth_mode_tostring = {{auth_none, "none"}, {auth_md5, "md5"}, {auth_crc32, "crc32"},{auth_simple,"simple"},{auth_hmac_sha1,"hmac_sha1"},};
unordered_map<int, const char *> cipher_mode_tostring={{cipher_none,"none"},{cipher_aes128cfb,"aes128cfb"},{cipher_aes128cbc,"aes128cbc"},{cipher_xor,"xor"},};
@@ -35,6 +37,8 @@ auth_mode_t auth_mode=auth_md5;
cipher_mode_t cipher_mode=cipher_aes128cbc;
int is_hmac_used=0;
int aes128cfb_old=0;
//TODO key negotiation and forward secrecy
int my_init_keys(const char * user_passwd,int is_client)
@@ -48,9 +52,10 @@ int my_init_keys(const char * user_passwd,int is_client)
md5((uint8_t*)tmp,strlen(tmp),(uint8_t*)normal_key);
if(auth_mode==auth_hmac_sha1)
is_hmac_used=1;
if(is_hmac_used)
if(is_hmac_used||g_fix_gro||1)
{
unsigned char salt[400]="";
char salt_text[400]="udp2raw_salt1";
@@ -82,6 +87,9 @@ int my_init_keys(const char * user_passwd,int is_client)
assert( hkdf_sha256_expand( pbkdf2_output1,32, (unsigned char *)info_cipher_decrypt,strlen(info_cipher_decrypt), cipher_key_decrypt, cipher_key_len ) ==0);
assert( hkdf_sha256_expand( pbkdf2_output1,32, (unsigned char *)info_hmac_encrypt,strlen(info_hmac_encrypt), hmac_key_encrypt, hmac_key_len ) ==0);
assert( hkdf_sha256_expand( pbkdf2_output1,32, (unsigned char *)info_hmac_decrypt,strlen(info_hmac_decrypt), hmac_key_decrypt, hmac_key_len ) ==0);
const char *gro_info="gro";
assert( hkdf_sha256_expand( pbkdf2_output1,32, (unsigned char *)gro_info,strlen(gro_info), (unsigned char *)gro_xor, 256 ) ==0);
}
print_binary_chars(normal_key,16);
@@ -291,6 +299,40 @@ int de_padding(const char *data ,int &data_len,int padding_num)
}
return 0;
}
void aes_ecb_encrypt(const char *data,char *output)
{
static int first_time=1;
char *key=(char*)cipher_key_encrypt;
if(aes_key_optimize)
{
if(first_time==0) key=0;
else first_time=0;
}
AES_ECB_encrypt_buffer((uint8_t*)data,(uint8_t*)key,(uint8_t*)output);
}
void aes_ecb_encrypt1(char *data)
{
char buf[16];
memcpy(buf,data,16);
aes_ecb_encrypt(buf,data);
}
void aes_ecb_decrypt(const char *data,char *output)
{
static int first_time=1;
char *key=(char*)cipher_key_decrypt;
if(aes_key_optimize)
{
if(first_time==0) key=0;
else first_time=0;
}
AES_ECB_decrypt_buffer((uint8_t*)data,(uint8_t*)key,(uint8_t*)output);
}
void aes_ecb_decrypt1(char *data)
{
char buf[16];
memcpy(buf,data,16);
aes_ecb_decrypt(buf,data);
}
int cipher_aes128cbc_encrypt(const char *data,char *output,int &len,char * key)
{
static int first_time=1;
@@ -312,6 +354,7 @@ int cipher_aes128cbc_encrypt(const char *data,char *output,int &len,char * key)
int cipher_aes128cfb_encrypt(const char *data,char *output,int &len,char * key)
{
static int first_time=1;
assert(len>=16);
char buf[buf_len];
memcpy(buf,data,len);//TODO inefficient code
@@ -320,6 +363,10 @@ int cipher_aes128cfb_encrypt(const char *data,char *output,int &len,char * key)
if(first_time==0) key=0;
else first_time=0;
}
if(!aes128cfb_old)
{
aes_ecb_encrypt(data,buf); //encrypt the first block
}
AES_CFB_encrypt_buffer((unsigned char *)output,(unsigned char *)buf,len,(unsigned char *)key,(unsigned char *)zero_iv);
return 0;
@@ -363,12 +410,19 @@ int cipher_aes128cbc_decrypt(const char *data,char *output,int &len,char * key)
int cipher_aes128cfb_decrypt(const char *data,char *output,int &len,char * key)
{
static int first_time=1;
if(len<16) return -1;
if(aes_key_optimize)
{
if(first_time==0) key=0;
else first_time=0;
}
AES_CFB_decrypt_buffer((unsigned char *)output,(unsigned char *)data,len,(unsigned char *)key,(unsigned char *)zero_iv);
if(!aes128cfb_old)
aes_ecb_decrypt1(output); //decrypt the first block
//if(de_padding(output,len,16)<0) return -1;
return 0;
}

View File

@@ -12,6 +12,7 @@
//extern char key[16];
const int aes_key_optimize=1; //if enabled,once you used a key for aes,you cant change it anymore
extern int aes128cfb_old;
int my_init_keys(const char *,int);
@@ -34,10 +35,15 @@ extern cipher_mode_t cipher_mode;
extern unordered_map<int, const char *> auth_mode_tostring;
extern unordered_map<int, const char *> cipher_mode_tostring;
extern char gro_xor[256+100];
int cipher_decrypt(const char *data,char *output,int &len,char * key);//internal interface ,exposed for test only
int cipher_encrypt(const char *data,char *output,int &len,char * key);//internal interface ,exposed for test only
void aes_ecb_encrypt(const char *data,char *output);
void aes_ecb_decrypt(const char *data,char *output);
void aes_ecb_encrypt1(char *data);
void aes_ecb_decrypt1(char *data);
#endif

View File

@@ -0,0 +1 @@

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

View File

@@ -7,9 +7,8 @@
#include <stdint.h>
//not used
//void AES_ECB_encrypt(const uint8_t* input, const uint8_t* key, uint8_t *output, const uint32_t length);
//void AES_ECB_decrypt(const uint8_t* input, const uint8_t* key, uint8_t *output, const uint32_t length);
void AES_ECB_encrypt_buffer(const uint8_t* input, const uint8_t* key, uint8_t *output);
void AES_ECB_decrypt_buffer(const uint8_t* input, const uint8_t* key, uint8_t *output);
void AES_CBC_encrypt_buffer(uint8_t* output, uint8_t* input, uint32_t length, const uint8_t* key, const uint8_t* iv);
void AES_CBC_decrypt_buffer(uint8_t* output, uint8_t* input, uint32_t length, const uint8_t* key, const uint8_t* iv);

View File

@@ -366,32 +366,25 @@ void AES_CBC_decrypt_buffer(uint8_t* output, uint8_t* input, uint32_t length, co
decrypt_cbc(rk, length, iv_tmp, input, output);
}
/*
void AES_ECB_encrypt(const uint8_t* input, const uint8_t* key, uint8_t* output, const uint32_t length)
void AES_ECB_encrypt_buffer(const uint8_t* input, const uint8_t* key, uint8_t* output)
{
uint8_t rk[AES_RKSIZE];
static uint8_t rk[AES_RKSIZE];
if (key == NULL)
{
return;
}
aeshw_init();
setkey_enc(rk, key);
if(key!=NULL)
setkey_enc(rk, key);
encrypt_ecb(AES_NR, rk, input, output);
}
void AES_ECB_decrypt(const uint8_t* input, const uint8_t* key, uint8_t *output, const uint32_t length)
void AES_ECB_decrypt_buffer(const uint8_t* input, const uint8_t* key, uint8_t *output)
{
uint8_t rk[AES_RKSIZE];
static uint8_t rk[AES_RKSIZE];
if (key == NULL)
{
return;
}
aeshw_init();
setkey_dec(rk, key);
if(key!=NULL)
setkey_dec(rk, key);
decrypt_ecb(AES_NR, rk, input, output);
}*/
}
static void encrypt_cfb( uint8_t* rk,
uint32_t length,size_t *iv_off,

View File

@@ -12,15 +12,29 @@
#endif
void AES_ECB_encrypt(const uint8_t* input, const uint8_t* key, uint8_t *output, const uint32_t length)
void AES_ECB_encrypt_buffer(const uint8_t* input, const uint8_t* key, uint8_t *output)
{
printf("AES_ECB_encrypt not implemented\n");
exit(-1);
static aes_context ctx;
if(key!=0)
{
aes_init( &ctx);
aes_setkey_enc(&ctx,key,AES_KEYSIZE);
}
int ret=aes_crypt_ecb( &ctx, AES_ENCRYPT, (const unsigned char*)input,(unsigned char*) output );
assert(ret==0);
return ;
}
void AES_ECB_decrypt(const uint8_t* input, const uint8_t* key, uint8_t *output, const uint32_t length)
void AES_ECB_decrypt_buffer(const uint8_t* input, const uint8_t* key, uint8_t *output)
{
printf("AES_ECB_encrypt not implemented\n");
exit(-1);
static aes_context ctx;
if(key!=0)
{
aes_init( &ctx);
aes_setkey_dec(&ctx,key,AES_KEYSIZE);
}
int ret=aes_crypt_ecb( &ctx, AES_DECRYPT, (const unsigned char*)input,(unsigned char*) output );
assert(ret==0);
return ;
}
void AES_CBC_encrypt_buffer(uint8_t* output, uint8_t* input, uint32_t length, const uint8_t* key, const uint8_t* iv)

View File

@@ -25,7 +25,6 @@ void sigint_cb(struct ev_loop *l, ev_signal *w, int revents)
}
int client_event_loop();
int server_event_loop();
int main(int argc, char *argv[])
{
@@ -33,6 +32,8 @@ int main(int argc, char *argv[])
assert(sizeof(unsigned int)==4);
assert(sizeof(unsigned long long)==8);
init_ws();
dup2(1, 2);//redirect stderr to stdout
#if defined(__MINGW32__)
enable_log_color=0;
@@ -48,7 +49,6 @@ int main(int argc, char *argv[])
ev_signal_init(&signal_watcher_sigpipe, sigpipe_cb, SIGPIPE);
ev_signal_start(loop, &signal_watcher_sigpipe);
#endif
ev_signal signal_watcher_sigterm;
ev_signal_init(&signal_watcher_sigterm, sigterm_cb, SIGTERM);
ev_signal_start(loop, &signal_watcher_sigterm);
@@ -59,11 +59,15 @@ int main(int argc, char *argv[])
}
else
{
mylog(log_fatal,"server mode not supported in multi-platform version\n");
myexit(-1);
/*
signal(SIGINT, signal_handler);
signal(SIGHUP, signal_handler);
signal(SIGKILL, signal_handler);
signal(SIGTERM, signal_handler);
signal(SIGQUIT, signal_handler);
*/
}
#if !defined(__MINGW32__)
if(geteuid() != 0)
@@ -87,7 +91,8 @@ int main(int argc, char *argv[])
my_init_keys(key_string,program_mode==client_mode?1:0);
iptables_rule();
init_raw_socket();
//init_raw_socket();
//init_raw_socket() has to be done after dev dectection in mp version
if(program_mode==client_mode)
{
@@ -95,7 +100,11 @@ int main(int argc, char *argv[])
}
else
{
mylog(log_fatal,"server mode not supported in multi-platform version\n");
myexit(-1);
/*
server_event_loop();
*/
}
return 0;

121
makefile
View File

@@ -8,84 +8,91 @@ cc_mips24kc_le=/toolchains/lede-sdk-17.01.2-ramips-mt7621_gcc-5.4.0_musl-1.1.16.
cc_arm= /toolchains/arm-2014.05/bin/arm-none-linux-gnueabi-g++
#cc_arm=/toolchains/lede-sdk-17.01.2-brcm2708-bcm2708_gcc-5.4.0_musl-1.1.16_eabi.Linux-x86_64/staging_dir/toolchain-arm_arm1176jzf-s+vfp_gcc-5.4.0_musl-1.1.16_eabi/bin/arm-openwrt-linux-muslgnueabi-g++
#cc_bcm2708=/home/wangyu/raspberry/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++
cc_tmp= /home/wangyu/OpenWrt-SDK-15.05-x86-64_gcc-4.8-linaro_uClibc-0.9.33.2.Linux-x86_64/staging_dir/toolchain-x86_64_gcc-4.8-linaro_uClibc-0.9.33.2/bin/x86_64-openwrt-linux-uclibc-g++
cc_mingw_cross=i686-w64-mingw32-g++-posix
FLAGS= -std=c++11 -Wall -Wextra -Wno-unused-variable -Wno-unused-parameter -Wno-missing-field-initializers ${OPT}
COMMON=main.cpp lib/md5.cpp lib/pbkdf2-sha1.cpp lib/pbkdf2-sha256.cpp encrypt.cpp log.cpp network.cpp common.cpp connection.cpp misc.cpp fd_manager.cpp client.cpp server.cpp -lpthread my_ev.cpp -isystem libev
SOURCES= $(COMMON) lib/aes_faster_c/aes.cpp lib/aes_faster_c/wrapper.cpp
SOURCES_TINY_AES= $(COMMON) lib/aes.c
COMMON=main.cpp lib/md5.cpp encrypt.cpp log.cpp network.cpp common.cpp connection.cpp misc.cpp fd_manager.cpp client.cpp -lpthread
PCAP="-lpcap"
LIBNET=-D_DEFAULT_SOURCE `libnet-config --defines` `libnet-config --libs`
SOURCES0= $(COMMON) lib/aes_faster_c/aes.cpp lib/aes_faster_c/wrapper.cpp lib/pbkdf2-sha1.cpp lib/pbkdf2-sha256.cpp
SOURCES=${SOURCES0} my_ev.cpp -isystem libev
SOURCES_TINY_AES= $(COMMON) lib/aes.cpp
SOURCES_AES_ACC=$(COMMON) $(wildcard lib/aes_acc/aes*.c)
NAME=udp2raw
NAME=udp2raw_mp
OUTPUTS=${NAME} ${NAME}_nolibnet ${NAME}.exe ${NAME}_nolibnet.exe
TARGETS=amd64 arm amd64_hw_aes arm_asm_aes mips24kc_be mips24kc_be_asm_aes x86 x86_asm_aes mips24kc_le mips24kc_le_asm_aes
TAR=${NAME}_binaries.tar.gz `echo ${TARGETS}|sed -r 's/([^ ]+)/udp2raw_\1/g'` version.txt
all:git_version
rm -f ${NAME}
${cc_local} -o ${NAME} -I. ${SOURCES} ${FLAGS} -lrt -ggdb -static -O3
echo "\ndo not use 'make all', instead, use 'make linux' 'make mac' 'make freebsd' 'make cygwin' \nyou can also try 'make linux_nolibnet' 'make mac_nolibnet' 'make freebsd_nolibnet' "
cygwin:git_version
rm -f ${OUTPUTS}
${cc_local} -o ${NAME}_nolibnet -I. ${SOURCES} pcap_wrapper.cpp ${FLAGS} -lrt -ggdb -static -O2 -D_GNU_SOURCE
mingw:git_version
rm -f ${OUTPUTS}
${cc_local} -o ${NAME}_nolibnet -I. ${SOURCES} pcap_wrapper.cpp ${FLAGS} -ggdb -static -O2 -lws2_32
mingw_cross:git_version
${cc_mingw_cross} -o ${NAME}_nolibnet.exe -I. ${SOURCES} pcap_wrapper.cpp ${FLAGS} -ggdb -static -O2 -lws2_32
mingw_cross_wepoll:git_version
${cc_mingw_cross} -o ${NAME}_nolibnet_wepoll.exe -I. ${SOURCES0} pcap_wrapper.cpp ${FLAGS} -ggdb -static -O2 -DNO_LIBEV_EMBED -D_WIN32 -lev -lws2_32
linux:git_version
rm -f ${OUTPUTS}
${cc_local} -o ${NAME} -I. ${SOURCES} ${PCAP} ${LIBNET} ${FLAGS} -lrt -ggdb -static -O2
linux_nolibnet:git_version
rm -f ${OUTPUTS}
${cc_local} -o ${NAME}_nolibnet -I. ${SOURCES} ${PCAP} ${FLAGS} -lrt -ggdb -static -O2 -DNO_LIBNET
freebsd:git_version
rm -f ${OUTPUTS}
${cc_local} -o ${NAME} -I. ${SOURCES} ${PCAP} ${LIBNET} ${FLAGS} -lrt -ggdb -static -O2
freebsd_nolibnet:git_version
rm -f ${OUTPUTS}
${cc_local} -o ${NAME}_nolibnet -I. ${SOURCES} ${PCAP} ${FLAGS} -lrt -ggdb -static -O2 -DNO_LIBNET
mac:git_version
rm -f ${OUTPUTS}
${cc_local} -o ${NAME} -I. ${SOURCES} ${PCAP} ${LIBNET} ${FLAGS} -ggdb -O2
mac_nolibnet:git_version
rm -f ${OUTPUTS}
${cc_local} -o ${NAME}_nolibnet -I. ${SOURCES} ${PCAP} ${FLAGS} -ggdb -O2 -DNO_LIBNET
mac_nolibnet_static:git_version #it doesnt work
rm -f ${OUTPUTS}
${cc_local} -o ${NAME} -I. ${SOURCES} -static-libstdc++ /usr/local/Cellar/libpcap/1.8.1/lib/libpcap.a ${FLAGS} -ggdb -O2 -DNO_LIBNET
fast: git_version
rm -f ${NAME}
${cc_local} -o ${NAME} -I. ${SOURCES} ${FLAGS} -lrt -ggdb
debug: git_version
rm -f ${NAME}
${cc_local} -o ${NAME} -I. ${SOURCES} ${FLAGS} -lrt -Wformat-nonliteral -D MY_DEBUG
${cc_local} -o ${NAME} -I. ${SOURCES} ${PCAP} ${LIBNET} ${FLAGS} -lrt -ggdb -static -O2 -Wformat-nonliteral -D MY_DEBUG
debug2: git_version
rm -f ${NAME}
${cc_local} -o ${NAME} -I. ${SOURCES} ${FLAGS} -lrt -Wformat-nonliteral -ggdb
dynamic: git_version
${cc_local} -o ${NAME}_$@ -I. ${SOURCES} ${FLAGS} -lrt -O3
mips24kc_be: git_version
${cc_mips24kc_be} -o ${NAME}_$@ -I. ${SOURCES} ${FLAGS} -lrt -lgcc_eh -static -O3
mips24kc_be_asm_aes: git_version
${cc_mips24kc_be} -o ${NAME}_$@ -I. ${SOURCES_AES_ACC} ${FLAGS} -lrt -lgcc_eh -static -O3 lib/aes_acc/asm/mips_be.S
mips24kc_le: git_version
${cc_mips24kc_le} -o ${NAME}_$@ -I. ${SOURCES} ${FLAGS} -lrt -lgcc_eh -static -O3
mips24kc_le_asm_aes: git_version
${cc_mips24kc_le} -o ${NAME}_$@ -I. ${SOURCES_AES_ACC} ${FLAGS} -lrt -lgcc_eh -static -O3 lib/aes_acc/asm/mips.S
#bcm2708:
# ${cc_bcm2708} -o ${NAME}_bcm2708 -I. ${SOURCES} ${FLAGS} -lrt -static -O3
amd64:git_version
${cc_local} -o ${NAME}_$@ -I. ${SOURCES} ${FLAGS} -lrt -static -O3
amd64_perf:git_version
${cc_local} -o ${NAME}_$@ -I. ${SOURCES} ${FLAGS} -lrt -static -O0 -fno-omit-frame-pointer -g
amd64_hw_aes:git_version
${cc_local} -o ${NAME}_$@ -I. ${SOURCES_AES_ACC} ${FLAGS} -lrt -static -O3 lib/aes_acc/asm/x64.S
x86:git_version
${cc_local} -o ${NAME}_$@ -I. ${SOURCES} ${FLAGS} -lrt -static -O3 -m32
x86_asm_aes:git_version
${cc_local} -o ${NAME}_$@ -I. ${SOURCES_AES_ACC} ${FLAGS} -lrt -static -O3 -m32 lib/aes_acc/asm/x86.S
arm:git_version
${cc_arm} -o ${NAME}_$@ -I. ${SOURCES} ${FLAGS} -lrt -static -O3
arm_perf:git_version
${cc_arm} -o ${NAME}_$@ -I. ${SOURCES} ${FLAGS} -lrt -static -mapcs-frame -fno-omit-frame-pointer -g -O0 -lgcc_eh
arm_asm_aes:git_version
${cc_arm} -o ${NAME}_$@ -I. ${SOURCES_AES_ACC} ${FLAGS} -lrt -static -O3 lib/aes_acc/asm/arm.S
cross:git_version
${cc_cross} -o ${NAME}_cross -I. ${SOURCES} ${FLAGS} -lrt -O3
cross2:git_version
${cc_cross} -o ${NAME}_cross -I. ${SOURCES} ${FLAGS} -lrt -static -lgcc_eh -O3
cross3:git_version
${cc_cross} -o ${NAME}_cross -I. ${SOURCES} ${FLAGS} -lrt -static -O3
release: ${TARGETS}
cp git_version.h version.txt
tar -zcvf ${TAR}
#dynamic: git_version
# ${cc_local} -o ${NAME}_$@ -I. ${SOURCES} ${FLAGS} -lrt -O3
clean:
rm -f ${TAR}
rm -f udp2raw.exe ${OUTPUTS}
rm -f udp2raw udp2raw_cross udp2raw_cmake udp2raw_dynamic
rm -f git_version.h
git_version:
echo "const char *gitversion = \"$(shell git rev-parse HEAD)\";" > git_version.h

221
misc.cpp
View File

@@ -47,8 +47,8 @@ my_id_t const_id=0;//an id used for connection recovery,its generated randomly,i
int udp_fd=-1; //for client only. client use this fd to listen and handle udp connection
int bind_fd=-1; //bind only,never send or recv. its just a dummy fd for bind,so that other program wont occupy the same port
int epollfd=-1; //fd for epoll
int timer_fd=-1; //the general timer fd for client and server.for server this is not the only timer find,every connection has a timer fd.
//int epollfd=-1; //fd for epoll
//int timer_fd=-1; //the general timer fd for client and server.for server this is not the only timer find,every connection has a timer fd.
int fail_time_counter=0;//determine if the max_fail_time is reached
int epoll_trigger_counter=0;//for debug only
int debug_flag=0;//for debug only
@@ -70,12 +70,6 @@ char fifo_file[1000]="";
int clear_iptables=0;
int wait_xtables_lock=0;
string iptables_command0="iptables/ip6tables ";
string iptables_command="";
string iptables_pattern="";
int iptables_rule_added=0;
int iptables_rule_keeped=0;
int iptables_rule_keep_index=0;
program_mode_t program_mode=unset_mode;//0 unset; 1client 2server
raw_mode_t raw_mode=mode_faketcp;
@@ -94,6 +88,7 @@ int socket_buf_size=1024*1024;
//char lower_level_arg[1000];
/*
int process_lower_level_arg()//handle --lower-level option
{
lower_level=1;
@@ -121,7 +116,7 @@ int process_lower_level_arg()//handle --lower-level option
dest_hw_addr[i] = uint8_t(hw[i]);
}
return 0;
}
}*/
void print_help()
{
char git_version_buf[100]={0};
@@ -131,12 +126,16 @@ void print_help()
printf("build date:%s %s\n",__DATE__,__TIME__);
printf("repository: https://github.com/wangyu-/udp2raw-tunnel\n");
printf("\n");
#ifdef NO_LIBNET
printf("libnet is disabled at compile time\n");
printf("\n");
#endif
printf("usage:\n");
printf(" run as client : ./this_program -c -l local_listen_ip:local_port -r server_address:server_port [options]\n");
printf(" run as server : ./this_program -s -l server_listen_ip:server_port -r remote_address:remote_port [options]\n");
printf("\n");
printf("common options,these options must be same on both side:\n");
printf(" --raw-mode <string> avaliable values:faketcp(default),udp,icmp\n");
printf(" --raw-mode <string> avaliable values:faketcp(default),udp,icmp and easy-faketcp\n");
printf(" -k,--key <string> password to gen symetric key,default:\"secret key\"\n");
printf(" --cipher-mode <string> avaliable values:aes128cfb,aes128cbc(default),xor,none\n");
printf(" --auth-mode <string> avaliable values:hmac_sha1,md5(default),crc32,simple,none\n");
@@ -144,6 +143,8 @@ void print_help()
printf(" -g,--gen-rule generate iptables rule then exit,so that you can copy and\n");
printf(" add it manually.overrides -a\n");
printf(" --disable-anti-replay disable anti-replay,not suggested\n");
printf(" --fix-gro try to fix huge packet caused by GRO. this option is at an early stage.\n");
printf(" make sure client and server are at same version.\n");
//printf("\n");
printf("client options:\n");
@@ -164,7 +165,6 @@ void print_help()
printf(" --disable-bpf disable the kernel space filter,most time its not necessary\n");
printf(" unless you suspect there is a bug\n");
// printf("\n");
printf(" --dev <string> bind raw socket to a device, not necessary but improves performance\n");
printf(" --sock-buf <number> buf size for socket,>=10 and <=10240,unit:kbyte,default:1024\n");
printf(" --force-sock-buf bypass system limitation while setting sock-buf\n");
printf(" --seq-mode <number> seq increase mode for faketcp:\n");
@@ -186,7 +186,6 @@ void print_help()
printf(" --clear clear any iptables rules added by this program.overrides everything\n");
printf(" --retry-on-error retry on error, allow to start udp2raw before network is initialized\n");
printf(" -h,--help print this help message\n");
//printf("common options,these options must be same on both side\n");
}
@@ -297,7 +296,10 @@ void process_arg(int argc, char *argv[]) //process all options
{"set-ttl", required_argument, 0, 1},
{"dev", required_argument, 0, 1},
{"dns-resolve", no_argument, 0, 1},
{"pcap-send", no_argument, 0, 1},
{"easy-tcp", no_argument, 0, 1},
{"no-pcap-mutex", no_argument, 0, 1},
{"fix-gro", no_argument, 0, 1},
{NULL, 0, 0, 0}
};
@@ -466,6 +468,8 @@ void process_arg(int argc, char *argv[]) //process all options
case 'h':
break;
case 'a':
mylog(log_fatal,"-a not supported in this version, check -g or --raw-mode easyfaketcp\n");
myexit(-1);
auto_add_iptables_rule=1;
break;
case 'g':
@@ -479,6 +483,9 @@ void process_arg(int argc, char *argv[]) //process all options
mylog(log_debug,"option_index: %d\n",option_index);
if(strcmp(long_options[option_index].name,"clear")==0)
{
mylog(log_fatal,"--clear not supported in this version\n");
myexit(-1);
clear_iptables=1;
}
else if(strcmp(long_options[option_index].name,"source-ip")==0)
@@ -561,9 +568,16 @@ void process_arg(int argc, char *argv[]) //process all options
}
else if(strcmp(long_options[option_index].name,"cipher-mode")==0)
{
string s=optarg;
if(s=="aes128cfb_0")
{
s="aes128cfb";
aes128cfb_old=1;
mylog(log_warn,"aes128cfb_0 is used\n");
}
for(i=0;i<cipher_end;i++)
{
if(strcmp(optarg,cipher_mode_tostring[i])==0)
if(strcmp(s.c_str(),cipher_mode_tostring[i])==0)
{
cipher_mode=(cipher_mode_t)i;
break;
@@ -581,20 +595,30 @@ void process_arg(int argc, char *argv[]) //process all options
}
else if(strcmp(long_options[option_index].name,"lower-level")==0)
{
process_lower_level_arg();
//process_lower_level_arg();
mylog(log_fatal,"--lower-level not supported in this version\n");
myexit(-1);
//lower_level=1;
//strcpy(lower_level_arg,optarg);
}
else if(strcmp(long_options[option_index].name,"simple-rule")==0)
{
mylog(log_fatal,"--simple-rule not supported in this version\n");
myexit(-1);
simple_rule=1;
}
else if(strcmp(long_options[option_index].name,"keep-rule")==0)
{
mylog(log_fatal,"--keep-rule not supported in this version\n");
myexit(-1);
keep_rule=1;
}
else if(strcmp(long_options[option_index].name,"gen-add")==0)
{
mylog(log_fatal,"--gen-add not supported in this version\n");
myexit(-1);
generate_iptables_rule_add=1;
}
else if(strcmp(long_options[option_index].name,"disable-color")==0)
@@ -627,6 +651,8 @@ void process_arg(int argc, char *argv[]) //process all options
}
else if(strcmp(long_options[option_index].name,"force-sock-buf")==0)
{
mylog(log_fatal,"--force-sock-buf not supported in this version\n");
myexit(-1);
force_socket_buf=1;
}
else if(strcmp(long_options[option_index].name,"retry-on-error")==0)
@@ -683,6 +709,8 @@ void process_arg(int argc, char *argv[]) //process all options
}
else if(strcmp(long_options[option_index].name,"fifo")==0)
{
mylog(log_fatal,"--fifo not supported in this version\n");
myexit(-1);
sscanf(optarg,"%s",fifo_file);
mylog(log_info,"fifo_file =%s \n",fifo_file);
@@ -733,11 +761,26 @@ void process_arg(int argc, char *argv[]) //process all options
enable_dns_resolve=1;
mylog(log_info,"dns-resolve enabled\n");
}
else if(strcmp(long_options[option_index].name,"pcap-send")==0)
{
send_with_pcap=1;
mylog(log_info,"--pcap-send enabled, now pcap will be used for sending packet instead of libnet\n");
}
else if(strcmp(long_options[option_index].name,"no-pcap-mutex")==0)
{
use_pcap_mutex=0;
mylog(log_warn,"--no-pcap-mutex enabled, we will assume the underlying pcap calls are threadsafe\n");
}
else if(strcmp(long_options[option_index].name,"easy-tcp")==0)
{
use_tcp_dummy_socket=1;
mylog(log_info,"--easy-tcp enabled, now a dummy tcp socket will be created for handshake and block rst\n");
}
else if(strcmp(long_options[option_index].name,"fix-gro")==0)
{
mylog(log_info,"--fix-gro enabled\n");
g_fix_gro=1;
}
else
{
mylog(log_warn,"ignored unknown long option ,option_index:%d code:<%x>\n",option_index, optopt);
@@ -890,6 +933,7 @@ void pre_process_arg(int argc, char *argv[])//mainly for load conf file
process_arg(new_argc,new_argv_char);
}
/*
void *run_keep(void *none) //called in a new thread for --keep-rule option
{
@@ -1020,29 +1064,6 @@ void iptables_rule() // handles -a -g --gen-add --keep-rule --clear --wait-loc
}
pattern+=tmp_pattern;
}
/*
if(!simple_rule)
{
pattern += " -m comment --comment udp2rawDwrW_";
char const_id_str[100];
sprintf(const_id_str, "%x_", const_id);
pattern += const_id_str;
time_t timer;
char buffer[26];
struct tm* tm_info;
time(&timer);
tm_info = localtime(&timer);
strftime(buffer, 26, "%Y-%m-%d-%H:%M:%S", tm_info);
pattern += buffer;
}*/
if(generate_iptables_rule)
{
@@ -1078,7 +1099,7 @@ void iptables_rule() // handles -a -g --gen-add --keep-rule --clear --wait-loc
mylog(log_warn," -a has not been set, make sure you have added the needed iptables rules manually\n");
}
}
*/
int unit_test()
{
printf("running unit test\n");
@@ -1137,6 +1158,7 @@ int unit_test()
return 0;
}
/*
int set_timer(int epollfd,int &timer_fd)//put a timer_fd into epoll,general function,used both in client and server
{
int ret;
@@ -1308,19 +1330,6 @@ int iptables_rule_init(const char * s,u32_t const_id,int keep)
int keep_iptables_rule() //magic to work on a machine without grep/iptables --check/-m commment
{
/*
if(iptables_rule_keeped==0) return 0;
uint64_t tmp_current_time=get_current_time();
if(tmp_current_time-keep_rule_last_time<=iptables_rule_keep_interval)
{
return 0;
}
else
{
keep_rule_last_time=tmp_current_time;
}*/
mylog(log_debug,"keep_iptables_rule begin %llu\n",get_current_time());
iptables_rule_keep_index+=1;
@@ -1366,6 +1375,116 @@ int clear_iptables_rule()
return 0;
}
*/
void iptables_rule() // handles -a -g --gen-add --keep-rule --clear --wait-lock
{
if(generate_iptables_rule)
{
if(raw_mode==mode_faketcp && use_tcp_dummy_socket==1)
{
mylog(log_fatal, "failed,-g doesnt work with easy-faketcp mode\n");
myexit(-1);
}
if(raw_mode==mode_udp)
{
mylog(log_warn, "It not necessary to use iptables/firewall rule in udp mode\n");
}
log_bare(log_warn,"for linux, use:\n");
if(raw_ip_version==AF_INET)
{
if(raw_mode==mode_faketcp)
printf("iptables -I INPUT -s %s -p tcp -m tcp --sport %d -j DROP\n",remote_addr.get_ip(),remote_addr.get_port());
if(raw_mode==mode_udp)
printf("iptables -I INPUT -s %s -p udp -m udp --sport %d -j DROP\n",remote_addr.get_ip(),remote_addr.get_port());
if(raw_mode==mode_icmp)
printf("iptables -I INPUT -s %s -p icmp --icmp-type 0 -j DROP\n",remote_addr.get_ip());
printf("\n");
}
else
{
assert(raw_ip_version==AF_INET6);
if(raw_mode==mode_faketcp)
printf("ip6tables -I INPUT -s %s -p tcp -m tcp --sport %d -j DROP\n",remote_addr.get_ip(),remote_addr.get_port());
if(raw_mode==mode_udp)
printf("ip6tables -I INPUT -s %s -p udp -m udp --sport %d -j DROP\n",remote_addr.get_ip(),remote_addr.get_port());
if(raw_mode==mode_icmp)
printf("ip6tables -I INPUT -s %s -p -p icmpv6 --icmpv6-type 129 -j DROP\n",remote_addr.get_ip());
printf("\n");
}
log_bare(log_warn,"for mac/bsd use:\n");
if(raw_ip_version==AF_INET)
{
if(raw_mode==mode_faketcp)
printf("echo 'block drop inet proto tcp from %s port %d to any' > ./1.conf\n",remote_addr.get_ip(),remote_addr.get_port());
if(raw_mode==mode_udp)
printf("echo 'block drop inet proto udp from %s port %d to any' > ./1.conf\n",remote_addr.get_ip(),remote_addr.get_port());
if(raw_mode==mode_icmp)
printf("echo 'block drop inet proto icmp from %s to any' > ./1.conf\n",remote_addr.get_ip());
}
else
{
assert(raw_ip_version==AF_INET6);
if(raw_mode==mode_faketcp)
printf("echo 'block drop inet6 proto tcp from %s port %d to any' > ./1.conf\n",remote_addr.get_ip(),remote_addr.get_port());
if(raw_mode==mode_udp)
printf("echo 'block drop inet6 proto udp from %s port %d to any' > ./1.conf\n",remote_addr.get_ip(),remote_addr.get_port());
if(raw_mode==mode_icmp)
printf("echo 'block drop inet6 proto icmp6 from %s to any' > ./1.conf\n",remote_addr.get_ip());
}
printf("pfctl -f ./1.conf\n");
printf("pfctl -e\n");
printf("\n");
log_bare(log_warn,"for windows vista and above use:\n");
if(raw_ip_version==AF_INET)
{
if(raw_mode==mode_faketcp)
{
printf("netsh advfirewall firewall add rule name=udp2raw protocol=TCP dir=in remoteip=%s remoteport=%d action=block\n",remote_addr.get_ip(),remote_addr.get_port());
printf("netsh advfirewall firewall add rule name=udp2raw protocol=TCP dir=out remoteip=%s remoteport=%d action=block\n",remote_addr.get_ip(),remote_addr.get_port());
}
if(raw_mode==mode_udp)
{
printf("netsh advfirewall firewall add rule name=udp2raw protocol=UDP dir=in remoteip=%s remoteport=%d action=block\n",remote_addr.get_ip(),remote_addr.get_port());
printf("netsh advfirewall firewall add rule name=udp2raw protocol=UDP dir=out remoteip=%s remoteport=%d action=block\n",remote_addr.get_ip(),remote_addr.get_port());
}
if(raw_mode==mode_icmp)
{
printf("netsh advfirewall firewall add rule name=udp2raw protocol=ICMPV4 dir=in remoteip=%s action=block\n",remote_addr.get_ip());
printf("netsh advfirewall firewall add rule name=udp2raw protocol=ICMPV4 dir=out remoteip=%s action=block\n",remote_addr.get_ip());
}
}
else
{
assert(raw_ip_version==AF_INET6);
if(raw_mode==mode_faketcp)
{
printf("netsh advfirewall firewall add rule name=udp2raw protocol=TCP dir=in remoteip=%s remoteport=%d action=block\n",remote_addr.get_ip(),remote_addr.get_port());
printf("netsh advfirewall firewall add rule name=udp2raw protocol=TCP dir=out remoteip=%s remoteport=%d action=block\n",remote_addr.get_ip(),remote_addr.get_port());
}
if(raw_mode==mode_udp)
{
printf("netsh advfirewall firewall add rule name=udp2raw protocol=UDP dir=in remoteip=%s remoteport=%d action=block\n",remote_addr.get_ip(),remote_addr.get_port());
printf("netsh advfirewall firewall add rule name=udp2raw protocol=UDP dir=out remoteip=%s remoteport=%d action=block\n",remote_addr.get_ip(),remote_addr.get_port());
}
if(raw_mode==mode_icmp)
{
printf("netsh advfirewall firewall add rule name=udp2raw protocol=ICMPV6 dir=in remoteip=%s action=block\n",remote_addr.get_ip());
printf("netsh advfirewall firewall add rule name=udp2raw protocol=ICMPV6 dir=out remoteip=%s action=block\n",remote_addr.get_ip());
}
}
myexit(0);
}
}
void signal_handler(int sig)
{
about_to_exit=1;

15
misc.h
View File

@@ -75,10 +75,12 @@ union current_state_t
client_current_state_t client_current_state;
};
extern char remote_address[max_addr_len];
//extern char remote_address[max_address_len];
//extern char local_ip[100], remote_ip[100],source_ip[100];//local_ip is for -l option,remote_ip for -r option,source for --source-ip
//extern u32_t local_ip_uint32,remote_ip_uint32,source_ip_uint32;//convert from last line.
//extern int local_port , remote_port,source_port;//similiar to local_ip remote_ip,buf for port.source_port=0 indicates --source-port is not enabled
extern char local_ip[100], remote_ip[100],source_ip[100];//local_ip is for -l option,remote_ip for -r option,source for --source-ip
extern u32_t local_ip_uint32,remote_ip_uint32,source_ip_uint32;//convert from last line.
extern int local_port , remote_port,source_port;//similiar to local_ip remote_ip,buf for port.source_port=0 indicates --source-port is not enabled
extern address_t local_addr,remote_addr,source_addr;
@@ -93,8 +95,8 @@ extern my_id_t const_id;//an id used for connection recovery,its generated rando
extern int udp_fd; //for client only. client use this fd to listen and handle udp connection
extern int bind_fd; //bind only,never send or recv. its just a dummy fd for bind,so that other program wont occupy the same port
extern int epollfd; //fd for epoll
extern int timer_fd; //the general timer fd for client and server.for server this is not the only timer find,every connection has a timer fd.
//extern int epollfd; //fd for epoll
//extern int timer_fd; //the general timer fd for client and server.for server this is not the only timer find,every connection has a timer fd.
extern int fail_time_counter;//determine if the max_fail_time is reached
extern int epoll_trigger_counter;//for debug only
extern int debug_flag;//for debug only
@@ -124,11 +126,12 @@ extern int about_to_exit;
extern int socket_buf_size;
extern pthread_t keep_thread;
extern int keep_thread_running;
int process_lower_level_arg();
void print_help();
void iptables_rule();

View File

@@ -9,6 +9,8 @@
#include "log.h"
#include "misc.h"
int g_fix_gro=0;
int raw_recv_fd=-1;
int raw_send_fd=-1;
u32_t link_level_header_len=0;//set it to 14 if SOCK_RAW is used in socket(PF_PACKET, SOCK_RAW, htons(ETH_P_IP));
@@ -33,26 +35,58 @@ char dev[100]="";
unsigned short g_ip_id_counter=0;
unsigned char dest_hw_addr[sizeof(sockaddr_ll::sll_addr)]=
{0xff,0xff,0xff,0xff,0xff,0xff,0,0};
//unsigned char dest_hw_addr[sizeof(sockaddr_ll::sll_addr)]=
// {0xff,0xff,0xff,0xff,0xff,0xff,0,0};
//{0x00,0x23,0x45,0x67,0x89,0xb9};
const u32_t receive_window_lower_bound=40960;
const u32_t receive_window_random_range=512;
const unsigned char wscale=0x05;
char g_packet_buf[buf_len]; //looks dirty but works well
char g_packet_buf[huge_buf_len]; //looks dirty but works well
int g_packet_buf_len=-1;
int g_packet_buf_cnt=0;
/*
union
{
sockaddr_ll ll;
sockaddr_in ipv4;
sockaddr_in6 ipv6;
}g_sockaddr;
socklen_t g_sockaddr_len = -1;
socklen_t g_sockaddr_len = -1;*/
#ifndef NO_LIBNET
libnet_t *libnet_handle;
libnet_ptag_t g_ptag=0;
int send_with_pcap=0;
#else
int send_with_pcap=1;
#endif
int pcap_header_captured=0;
int pcap_header_buf[buf_len];
int pcap_captured_full_len=-1;
pcap_t *pcap_handle;
int pcap_link_header_len=-1;
//int pcap_cnt=0;
queue_t my_queue;
pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t pcap_mutex = PTHREAD_MUTEX_INITIALIZER;
int use_pcap_mutex=1;
ev_async async_watcher;
struct ev_loop* g_default_loop;
pthread_t pcap_recv_thread;
struct bpf_program g_filter;
long long g_filter_compile_cnt=0;
#if 0
struct sock_filter code_tcp_old[] = {
{ 0x28, 0, 0, 0x0000000c },//0
{ 0x15, 0, 10, 0x00000800 },//1
@@ -216,6 +250,7 @@ tcpdump -i eth1 ip and icmp -dd
(010) ret #0
*/
#endif
packet_info_t::packet_info_t()
{
@@ -254,7 +289,92 @@ packet_info_t::packet_info_t()
}
void my_packet_handler(
u_char *args,
const struct pcap_pkthdr *packet_header,
const u_char *pkt_data
)
{
/*printf("<%d %d>\n",(int)packet_header->caplen,(int)packet_header->len );
for(int i=0;i<sizeof(pcap_pkthdr);i++)
{
char *p=(char *) packet_header;
printf("<%x>",int( p[i] ));
}
printf("\n");*/
//mylog(log_debug,"received a packet!\n");
assert(packet_header->caplen <= packet_header->len);
assert(packet_header->caplen <= max_data_len);
//if(packet_header->caplen > max_data_len) return ;
if(g_fix_gro==0&&packet_header->caplen<packet_header->len) return;
if((int)packet_header->caplen<pcap_link_header_len) return;
//mylog(log_debug,"and its vaild!\n");
pthread_mutex_lock(&queue_mutex);
if(!my_queue.full())
my_queue.push_back((char *)pkt_data,(int)(packet_header->caplen));
pthread_mutex_unlock(&queue_mutex);
//pcap_cnt++;
ev_async_send (g_default_loop,&async_watcher);
return;
}
void *pcap_recv_thread_entry(void *none)
{
struct pcap_pkthdr *packet_header;
const u_char *pkt_data;
while(1)
{
if(use_pcap_mutex) pthread_mutex_lock(&pcap_mutex);
int ret=pcap_loop(pcap_handle, -1, my_packet_handler, NULL); //use -1 instead of 0 as cnt, since 0 is undefined in old versions
if(use_pcap_mutex) pthread_mutex_unlock(&pcap_mutex);
if(ret==-1)
mylog(log_warn,"pcap_loop exited with value %d\n",ret);
else
{
mylog(log_debug,"pcap_loop exited with value %d\n",ret);
}
ev_sleep(1.0);
//myexit(-1);
}
/*
while(1)
{
//printf("!!!\n");
pthread_mutex_lock(&pcap_mutex);
int ret=pcap_next_ex(pcap_handle,&packet_header,&pkt_data);
pthread_mutex_unlock(&pcap_mutex);
switch (ret)
{
case 0:
continue;
case 1:
break;
case -1:
mylog(log_fatal,"pcap_next_ex error [%s]\n",pcap_geterr(pcap_handle));
myexit(-1);
break;
case -2:
assert(0==1);//
break;
default:
assert(0==1);//
}
}
myexit(-1);*/
return 0;
}
extern void async_cb(struct ev_loop *loop, struct ev_async *watcher, int revents);
#if 0
int init_raw_socket()
{
assert(raw_ip_version==AF_INET||raw_ip_version==AF_INET6);
@@ -379,6 +499,225 @@ int init_raw_socket()
return 0;
}
#endif
int init_raw_socket()
{
#ifndef NO_LIBNET
char libnet_errbuf[LIBNET_ERRBUF_SIZE];
if(raw_ip_version==AF_INET)
{
libnet_handle = libnet_init(LIBNET_RAW4, dev, libnet_errbuf);
}
else
{
assert(raw_ip_version==AF_INET6);
libnet_handle = libnet_init(LIBNET_RAW6, dev, libnet_errbuf);
}
if(libnet_handle==0)
{
mylog(log_fatal,"libnet_init failed bc of [%s]\n",libnet_errbuf);
myexit(-1);
}
g_ptag=0;
libnet_clear_packet(libnet_handle);
#endif
char pcap_errbuf[PCAP_ERRBUF_SIZE];
//pcap_handle=pcap_open_live(dev,max_data_len,0,1000,pcap_errbuf);
pcap_handle = pcap_create( dev, pcap_errbuf );
if(pcap_handle==0)
{
mylog(log_fatal,"pcap_create failed bc of [%s]\n",pcap_errbuf);
myexit(-1);
}
assert( pcap_set_snaplen(pcap_handle, huge_data_len) ==0);
assert( pcap_set_promisc(pcap_handle, 0) ==0);
assert( pcap_set_timeout(pcap_handle, 1) ==0);
assert( pcap_set_immediate_mode(pcap_handle,1) ==0);
int ret = pcap_activate( pcap_handle );
if( ret < 0 )
{
printf("pcap_activate failed %s\n", pcap_geterr(pcap_handle));
myexit(-1);
}
if(send_with_pcap)
{
ret=pcap_setdirection(pcap_handle,PCAP_D_INOUT);//must be used after being actived
if(ret!=0) mylog(log_debug,"pcap_setdirection(pcap_handle,PCAP_D_INOUT) failed with value %d, %s\n",ret,pcap_geterr(pcap_handle));
}
else
{
ret=pcap_setdirection(pcap_handle,PCAP_D_IN);
if(ret!=0) mylog(log_debug,"pcap_setdirection(pcap_handle,PCAP_D_IN) failed with value %d, %s\n",ret,pcap_geterr(pcap_handle));
}
ret=pcap_datalink(pcap_handle);
if(ret==DLT_EN10MB)
{
pcap_link_header_len=14;
}
else if(ret==DLT_NULL)
{
pcap_link_header_len=4;
}
else if(ret==DLT_LINUX_SLL)
{
pcap_link_header_len=16;
}
else
{
mylog(log_fatal,"unknown pcap link type : %d\n",ret);
myexit(-1);
}
char filter_exp[1000];
address_t tmp_addr;
if(get_src_adress2(tmp_addr,remote_addr)!=0)
{
mylog(log_error,"get_src_adress() failed, maybe you dont have internet\n");
myexit(-1);
}
string src=tmp_addr.get_ip();
string dst=remote_addr.get_ip();
if(raw_ip_version==AF_INET)
{
//sprintf(filter_exp,"ip and src %s and dst %s and (tcp or udp or icmp)",my_ntoa(source_ip_uint32),dst.c_str());
sprintf(filter_exp,"ip and src %s and dst %s and (tcp or udp or icmp)",src.c_str(),dst.c_str());
}
else
{
assert(raw_ip_version==AF_INET6);
sprintf(filter_exp,"ip6 and src %s and dst %s and (tcp or udp or icmp6)",src.c_str(),dst.c_str());
}
if (pcap_compile(pcap_handle, &g_filter, filter_exp, 0, PCAP_NETMASK_UNKNOWN ) == -1) {
printf("Bad filter - %s\n", pcap_geterr(pcap_handle));
myexit(-1);
}
g_filter_compile_cnt++;
if (pcap_setfilter(pcap_handle, &g_filter) == -1) {
printf("Error setting filter - %s\n", pcap_geterr(pcap_handle));
myexit(-1);
}
///////////////////////////////////////////////////////////////new thread created here
if(pthread_create(&pcap_recv_thread, NULL, pcap_recv_thread_entry, 0)) {
mylog(log_fatal, "Error creating thread\n");
myexit(-1);
}
////////////////////////////////////////////////////////////////////////////////
g_ip_id_counter=get_true_random_number()%65535;
/*
if(lower_level==0)
{
raw_send_fd = socket(AF_INET , SOCK_RAW , IPPROTO_TCP);
if(raw_send_fd == -1) {
mylog(log_fatal,"Failed to create raw_send_fd\n");
//perror("Failed to create raw_send_fd");
myexit(1);
}
int one = 1;
const int *val = &one;
if (setsockopt (raw_send_fd, IPPROTO_IP, IP_HDRINCL, val, sizeof (one)) < 0) {
mylog(log_fatal,"Error setting IP_HDRINCL %d\n",errno);
//perror("Error setting IP_HDRINCL");
myexit(2);
}
}
else
{
raw_send_fd = socket(PF_PACKET , SOCK_DGRAM , htons(ETH_P_IP));
if(raw_send_fd == -1) {
mylog(log_fatal,"Failed to create raw_send_fd\n");
//perror("Failed to create raw_send_fd");
myexit(1);
}
//init_ifindex(if_name);
}
if(force_socket_buf)
{
if(setsockopt(raw_send_fd, SOL_SOCKET, SO_SNDBUFFORCE, &socket_buf_size, sizeof(socket_buf_size))<0)
{
mylog(log_fatal,"SO_SNDBUFFORCE fail socket_buf_size=%d errno=%s\n",socket_buf_size,strerror(errno));
myexit(1);
}
}
else
{
if(setsockopt(raw_send_fd, SOL_SOCKET, SO_SNDBUF, &socket_buf_size, sizeof(socket_buf_size))<0)
{
mylog(log_fatal,"SO_SNDBUF fail socket_buf_size=%d errno=%s\n",socket_buf_size,strerror(errno));
myexit(1);
}
}
//raw_fd = socket(AF_PACKET, SOCK_DGRAM, htons(ETH_P_ALL));
raw_recv_fd= socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP));
if(raw_recv_fd == -1) {
mylog(log_fatal,"Failed to create raw_recv_fd\n");
//perror("");
myexit(1);
}
if(force_socket_buf)
{
if(setsockopt(raw_recv_fd, SOL_SOCKET, SO_RCVBUFFORCE, &socket_buf_size, sizeof(socket_buf_size))<0)
{
mylog(log_fatal,"SO_RCVBUFFORCE fail socket_buf_size=%d errno=%s\n",socket_buf_size,strerror(errno));
myexit(1);
}
}
else
{
if(setsockopt(raw_recv_fd, SOL_SOCKET, SO_RCVBUF, &socket_buf_size, sizeof(socket_buf_size))<0)
{
mylog(log_fatal,"SO_RCVBUF fail socket_buf_size=%d errno=%s\n",socket_buf_size,strerror(errno));
myexit(1);
}
}
//IP_HDRINCL to tell the kernel that headers are included in the packet
setnonblocking(raw_send_fd); //not really necessary
setnonblocking(raw_recv_fd);*/
return 0;
}
/*
void init_filter(int port)
{
sock_fprog bpf;
@@ -447,10 +786,157 @@ void init_filter(int port)
//perror("filter");
myexit(-1);
}
}
*/
void init_filter(int port)
{
/*
sock_fprog bpf;*/
if(raw_mode==mode_faketcp||raw_mode==mode_udp)
{
filter_port=port;
}
char filter_exp[1000];
if(raw_ip_version==AF_INET)
{
if(raw_mode==mode_faketcp)
{
sprintf(filter_exp,"ip and tcp and src %s and src port %d and dst port %d",remote_addr.get_ip(),remote_addr.get_port(),port);
}
else if(raw_mode==mode_udp)
{
sprintf(filter_exp,"ip and udp and src %s and src port %d and dst port %d",remote_addr.get_ip(),remote_addr.get_port(),port);
}
else if(raw_mode==mode_icmp)
{
sprintf(filter_exp,"ip and icmp and src %s",remote_addr.get_ip());
}
else
{
mylog(log_fatal,"unknow raw mode\n");
myexit(-1);
}
}
else
{
assert(raw_ip_version==AF_INET6);
if(raw_mode==mode_faketcp)
{
sprintf(filter_exp,"ip6 and tcp and src %s and src port %d and dst port %d",remote_addr.get_ip(),remote_addr.get_port(),port);
}
else if(raw_mode==mode_udp)
{
sprintf(filter_exp,"ip6 and udp and src %s and src port %d and dst port %d",remote_addr.get_ip(),remote_addr.get_port(),port);
}
else if(raw_mode==mode_icmp)
{
sprintf(filter_exp,"ip6 and icmp6 and src %s",remote_addr.get_ip());
}
else
{
mylog(log_fatal,"unknow raw mode\n");
myexit(-1);
}
}
mylog(log_info,"filter expression is [%s]\n",filter_exp);
//pthread_mutex_lock(&pcap_mutex);//not sure if mutex is needed here
long long tmp_cnt=0;
if(use_pcap_mutex)
{
while(pthread_mutex_trylock(&pcap_mutex)!=0)
{
tmp_cnt++;
pcap_breakloop(pcap_handle);
if(tmp_cnt==100)
{
mylog(log_warn,"%lld attempts of pcap_breakloop()\n", tmp_cnt);
}
if(tmp_cnt%1000==0)
{
mylog(log_warn,"%lld attempts of pcap_breakloop()\n", tmp_cnt);
if(tmp_cnt>5000)
{
mylog(log_fatal,"we might have already run into a deadlock\n");
}
}
ev_sleep(0.001);
}
mylog(log_info,"breakloop() succeed after %lld attempt(s)\n", tmp_cnt);
}
if(1)
{
int ret=pcap_setdirection(pcap_handle,PCAP_D_IN);
if(ret!=0) mylog(log_debug,"pcap_setdirection(pcap_handle,PCAP_D_IN) failed with value %d, %s\n",ret,pcap_geterr(pcap_handle));
}
assert(g_filter_compile_cnt!=0);
pcap_freecode(&g_filter);
if (pcap_compile(pcap_handle, &g_filter, filter_exp, 0, PCAP_NETMASK_UNKNOWN ) == -1) {
mylog(log_fatal,"Bad filter - %s\n", pcap_geterr(pcap_handle));
myexit(-1);
}
g_filter_compile_cnt++;
if (pcap_setfilter(pcap_handle, &g_filter) == -1)
{
mylog(log_fatal,"Error setting filter - %s\n", pcap_geterr(pcap_handle));
myexit(-1);
}
if(use_pcap_mutex) pthread_mutex_unlock(&pcap_mutex);
/*
if(disable_bpf_filter) return;
//if(raw_mode==mode_icmp) return ;
//code_tcp[8].k=code_tcp[10].k=port;
if(raw_mode==mode_faketcp)
{
bpf.len = sizeof(code_tcp)/sizeof(code_tcp[0]);
code_tcp[code_tcp_port_index].k=port;
bpf.filter = code_tcp;
}
else if(raw_mode==mode_udp)
{
bpf.len = sizeof(code_udp)/sizeof(code_udp[0]);
code_udp[code_udp_port_index].k=port;
bpf.filter = code_udp;
}
else if(raw_mode==mode_icmp)
{
bpf.len = sizeof(code_icmp)/sizeof(code_icmp[0]);
bpf.filter = code_icmp;
}
int dummy;
int ret=setsockopt(raw_recv_fd, SOL_SOCKET, SO_DETACH_FILTER, &dummy, sizeof(dummy)); //in case i forgot to remove
if (ret != 0)
{
mylog(log_debug,"error remove fiter\n");
//perror("filter");
//exit(-1);
}
ret = setsockopt(raw_recv_fd, SOL_SOCKET, SO_ATTACH_FILTER, &bpf, sizeof(bpf));
if (ret != 0)
{
mylog(log_fatal,"error set fiter\n");
//perror("filter");
myexit(-1);
}*/
}
void remove_filter()
{
filter_port=0;
/*
int dummy;
int ret=setsockopt(raw_recv_fd, SOL_SOCKET, SO_DETACH_FILTER, &dummy, sizeof(dummy));
if (ret != 0)
@@ -459,10 +945,12 @@ void remove_filter()
//perror("filter");
//exit(-1);
}
*/
}
int init_ifindex(const char * if_name,int fd,int &index)
{
/*
struct ifreq ifr;
size_t if_name_len=strlen(if_name);
if (if_name_len<sizeof(ifr.ifr_name)) {
@@ -479,8 +967,11 @@ int init_ifindex(const char * if_name,int fd,int &index)
}
index=ifr.ifr_ifindex;
mylog(log_info,"ifname:%s ifindex:%d\n",if_name,index);
*/
return 0;
}
#if 0
bool interface_has_arp(const char * interface) {
struct ifreq ifr;
// int sock = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
@@ -495,6 +986,8 @@ bool interface_has_arp(const char * interface) {
//close(sock);
return !(ifr.ifr_flags & IFF_NOARP);
}
#endif
/*
struct route_info_t
{
string if_name;
@@ -539,7 +1032,8 @@ vector<int> find_route_entry(const vector<route_info_t> &route_info_vec,u32_t ip
}
}
return res;
}
}*/
/*
int find_direct_dest(const vector<route_info_t> &route_info_vec,u32_t ip,u32_t &dest_ip,string &if_name)
{
vector<int> res;
@@ -610,7 +1104,9 @@ int find_arp(const vector<arp_info_t> &arp_info_vec,u32_t ip,string if_name,stri
}
hw=arp_info_vec[pos].hw;
return 0;
}
}*/
/*
int find_lower_level_info(u32_t ip,u32_t &dest_ip,string &if_name,string &hw)
{
ip=htonl(ip);
@@ -699,8 +1195,8 @@ int find_lower_level_info(u32_t ip,u32_t &dest_ip,string &if_name,string &hw)
dest_ip=ntohl(dest_ip);
return 0;
}
}*/
#if 0
int send_raw_packet(raw_info_t &raw_info,const char * packet,int len)
{
const packet_info_t &send_info=raw_info.send_info;
@@ -733,10 +1229,12 @@ int send_raw_packet(raw_info_t &raw_info,const char * packet,int len)
else
{
assert(0==1);
/*
struct sockaddr_ll addr={0}; //={0} not necessary
memcpy(&addr,&send_info.addr_ll,sizeof(addr));
ret = sendto(raw_send_fd, packet, len , 0, (struct sockaddr *) &addr, sizeof (addr));
ret = sendto(raw_send_fd, packet, len , 0, (struct sockaddr *) &addr, sizeof (addr));*/
}
if(ret==-1)
{
@@ -751,6 +1249,71 @@ int send_raw_packet(raw_info_t &raw_info,const char * packet,int len)
}
return 0;
}
#endif
int send_raw_packet(raw_info_t &raw_info,const char * packet,int len)
{
const packet_info_t &send_info=raw_info.send_info;
const packet_info_t &recv_info=raw_info.recv_info;
if(! send_with_pcap)
{
#ifndef NO_LIBNET
//g_ptag=libnet_build_ipv4(ip_tot_len, iph->tos, ntohs(iph->id), ntohs(iph->frag_off),
// iph->ttl , iph->protocol , iph->check , iph->saddr, iph->daddr,
// (const unsigned char *)payload, payloadlen, libnet_handle, g_ptag);
//assert(g_ptag!=-1 &&g_ptag!=0);
//int ret;
//ret= libnet_write(libnet_handle);
//assert(ret!=-1);
//iph->tot_len=htons(ip_tot_len);
//iph->check =csum ((unsigned short *) send_raw_ip_buf, iph->ihl*4);
if(raw_ip_version==AF_INET)
{
libnet_write_raw_ipv4(libnet_handle,(const unsigned char *)packet,len); //todo, this api is marked as internal, maybe we should avoid using it.
}
else
{
assert(raw_ip_version==AF_INET6);
libnet_write_raw_ipv6(libnet_handle,(const unsigned char *)packet,len);
}
#endif
}
else
{
char buf[buf_len];
assert(pcap_header_captured==1);
assert(pcap_link_header_len!=-1);
memcpy(buf,pcap_header_buf,pcap_link_header_len);
memcpy(buf+pcap_link_header_len,packet,len);
//pthread_mutex_lock(&pcap_mutex); looks like this is not necessary, and it harms performance
int ret=pcap_sendpacket(pcap_handle,(const unsigned char *)buf,len+pcap_link_header_len);
if(ret!=0)
{
mylog(log_fatal,"pcap_sendpcaket failed with vaule %d,%s\n",ret,pcap_geterr(pcap_handle));
//pthread_mutex_unlock(&pcap_mutex);
myexit(-1);
}
//pthread_mutex_unlock(&pcap_mutex);
/*
unsigned char *p=(unsigned char *)send_raw_ip_buf0;
for(int i=0;i<ip_tot_len+pcap_link_header_len;i++)
printf("<%02x>",int(p[i]));
printf("\n");
assert(pcap_sendpacket(pcap_handle,(const unsigned char *)pcap_header_buf,cap_len)==0);
p=(unsigned char *)pcap_header_buf;
for(int i=0;i<cap_len;i++)
printf("<%02x>",int(p[i]));
printf("\n");
printf("pcap send!\n");*/
}
return 0;
}
int send_raw_ip(raw_info_t &raw_info,const char * payload,int payloadlen)
{
const packet_info_t &send_info=raw_info.send_info;
@@ -794,16 +1357,22 @@ int send_raw_ip(raw_info_t &raw_info,const char * payload,int payloadlen)
iph->daddr = send_info.new_dst_ip.v4;
ip_tot_len=sizeof (struct my_iphdr)+payloadlen;
/*
if(lower_level)iph->tot_len = htons(ip_tot_len); //this is not necessary ,kernel will always auto fill this //http://man7.org/linux/man-pages/man7/raw.7.html
else
iph->tot_len = 0;
*/
iph->tot_len = htons(ip_tot_len);//always fill for mp version
memcpy(send_raw_ip_buf+sizeof(my_iphdr) , payload, payloadlen);
/*
if(lower_level) iph->check =
csum ((unsigned short *) send_raw_ip_buf, iph->ihl*4); //this is not necessary ,kernel will always auto fill this
else
iph->check=0;
*/
iph->check =csum((unsigned short *) send_raw_ip_buf, iph->ihl*4);//always cal checksum for mp version
}
else
{
@@ -829,26 +1398,53 @@ int send_raw_ip(raw_info_t &raw_info,const char * payload,int payloadlen)
int pre_recv_raw_packet()
{
//not used in mp version,use async cb instead
/*
assert(g_packet_buf_cnt==0);
g_sockaddr_len=sizeof(g_sockaddr.ll);
g_packet_buf_len = recvfrom(raw_recv_fd, g_packet_buf, max_data_len+1, 0 ,(sockaddr*)&g_sockaddr , &g_sockaddr_len);
g_packet_buf_len = recvfrom(raw_recv_fd, g_packet_buf, huge_data_len+1, 0 ,(sockaddr*)&g_sockaddr , &g_sockaddr_len);
//assert(g_sockaddr_len==sizeof(g_sockaddr.ll)); //g_sockaddr_len=18, sizeof(g_sockaddr.ll)=20, why its not equal? maybe its bc sll_halen is 6?
//assert(g_addr_ll_size==sizeof(g_addr_ll));
if(g_packet_buf_len==max_data_len+1)
if(g_packet_buf_len==huge_data_len+1)
{
mylog(log_warn,"huge packet, data_len > %d,dropped\n",max_data_len);
if(g_fix_gro==0)
{
mylog(log_warn,"huge packet, data_len %d > %d,dropped\n",g_packet_buf_len,huge_data_len);
return -1;
}
else
{
mylog(log_debug,"huge packet, data_len %d > %d,not dropped\n",g_packet_buf_len,huge_data_len);
g_packet_buf_len=huge_data_len;
}
}
if(g_packet_buf_len> max_data_len+1)
{
if(g_fix_gro==0)
{
mylog(log_warn, "huge packet, data_len %d > %d(max_data_len) dropped, maybe you need to turn down mtu at upper level, or you may take a look at --fix-gro\n", g_packet_buf_len,
max_data_len);
return -1;
}
else
{
mylog(log_debug, "huge packet, data_len %d > %d(max_data_len) not dropped\n", g_packet_buf_len,
max_data_len);
//return -1;
}
}
if(g_packet_buf_len<0)
{
mylog(log_trace,"recv_len %d\n",g_packet_buf_len);
return -1;
}
g_packet_buf_cnt++;
g_packet_buf_cnt++;*/
return 0;
}
int discard_raw_packet()
@@ -857,6 +1453,7 @@ int discard_raw_packet()
g_packet_buf_cnt--;
return 0;
}
/*
int recv_raw_packet(char * &packet,int &len,int peek)
{
assert(g_packet_buf_cnt==1);
@@ -884,7 +1481,19 @@ int recv_raw_packet(char * &packet,int &len,int peek)
packet=g_packet_buf+int(link_level_header_len);
len=g_packet_buf_len-int(link_level_header_len);
return 0;
}*/
int recv_raw_packet(char * &packet,int &len,int peek)
{
assert(g_packet_buf_cnt==1);
if(!peek)
g_packet_buf_cnt--;
packet=g_packet_buf;
len=g_packet_buf_len;
return 0;
}
int recv_raw_ip(raw_info_t &raw_info,char * &payload,int &payloadlen)
{
char *raw_packet_buf;
@@ -942,7 +1551,7 @@ int recv_raw_ip(raw_info_t &raw_info,char * &payload,int &payloadlen)
if(lower_level)
{
memcpy(&recv_info.addr_ll,&g_sockaddr.ll,sizeof(recv_info.addr_ll));
//memcpy(&recv_info.addr_ll,&g_sockaddr.ll,sizeof(recv_info.addr_ll));
}
@@ -1925,9 +2534,8 @@ int recv_raw_tcp(raw_info_t &raw_info,char * &payload,int &payloadlen)
if(tcp_chk!=0)
{
mylog(log_debug,"tcp_chk:%x\n",tcp_chk);
mylog(log_debug,"tcp header error\n");
return -1;
mylog(log_debug,"tcp_chk:%x, tcp checksum failed, ignored\n",tcp_chk);
//return -1;
}
@@ -2509,7 +3117,7 @@ int try_to_list_and_bind2(int &fd,address_t address) //try to bind to a port,ma
temp_bind_addr.sin_port = htons(port);
temp_bind_addr.sin_addr.s_addr = local_ip_uint32;*/
if (bind(fd, (struct sockaddr*)&address.inner, address.get_len()) !=0)
if (::bind(fd, (struct sockaddr*)&address.inner, address.get_len()) !=0)
{
mylog(log_debug,"bind fail\n");
return -1;
@@ -2538,14 +3146,14 @@ int client_bind_to_a_new_port(int &fd,u32_t local_ip_uint32)//find a free port a
mylog(log_fatal,"bind port fail\n");
myexit(-1);
return -1;////for compiler check
}*/
}
*/
int client_bind_to_a_new_port2(int &fd,const address_t& address)//find a free port and bind to it.
{
address_t tmp=address;
int raw_send_port=10000+get_true_random_number()%(65535-10000);
for(int i=0;i<1000;i++)//try 1000 times at max,this should be enough
{
int raw_send_port=10000+get_true_random_number()%(65535-10000);
tmp.set_port(raw_send_port);
if (try_to_list_and_bind2(fd,tmp)==0)
{

View File

@@ -14,11 +14,11 @@ extern int use_tcp_dummy_socket;
extern int seq_mode;
extern int max_seq_mode;
extern int filter_port;
//extern u32_t bind_address_uint32;
extern u32_t bind_address_uint32;
extern int disable_bpf_filter;
extern int lower_level;
extern int lower_level_manual;
//extern int lower_level;
//extern int lower_level_manual;
extern char if_name[100];
extern char dev[100];
extern unsigned char dest_hw_addr[];
@@ -27,10 +27,34 @@ extern int random_drop;
extern int ifindex;
extern char g_packet_buf[buf_len];
extern char g_packet_buf[huge_buf_len];
extern int g_packet_buf_len;
extern int g_packet_buf_cnt;
extern queue_t my_queue;
extern ev_async async_watcher;
extern struct ev_loop* g_default_loop;
extern pthread_mutex_t queue_mutex;
extern int use_pcap_mutex;
extern int pcap_cnt;
extern int pcap_link_header_len;
extern int send_with_pcap;
extern int pcap_header_captured;
extern int pcap_header_buf[buf_len];
struct icmphdr
{
uint8_t type;
uint8_t code;
uint16_t check_sum;
uint16_t id;
uint16_t seq;
};
struct my_iphdr
{
@@ -138,6 +162,7 @@ struct my_tcphdr
};
};
struct my_ip6hdr
{
# ifdef UDP2RAW_LITTLE_ENDIAN
@@ -190,9 +215,11 @@ struct packet_info_t //todo change this to union
{
uint8_t protocol;
//u32_t src_ip;
//u32_t dst_ip;
u32_t src_ip;
u32_t dst_ip;
my_ip_t new_src_ip;
my_ip_t new_dst_ip;
@@ -213,7 +240,7 @@ struct packet_info_t //todo change this to union
bool has_ts;
sockaddr_ll addr_ll;
//sockaddr_ll addr_ll;
i32_t data_len;
@@ -226,8 +253,10 @@ struct raw_info_t
packet_info_t recv_info;
//int last_send_len;
//int last_recv_len;
bool peek=0;
//bool csum=1;
u32_t reserved_send_seq;
//uint32_t first_seq,first_ack_seq;
int rst_received=0;
@@ -236,13 +265,15 @@ struct raw_info_t
};//g_raw_info;
int init_raw_socket();
void init_filter(int port);
void remove_filter();
int init_ifindex(const char * if_name,int fd,int &index);
//int init_ifindex(const char * if_name,int fd,int &index);
int init_ifindex(const char * if_name,int &index);
int find_lower_level_info(u32_t ip,u32_t &dest_ip,string &if_name,string &hw);
@@ -256,7 +287,6 @@ int client_bind_to_a_new_port(int & bind_fd,u32_t local_ip_uint32);//find a free
int client_bind_to_a_new_port2(int &fd,const address_t& address);
int discard_raw_packet();
int pre_recv_raw_packet();
int send_raw_ip(raw_info_t &raw_info,const char * payload,int payloadlen);

125
pcap_wrapper.cpp Normal file
View File

@@ -0,0 +1,125 @@
#include <windows.h>
#include <pcap_wrapper.h>
#include <assert.h>
#include <stdio.h>
int (*pcap_loop )(pcap_t *, int, pcap_handler, u_char *);
int (*pcap_breakloop )(pcap_t *);
pcap_t* (*pcap_create)(const char *, char *);
int (*pcap_set_snaplen) (pcap_t *, int)=0;
int (*pcap_set_promisc) (pcap_t *, int)=0;
int (*pcap_can_set_rfmon) (pcap_t *)=0;
int (*pcap_set_rfmon )(pcap_t *, int)=0;
int (*pcap_set_timeout)(pcap_t *, int)=0;
int (*pcap_set_buffer_size)(pcap_t *, int)=0;
int (*pcap_activate)(pcap_t *)=0;
int (*pcap_setfilter)(pcap_t *, struct bpf_program *)=0;
int (*pcap_setdirection)(pcap_t *, pcap_direction_t)=0;
int (*pcap_datalink)(pcap_t *)=0;
void (*pcap_freecode)(struct bpf_program *)=0;
int (*pcap_compile)(pcap_t *, struct bpf_program *, const char *, int,
bpf_u_int32)=0;
char* (*pcap_geterr)(pcap_t *)=0;
int (*pcap_sendpacket)(pcap_t *, const u_char *, int)=0;
char* (*pcap_lookupdev)(char *)=0;
int (*pcap_findalldevs)(pcap_if_t **, char *)=0;
struct init_pcap_t
{
init_pcap_t()
{
init_pcap();
}
}do_it;
static void init_npcap_dll_path()
{
BOOL(WINAPI *SetDllDirectory)(LPCTSTR);
char sysdir_name[512];
int len;
SetDllDirectory = (BOOL(WINAPI *)(LPCTSTR)) GetProcAddress(GetModuleHandle("kernel32.dll"), "SetDllDirectoryA");
if (SetDllDirectory == NULL) {
printf("Error in SetDllDirectory\n");
}
else {
len = GetSystemDirectory(sysdir_name, 480); // be safe
if (!len)
printf("Error in GetSystemDirectory (%d)\n", (int)GetLastError());
strcat(sysdir_name, "\\Npcap");
if (SetDllDirectory(sysdir_name) == 0)
printf("Error in SetDllDirectory(\"System32\\Npcap\")\n");
}
}
#define EXPORT_FUN(XXX) do{ XXX= (__typeof__(XXX)) GetProcAddress(wpcap, #XXX); }while(0)
int init_pcap()
{
HMODULE wpcap=LoadLibrary("wpcap.dll");
if(wpcap!=0)
{
printf("using system32/wpcap.dll\n");
}
else
{
init_npcap_dll_path();
//SetDllDirectory("C:\\Windows\\System32\\Npcap\\");
wpcap=LoadLibrary("wpcap.dll");
if(wpcap!=0)
printf("using system32/npcap/wpcap.dll\n");
}
if(wpcap==0)
{
printf("cant not open wpcap.dll, make sure winpcap/npcap is installed\n");
exit(-1);
}
assert(wpcap!=0);
EXPORT_FUN(pcap_loop);
EXPORT_FUN(pcap_breakloop);
EXPORT_FUN(pcap_create);
EXPORT_FUN(pcap_set_snaplen);
EXPORT_FUN(pcap_set_promisc);
EXPORT_FUN(pcap_set_timeout);
EXPORT_FUN(pcap_activate);
EXPORT_FUN(pcap_setfilter);
EXPORT_FUN(pcap_setdirection);
EXPORT_FUN(pcap_datalink);
EXPORT_FUN(pcap_freecode);
EXPORT_FUN(pcap_compile);
EXPORT_FUN(pcap_geterr);
EXPORT_FUN(pcap_sendpacket);
EXPORT_FUN(pcap_lookupdev);
EXPORT_FUN(pcap_findalldevs);
/*
pcap_loop = (__typeof__(pcap_loop))GetProcAddress(wpcap, "pcap_loop");
pcap_create = (__typeof__(pcap_create))GetProcAddress(wpcap, "pcap_create");
pcap_set_snaplen = (__typeof__(pcap_set_snaplen))GetProcAddress(wpcap, "pcap_set_snaplen");
pcap_set_promisc = (__typeof__(pcap_set_promisc))GetProcAddress(wpcap, "pcap_set_promisc");
pcap_set_timeout = (__typeof__(pcap_set_timeout))GetProcAddress(wpcap, "pcap_set_timeout");
pcap_activate = (__typeof__(pcap_activate))GetProcAddress(wpcap, "pcap_activate");
pcap_setfilter = (__typeof__(pcap_setfilter))GetProcAddress(wpcap, "pcap_setfilter");
pcap_setdirection = (__typeof__(pcap_setdirection))GetProcAddress(wpcap, "pcap_setdirection");
pcap_datalink = (__typeof__(pcap_datalink))GetProcAddress(wpcap, "pcap_datalink");
pcap_freecode = (__typeof__(pcap_freecode))GetProcAddress(wpcap, "pcap_freecode");
pcap_compile = (__typeof__(pcap_compile))GetProcAddress(wpcap, "pcap_compile");
pcap_geterr = (__typeof__(pcap_geterr))GetProcAddress(wpcap, "pcap_geterr");
pcap_sendpacket = (__typeof__(pcap_sendpacket))GetProcAddress(wpcap, "pcap_sendpacket");
pcap_lookupdev = (__typeof__(pcap_lookupdev))GetProcAddress(wpcap, "pcap_lookupdev");
pcap_findalldevs = (__typeof__(pcap_findalldevs))GetProcAddress(wpcap, "pcap_findalldevs");
//pcap_loop = (__typeof__(pcap_loop))GetProcAddress(wpcap, "pcap_loop");
//pcap_loop = (__typeof__(pcap_loop))GetProcAddress(wpcap, "pcap_loop");
//pcap_loop = (__typeof__(pcap_loop))GetProcAddress(wpcap, "pcap_loop");
*/
return 0;
}

127
pcap_wrapper.h Normal file
View File

@@ -0,0 +1,127 @@
#pragma once
//#ifdef __cplusplus
//extern "C" {
//#endif
//#include <sys/time.h>
//#include <stdint.h>
struct bpf_program
{
char a[2000];
};
struct pcap_t
{
char a[2000];
};
typedef unsigned int bpf_u_int32;
typedef struct my_timeval {
int tv_sec;
int tv_usec;
} my_timeval;
struct pcap_pkthdr {
struct my_timeval ts; /* time stamp */
bpf_u_int32 caplen; /* length of portion present */
bpf_u_int32 len; /* length this packet (off wire) */
};
typedef enum {
PCAP_D_INOUT = 0,
PCAP_D_IN,
PCAP_D_OUT
} pcap_direction_t;
struct pcap_addr {
struct pcap_addr *next;
struct sockaddr *addr; /* address */
struct sockaddr *netmask; /* netmask for that address */
struct sockaddr *broadaddr; /* broadcast address for that address */
struct sockaddr *dstaddr; /* P2P destination address for that address */
};
struct pcap_if {
struct pcap_if *next;
char *name; /* name to hand to "pcap_open_live()" */
char *description; /* textual description of interface, or NULL */
struct pcap_addr *addresses;
bpf_u_int32 flags; /* PCAP_IF_ interface flags */
};
typedef struct pcap_if pcap_if_t;
typedef struct pcap_addr pcap_addr_t;
typedef unsigned char u_char;
#define PCAP_ERRBUF_SIZE 256
#define DLT_NULL 0 /* BSD loopback encapsulation */
#define DLT_EN10MB 1 /* Ethernet (10Mb) */
#define DLT_EN3MB 2 /* Experimental Ethernet (3Mb) */
#define DLT_AX25 3 /* Amateur Radio AX.25 */
#define DLT_PRONET 4 /* Proteon ProNET Token Ring */
#define DLT_CHAOS 5 /* Chaos */
#define DLT_IEEE802 6 /* 802.5 Token Ring */
#define DLT_ARCNET 7 /* ARCNET, with BSD-style header */
#define DLT_SLIP 8 /* Serial Line IP */
#define DLT_PPP 9 /* Point-to-point Protocol */
#define DLT_FDDI 10 /* FDDI */
#define DLT_LINUX_SLL 113
#define PCAP_NETMASK_UNKNOWN 0xffffffff
typedef void (*pcap_handler)(u_char *, const struct pcap_pkthdr *,
const u_char *);
extern int (*pcap_loop )(pcap_t *, int, pcap_handler, u_char *);
extern int (*pcap_breakloop )(pcap_t *);
extern pcap_t* (*pcap_create)(const char *, char *);
extern int (*pcap_set_snaplen) (pcap_t *, int);
extern int (*pcap_set_promisc) (pcap_t *, int);
extern int (*pcap_can_set_rfmon) (pcap_t *);
extern int (*pcap_set_rfmon )(pcap_t *, int);
extern int (*pcap_set_timeout)(pcap_t *, int);
extern int (*pcap_set_buffer_size)(pcap_t *, int);
extern int (*pcap_activate)(pcap_t *);
extern int (*pcap_setfilter)(pcap_t *, struct bpf_program *);
extern int (*pcap_setdirection)(pcap_t *, pcap_direction_t);
extern int (*pcap_datalink)(pcap_t *);
extern void (*pcap_freecode)(struct bpf_program *);
extern int (*pcap_compile)(pcap_t *, struct bpf_program *, const char *, int,
bpf_u_int32);
extern char* (*pcap_geterr)(pcap_t *);
extern int (*pcap_sendpacket)(pcap_t *, const u_char *, int);
extern char* (*pcap_lookupdev)(char *);
extern int (*pcap_findalldevs)(pcap_if_t **, char *);
inline int pcap_set_immediate_mode(pcap_t *,int)
{
return 0;
}
//#ifdef __cplusplus
//}
//#endif
int init_pcap();

View File

@@ -1,899 +0,0 @@
/*
* server.cpp
*
* Created on: Aug 29, 2018
* Author: root
*/
#include "common.h"
#include "network.h"
#include "connection.h"
#include "misc.h"
#include "log.h"
#include "lib/md5.h"
#include "encrypt.h"
#include "fd_manager.h"
int server_on_timer_multi(conn_info_t &conn_info) //for server. called when a timer is ready in epoll.for server,there will be one timer for every connection
// there is also a global timer for server,but its not handled here
{
char ip_port[40];
//u32_t ip=conn_info.raw_info.send_info.dst_ip;
//u32_t port=conn_info.raw_info.send_info.dst_port;
address_t tmp_addr;
tmp_addr.from_ip_port_new(raw_ip_version,&conn_info.raw_info.send_info.new_dst_ip,conn_info.raw_info.send_info.dst_port);
//sprintf(ip_port,"%s:%d",my_ntoa(ip),port);
tmp_addr.to_str(ip_port);
//keep_iptables_rule();
mylog(log_trace,"server timer!\n");
raw_info_t &raw_info=conn_info.raw_info;
assert(conn_info.state.server_current_state==server_ready);
if(conn_info.state.server_current_state==server_ready)
{
conn_info.blob->conv_manager.s.clear_inactive(ip_port);
/*
if( get_current_time()-conn_info.last_hb_recv_time>heartbeat_timeout )
{
mylog(log_trace,"%lld %lld\n",get_current_time(),conn_info.last_state_time);
conn_info.server_current_state=server_nothing;
//conn_manager.current_ready_ip=0;
//conn_manager.current_ready_port=0;
mylog(log_info,"changed state to server_nothing\n");
return 0;
}*/ //dont need to do this at server,conn_manger will clear expired connections
if(get_current_time()-conn_info.last_hb_sent_time<heartbeat_interval)
{
return 0;
}
if(hb_mode==0)
send_safer(conn_info,'h',hb_buf,0); /////////////send
else
send_safer(conn_info,'h',hb_buf,hb_len);
conn_info.last_hb_sent_time=get_current_time();
mylog(log_debug,"heart beat sent<%x,%x>\n",conn_info.my_id,conn_info.oppsite_id);
}
else
{
mylog(log_fatal,"this shouldnt happen!\n");
myexit(-1);
}
return 0;
}
int server_on_raw_recv_ready(conn_info_t &conn_info,char * ip_port,char type,char *data,int data_len) //called while the state for a connection is server_ready
//receives data and heart beat by recv_safer.
{
raw_info_t &raw_info = conn_info.raw_info;
packet_info_t &send_info = conn_info.raw_info.send_info;
packet_info_t &recv_info = conn_info.raw_info.recv_info;
//char ip_port[40];
//sprintf(ip_port,"%s:%d",my_ntoa(recv_info.src_ip),recv_info.src_port);
/*
if (recv_info.src_ip != send_info.dst_ip
|| recv_info.src_port != send_info.dst_port) {
mylog(log_debug, "unexpected adress\n");
return 0;
}*/
if (type == 'h' && data_len >= 0) {
//u32_t tmp = ntohl(*((u32_t *) &data[sizeof(u32_t)]));
mylog(log_debug,"[%s][hb]received hb \n",ip_port);
conn_info.last_hb_recv_time = get_current_time();
return 0;
} else if (type== 'd' && data_len >=int( sizeof(u32_t) ))
{
//u32_t tmp_conv_id = ntohl(*((u32_t *) &data[0]));
my_id_t tmp_conv_id;
memcpy(&tmp_conv_id,&data[0],sizeof(tmp_conv_id));
tmp_conv_id=ntohl(tmp_conv_id);
if(hb_mode==0)
conn_info.last_hb_recv_time = get_current_time();
mylog(log_trace, "conv:%u\n", tmp_conv_id);
if (!conn_info.blob->conv_manager.s.is_conv_used(tmp_conv_id)) {
if (conn_info.blob->conv_manager.s.get_size() >= max_conv_num) {
mylog(log_warn,
"[%s]ignored new conv %x connect bc max_conv_num exceed\n",ip_port,
tmp_conv_id);
return 0;
}
/*
struct sockaddr_in remote_addr_in={0};
socklen_t slen = sizeof(sockaddr_in);
//memset(&remote_addr_in, 0, sizeof(remote_addr_in));
remote_addr_in.sin_family = AF_INET;
remote_addr_in.sin_port = htons(remote_port);
remote_addr_in.sin_addr.s_addr = remote_ip_uint32;
int new_udp_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (new_udp_fd < 0) {
mylog(log_warn, "[%s]create udp_fd error\n",ip_port);
return -1;
}
setnonblocking(new_udp_fd);
set_buf_size(new_udp_fd,socket_buf_size);
mylog(log_debug, "[%s]created new udp_fd %d\n",ip_port, new_udp_fd);
int ret = connect(new_udp_fd, (struct sockaddr *) &remote_addr_in,
slen);
if (ret != 0) {
mylog(log_warn, "udp fd connect fail\n");
close(new_udp_fd);
return -1;
}*/
int new_udp_fd=remote_addr.new_connected_udp_fd();
if (new_udp_fd < 0) {
mylog(log_warn, "[%s]new_connected_udp_fd() failed\n",ip_port);
return -1;
}
struct epoll_event ev;
fd64_t new_udp_fd64 = fd_manager.create(new_udp_fd);
fd_manager.get_info(new_udp_fd64).p_conn_info=&conn_info;
mylog(log_trace, "[%s]u64: %lld\n",ip_port, new_udp_fd64);
ev.events = EPOLLIN;
ev.data.u64 = new_udp_fd64;
int ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, new_udp_fd, &ev);
if (ret != 0) {
mylog(log_warn, "[%s]add udp_fd error\n",ip_port);
close(new_udp_fd);
return -1;
}
conn_info.blob->conv_manager.s.insert_conv(tmp_conv_id, new_udp_fd64);
//assert(conn_manager.udp_fd_mp.find(new_udp_fd)==conn_manager.udp_fd_mp.end());
//conn_manager.udp_fd_mp[new_udp_fd] = &conn_info;
//pack_u64(conn_info.raw_info.recv_info.src_ip,conn_info.raw_info.recv_info.src_port);
mylog(log_info, "[%s]new conv conv_id=%x, assigned fd=%d\n",ip_port,
tmp_conv_id, new_udp_fd);
}
fd64_t fd64 = conn_info.blob->conv_manager.s.find_data_by_conv(tmp_conv_id);
conn_info.blob->conv_manager.s.update_active_time(tmp_conv_id);
int fd = fd_manager.to_fd(fd64);
mylog(log_trace, "[%s]received a data from fake tcp,len:%d\n",ip_port, data_len);
int ret = send(fd, data + sizeof(u32_t),
data_len - ( sizeof(u32_t)), 0);
mylog(log_trace, "[%s]%d byte sent ,fd :%d\n ",ip_port, ret, fd);
if (ret < 0) {
mylog(log_warn, "send returned %d\n", ret);
//perror("what happened????");
}
return 0;
}
return 0;
}
int server_on_raw_recv_pre_ready(conn_info_t &conn_info,char * ip_port,u32_t tmp_oppsite_const_id)// do prepare work before state change to server ready for a specifc connection
//connection recovery is also handle here
{
//u32_t ip;uint16_t port;
//ip=conn_info.raw_info.recv_info.src_ip;
//port=conn_info.raw_info.recv_info.src_port;
//char ip_port[40];
//sprintf(ip_port,"%s:%d",my_ntoa(ip),port);
mylog(log_info,"[%s]received handshake oppsite_id:%x my_id:%x\n",ip_port,conn_info.oppsite_id,conn_info.my_id);
mylog(log_info,"[%s]oppsite const_id:%x \n",ip_port,tmp_oppsite_const_id);
if(conn_manager.const_id_mp.find(tmp_oppsite_const_id)==conn_manager.const_id_mp.end())
{
//conn_manager.const_id_mp=
if(conn_manager.ready_num>=max_ready_conn_num)
{
mylog(log_info,"[%s]max_ready_conn_num,cant turn to ready\n",ip_port);
conn_info.state.server_current_state =server_idle;
return 0;
}
conn_info.prepare();
conn_info.state.server_current_state = server_ready;
conn_info.oppsite_const_id=tmp_oppsite_const_id;
conn_manager.ready_num++;
conn_manager.const_id_mp[tmp_oppsite_const_id]=&conn_info;
//conn_info.last_state_time=get_current_time(); //dont change this!!!!!!!!!!!!!!!!!!!!!!!!!
//conn_manager.current_ready_ip=ip;
//conn_manager.current_ready_port=port;
//my_id=conn_info.my_id;
//oppsite_id=conn_info.oppsite_id;
conn_info.last_hb_recv_time = get_current_time();
conn_info.last_hb_sent_time = conn_info.last_hb_recv_time;//=get_current_time()
if(hb_mode==0)
send_safer(conn_info,'h',hb_buf,0);/////////////send
else
send_safer(conn_info,'h',hb_buf,hb_len);
mylog(log_info, "[%s]changed state to server_ready\n",ip_port);
conn_info.blob->anti_replay.re_init();
//g_conn_info=conn_info;
int new_timer_fd;
set_timer_server(epollfd, new_timer_fd,conn_info.timer_fd64);
fd_manager.get_info(conn_info.timer_fd64).p_conn_info=&conn_info;
//assert(conn_manager.timer_fd_mp.find(new_timer_fd)==conn_manager.timer_fd_mp.end());
//conn_manager.timer_fd_mp[new_timer_fd] = &conn_info;//pack_u64(ip,port);
//timer_fd_mp[new_timer_fd]
/*
if(oppsite_const_id!=0&&tmp_oppsite_const_id!=oppsite_const_id) //TODO MOVE TO READY
{
mylog(log_info,"cleared all conv bc of const id doesnt match\n");
conv_manager.clear();
}*/
//oppsite_const_id=tmp_oppsite_const_id;
}
else
{
conn_info_t &ori_conn_info=*conn_manager.const_id_mp[tmp_oppsite_const_id];
if(ori_conn_info.state.server_current_state==server_ready)
{
if(conn_info.last_state_time<ori_conn_info.last_state_time)
{
mylog(log_info,"[%s]conn_info.last_state_time<ori_conn_info.last_state_time. ignored new handshake\n",ip_port);
conn_info.state.server_current_state=server_idle;
conn_info.oppsite_const_id=0;
return 0;
}
address_t addr1;addr1.from_ip_port_new(raw_ip_version,&ori_conn_info.raw_info.recv_info.new_src_ip,ori_conn_info.raw_info.recv_info.src_port);
if(!conn_manager.exist(addr1))//TODO remove this
{
mylog(log_fatal,"[%s]this shouldnt happen\n",ip_port);
myexit(-1);
}
address_t addr2;addr2.from_ip_port_new(raw_ip_version,&conn_info.raw_info.recv_info.new_src_ip,conn_info.raw_info.recv_info.src_port);
if(!conn_manager.exist(addr2))//TODO remove this
{
mylog(log_fatal,"[%s]this shouldnt happen2\n",ip_port);
myexit(-1);
}
conn_info_t *&p_ori=conn_manager.find_insert_p(addr1);
conn_info_t *&p=conn_manager.find_insert_p(addr2);
conn_info_t *tmp=p;
p=p_ori;
p_ori=tmp;
mylog(log_info,"[%s]grabbed a connection\n",ip_port);
//ori_conn_info.state.server_current_state=server_ready;
ori_conn_info.recover(conn_info);
//send_safer(ori_conn_info, 'h',hb_buf, hb_len);
//ori_conn_info.blob->anti_replay.re_init();
if(hb_mode==0)
send_safer(ori_conn_info,'h',hb_buf,0);/////////////send
else
send_safer(ori_conn_info,'h',hb_buf,hb_len);
ori_conn_info.last_hb_recv_time=get_current_time();
conn_info.state.server_current_state=server_idle;
conn_info.oppsite_const_id=0;
}
else
{
mylog(log_fatal,"[%s]this should never happen\n",ip_port);
myexit(-1);
}
return 0;
}
return 0;
}
int server_on_raw_recv_handshake1(conn_info_t &conn_info,char * ip_port,char * data, int data_len)//called when server received a handshake1 packet from client
{
packet_info_t &send_info=conn_info.raw_info.send_info;
packet_info_t &recv_info=conn_info.raw_info.recv_info;
raw_info_t &raw_info=conn_info.raw_info;
//u32_t ip=conn_info.raw_info.recv_info.src_ip;
//uint16_t port=conn_info.raw_info.recv_info.src_port;
//char ip_port[40];
//sprintf(ip_port,"%s:%d",my_ntoa(ip),port);
if(data_len<int( 3*sizeof(my_id_t)))
{
mylog(log_debug,"[%s] data_len=%d too short to be a handshake\n",ip_port,data_len);
return -1;
}
//id_t tmp_oppsite_id= ntohl(* ((u32_t *)&data[0]));
my_id_t tmp_oppsite_id;
memcpy(&tmp_oppsite_id,(u32_t *)&data[0],sizeof(tmp_oppsite_id));
tmp_oppsite_id=ntohl(tmp_oppsite_id);
//id_t tmp_my_id=ntohl(* ((u32_t *)&data[sizeof(id_t)]));
my_id_t tmp_my_id;
memcpy(&tmp_my_id,&data[sizeof(my_id_t)],sizeof(tmp_my_id));
tmp_my_id=ntohl(tmp_my_id);
if(tmp_my_id==0) //received init handshake again
{
if(raw_mode==mode_faketcp)
{
send_info.seq=recv_info.ack_seq;
send_info.ack_seq=recv_info.seq+raw_info.recv_info.data_len;
send_info.ts_ack=recv_info.ts;
}
if(raw_mode==mode_icmp)
{
send_info.my_icmp_seq=recv_info.my_icmp_seq;
}
send_handshake(raw_info,conn_info.my_id,tmp_oppsite_id,const_id); //////////////send
mylog(log_info,"[%s]changed state to server_handshake1,my_id is %x\n",ip_port,conn_info.my_id);
}
else if(tmp_my_id==conn_info.my_id)
{
conn_info.oppsite_id=tmp_oppsite_id;
//id_t tmp_oppsite_const_id=ntohl(* ((u32_t *)&data[sizeof(id_t)*2]));
my_id_t tmp_oppsite_const_id;
memcpy(&tmp_oppsite_const_id,&data[sizeof(my_id_t)*2],sizeof(tmp_oppsite_const_id));
tmp_oppsite_const_id=ntohl(tmp_oppsite_const_id);
if(raw_mode==mode_faketcp)
{
send_info.seq=recv_info.ack_seq;
send_info.ack_seq=recv_info.seq+raw_info.recv_info.data_len;
send_info.ts_ack=recv_info.ts;
}
if(raw_mode==mode_icmp)
{
send_info.my_icmp_seq=recv_info.my_icmp_seq;
}
server_on_raw_recv_pre_ready(conn_info,ip_port,tmp_oppsite_const_id);
}
else
{
mylog(log_debug,"[%s]invalid my_id %x,my_id is %x\n",ip_port,tmp_my_id,conn_info.my_id);
}
return 0;
}
int server_on_raw_recv_multi() //called when server received an raw packet
{
char dummy_buf[buf_len];
raw_info_t peek_raw_info;
peek_raw_info.peek=1;
packet_info_t &peek_info=peek_raw_info.recv_info;
mylog(log_trace,"got a packet\n");
if(pre_recv_raw_packet()<0) return -1;
if(peek_raw(peek_raw_info)<0)
{
discard_raw_packet();
//recv(raw_recv_fd, 0,0, 0 );//
//struct sockaddr saddr;
//socklen_t saddr_size=sizeof(saddr);
///recvfrom(raw_recv_fd, 0,0, 0 ,&saddr , &saddr_size);//
mylog(log_trace,"peek_raw failed\n");
return -1;
}else
{
mylog(log_trace,"peek_raw success\n");
}
//u32_t ip=peek_info.src_ip;uint16_t port=peek_info.src_port;
int data_len; char *data;
address_t addr;
addr.from_ip_port_new(raw_ip_version,&peek_info.new_src_ip,peek_info.src_port);
char ip_port[40];
addr.to_str(ip_port);
//sprintf(ip_port,"%s:%d",my_ntoa(ip),port);
mylog(log_trace,"[%s]peek_raw\n",ip_port);
if(raw_mode==mode_faketcp&&peek_info.syn==1)
{
if(!conn_manager.exist(addr)||conn_manager.find_insert(addr).state.server_current_state!=server_ready)
{//reply any syn ,before state become ready
raw_info_t tmp_raw_info;
if(recv_raw0(tmp_raw_info,data,data_len)<0)
{
return 0;
}
if(use_tcp_dummy_socket!=0)
return 0;
raw_info_t &raw_info=tmp_raw_info;
packet_info_t &send_info=raw_info.send_info;
packet_info_t &recv_info=raw_info.recv_info;
send_info.new_src_ip=recv_info.new_dst_ip;
send_info.src_port=recv_info.dst_port;
send_info.dst_port = recv_info.src_port;
send_info.new_dst_ip = recv_info.new_src_ip;
if(lower_level)
{
handle_lower_level(raw_info);
}
if(data_len==0&&raw_info.recv_info.syn==1&&raw_info.recv_info.ack==0)
{
send_info.ack_seq = recv_info.seq + 1;
send_info.psh = 0;
send_info.syn = 1;
send_info.ack = 1;
send_info.ts_ack=recv_info.ts;
mylog(log_info,"[%s]received syn,sent syn ack back\n",ip_port);
send_raw0(raw_info, 0, 0);
return 0;
}
}
else
{
discard_raw_packet();
//recv(raw_recv_fd, 0,0,0);
}
return 0;
}
if(!conn_manager.exist(addr))
{
if(conn_manager.mp.size()>=max_handshake_conn_num)
{
mylog(log_info,"[%s]reached max_handshake_conn_num,ignored new handshake\n",ip_port);
discard_raw_packet();
//recv(raw_recv_fd, 0,0, 0 );//
return 0;
}
raw_info_t tmp_raw_info;
if(raw_mode==mode_icmp)
{
tmp_raw_info.send_info.dst_port=tmp_raw_info.send_info.src_port=addr.get_port();
}
if(recv_bare(tmp_raw_info,data,data_len)<0)
{
return 0;
}
if(data_len<int( 3*sizeof(my_id_t)))
{
mylog(log_debug,"[%s]too short to be a handshake\n",ip_port);
return -1;
}
//id_t zero=ntohl(* ((u32_t *)&data[sizeof(id_t)]));
my_id_t zero;
memcpy(&zero,&data[sizeof(my_id_t)],sizeof(zero));
zero=ntohl(zero);
if(zero!=0)
{
mylog(log_debug,"[%s]not a invalid initial handshake\n",ip_port);
return -1;
}
mylog(log_info,"[%s]got packet from a new ip\n",ip_port);
conn_info_t &conn_info=conn_manager.find_insert(addr);
conn_info.raw_info=tmp_raw_info;
raw_info_t &raw_info=conn_info.raw_info;
packet_info_t &send_info=conn_info.raw_info.send_info;
packet_info_t &recv_info=conn_info.raw_info.recv_info;
//conn_info.ip_port.ip=ip;
//conn_info.ip_port.port=port;
send_info.new_src_ip=recv_info.new_dst_ip;
send_info.src_port=recv_info.dst_port;
send_info.dst_port = recv_info.src_port;
send_info.new_dst_ip = recv_info.new_src_ip;
if(lower_level)
{
handle_lower_level(raw_info);
}
//id_t tmp_oppsite_id= ntohl(* ((u32_t *)&data[0]));
//mylog(log_info,"[%s]handshake1 received %x\n",ip_port,tmp_oppsite_id);
conn_info.my_id=get_true_random_number_nz();
mylog(log_info,"[%s]created new conn,state: server_handshake1,my_id is %x\n",ip_port,conn_info.my_id);
conn_info.state.server_current_state = server_handshake1;
conn_info.last_state_time = get_current_time();
server_on_raw_recv_handshake1(conn_info,ip_port,data,data_len);
return 0;
}
conn_info_t & conn_info=conn_manager.find_insert(addr);//insert if not exist
packet_info_t &send_info=conn_info.raw_info.send_info;
packet_info_t &recv_info=conn_info.raw_info.recv_info;
raw_info_t &raw_info=conn_info.raw_info;
if(conn_info.state.server_current_state==server_handshake1)
{
if(recv_bare(raw_info,data,data_len)!=0)
{
return -1;
}
return server_on_raw_recv_handshake1(conn_info,ip_port,data,data_len);
}
if(conn_info.state.server_current_state==server_ready)
{
char type;
//mylog(log_info,"before recv_safer\n");
if (recv_safer(conn_info,type, data, data_len) != 0) {
return -1;
}
//mylog(log_info,"after recv_safer\n");
return server_on_raw_recv_ready(conn_info,ip_port,type,data,data_len);
}
if(conn_info.state.server_current_state==server_idle)
{
discard_raw_packet();
//recv(raw_recv_fd, 0,0, 0 );//
return 0;
}
mylog(log_fatal,"we should never run to here\n");
myexit(-1);
return -1;
}
int server_on_udp_recv(conn_info_t &conn_info,fd64_t fd64)
{
char buf[buf_len];
if(conn_info.state.server_current_state!=server_ready)//TODO remove this for peformance
{
mylog(log_fatal,"p_conn_info->state.server_current_state!=server_ready!!!this shouldnt happen\n");
myexit(-1);
}
//conn_info_t &conn_info=*p_conn_info;
assert(conn_info.blob->conv_manager.s.is_data_used(fd64));
u32_t conv_id=conn_info.blob->conv_manager.s.find_conv_by_data(fd64);
int fd=fd_manager.to_fd(fd64);
int recv_len=recv(fd,buf,max_data_len+1,0);
mylog(log_trace,"received a packet from udp_fd,len:%d\n",recv_len);
if(recv_len==max_data_len+1)
{
mylog(log_warn,"huge packet, data_len > %d,dropped\n",max_data_len);
return -1;
}
if(recv_len<0)
{
mylog(log_debug,"udp fd,recv_len<0 continue,%s\n",strerror(errno));
return -1;
}
if(recv_len>=mtu_warn)
{
mylog(log_warn,"huge packet,data len=%d (>=%d).strongly suggested to set a smaller mtu at upper level,to get rid of this warn\n ",recv_len,mtu_warn);
}
//conn_info.conv_manager->update_active_time(conv_id); server dosnt update from upd side,only update from raw side. (client updates at both side)
if(conn_info.state.server_current_state==server_ready)
{
send_data_safer(conn_info,buf,recv_len,conv_id);
//send_data(g_packet_info_send,buf,recv_len,my_id,oppsite_id,conv_id);
mylog(log_trace,"send_data_safer ,sent !!\n");
}
return 0;
}
int server_event_loop()
{
char buf[buf_len];
int i, j, k;int ret;
if(raw_ip_version==AF_INET)
{
if(local_addr.inner.ipv4.sin_addr.s_addr!=0)
{
bind_addr_used=1;
bind_addr.v4=local_addr.inner.ipv4.sin_addr.s_addr;
}
}
else
{
assert(raw_ip_version==AF_INET6);
char zero_arr[16]={0};
if(memcmp(&local_addr.inner.ipv6.sin6_addr,zero_arr,16)!=0)
{
bind_addr_used=1;
bind_addr.v6=local_addr.inner.ipv6.sin6_addr;
}
}
//bind_address_uint32=local_ip_uint32;//only server has bind adress,client sets it to zero
if(lower_level)
{
if(lower_level_manual)
{
init_ifindex(if_name,raw_send_fd,ifindex);
mylog(log_info,"we are running at lower-level (manual) mode\n");
}
else
{
mylog(log_info,"we are running at lower-level (auto) mode\n");
}
}
if(raw_mode==mode_faketcp)
{
bind_fd=socket(local_addr.get_type(),SOCK_STREAM,0);
}
else if(raw_mode==mode_udp||raw_mode==mode_icmp)//bind an adress to avoid collision,for icmp,there is no port,just bind a udp port
{
bind_fd=socket(local_addr.get_type(),SOCK_DGRAM,0);
}
//struct sockaddr_in temp_bind_addr={0};
// bzero(&temp_bind_addr, sizeof(temp_bind_addr));
//temp_bind_addr.sin_family = AF_INET;
//temp_bind_addr.sin_port = local_addr.get_port();
//temp_bind_addr.sin_addr.s_addr = local_addr.inner.ipv4.sin_addr.s_addr;
if (bind(bind_fd, (struct sockaddr*)&local_addr.inner, local_addr.get_len()) !=0)
{
mylog(log_fatal,"bind fail\n");
myexit(-1);
}
if(raw_mode==mode_faketcp)
{
if(listen(bind_fd, SOMAXCONN) != 0 )
{
mylog(log_fatal,"listen fail\n");
myexit(-1);
}
}
//init_raw_socket();
init_filter(local_addr.get_port());//bpf filter
epollfd = epoll_create1(0);
const int max_events = 4096;
struct epoll_event ev, events[max_events];
if (epollfd < 0) {
mylog(log_fatal,"epoll return %d\n", epollfd);
myexit(-1);
}
ev.events = EPOLLIN;
ev.data.u64 = raw_recv_fd;
ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, raw_recv_fd, &ev);
if (ret!= 0) {
mylog(log_fatal,"add raw_fd error\n");
myexit(-1);
}
int timer_fd;
set_timer(epollfd,timer_fd);
u64_t begin_time=0;
u64_t end_time=0;
mylog(log_info,"now listening at %s\n",local_addr.get_str());
int fifo_fd=-1;
if(fifo_file[0]!=0)
{
fifo_fd=create_fifo(fifo_file);
ev.events = EPOLLIN;
ev.data.u64 = fifo_fd;
ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, fifo_fd, &ev);
if (ret!= 0) {
mylog(log_fatal,"add fifo_fd to epoll error %s\n",strerror(errno));
myexit(-1);
}
mylog(log_info,"fifo_file=%s\n",fifo_file);
}
while(1)////////////////////////
{
if(about_to_exit) myexit(0);
int nfds = epoll_wait(epollfd, events, max_events, 180 * 1000);
if (nfds < 0) { //allow zero
if(errno==EINTR )
{
mylog(log_info,"epoll interrupted by signal,continue\n");
//myexit(0);
}
else
{
mylog(log_fatal,"epoll_wait return %d,%s\n", nfds,strerror(errno));
myexit(-1);
}
}
int idx;
for (idx = 0; idx < nfds; ++idx)
{
//mylog(log_debug,"ndfs: %d \n",nfds);
epoll_trigger_counter++;
//printf("%d %d %d %d\n",timer_fd,raw_recv_fd,raw_send_fd,n);
if ((events[idx].data.u64 ) == (u64_t)timer_fd)
{
if(debug_flag)begin_time=get_current_time();
conn_manager.clear_inactive();
u64_t dummy;
int unused=read(timer_fd, &dummy, 8);
//current_time_rough=get_current_time();
if(debug_flag)
{
end_time=get_current_time();
mylog(log_debug,"timer_fd,%llu,%llu,%llu\n",begin_time,end_time,end_time-begin_time);
}
mylog(log_trace,"epoll_trigger_counter: %d \n",epoll_trigger_counter);
epoll_trigger_counter=0;
}
else if (events[idx].data.u64 == (u64_t)raw_recv_fd)
{
if(debug_flag)begin_time=get_current_time();
server_on_raw_recv_multi();
if(debug_flag)
{
end_time=get_current_time();
mylog(log_debug,"raw_recv_fd,%llu,%llu,%llu \n",begin_time,end_time,end_time-begin_time);
}
}
else if (events[idx].data.u64 == (u64_t)fifo_fd)
{
int len=read (fifo_fd, buf, sizeof (buf));
if(len<0)
{
mylog(log_warn,"fifo read failed len=%d,errno=%s\n",len,strerror(errno));
continue;
}
//assert(len>=0);
buf[len]=0;
while(len>=1&&buf[len-1]=='\n')
buf[len-1]=0;
mylog(log_info,"got data from fifo,len=%d,s=[%s]\n",len,buf);
mylog(log_info,"unknown command\n");
}
else if (events[idx].data.u64>u32_t(-1) )
{
fd64_t fd64=events[idx].data.u64;
if(!fd_manager.exist(fd64))
{
mylog(log_trace ,"fd64 no longer exist\n");
return -1;
}
assert(fd_manager.exist_info(fd64));
conn_info_t* p_conn_info=fd_manager.get_info(fd64).p_conn_info;
conn_info_t &conn_info=*p_conn_info;
if(fd64==conn_info.timer_fd64)//////////timer_fd64
{
if(debug_flag)begin_time=get_current_time();
int fd=fd_manager.to_fd(fd64);
u64_t dummy;
int unused=read(fd, &dummy, 8);
assert(conn_info.state.server_current_state == server_ready); //TODO remove this for peformance
server_on_timer_multi(conn_info);
if(debug_flag)
{
end_time=get_current_time();
mylog(log_debug,"(events[idx].data.u64 >>32u) == 2u ,%llu,%llu,%llu \n",begin_time,end_time,end_time-begin_time);
}
}
else//udp_fd64
{
if(debug_flag)begin_time=get_current_time();
server_on_udp_recv(conn_info,fd64);
if(debug_flag)
{
end_time=get_current_time();
mylog(log_debug,"(events[idx].data.u64 >>32u) == 1u,%lld,%lld,%lld \n",begin_time,end_time,end_time-begin_time);
}
}
}
else
{
mylog(log_fatal,"unknown fd,this should never happen\n");
myexit(-1);
}
}
}
return 0;
}