-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathEthUDP.c
2035 lines (1853 loc) · 59 KB
/
EthUDP.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* EthUDP: used to create tunnel over ipv4/ipv6 network
by james@ustc.edu.cn 2009.04.02
*/
// kernel use auxdata to send vlan tag, we use auxdata to reconstructe vlan header
#define HAVE_PACKET_AUXDATA 1
// enable OPENSSL encrypt/decrypt support
#define ENABLE_OPENSSL 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <fcntl.h>
#include <unistd.h>
#include <syslog.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <time.h>
#include <net/if.h>
#include <linux/if_packet.h>
#include <linux/if_ether.h>
#include <linux/if_tun.h>
#include <netinet/ip.h>
#include <netinet/ip6.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
#include <netdb.h>
#include <stdarg.h>
#include <errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <lz4.h>
#include <pcap.h>
#define MAXLEN 2048
#define MAX_PACKET_SIZE 9234 // Jumbo Frame
#define MAXFD 64
#define STATUS_BAD 0
#define STATUS_OK 1
#define MASTER 0
#define SLAVE 1
#define MODEE 0 // raw ether bridge mode
#define MODEI 1 // tap interface mode
#define MODEB 2 // bridge mode
#define MODET 3 // tcpdump full packet to remote
#define MODEU 4 // tcpdump udp packet to remote
//#define DEBUGPINGPONG 1
//#define DEBUGSSL 1
// ip & brctl command
#define IPCMD "/sbin/ip"
#define BRIDGECMD "/usr/sbin/brctl"
#define XOR 1
#ifdef ENABLE_OPENSSL
#include <openssl/evp.h>
#define AES_128 2
#define AES_192 3
#define AES_256 3
#else
#define EVP_MAX_BLOCK_LENGTH 0
#endif
#define max(a,b) ((a) > (b) ? (a) : (b))
#ifdef HAVE_PACKET_AUXDATA
#define VLAN_TAG_LEN 4
struct vlan_tag {
u_int16_t vlan_tpid; /* ETH_P_8021Q */
u_int16_t vlan_tci; /* VLAN TCI */
};
#endif
u_int16_t ETHP8021Q; // 0x8100 in network order
struct _EtherHeader {
uint16_t destMAC1;
uint32_t destMAC2;
uint16_t srcMAC1;
uint32_t srcMAC2;
uint32_t VLANTag;
uint16_t type;
int32_t payload;
} __attribute__ ((packed));
typedef struct _EtherHeader EtherPacket;
struct packet_buf {
time_t rcvt; // recv time, 0 if not valid
int len; // buf len
unsigned char *buf; // packet header is 8 bytes: UDPFRG+seq
};
#define MAXPKTS 65536
struct packet_buf packet_bufs[MAXPKTS]; // buf[0] & buf[1] is pair, store the orignal big UDP packets
int daemon_proc; /* set nonzero by daemon_init() */
volatile int debug = 0;
int mode = -1; // 0 eth bridge, 1 interface, 2 bridge
int mtu = 0;
int udp_frg_seq = 0;
int master_slave = 0;
int read_only = 0, write_only = 0;
int fixmss = 0;
int nopromisc = 0;
int loopback_check = 0;
int packet_len = 1500;
char name[MAXLEN];
char run_cmd[MAXLEN];
char dev_name[IFNAMSIZ];
int run_seconds = 0;
int32_t ifindex;
char mypassword[MAXLEN];
int enc_algorithm;
unsigned char enc_key[MAXLEN];
#ifdef ENABLE_OPENSSL
unsigned char enc_iv[EVP_MAX_IV_LENGTH];
#endif
int enc_key_len = 0;
int fdudp[2], fdraw;
int nat[2];
pcap_t *pcap_handle;
int lz4 = 0;
volatile long long udp_total = 0;
volatile long long compress_overhead = 0;
volatile long long compress_save = 0;
volatile long long encrypt_overhead = 0;
#define LZ4_SPACE 128
int vlan_map = 0;
int my_vlan[4096];
int remote_vlan[4096];
volatile struct sockaddr_storage local_addr[2];
volatile struct sockaddr_storage cmd_remote_addr[2];
volatile struct sockaddr_storage remote_addr[2];
volatile unsigned long myticket, last_pong[2]; // myticket inc 1 every 1 second after start
volatile unsigned long ping_send[2], ping_recv[2], pong_send[2], pong_recv[2];
volatile unsigned long raw_send_pkt, raw_send_byte, raw_recv_pkt, raw_recv_byte;
volatile unsigned long udp_send_pkt[2], udp_send_byte[2], udp_recv_pkt[2], udp_recv_byte[2];
volatile unsigned long udp_send_err[2], raw_send_err;
volatile int master_status = STATUS_BAD;
volatile int slave_status = STATUS_BAD;
volatile int current_remote = MASTER;
volatile int got_signal = 1;
void sig_handler_hup(int signo)
{
got_signal = 1;
}
void sig_handler_usr1(int signo)
{
udp_total = compress_overhead = compress_save = encrypt_overhead = 0;
raw_send_pkt = raw_send_byte = raw_recv_pkt = raw_recv_byte = 0;
udp_send_pkt[0] = udp_send_byte[0] = udp_recv_pkt[0] = udp_recv_byte[0] = 0;
udp_send_pkt[1] = udp_send_byte[1] = udp_recv_pkt[1] = udp_recv_byte[1] = 0;
}
void err_doit(int errnoflag, int level, const char *fmt, va_list ap)
{
int errno_save, n;
char buf[MAXLEN];
errno_save = errno; /* value caller might want printed */
vsnprintf(buf, sizeof(buf), fmt, ap); /* this is safe */
n = strlen(buf);
if (errnoflag)
snprintf(buf + n, sizeof(buf) - n, ": %s", strerror(errno_save));
strcat(buf, "\n");
if (daemon_proc) {
if (name[0])
syslog(level, "%s: %s", name, buf);
else
syslog(level, "%s", buf);
} else {
fflush(stdout); /* in case stdout and stderr are the same */
if (name[0]) {
fputs(name, stderr);
fputs(": ", stderr);
}
fputs(buf, stderr);
fflush(stderr);
}
return;
}
void err_msg(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
err_doit(0, LOG_INFO, fmt, ap);
va_end(ap);
return;
}
void Debug(const char *fmt, ...)
{
va_list ap;
if (debug) {
va_start(ap, fmt);
err_doit(0, LOG_INFO, fmt, ap);
va_end(ap);
}
return;
}
void err_quit(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
err_doit(0, LOG_ERR, fmt, ap);
va_end(ap);
exit(1);
}
void err_sys(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
err_doit(1, LOG_ERR, fmt, ap);
va_end(ap);
exit(1);
}
void daemon_init(const char *pname, int facility)
{
int i;
pid_t pid;
if ((pid = fork()) != 0)
exit(0); /* parent terminates */
/* 41st child continues */
setsid(); /* become session leader */
signal(SIGHUP, SIG_IGN);
if ((pid = fork()) != 0)
exit(0); /* 1st child terminates */
/* 42nd child continues */
daemon_proc = 1; /* for our err_XXX() functions */
umask(0); /* clear our file mode creation mask */
for (i = 0; i < MAXFD; i++)
close(i);
openlog(pname, LOG_PID, facility);
}
int udp_server(const char *host, const char *serv, socklen_t * addrlenp, int index)
{
int sockfd, n;
int on = 1;
struct addrinfo hints, *res, *ressave;
bzero(&hints, sizeof(struct addrinfo));
hints.ai_flags = AI_PASSIVE;
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
if ((n = getaddrinfo(host, serv, &hints, &res)) != 0)
err_quit("udp_server error for %s, %s", host, serv);
ressave = res;
do {
sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (sockfd < 0)
continue; /* error, try next one */
memcpy((void *)&(local_addr[index]), res->ai_addr, res->ai_addrlen);
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, 1);
if (bind(sockfd, res->ai_addr, res->ai_addrlen) == 0)
break; /* success */
close(sockfd); /* bind error, close and try next one */
}
while ((res = res->ai_next) != NULL);
if (res == NULL) /* errno from final socket() or bind() */
err_sys("udp_server error for %s, %s", host, serv);
if (addrlenp)
*addrlenp = res->ai_addrlen; /* return size of protocol address */
freeaddrinfo(ressave);
return (sockfd);
}
int udp_xconnect(char *lhost, char *lserv, char *rhost, char *rserv, int index)
{
int sockfd, n;
struct addrinfo hints, *res, *ressave;
sockfd = udp_server(lhost, lserv, NULL, index);
n = 10 * 1024 * 1024;
setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &n, sizeof(n));
if (debug) {
socklen_t ln;
if (getsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &n, &ln) == 0)
Debug("UDP socket RCVBUF setting to %d\n", n);
}
// set IP_MTU_DISCOVER, otherwise UDP has DFbit set
n = 0;
if (setsockopt(sockfd, IPPROTO_IP, IP_MTU_DISCOVER, &n, sizeof(n)) != 0)
err_msg("udp_xeonnect setsockopt returned error, errno %d\n", errno);
bzero(&hints, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
if ((n = getaddrinfo(rhost, rserv, &hints, &res)) != 0)
err_quit("udp_xconnect error for %s, %s", rhost, rserv);
ressave = res;
do {
void *raddr;
if (res->ai_family == AF_INET) { // IPv4
struct sockaddr_in *ipv4 = (struct sockaddr_in *)res->ai_addr;
raddr = &(ipv4->sin_addr);
if ((memcmp(raddr, "\0\0\0\0", 4) == 0) || (ipv4->sin_port == 0)) {
Debug("nat = 1");
nat[index] = 1;
memcpy((void *)&(cmd_remote_addr[index]), res->ai_addr, res->ai_addrlen);
freeaddrinfo(ressave);
return sockfd;
}
} else { // IPv6
struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)res->ai_addr;
raddr = &(ipv6->sin6_addr);
if ((memcmp(raddr, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16) == 0) || (ipv6->sin6_port == 0)) {
Debug("nat = 1");
nat[index] = 1;
memcpy((void *)&(cmd_remote_addr[index]), res->ai_addr, res->ai_addrlen);
freeaddrinfo(ressave);
return sockfd;
}
}
if (connect(sockfd, res->ai_addr, res->ai_addrlen) == 0) {
memcpy((void *)&(cmd_remote_addr[index]), res->ai_addr, res->ai_addrlen);
memcpy((void *)&(remote_addr[index]), res->ai_addr, res->ai_addrlen);
break; /* success */
}
}
while ((res = res->ai_next) != NULL);
if (res == NULL) /* errno set from final connect() */
err_sys("udp_xconnect error for %s, %s", rhost, rserv);
freeaddrinfo(ressave);
return (sockfd);
}
/**
* Open a rawsocket for the network interface
*/
int32_t open_rawsocket(char *ifname, int32_t * rifindex)
{
unsigned char buf[MAX_PACKET_SIZE];
int32_t ifindex;
struct ifreq ifr;
struct sockaddr_ll sll;
int n;
int32_t fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
if (fd == -1)
err_sys("socket %s - ", ifname);
// get interface index
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, ifname, IFNAMSIZ);
if (ioctl(fd, SIOCGIFINDEX, &ifr) == -1)
err_sys("SIOCGIFINDEX %s - ", ifname);
ifindex = ifr.ifr_ifindex;
*rifindex = ifindex;
if (!nopromisc) { // set promiscuous mode
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, ifname, IFNAMSIZ);
ioctl(fd, SIOCGIFFLAGS, &ifr);
ifr.ifr_flags |= IFF_PROMISC;
ioctl(fd, SIOCSIFFLAGS, &ifr);
}
memset(&sll, 0xff, sizeof(sll));
sll.sll_family = AF_PACKET;
sll.sll_protocol = htons(ETH_P_ALL);
sll.sll_ifindex = ifindex;
if (bind(fd, (struct sockaddr *)&sll, sizeof(sll)) == -1)
err_sys("bind %s - ", ifname);
/* flush all received packets.
*
* raw-socket receives packets from all interfaces
* when the socket is not bound to an interface
*/
int32_t i, l = 0;
do {
fd_set fds;
struct timeval t;
FD_ZERO(&fds);
FD_SET(fd, &fds);
memset(&t, 0, sizeof(t));
i = select(FD_SETSIZE, &fds, NULL, NULL, &t);
if (i > 0) {
recv(fd, buf, i, 0);
l++;
};
Debug("interface %d flushed %d packets", ifindex, l);
}
while (i > 0);
/* Enable auxillary data if supported and reserve room for
* reconstructing VLAN headers. */
#ifdef HAVE_PACKET_AUXDATA
int val = 1;
if (setsockopt(fd, SOL_PACKET, PACKET_AUXDATA, &val, sizeof(val)) == -1 && errno != ENOPROTOOPT) {
err_sys("setsockopt(packet_auxdata): %s", strerror(errno));
}
#endif /* HAVE_PACKET_AUXDATA */
Debug("%s opened (fd=%d interface=%d)", ifname, fd, ifindex);
n = 10 * 1024 * 1024;
setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &n, sizeof(n));
if (debug) {
socklen_t ln;
if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &n, &ln) == 0) {
Debug("RAW socket RCVBUF setting to %d", n);
}
}
return fd;
}
int xor_encrypt(u_int8_t * buf, int n, u_int8_t * nbuf)
{
int i;
for (i = 0; i < n; i++)
nbuf[i] = buf[i] ^ enc_key[i % enc_key_len];
return n;
}
#ifdef ENABLE_OPENSSL
int openssl_encrypt(u_int8_t * buf, int len, u_int8_t * nbuf)
{
EVP_CIPHER_CTX *ctx;
int outlen1, outlen2;
#ifdef DEBUGSSL
Debug("aes encrypt len=%d", len);
#endif
ctx = EVP_CIPHER_CTX_new();
if (enc_algorithm == AES_128)
EVP_EncryptInit(ctx, EVP_aes_128_cbc(), enc_key, enc_iv);
else if (enc_algorithm == AES_192)
EVP_EncryptInit(ctx, EVP_aes_192_cbc(), enc_key, enc_iv);
else if (enc_algorithm == AES_256)
EVP_EncryptInit(ctx, EVP_aes_256_cbc(), enc_key, enc_iv);
EVP_EncryptUpdate(ctx, nbuf, &outlen1, buf, len);
EVP_EncryptFinal(ctx, nbuf + outlen1, &outlen2);
len = outlen1 + outlen2;
#ifdef DEBUGSSL
Debug("after aes encrypt len=%d", len);
#endif
EVP_CIPHER_CTX_free(ctx);
return len;
}
int openssl_decrypt(u_int8_t * buf, int len, u_int8_t * nbuf)
{
EVP_CIPHER_CTX *ctx;
int outlen1, outlen2;
#ifdef DEBUGSSL
Debug("aes decrypt len=%d", len);
#endif
ctx = EVP_CIPHER_CTX_new();
if (enc_algorithm == AES_128)
EVP_DecryptInit(ctx, EVP_aes_128_cbc(), enc_key, enc_iv);
else if (enc_algorithm == AES_192)
EVP_DecryptInit(ctx, EVP_aes_192_cbc(), enc_key, enc_iv);
else if (enc_algorithm == AES_256)
EVP_DecryptInit(ctx, EVP_aes_256_cbc(), enc_key, enc_iv);
if (EVP_DecryptUpdate(ctx, nbuf, &outlen1, buf, len) != 1 || EVP_DecryptFinal(ctx, nbuf + outlen1, &outlen2) != 1)
len = 0;
else
len = outlen1 + outlen2;
#ifdef DEBUGSSL
Debug("after aes decrypt len=%d", len);
#endif
EVP_CIPHER_CTX_free(ctx);
return len;
}
#endif
int do_encrypt(u_int8_t * buf, int len, u_int8_t * nbuf)
{
u_int8_t lzbuf[MAX_PACKET_SIZE + LZ4_SPACE];
int nlen;
udp_total += len;
if (lz4 > 0) {
nlen = LZ4_compress_fast((char *)buf, (char *)lzbuf, len, len + LZ4_SPACE, lz4);
if (nlen <= 0) {
err_msg("lz4 compress error");
return 0;
}
if (debug)
Debug("compress %d-->%d save %d byte", len, nlen, len - nlen);
if (nlen < len) { // compressed
lzbuf[nlen] = 0xff; // 0xff means compressed data
nlen++;
compress_save += len - nlen;
len = nlen;
buf = lzbuf;
} else {
buf[len] = 0xaa; // 0xaa means not compressed data
compress_overhead++;
len++;
if (debug)
Debug("not compressed %d", len);
}
}
if (enc_key_len <= 0) {
memcpy(nbuf, buf, len);
return len;
}
if (enc_algorithm == XOR)
nlen = xor_encrypt(buf, len, nbuf);
#ifdef ENABLE_OPENSSL
else if ((enc_algorithm == AES_128)
|| (enc_algorithm == AES_192)
|| (enc_algorithm == AES_256))
nlen = openssl_encrypt(buf, len, nbuf);
#endif
else
return 0;
if (debug)
Debug("encrypt_overhead %d", nlen - len);
encrypt_overhead += nlen - len;
return nlen;
}
int do_decrypt(u_int8_t * buf, int len, u_int8_t * nbuf)
{
u_int8_t lzbuf[MAX_PACKET_SIZE + LZ4_SPACE];
if (enc_key_len > 0) {
if (enc_algorithm == XOR) {
len = xor_encrypt(buf, len, lzbuf);
buf = lzbuf;
}
#ifdef ENABLE_OPENSSL
else if ((enc_algorithm == AES_128)
|| (enc_algorithm == AES_192)
|| (enc_algorithm == AES_256)) {
len = openssl_decrypt(buf, len, lzbuf);
buf = lzbuf;
}
#endif
}
if ((lz4 > 0) && (len > 0)) {
len--;
if (buf[len] == 0xaa) { // not compressed data
if (debug)
Debug("decompress not compressed data %d", len);
memcpy(nbuf, buf, len);
} else if (buf[len] == 0xff) { // compressed data
int nlen;
nlen = LZ4_decompress_safe((char *)buf, (char *)nbuf, len, MAX_PACKET_SIZE + LZ4_SPACE);
if (nlen < 0) {
err_msg("lz4 decompress error");
return 0;
}
if (debug)
Debug("decompress %d-->%d", len, nlen);
len = nlen;
} else {
err_msg("len %d last byte error 0x%02X", len, buf[len]);
return 0;
}
} else
memcpy(nbuf, buf, len);
return len;
}
char *stamp(void)
{
static char st_buf[200];
struct timeval tv;
struct timezone tz;
struct tm *tm;
gettimeofday(&tv, &tz);
tm = localtime(&tv.tv_sec);
snprintf(st_buf, 200, "%02d%02d %02d:%02d:%02d.%06ld", tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, tv.tv_usec);
return st_buf;
}
void printPacket(EtherPacket * packet, ssize_t packetSize, char *message)
{
printf("%s ", stamp());
if ((ntohl(packet->VLANTag) >> 16) == 0x8100) // VLAN tag
printf("%s #%04x (VLAN %d) from %04x%08x to %04x%08x, len=%d\n",
message, ntohs(packet->type),
ntohl(packet->VLANTag) & 0xFFF, ntohs(packet->srcMAC1),
ntohl(packet->srcMAC2), ntohs(packet->destMAC1), ntohl(packet->destMAC2), (int)packetSize);
else
printf("%s #%04x (no VLAN) from %04x%08x to %04x%08x, len=%d\n",
message, ntohl(packet->VLANTag) >> 16,
ntohs(packet->srcMAC1), ntohl(packet->srcMAC2), ntohs(packet->destMAC1), ntohl(packet->destMAC2), (int)packetSize);
fflush(stdout);
}
// function from http://www.bloof.de/tcp_checksumming, thanks to crunsh
u_int16_t tcp_sum_calc(u_int16_t len_tcp, u_int16_t src_addr[], u_int16_t dest_addr[], u_int16_t buff[])
{
u_int16_t prot_tcp = 6;
u_int32_t sum = 0;
int nleft = len_tcp;
u_int16_t *w = buff;
/* calculate the checksum for the tcp header and payload */
while (nleft > 1) {
sum += *w++;
nleft -= 2;
}
/* if nleft is 1 there ist still on byte left. We add a padding byte (0xFF) to build a 16bit word */
if (nleft > 0)
sum += *w & ntohs(0xFF00); /* Thanks to Dalton */
/* add the pseudo header */
sum += src_addr[0];
sum += src_addr[1];
sum += dest_addr[0];
sum += dest_addr[1];
sum += htons(len_tcp);
sum += htons(prot_tcp);
// keep only the last 16 bits of the 32 bit calculated sum and add the carries
sum = (sum >> 16) + (sum & 0xFFFF);
sum += (sum >> 16);
// Take the one's complement of sum
sum = ~sum;
return ((u_int16_t) sum);
}
u_int16_t tcp_sum_calc_v6(u_int16_t len_tcp, u_int16_t src_addr[], u_int16_t dest_addr[], u_int16_t buff[])
{
u_int16_t prot_tcp = 6;
u_int32_t sum = 0;
int nleft = len_tcp;
u_int16_t *w = buff;
/* calculate the checksum for the tcp header and payload */
while (nleft > 1) {
sum += *w++;
nleft -= 2;
}
/* if nleft is 1 there ist still on byte left. We add a padding byte (0xFF) to build a 16bit word */
if (nleft > 0)
sum += *w & ntohs(0xFF00); /* Thanks to Dalton */
/* add the pseudo header */
int i;
for (i = 0; i < 8; i++)
sum = sum + src_addr[i] + dest_addr[i];
sum += htons(len_tcp); // why using 32bit len_tcp
sum += htons(prot_tcp);
// keep only the last 16 bits of the 32 bit calculated sum and add the carries
sum = (sum >> 16) + (sum & 0xFFFF);
sum += (sum >> 16);
// Take the one's complement of sum
sum = ~sum;
return ((u_int16_t) sum);
}
static unsigned int optlen(const u_int8_t * opt, unsigned int offset)
{
/* Beware zero-length options: make finite progress */
if (opt[offset] <= TCPOPT_NOP || opt[offset + 1] == 0)
return 1;
else
return opt[offset + 1];
}
void fix_mss(u_int8_t * buf, int len, int index)
{
u_int8_t *packet;
int i;
if (len < 54)
return;
packet = buf + 12; // skip ethernet dst & src addr
len -= 12;
if ((packet[0] == 0x81) && (packet[1] == 0x00)) { // skip 802.1Q tag 0x8100
packet += 4;
len -= 4;
}
if ((packet[0] == 0x08) && (packet[1] == 0x00)) { // IPv4 packet 0x0800
packet += 2;
len -= 2;
struct iphdr *ip = (struct iphdr *)packet;
if (ip->version != 4)
return; // check ipv4
if (ntohs(ip->frag_off) & 0x1fff)
return; // not the first fragment
if (ip->protocol != IPPROTO_TCP)
return; // not tcp packet
if (ntohs(ip->tot_len) > len)
return; // tot_len should < len
struct tcphdr *tcph = (struct tcphdr *)(packet + ip->ihl * 4);
if (!tcph->syn)
return;
if (debug)
Debug("fixmss ipv4 tcp syn");
u_int8_t *opt = (u_int8_t *) tcph;
for (i = sizeof(struct tcphdr); i < tcph->doff * 4; i += optlen(opt, i)) {
if (opt[i] == 2 && tcph->doff * 4 - i >= 4 && // TCP_MSS
opt[i + 1] == 4) {
u_int16_t newmss = fixmss, oldmss;
oldmss = (opt[i + 2] << 8) | opt[i + 3];
/* Never increase MSS, even when setting it, as
* doing so results in problems for hosts that rely
* on MSS being set correctly.
*/
if (oldmss <= newmss)
return;
if (debug)
Debug("change inner v4 tcp mss from %d to %d", oldmss, newmss);
opt[i + 2] = (newmss & 0xff00) >> 8;
opt[i + 3] = newmss & 0x00ff;
tcph->check = 0; /* Checksum field has to be set to 0 before checksumming */
tcph->check = (u_int16_t)
tcp_sum_calc((u_int16_t)
(ntohs(ip->tot_len) - ip->ihl * 4), (u_int16_t *) & ip->saddr, (u_int16_t *) & ip->daddr, (u_int16_t *) tcph);
return;
}
}
} else if ((packet[0] == 0x86) && (packet[1] == 0xdd)) { // IPv6 packet, 0x86dd
packet += 2;
len -= 2;
struct ip6_hdr *ip6 = (struct ip6_hdr *)packet;
if ((ip6->ip6_vfc & 0xf0) != 0x60)
return; // check ipv6
if (ip6->ip6_nxt != IPPROTO_TCP)
return; // not tcp packet
if (ntohs(ip6->ip6_plen) > len)
return; // tot_len should < len
struct tcphdr *tcph = (struct tcphdr *)(packet + 40);
if (!tcph->syn)
return;
if (debug)
Debug("fixmss ipv6 tcp syn");
u_int8_t *opt = (u_int8_t *) tcph;
for (i = sizeof(struct tcphdr); i < tcph->doff * 4; i += optlen(opt, i)) {
if (opt[i] == 2 && tcph->doff * 4 - i >= 4 && // TCP_MSS
opt[i + 1] == 4) {
u_int16_t newmss = fixmss, oldmss;
oldmss = (opt[i + 2] << 8) | opt[i + 3];
/* Never increase MSS, even when setting it, as
* doing so results in problems for hosts that rely
* on MSS being set correctly.
*/
if (oldmss <= newmss)
return;
if (debug)
Debug("change inner v6 tcp mss from %d to %d", oldmss, newmss);
opt[i + 2] = (newmss & 0xff00) >> 8;
opt[i + 3] = newmss & 0x00ff;
tcph->check = 0; /* Checksum field has to be set to 0 before checksumming */
tcph->check = (u_int16_t) tcp_sum_calc_v6((u_int16_t)
ntohs(ip6->ip6_plen),
(u_int16_t *) & ip6->ip6_src, (u_int16_t *) & ip6->ip6_dst, (u_int16_t *)
tcph);
return;
}
}
}
}
/* return 1 if packet will cause loopback, DSTIP or SRCIP == remote address && PROTO == UDP
*/
int do_loopback_check(u_int8_t * buf, int len)
{
u_int8_t *packet;
if (len < 14) // MAC(12)+Proto(2)+IP(20)
return 0;
packet = buf + 12; // skip ethernet dst & src addr
len -= 12;
if ((packet[0] == 0x81) && (packet[1] == 0x00)) { // skip 802.1Q tag 0x8100
packet += 4;
len -= 4;
}
if ((packet[0] == 0x08) && (packet[1] == 0x00)) { // IPv4 packet 0x0800
packet += 2;
len -= 2;
if (len < 20) // IP header len is 20
return 0;
struct iphdr *ip = (struct iphdr *)packet;
if (ip->version != 4)
return 0; // not ipv4
if (ip->protocol != IPPROTO_UDP)
return 0; // not udp packet
struct sockaddr_in *r = (struct sockaddr_in *)(&remote_addr[MASTER]);
if (ip->saddr == r->sin_addr.s_addr) {
if (debug)
Debug("master remote ipaddr == src addr, loopback");
return 1;
} else if (ip->daddr == r->sin_addr.s_addr) {
if (debug)
Debug("master remote ipaddr == dst addr, loopback");
return 1;
}
if (master_slave) {
r = (struct sockaddr_in *)(&remote_addr[SLAVE]);
if (ip->saddr == r->sin_addr.s_addr) {
if (debug)
Debug("slave remote ipaddr == src addr, loopback");
return 1;
} else if (ip->daddr == r->sin_addr.s_addr) {
if (debug)
Debug("slave remote ipaddr == dst addr, loopback");
return 1;
}
}
} else if ((packet[0] == 0x86) && (packet[1] == 0xdd)) { // IPv6 packet, 0x86dd
packet += 2;
len -= 2;
if (len < 40) // IPv6 header len is 40
return 0;
struct ip6_hdr *ip6 = (struct ip6_hdr *)packet;
if ((ip6->ip6_vfc & 0xf0) != 0x60)
return 0; // not ipv6
if (ip6->ip6_nxt != IPPROTO_UDP)
return 0; // not udp packet
struct sockaddr_in6 *r = (struct sockaddr_in6 *)&remote_addr[MASTER];
if (memcmp(&ip6->ip6_src, &r->sin6_addr, 16) == 0) {
if (debug)
Debug("master remote ip6_addr == src ip6 addr, loopback");
return 1;
} else if (memcmp(&ip6->ip6_dst, &r->sin6_addr, 16) == 0) {
if (debug)
Debug("master remote ip6_addr == dst ip6 addr, loopback");
return 1;
}
if (master_slave) {
r = (struct sockaddr_in6 *)&remote_addr[SLAVE];
if (memcmp(&ip6->ip6_src, &r->sin6_addr, 16) == 0) {
if (debug)
Debug("slave remote ip6_addr == src ip6 addr, loopback");
return 1;
} else if (memcmp(&ip6->ip6_dst, &r->sin6_addr, 16) == 0) {
if (debug)
Debug("slave remote ip6_addr == dst ip6 addr, loopback");
return 1;
}
}
}
return 0;
}
void send_udp_to_remote(u_int8_t * buf, int len, int index);
void send_frag_udp(u_int8_t * buf, int len, int index)
{
unsigned char newbuf[MAX_PACKET_SIZE];
if (len >= 2000) // should not go here
return;
if (len <= 1000) // should not go here
return;
memcpy(newbuf, "UDPFRG", 6);
newbuf[6] = (udp_frg_seq >> 8) & 0xff;
newbuf[7] = udp_frg_seq & 0xff;
memcpy(newbuf + 8, buf, 1000);
if (debug)
Debug("send frag %d, len=1000, total_len=%d", udp_frg_seq, len);
send_udp_to_remote(newbuf, 1008, index);
udp_frg_seq++;
if (udp_frg_seq >= MAXPKTS)
udp_frg_seq = 0;
newbuf[6] = (udp_frg_seq >> 8) & 0xff;
newbuf[7] = udp_frg_seq & 0xff;
memcpy(newbuf + 8, buf + 1000, len - 1000);
if (debug)
Debug("send frag %d, len=%d, total_len=%d", udp_frg_seq, len - 1000, len);
send_udp_to_remote(newbuf, 8 + len - 1000, index);
udp_frg_seq++;
if (udp_frg_seq >= MAXPKTS)
udp_frg_seq = 0;
}
void send_udp_to_remote(u_int8_t * buf, int len, int index) // send udp packet to remote
{
if ((mtu > 0) && (len > mtu - 28))
return send_frag_udp(buf, len, index);
if (nat[index]) {
char rip[200];
if (remote_addr[index].ss_family == AF_INET) {
struct sockaddr_in *r = (struct sockaddr_in *)(&remote_addr[index]);
if (debug)
Debug("nat mode: send len %d to %s:%d", len, inet_ntop(r->sin_family, (void *)&r->sin_addr, rip, 200), ntohs(r->sin_port));
if (r->sin_port) {
sendto(fdudp[index], buf, len, 0, (struct sockaddr *)&remote_addr[index], sizeof(struct sockaddr_storage));
udp_send_pkt[index]++;
udp_send_byte[index] += len;
}
} else if (remote_addr[index].ss_family == AF_INET6) {
struct sockaddr_in6 *r = (struct sockaddr_in6 *)&remote_addr[index];
if (debug)
Debug("nat mode: send len %d to [%s]:%d", len, inet_ntop(r->sin6_family, (void *)&r->sin6_addr, rip, 200), ntohs(r->sin6_port));
if (r->sin6_port) {
sendto(fdudp[index], buf, len, 0, (struct sockaddr *)&remote_addr[index], sizeof(struct sockaddr_storage));
udp_send_pkt[index]++;
udp_send_byte[index] += len;
}
}
} else {
if (write(fdudp[index], buf, len) != len)
udp_send_err[index]++;
else {
udp_send_pkt[index]++;
udp_send_byte[index] += len;
}
}
}
void print_addrinfo(int index)
{
char localip[200];
char cmd_remoteip[200];
char remoteip[200];
if (local_addr[index].ss_family == AF_INET) {
struct sockaddr_in *r = (struct sockaddr_in *)(&local_addr[index]);
int lp, c_rp, rp;
lp = ntohs(r->sin_port);
inet_ntop(AF_INET, &r->sin_addr, localip, 200);
r = (struct sockaddr_in *)(&cmd_remote_addr[index]);
c_rp = ntohs(r->sin_port);
inet_ntop(AF_INET, &r->sin_addr, cmd_remoteip, 200);
r = (struct sockaddr_in *)(&remote_addr[index]);
rp = ntohs(r->sin_port);
inet_ntop(AF_INET, &r->sin_addr, remoteip, 200);
if (nat[index])
err_msg("%s: ST:%d %s:%d --> %s:%d(%s:%d)", index == 0 ? "MASTER" : " SLAVE", index == 0 ? master_status : slave_status, localip, lp,
remoteip, rp, cmd_remoteip, c_rp);
else
err_msg("%s: ST:%d %s:%d --> %s:%d", index == 0 ? "MASTER" : " SLAVE", index == 0 ? master_status : slave_status, localip, lp, remoteip,
rp);
} else if (local_addr[index].ss_family == AF_INET6) {
struct sockaddr_in6 *r = (struct sockaddr_in6 *)(&local_addr[index]);
int lp, c_rp, rp;