-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.c
More file actions
1767 lines (1477 loc) · 61.3 KB
/
main.c
File metadata and controls
1767 lines (1477 loc) · 61.3 KB
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
/*
A virtual router basedon WinTAP and NPcap for multi-network link aggregation.
Copyright (C) <2024> <Repeerc>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <winioctl.h>
#include <ws2def.h>
#include <pthread.h>
#include <iphlpapi.h>
#include <assert.h>
#include <time.h>
#include <pcap.h>
#define REG_PATH "SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002bE10318}\\"
#define NAME_REG_PATH "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\"
#define NPF_PREFIX "\\Device\\NPF_"
#define MAX_OUTPUT_DEVS 32
#define QUEUE_SIZE 1024
#define MAX_THREADS 5
#define STATUS_UPDATE_TIME 1000
#define BLACK 0
#define BLUE 1
#define GREEN 2
#define TURQUOISE 3
#define RED 4
#define PURPLE 5
#define YELLOW 0xE
#define WHITE 7
void SetColor(UINT8 fg, UINT8 bg)
{
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, MAKEWORD(fg, bg));
}
static UINT8 self_mac[] = {0xCC, 0x14, 0x40, 0x80, 0x20, 0x22};
static UINT8 TAP_DEV_MAC[6];
static IN_ADDR self_ip;
HANDLE tap_send_thread[MAX_THREADS];
HANDLE tap_recv_thread[MAX_THREADS];
typedef struct
{
void *buffer[QUEUE_SIZE];
int head;
int tail;
int count;
CRITICAL_SECTION lock;
CONDITION_VARIABLE notEmpty;
CONDITION_VARIABLE notFull;
} Queue;
typedef struct net_status_t
{
uint64_t tx_packets;
uint64_t rx_packets;
uint64_t tx_last_bytes;
uint64_t rx_last_bytes;
uint64_t tx_bytes;
uint64_t rx_bytes;
uint64_t tcp;
uint64_t udp;
uint64_t icmp;
uint64_t arp;
} net_status_t;
typedef struct output_dev_t
{
int index;
char *dev_guid;
char *dev_path;
char *dev_desc;
pcap_t *fp;
BOOL connected;
UINT32 ip;
UINT32 gateway_ip;
UINT8 dev_mac[6];
UINT8 gateway_mac[6];
HANDLE thread;
HANDLE send_thread[MAX_THREADS];
HANDLE recv_thread[MAX_THREADS];
Queue dev_rx_queue;
Queue dev_tx_queue;
net_status_t status;
} output_dev_t;
Queue tap_rx_queue;
Queue tap_tx_queue;
net_status_t tap_net_status;
void initQueue(Queue *q)
{
q->head = 0;
q->tail = 0;
q->count = 0;
InitializeCriticalSection(&q->lock);
InitializeConditionVariable(&q->notEmpty);
InitializeConditionVariable(&q->notFull);
}
void destroyQueue(Queue *q)
{
DeleteCriticalSection(&q->lock);
}
void enqueue(Queue *q, void *value)
{
EnterCriticalSection(&q->lock);
while (q->count == QUEUE_SIZE)
{
SleepConditionVariableCS(&q->notFull, &q->lock, INFINITE);
}
q->buffer[q->tail] = value;
q->tail = (q->tail + 1) % QUEUE_SIZE;
q->count++;
WakeConditionVariable(&q->notEmpty);
LeaveCriticalSection(&q->lock);
}
void *dequeue(Queue *q)
{
EnterCriticalSection(&q->lock);
while (q->count == 0)
{
SleepConditionVariableCS(&q->notEmpty, &q->lock, INFINITE);
}
void *value = q->buffer[q->head];
q->head = (q->head + 1) % QUEUE_SIZE;
q->count--;
WakeConditionVariable(&q->notFull);
LeaveCriticalSection(&q->lock);
return value;
}
#define TCP_STATUS_CLOSED 0
#define TCP_STATUS_SYN_SEND 1
#define TCP_STATUS_ESTABLISHED 2
typedef struct tcp_port_status_t
{
uint8_t out_dev_id;
uint8_t occupany;
uint16_t keepalive_cnt;
int tcp_status;
} tcp_port_status_t;
tcp_port_status_t tcp_port[65536];
output_dev_t out_dev[MAX_OUTPUT_DEVS];
unsigned int registered_devs = 0;
typedef struct __attribute__((packed)) ipParames_t
{
IN_ADDR ip;
IN_ADDR gateway;
IN_ADDR mask;
} ipParames_t;
typedef struct __attribute__((packed)) eth_header_t
{
UINT8 dst_mac[6];
UINT8 src_mac[6];
UINT16 eth_type;
} eth_header_t;
typedef struct __attribute__((packed)) ip_hdr_t
{
UINT8 header_len : 4;
UINT8 version : 4;
UINT8 tos;
UINT16 total_length;
UINT16 id;
UINT16 frag_offset;
UINT8 ttl;
UINT8 protocol;
UINT16 checksum;
union
{
UINT32 src_ip_dw;
UINT8 src_ip[4];
} src_ip_u;
union
{
UINT32 dst_ip_dw;
UINT8 dst_ip[4];
} dst_ip_u;
} ip_hdr_t;
typedef struct __attribute__((packed)) tcp_hdr_t
{
UINT16 source;
UINT16 dest;
UINT32 seq;
UINT32 ack_seq;
UINT16 res1 : 4,
doff : 4,
fin : 1,
syn : 1,
rst : 1,
psh : 1,
ack : 1,
urg : 1,
ece : 1,
cwr : 1;
UINT16 winsz;
UINT16 checksum;
UINT16 urgent_ptr;
} tcp_hdr_t;
typedef struct __attribute__((packed)) udp_hdr_t
{
UINT16 source;
UINT16 dest;
UINT16 len;
UINT16 checksum;
} udp_hdr_t;
typedef struct icmp_header_t
{
unsigned char type;
unsigned char code;
unsigned short checksum;
unsigned short id;
unsigned short sequence;
} icmp_header_t;
typedef struct __attribute__((packed)) arp_header_t
{
UINT16 hdwr_type;
UINT16 protocol_type;
UINT8 hdwr_sz;
UINT8 protocol_sz;
UINT16 opcode;
UINT8 sender_mac[6];
union
{
UINT8 sender_ip[4];
UINT32 sender_ip_4;
};
UINT8 target_mac[6];
union
{
UINT8 target_ip[4];
UINT32 target_ip_4;
};
} arp_header_t;
#define ETHERTYPE_ARP 0x0806
#define ETHERTYPE_IP 0x0800
#define ETHERTYPE_IPV6 0x86DD
#define ETH_ALEN 6
#define ARP_REQUEST 0x0001
#define ARP_REPLY 0x0002
#define TAP_WIN_CONTROL_CODE(request, method) \
CTL_CODE(FILE_DEVICE_UNKNOWN, request, method, FILE_ANY_ACCESS)
#define TAP_WIN_IOCTL_GET_MAC TAP_WIN_CONTROL_CODE(1, METHOD_BUFFERED)
#define TAP_WIN_IOCTL_GET_VERSION TAP_WIN_CONTROL_CODE(2, METHOD_BUFFERED)
#define TAP_WIN_IOCTL_GET_MTU TAP_WIN_CONTROL_CODE(3, METHOD_BUFFERED)
#define TAP_WIN_IOCTL_GET_INFO TAP_WIN_CONTROL_CODE(4, METHOD_BUFFERED)
#define TAP_WIN_IOCTL_CONFIG_POINT_TO_POINT TAP_WIN_CONTROL_CODE(5, METHOD_BUFFERED)
#define TAP_WIN_IOCTL_SET_MEDIA_STATUS TAP_WIN_CONTROL_CODE(6, METHOD_BUFFERED)
#define TAP_WIN_IOCTL_CONFIG_DHCP_MASQ TAP_WIN_CONTROL_CODE(7, METHOD_BUFFERED)
#define TAP_WIN_IOCTL_GET_LOG_LINE TAP_WIN_CONTROL_CODE(8, METHOD_BUFFERED)
#define TAP_WIN_IOCTL_CONFIG_DHCP_SET_OPT TAP_WIN_CONTROL_CODE(9, METHOD_BUFFERED)
int get_tap_instance(wchar_t *id, char *name)
{
for (int seq = 0; seq <= 9999; seq++)
{
HKEY hKey;
HKEY hKeyNetwork;
LONG status;
DWORD dwSize;
DWORD dwType;
BYTE byData[1024];
DWORD dwSizeName;
DWORD dwTypeName;
BYTE byDataName[1024];
char path[1024];
sprintf_s(path, sizeof(path), REG_PATH "%04d", seq);
status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT(path), 0, KEY_READ, &hKey);
if (status != ERROR_SUCCESS)
{
// printf("RegOpenKeyEx failed: %ld\n", status);
printf("No found TAP adapter \"mix-tap\": %ld\n", status);
return -1;
}
dwSize = sizeof(byData) - 1;
memset(byData, 0, sizeof(byData));
status = RegQueryValueEx(hKey, TEXT("MatchingDeviceId"), NULL, &dwType, byData, &dwSize);
if (status == ERROR_SUCCESS && dwType == REG_SZ)
{
if (strcmp("tap0901", (char *)byData) == 0)
{
dwSize = sizeof(byData) - 1;
memset(byData, 0, sizeof(byData));
status = RegQueryValueEx(hKey, TEXT("NetCfgInstanceId"), NULL, &dwType, byData, &dwSize);
if (status == ERROR_SUCCESS && dwType == REG_SZ)
{
sprintf_s(path, sizeof(path), NAME_REG_PATH "%s\\Connection", (char *)byData);
// printf("adapter reg path:%s\n", path);
status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT(path), 0, KEY_READ, &hKeyNetwork);
;
if (status != ERROR_SUCCESS)
{
RegCloseKey(hKey);
continue;
}
dwSizeName = sizeof(byDataName) - 1;
memset(byDataName, 0, sizeof(byDataName));
status = RegQueryValueEx(hKeyNetwork, TEXT("Name"), NULL, &dwTypeName, byDataName, &dwSizeName);
if (strcmp((char *)byDataName, "mix-tap"))
{
RegCloseKey(hKeyNetwork);
RegCloseKey(hKey);
continue;
}
printf("adapter name:%s\n", (char *)byDataName);
strcpy(name, (char *)byDataName);
int len = strlen((char *)byData);
for (int i = 0; i < len; i++)
{
id[i] = byData[i];
}
id[len] = 0;
RegCloseKey(hKeyNetwork);
RegCloseKey(hKey);
return 0;
}
else
{
printf("err: %ld\n", status);
}
printf("Value: [%s]\n", byData);
}
}
RegCloseKey(hKey);
}
return -1;
}
HANDLE tuntap = INVALID_HANDLE_VALUE;
ipParames_t defConf = {
.ip.S_un.S_un_b = {0, 0, 0, 0},
.gateway.S_un.S_un_b = {0, 0, 0, 0},
.mask.S_un.S_un_b = {0, 0, 0, 0},
};
BOOL WINAPI ConsoleCtrlHandler(DWORD ctrlType)
{
if (ctrlType == CTRL_C_EVENT)
{
printf("CTRL+C received. Exiting...\n");
for(int j = 0; j < MAX_THREADS ; j++)
{
CloseHandle(tap_recv_thread[j]);
CloseHandle(tap_send_thread[j]);
}
destroyQueue(&tap_rx_queue);
destroyQueue(&tap_tx_queue);
CloseHandle(tuntap);
for(int i = 0; i < registered_devs; i++)
{
for(int j = 0; j < MAX_THREADS ; j++)
{
CloseHandle(out_dev[i].send_thread[j]);
CloseHandle(out_dev[i].recv_thread[j]);
}
CloseHandle(out_dev[i].thread);
destroyQueue(&out_dev[i].dev_rx_queue);
destroyQueue(&out_dev[i].dev_tx_queue);
pcap_close(out_dev[i].fp);
}
WSACleanup();
exit(0);
return TRUE;
}
return FALSE;
}
int info(const char *__format, ...)
{
int __retval;
va_list __local_argv;
va_start(__local_argv, __format);
__retval = vfprintf(stdout, __format, __local_argv);
va_end(__local_argv);
return __retval;
}
UINT32 MTU = 0;
UINT32 MAX_FRAME_SZ = 0;
void print_mac(UINT8 mac[6])
{
for (int i = 0; i < 5; i++)
info("%02X:", mac[i]);
info("%02X", mac[5]);
}
void print_ip(UINT8 ip[4])
{
for (int i = 0; i < 3; i++)
info("%d.", ip[i]);
info("%d", ip[3]);
}
void print_inaddr(struct in_addr ip)
{
printf("%d.%d.%d.%d", ip.S_un.S_un_b.s_b1, ip.S_un.S_un_b.s_b2, ip.S_un.S_un_b.s_b3, ip.S_un.S_un_b.s_b4);
}
UINT16 calc_ip_checksum(UINT16 *buf, int nbyte)
{
UINT32 sum = 0;
while (nbyte > 1)
{
sum += *buf;
buf++;
nbyte -= 2;
}
if (nbyte)
{
sum += *buf & 0xFF;
}
while (sum >> 16)
{
sum = (sum & 0xFFFF) + (sum >> 16);
}
return (UINT16)(~sum);
}
struct __attribute__((packed)) pseudo_header
{
uint32_t source_address;
uint32_t dest_address;
uint8_t placeholder;
uint8_t protocol;
uint16_t tcp_length;
};
UINT16 calc_tcp_checksum(UINT32 src_ip, UINT32 dst_ip, UINT8 *tcp_head, int nbyte)
{
UINT16 res = 0;
struct pseudo_header psh;
psh.source_address = src_ip;
psh.dest_address = dst_ip;
psh.placeholder = 0;
psh.protocol = IPPROTO_TCP;
psh.tcp_length = htons(nbyte);
int psize = sizeof(struct pseudo_header) + nbyte;
char *pseudogram = malloc(psize);
memcpy(pseudogram, (char *)&psh, sizeof(struct pseudo_header));
memcpy(pseudogram + sizeof(struct pseudo_header), tcp_head, nbyte);
res = calc_ip_checksum((UINT16 *)pseudogram, psize);
free(pseudogram);
return res;
}
UINT16 calc_udp_checksum(UINT32 src_ip, UINT32 dst_ip, UINT8 *udp_head, int nbyte)
{
UINT16 res = 0;
struct pseudo_header psh;
psh.source_address = src_ip;
psh.dest_address = dst_ip;
psh.placeholder = 0;
psh.protocol = IPPROTO_UDP;
psh.tcp_length = htons(nbyte);
int psize = sizeof(struct pseudo_header) + nbyte;
char *pseudogram = malloc(psize);
memcpy(pseudogram, (char *)&psh, sizeof(struct pseudo_header));
memcpy(pseudogram + sizeof(struct pseudo_header), udp_head, nbyte);
res = calc_ip_checksum((UINT16 *)pseudogram, psize);
free(pseudogram);
return res;
}
struct frame_tx_info
{
void *dat;
size_t len;
};
DWORD WINAPI tap_tx_thread(LPVOID arg)
{
while (1)
{
struct frame_tx_info *inf = dequeue(&tap_tx_queue);
OVERLAPPED txOverLapped = {0};
DWORD wrSz = 0;
txOverLapped.hEvent = CreateEvent(0, 0, 0, "");
WriteFile(tuntap, inf->dat, inf->len, &wrSz, &txOverLapped);
InterlockedExchangeAdd64((int64_t *)&tap_net_status.tx_bytes, inf->len);
InterlockedIncrement64((int64_t *)&tap_net_status.tx_packets);
WaitForSingleObject(txOverLapped.hEvent, INFINITE);
free(inf->dat);
free(inf);
}
return 0;
}
// void *frame_tx(void *dat, size_t len)
// {
// // struct frame_tx_info *arg = calloc(1, sizeof(struct frame_tx_info));
// // arg->dat = dat;
// // arg->len = len;
// // pthread_create(NULL, NULL, frame_tx_thread, arg);
// OVERLAPPED txOverLapped = {0};
// DWORD wrSz = 0;
// txOverLapped.hEvent = CreateEvent(0, 0, 0, "");
// WriteFile(tuntap, dat, len, &wrSz, &txOverLapped);
// WaitForSingleObject(txOverLapped.hEvent, INFINITE);
// free(dat);
// return NULL;
// }
typedef struct dev_pack_send_info_t
{
int dev;
void *dat;
size_t len;
uint16_t tcp_port;
} dev_pack_send_info_t;
DWORD WINAPI dev_send_pack_thread(LPVOID arg)
{
uint32_t dev_idx = (uint64_t)arg;
while (1)
{
dev_pack_send_info_t *inf = dequeue(&out_dev[dev_idx].dev_tx_queue);
if (out_dev[inf->dev].connected)
{
if (pcap_sendpacket(out_dev[inf->dev].fp, // Adapter
inf->dat, // buffer with the packet
inf->len // size
) < 0)
{
fprintf(stderr, "\nError sending the packet: %s\n", pcap_geterr(out_dev[inf->dev].fp));
out_dev[inf->dev].connected = FALSE;
out_dev[inf->dev].ip = 0;
tcp_port[inf->tcp_port].tcp_status = TCP_STATUS_CLOSED;
}
InterlockedAdd64((int64_t *)&out_dev[inf->dev].status.tx_bytes, inf->len);
InterlockedIncrement64((int64_t *)&out_dev[inf->dev].status.tx_packets);
}
free(inf->dat);
free(inf);
}
return 0;
}
void *frame_rx(void *dat)
{
UINT8 *frame_dat = dat;
eth_header_t *eth_head = dat;
// info("src_mac:");
// print_mac(eth_head->src_mac);
// info(" dst_mac:");
// print_mac(eth_head->dst_mac);
// info(" eth_type:%04X\n", eth_head->eth_type);
switch (htons(eth_head->eth_type))
{
case ETHERTYPE_ARP:
{
arp_header_t *arp_head = (void *)&frame_dat[sizeof(eth_header_t)];
if (arp_head->target_ip_4 == self_ip.S_un.S_addr)
{
InterlockedIncrement64((int64_t *)&tap_net_status.arp);
// info("sender mac:");
// print_mac(arp_head->sender_mac);
// info(" sender ip:");
// print_ip(arp_head->sender_ip);
// info(" target mac:");
// print_mac(arp_head->target_mac);
// info(" target ip:");
// print_ip(arp_head->target_ip);
// info(" arp_type:%04X\n", arp_head->opcode);
int reply_len = sizeof(eth_header_t) + sizeof(arp_header_t);
UINT8 *reply = malloc(reply_len);
assert(reply);
eth_header_t *rep_eth = (void *)reply;
arp_header_t *rep_arp = (void *)&reply[sizeof(eth_header_t)];
memcpy(rep_eth->src_mac, self_mac, ETH_ALEN);
memcpy(rep_eth->dst_mac, arp_head->sender_mac, ETH_ALEN);
rep_eth->eth_type = htons(ETHERTYPE_ARP);
rep_arp->hdwr_type = htons(1); // Ethernet
rep_arp->protocol_type = htons(0x0800); // ETHERTYPE_IP
rep_arp->hdwr_sz = ETH_ALEN;
rep_arp->protocol_sz = 4;
rep_arp->opcode = htons(ARP_REPLY);
rep_arp->sender_ip_4 = self_ip.S_un.S_addr;
memcpy(rep_arp->sender_mac, self_mac, ETH_ALEN);
rep_arp->target_ip_4 = arp_head->sender_ip_4;
memcpy(rep_arp->target_mac, arp_head->sender_mac, ETH_ALEN);
struct frame_tx_info *frame_tx_inf = malloc(sizeof(struct frame_tx_info));
frame_tx_inf->dat = reply;
frame_tx_inf->len = reply_len;
enqueue(&tap_tx_queue, frame_tx_inf);
// frame_tx(reply, reply_len);
}
}
break;
case ETHERTYPE_IP:
{
void *ip_head_addr = (void *)&frame_dat[sizeof(eth_header_t)];
ip_hdr_t *ip_head = ip_head_addr;
if (ip_head->version == 4)
{
// UINT16 chksum = calc_ip_checksum((UINT16 *)ip_head_addr, ip_head->header_len * 4);
// if (!chksum)
{
void *ip_payload_addr = (void *)(((UINT32 *)ip_head_addr) + ip_head->header_len);
size_t ip_payload_len = ntohs(ip_head->total_length) - ip_head->header_len * 4;
InterlockedAdd64((int64_t *)&tap_net_status.rx_bytes, ntohs(ip_head->total_length) + 14);
// printf(" IP packet: src:");
// print_ip(ip_head->src_ip_u.src_ip);
// printf(" dst:");
// print_ip(ip_head->dst_ip_u.dst_ip);
// printf(" len: %d\n", ntohs(ip_head->total_length));
//========================== to this virtual router ==================
if (ip_head->dst_ip_u.dst_ip_dw == self_ip.S_un.S_addr)
{
switch (ip_head->protocol)
{
case IPPROTO_ICMP:
{
InterlockedIncrement64((int64_t *)&tap_net_status.icmp);
icmp_header_t *icmp_head = ip_payload_addr;
size_t reply_len = ntohs(ip_head->total_length) + sizeof(eth_header_t);
UINT8 *reply = malloc(reply_len);
assert(reply);
eth_header_t *rep_eth = (void *)reply;
void *rep_ip_head = (void *)&reply[sizeof(eth_header_t)];
ip_hdr_t *rep_ip = rep_ip_head;
memcpy(rep_eth->src_mac, self_mac, ETH_ALEN);
memcpy(rep_eth->dst_mac, eth_head->src_mac, ETH_ALEN);
rep_eth->eth_type = htons(ETHERTYPE_IP);
rep_ip->header_len = 5;
rep_ip->version = 4;
rep_ip->tos = 0;
rep_ip->total_length = ip_head->total_length;
rep_ip->id = htons(rand());
rep_ip->frag_offset = 0;
rep_ip->ttl = ip_head->ttl - 1;
rep_ip->protocol = IPPROTO_ICMP;
rep_ip->src_ip_u.src_ip_dw = self_ip.S_un.S_addr;
rep_ip->dst_ip_u.dst_ip_dw = ip_head->src_ip_u.src_ip_dw;
rep_ip->checksum = 0;
rep_ip->checksum = (calc_ip_checksum((UINT16 *)rep_ip_head, rep_ip->header_len * 4));
void *rep_ip_payload_addr = (void *)&reply[sizeof(eth_header_t) + sizeof(ip_hdr_t)];
memcpy(rep_ip_payload_addr, ip_payload_addr, ip_payload_len);
icmp_header_t *rep_icmp = rep_ip_payload_addr;
rep_icmp->type = 0;
rep_icmp->code = 0;
rep_icmp->id = icmp_head->id;
rep_icmp->sequence = icmp_head->sequence;
rep_icmp->checksum = 0;
rep_icmp->checksum = (calc_ip_checksum((UINT16 *)rep_ip_payload_addr, ip_payload_len));
struct frame_tx_info *frame_tx_inf = malloc(sizeof(struct frame_tx_info));
frame_tx_inf->dat = reply;
frame_tx_inf->len = reply_len;
enqueue(&tap_tx_queue, frame_tx_inf);
// frame_tx(reply, reply_len);
// free(reply);
}
break;
default:
break;
}
}
else
//========================== IP forward =========================
{
switch (ip_head->protocol)
{
case IPPROTO_ICMP:
{
InterlockedIncrement64((int64_t *)&tap_net_status.icmp);
int select = rand() % registered_devs; // = ((ntohs(tcp_head->source) % 3) == 0);
// static int sadd = 0;
size_t fwd_len = ntohs(ip_head->total_length) + sizeof(eth_header_t);
UINT8 *fwd_packet = malloc(fwd_len);
assert(fwd_packet);
eth_header_t *fwd_eth_hdr = (void *)fwd_packet;
// printf("sel:%s\n", out_dev[select].dev_path);
memcpy(fwd_eth_hdr->src_mac, out_dev[select].dev_mac, ETH_ALEN);
memcpy(fwd_eth_hdr->dst_mac, out_dev[select].gateway_mac, ETH_ALEN);
fwd_eth_hdr->eth_type = htons(ETHERTYPE_IP);
void *fwd_ip_head = (void *)&fwd_packet[sizeof(eth_header_t)];
memcpy(fwd_ip_head, ip_head, ntohs(ip_head->total_length));
ip_hdr_t *fwd_ip_h = fwd_ip_head;
fwd_ip_h->checksum = 0;
fwd_ip_h->ttl -= 1;
void *fwd_ip_payload_addr = (void *)&fwd_packet[sizeof(eth_header_t) + fwd_ip_h->header_len * 4];
fwd_ip_h->src_ip_u.src_ip_dw = out_dev[select].ip;
fwd_ip_h->checksum = calc_ip_checksum((UINT16 *)fwd_ip_head, fwd_ip_h->header_len * 4);
memcpy(fwd_ip_payload_addr, ip_payload_addr, ip_payload_len);
dev_pack_send_info_t *inf = malloc(sizeof(dev_pack_send_info_t));
inf->dev = select;
inf->dat = fwd_packet;
inf->len = fwd_len;
InterlockedIncrement64((int64_t *)&out_dev[select].status.icmp);
enqueue(&out_dev[select].dev_tx_queue, inf);
}
break;
case IPPROTO_TCP:
{
InterlockedIncrement64((int64_t *)&tap_net_status.tcp);
tcp_hdr_t *tcp_head = ip_payload_addr;
// chksum = calc_tcp_checksum(ip_head->src_ip_u.src_ip_dw, ip_head->dst_ip_u.dst_ip_dw, ip_payload_addr, ip_payload_len);
// if (chksum == 0)
{
// printf("TCP src port:%d, dst port:%d\n", ntohs(tcp_head->source), ntohs(tcp_head->dest));
// printf("ack:%d, syn:%d, rst:%d, fin:%d\n", tcp_head->ack, tcp_head->syn, tcp_head->rst, tcp_head->fin);
int select = 0; // = ((ntohs(tcp_head->source) % 3) == 0);
static int sadd = 0;
select = tcp_port[ntohs(tcp_head->source)].out_dev_id;
if (tcp_head->syn)
{
select = rand() % registered_devs;
// select = ntohs(tcp_head->source) % 2;
sadd += 1;
if (tcp_port[ntohs(tcp_head->source)].tcp_status != TCP_STATUS_CLOSED)
{
// printf("port %d collision\n", ntohs(tcp_head->source));
}
tcp_port[ntohs(tcp_head->source)].tcp_status = TCP_STATUS_SYN_SEND;
tcp_port[ntohs(tcp_head->source)].out_dev_id = select;
}
else if (tcp_head->rst || tcp_head->fin)
{
tcp_port[ntohs(tcp_head->source)].tcp_status = TCP_STATUS_CLOSED;
}
else
{
if (tcp_port[ntohs(tcp_head->source)].tcp_status == TCP_STATUS_ESTABLISHED)
{
// if((rand() % 100) > 80)
// break;
}
else
{
// printf("port %d closed\n", ntohs(tcp_head->source));
break;
}
}
size_t fwd_len = ntohs(ip_head->total_length) + sizeof(eth_header_t);
UINT8 *fwd_packet = malloc(fwd_len);
assert(fwd_packet);
eth_header_t *fwd_eth_hdr = (void *)fwd_packet;
// printf("sel:%s\n", out_dev[select].dev_path);
memcpy(fwd_eth_hdr->src_mac, out_dev[select].dev_mac, ETH_ALEN);
memcpy(fwd_eth_hdr->dst_mac, out_dev[select].gateway_mac, ETH_ALEN);
fwd_eth_hdr->eth_type = htons(ETHERTYPE_IP);
void *fwd_ip_head = (void *)&fwd_packet[sizeof(eth_header_t)];
memcpy(fwd_ip_head, ip_head, ntohs(ip_head->total_length));
ip_hdr_t *fwd_ip_h = fwd_ip_head;
fwd_ip_h->checksum = 0;
// fwd_ip_h->ttl -= 1;
void *fwd_ip_payload_addr = (void *)&fwd_packet[sizeof(eth_header_t) + fwd_ip_h->header_len * 4];
tcp_hdr_t *fwd_tcp_head = fwd_ip_payload_addr;
fwd_ip_h->src_ip_u.src_ip_dw = out_dev[select].ip;
fwd_ip_h->checksum = calc_ip_checksum((UINT16 *)fwd_ip_head, fwd_ip_h->header_len * 4);
memcpy(fwd_ip_payload_addr, ip_payload_addr, ip_payload_len);
fwd_tcp_head->checksum = 0;
fwd_tcp_head->checksum = calc_tcp_checksum(fwd_ip_h->src_ip_u.src_ip_dw, fwd_ip_h->dst_ip_u.dst_ip_dw, fwd_ip_payload_addr, ip_payload_len);
if (!fwd_tcp_head->checksum)
fwd_tcp_head->checksum = 0xFFFF;
dev_pack_send_info_t *inf = malloc(sizeof(dev_pack_send_info_t));
inf->dev = select;
inf->dat = fwd_packet;
inf->len = fwd_len;
inf->tcp_port = ntohs(tcp_head->source);
enqueue(&out_dev[select].dev_tx_queue, inf);
InterlockedIncrement64((int64_t *)&out_dev[select].status.tcp);
/*
if (pcap_sendpacket(out_dev[select].fp, // Adapter
fwd_packet, // buffer with the packet
fwd_len // size
) < 0)
{
fprintf(stderr, "\nError sending the packet: %s\n", pcap_geterr(out_dev[select].fp));
out_dev[select].connected = FALSE;
tcp_port[ntohs(tcp_head->source)].tcp_status = TCP_STATUS_CLOSED;
}
free(fwd_packet);
*/
}
}
break;
case IPPROTO_UDP:
{
InterlockedIncrement64((int64_t *)&tap_net_status.udp);
// udp_hdr_t *udp_head = ip_payload_addr;
if (ip_head->dst_ip_u.dst_ip[0] < 253)
{
int select = rand() % registered_devs; // = ((ntohs(tcp_head->source) % 3) == 0);
// static int sadd = 0;
size_t fwd_len = ntohs(ip_head->total_length) + sizeof(eth_header_t);
UINT8 *fwd_packet = malloc(fwd_len);
assert(fwd_packet);
eth_header_t *fwd_eth_hdr = (void *)fwd_packet;
// printf("sel:%s\n", out_dev[select].dev_path);
memcpy(fwd_eth_hdr->src_mac, out_dev[select].dev_mac, ETH_ALEN);
memcpy(fwd_eth_hdr->dst_mac, out_dev[select].gateway_mac, ETH_ALEN);
fwd_eth_hdr->eth_type = htons(ETHERTYPE_IP);
void *fwd_ip_head = (void *)&fwd_packet[sizeof(eth_header_t)];
memcpy(fwd_ip_head, ip_head, ntohs(ip_head->total_length));
ip_hdr_t *fwd_ip_h = fwd_ip_head;
fwd_ip_h->checksum = 0;
// fwd_ip_h->ttl -= 1;
void *fwd_ip_payload_addr = (void *)&fwd_packet[sizeof(eth_header_t) + fwd_ip_h->header_len * 4];
udp_hdr_t *fwd_udp_head = fwd_ip_payload_addr;
fwd_ip_h->src_ip_u.src_ip_dw = out_dev[select].ip;
fwd_ip_h->checksum = calc_ip_checksum((UINT16 *)fwd_ip_head, fwd_ip_h->header_len * 4);
memcpy(fwd_ip_payload_addr, ip_payload_addr, ip_payload_len);
fwd_udp_head->checksum = 0;
fwd_udp_head->checksum = calc_udp_checksum(fwd_ip_h->src_ip_u.src_ip_dw, fwd_ip_h->dst_ip_u.dst_ip_dw, fwd_ip_payload_addr, ip_payload_len);
if (!fwd_udp_head->checksum)
fwd_udp_head->checksum = 0xFFFF;
dev_pack_send_info_t *inf = malloc(sizeof(dev_pack_send_info_t));
inf->dev = select;
inf->dat = fwd_packet;
inf->len = fwd_len;
enqueue(&out_dev[select].dev_tx_queue, inf);
InterlockedIncrement64((int64_t *)&out_dev[select].status.udp);
}
}
break;
}
}
}
}
}
break;
default:
break;
}
// for(int i = 0; i < 16; i++)
//{
// printf("%02X ", frame_dat[i]);
// }
// printf("\n");
free(frame_dat);
return NULL;
}
DWORD WINAPI tap_rx_thread(LPVOID arg)
{
while (1)
{
void *dat = dequeue(&tap_rx_queue);
frame_rx(dat);
}
return 0;
}
int get_adapter_ip(output_dev_t *dev)
{
PIP_ADAPTER_INFO pAdapterInfo;
PIP_ADAPTER_INFO pAdapter = NULL;
DWORD dwRetVal = 0;
ULONG ulOutBufLen = sizeof(IP_ADAPTER_INFO);
int ret = 2;
pAdapterInfo = (IP_ADAPTER_INFO *)malloc(sizeof(IP_ADAPTER_INFO));
if (pAdapterInfo == NULL)
{
printf("Error allocating memory.\n");
return 1;
}
if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW)