This repository has been archived by the owner on Jan 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
sysdep.c
954 lines (821 loc) · 20 KB
/
sysdep.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
/* IPSec VPN client compatible with Cisco equipment.
Copyright (C) 2007 Maurice Massar
Copyright (C) 2007 Paolo Zarpellon <[email protected]> (Cygwin support)
based on VTun - Virtual Tunnel over TCP/IP network.
Copyright (C) 1998-2000 Maxim Krasnyansky <[email protected]>
VTun has been derived from VPPP package by Maxim Krasnyansky.
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 2 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.
*/
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <syslog.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <sys/socket.h>
#include <net/if.h>
#ifdef __sun__
#include <ctype.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <signal.h>
#include <stropts.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#endif
#if defined(__CYGWIN__)
#include <io.h>
#include <w32api/windef.h>
#include <w32api/winbase.h>
#include <w32api/winnt.h>
#include <w32api/winioctl.h>
#include <w32api/iphlpapi.h>
#include <w32api/iptypes.h>
#include <w32api/winreg.h>
#include <sys/cygwin.h>
#endif
#if defined(__DragonFly__)
#include <net/tun/if_tun.h>
#elif defined(__linux__)
#include <linux/if_tun.h>
#elif defined(__APPLE__)
/* xnu 1456.1.26 (OS X 10.6)+ supports native user tunnel (utun) sockets */
#include <ctype.h>
#include <sys/ioctl.h>
#include <sys/kern_control.h>
#include <sys/uio.h>
#include <sys/sys_domain.h>
#include <net/if_utun.h>
#include <netinet/ip.h>
#elif defined(__CYGWIN__)
#include "tap-win32.h"
#else
#include <net/if_tun.h>
#endif
#include "sysdep.h"
#if !defined(HAVE_VASPRINTF) || !defined(HAVE_ASPRINTF) || !defined(HAVE_ERROR)
#include <stdarg.h>
#endif
#if defined(__sun__)
extern char **environ;
static int ip_fd = -1, muxid;
#endif
#if defined(__APPLE__)
/* xnu 1456.1.26 (OS X 10.6)+ implements native user tunnels. untun devices are sockets
* rather than character devices. They behave like FreeBSD or OpenBSD tunnels and do not
* require the tuntaposx driver kext to be loaded to work.
*/
/* Try to open the specified utun device. Return -2 on early failure.
* Return -1 if utun is supported but the requested utun is alread in use.
*
* Using this mechanism because relying on sc.sc_unit = 0 to allocate the next
* available utun is unreliable after sleep/resume on Darwin 14.0/xnu-2782.1.9
* (aka OS X Yosemite 10.10 GM). Sometimes it will re-use utun0 and fail to work
* Sometimes it will allocate a utun that immediately causes a kernel panic
* when accessed.
*/
#define XNU_NO_UTUN_IFACE_NAME -3
#define XNU_UTUN_UNSUPPORTED -2
#define XNU_UTUN_IN_USE -1
static int xnu_open_utun(int utunnum)
{
int fd;
struct sockaddr_ctl sc;
struct ctl_info ctlInfo;
if (strlcpy(ctlInfo.ctl_name, UTUN_CONTROL_NAME, sizeof(ctlInfo.ctl_name)) >=
sizeof(ctlInfo.ctl_name))
{
printf("Opening utun: UTUN_CONTROL_NAME too long\n");
return XNU_UTUN_UNSUPPORTED;
}
//open socket
fd = socket(PF_SYSTEM, SOCK_DGRAM, SYSPROTO_CONTROL);
if (fd < 0) {
printf("Opening utun (%s): %s", "socket(SYSPROTO_CONTROL)",strerror (errno));
return XNU_UTUN_UNSUPPORTED;
}
if (ioctl(fd, CTLIOCGINFO, &ctlInfo) == -1)
{
close (fd);
printf("Opening utun (%s): %s", "ioctl(CTLIOCGINFO)", strerror (errno));
return XNU_UTUN_UNSUPPORTED;
}
//connect socket to utun
sc.sc_id = ctlInfo.ctl_id;
sc.sc_len = sizeof(sc);
sc.sc_family = AF_SYSTEM;
sc.ss_sysaddr = AF_SYS_CONTROL;
sc.sc_unit = utunnum + 1; //utunX where X is sc.sc_unit -1.
if (connect (fd, (struct sockaddr *)&sc, sizeof(sc)) < 0)
{
//utun is already in use.
close(fd);
return XNU_UTUN_IN_USE;
}
return fd;
}
int utun_open(char *dev)
{
int fd;
char utunname[IFNAMSIZ];
socklen_t utunname_len = sizeof(utunname);
int utunnum;
for(utunnum=0; utunnum<255; utunnum++)
{
fd = xnu_open_utun(utunnum);
if(fd != XNU_UTUN_IN_USE) break; //XNU_UTUN_IN_USE means requested utun is busy, try another.
}
if(fd >= 0) {
/* Retrieve the assigned interface name. */
if (getsockopt (fd, SYSPROTO_CONTROL, UTUN_OPT_IFNAME, utunname, &utunname_len)) {
printf("Error retrieving utun interface name\n");
return XNU_NO_UTUN_IFACE_NAME;
}
strcpy(dev, utunname); //return device name
}
return fd; //fd or error code
}
#endif
#if defined(__CYGWIN__)
/*
* Overlapped structures for asynchronous read and write
*/
static OVERLAPPED overlap_read, overlap_write;
typedef enum {
SEARCH_IF_GUID_FROM_NAME,
SEARCH_IF_NAME_FROM_GUID
} search_if_en;
#endif
/*
* Allocate TUN/TAP device, returns opened fd.
* Stores dev name in the first arg(must be large enough).
*/
#if defined(__sun__)
int tun_open(char *dev, enum if_mode_enum mode)
{
int tun_fd, if_fd, ppa = -1;
struct ifreq ifr;
char *ptr;
if (*dev) {
ptr = dev;
while (*ptr && !isdigit((int)*ptr))
ptr++;
ppa = atoi(ptr);
}
if ((ip_fd = open("/dev/ip", O_RDWR, 0)) < 0) {
logmsg(LOG_ERR, "Can't open /dev/ip");
return -1;
}
if ((tun_fd = open(((mode == IF_MODE_TUN) ? "/dev/tun" : "/dev/tap"), O_RDWR, 0)) < 0) {
logmsg(LOG_ERR, "Can't open /dev/tun");
return -1;
}
/* Assign a new PPA and get its unit number. */
if ((ppa = ioctl(tun_fd, TUNNEWPPA, ppa)) < 0) {
logmsg(LOG_ERR, "Can't assign new interface");
return -1;
}
if ((if_fd = open(((mode == IF_MODE_TUN) ? "/dev/tun" : "/dev/tap"), O_RDWR, 0)) < 0) {
logmsg(LOG_ERR, "Can't open /dev/tun (2)");
return -1;
}
if (ioctl(if_fd, I_PUSH, "ip") < 0) {
logmsg(LOG_ERR, "Can't push IP module");
return -1;
}
/* Assign ppa according to the unit number returned by tun device */
if (ioctl(if_fd, IF_UNITSEL, (char *)&ppa) < 0 && errno != EEXIST) {
logmsg(LOG_ERR, "Can't set PPA %d", ppa);
return -1;
}
if ((muxid = ioctl(ip_fd, I_PLINK, if_fd)) < 0) {
logmsg(LOG_ERR, "Can't link TUN device to IP");
return -1;
}
close(if_fd);
snprintf(dev, IFNAMSIZ, "%s%d", ((mode == IF_MODE_TUN) ? "tun" : "tap"), ppa);
memset(&ifr, 0, sizeof(ifr));
strcpy(ifr.ifr_name, dev);
ifr.ifr_ip_muxid = muxid;
if (ioctl(ip_fd, SIOCSIFMUXID, &ifr) < 0) {
ioctl(ip_fd, I_PUNLINK, muxid);
logmsg(LOG_ERR, "Can't set multiplexor id");
return -1;
}
return tun_fd;
}
#elif defined(__CYGWIN__)
/*
* Get interface guid/name from registry
*/
static char *search_if(char *value, char *key, search_if_en type)
{
int i = 0;
LONG status;
DWORD len;
HKEY net_conn_key;
BOOL found = FALSE;
char guid[256];
char ifname[256];
char conn_string[512];
HKEY conn_key;
DWORD value_type;
if (!value || !key) {
return NULL;
}
status = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
NETWORK_CONNECTIONS_KEY,
0,
KEY_READ,
&net_conn_key);
if (status != ERROR_SUCCESS) {
printf("Error opening registry key: %s\n", NETWORK_CONNECTIONS_KEY);
return NULL;
}
while (!found) {
len = sizeof(guid);
status = RegEnumKeyEx(net_conn_key, i++, guid, &len,
NULL, NULL, NULL, NULL);
if (status == ERROR_NO_MORE_ITEMS) {
break;
} else if (status != ERROR_SUCCESS) {
continue;
}
snprintf(conn_string, sizeof(conn_string),
"%s\\%s\\Connection",
NETWORK_CONNECTIONS_KEY, guid);
status = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
conn_string,
0,
KEY_READ,
&conn_key);
if (status != ERROR_SUCCESS) {
continue;
}
len = sizeof(ifname);
status = RegQueryValueEx(conn_key, "Name", NULL,
&value_type, ifname, &len);
if (status != ERROR_SUCCESS || value_type != REG_SZ) {
RegCloseKey(conn_key);
continue;
}
switch (type) {
case SEARCH_IF_GUID_FROM_NAME:
if (!strcmp(key, ifname)) {
strcpy(value, guid);
found = TRUE;
}
break;
case SEARCH_IF_NAME_FROM_GUID:
if (!strcmp(key, guid)) {
strcpy(value, ifname);
found = TRUE;
}
break;
default:
break;
}
RegCloseKey(conn_key);
}
RegCloseKey(net_conn_key);
if (found) {
return value;
}
return NULL;
}
/*
* Open the TUN/TAP device with the provided guid
*/
static int open_tun_device (char *guid, char *dev, enum if_mode_enum mode)
{
HANDLE handle;
ULONG len, status, info[3];
char device_path[512];
printf("Device: %s\n", dev);
if (mode == IF_MODE_TUN) {
printf("TUN mode is not supported\n");
return -1;
}
/*
* Let's try to open Windows TAP-Win32 adapter
*/
snprintf(device_path, sizeof(device_path), "%s%s%s",
USERMODEDEVICEDIR, guid, TAPSUFFIX);
handle = CreateFile(device_path,
GENERIC_READ | GENERIC_WRITE,
0, /* Don't let other processes share or open
the resource until the handle's been closed */
0,
OPEN_EXISTING,
FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
0);
if (handle == INVALID_HANDLE_VALUE) {
return -1;
}
/*
* get driver version info
*/
memset(info, 0, sizeof(info));
if (DeviceIoControl(handle, TAP_IOCTL_GET_VERSION,
&info, sizeof(info),
&info, sizeof(info), &len, NULL)) {
printf("TAP-Win32 Driver Version %d.%d %s\n",
(int) info[0],
(int) info[1],
(info[2] ? "(DEBUG)" : ""));
}
/*
* Set driver media status to 'connected'
*/
status = TRUE;
if (!DeviceIoControl(handle, TAP_IOCTL_SET_MEDIA_STATUS,
&status, sizeof(status),
&status, sizeof(status), &len, NULL)) {
printf("WARNING: The TAP-Win32 driver rejected a "
"TAP_IOCTL_SET_MEDIA_STATUS DeviceIoControl call.\n");
}
/*
* Initialize overlapped structures
*/
overlap_read.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
overlap_write.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (!overlap_read.hEvent || !overlap_write.hEvent) {
return -1;
}
/*
* Return fd
*/
return cygwin_attach_handle_to_fd(NULL, -1, handle, 1, GENERIC_READ | GENERIC_WRITE);
}
/*
* Allocate TUN device, returns opened fd.
* Stores dev name in the first arg (must be large enough).
*/
int tun_open (char *dev, enum if_mode_enum mode)
{
int fd = -1;
HKEY unit_key;
char guid[256];
char comp_id[256];
char enum_name[256];
char unit_string[512];
BOOL found = FALSE;
HKEY adapter_key;
DWORD value_type;
LONG status;
DWORD len;
if (!dev) {
return -1;
}
/*
* Device name has been provided. Open such device.
*/
if (*dev != '\0') {
if (!search_if(guid, dev, SEARCH_IF_GUID_FROM_NAME)) {
return -1;
}
return open_tun_device(guid, dev, mode);
}
/*
* Device name has non been specified. Look for one available!
*/
int i = 0;
status = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
ADAPTER_KEY,
0,
KEY_READ,
&adapter_key);
if (status != ERROR_SUCCESS) {
printf("Error opening registry key: %s", ADAPTER_KEY);
return -1;
}
while (!found) {
len = sizeof(enum_name);
status = RegEnumKeyEx(adapter_key, i++,
enum_name, &len,
NULL, NULL, NULL, NULL);
if (status == ERROR_NO_MORE_ITEMS) {
break;
} else if (status != ERROR_SUCCESS) {
continue;
}
snprintf(unit_string, sizeof(unit_string), "%s\\%s",
ADAPTER_KEY, enum_name);
status = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
unit_string,
0,
KEY_READ,
&unit_key);
if (status != ERROR_SUCCESS) {
continue;
}
len = sizeof(comp_id);
status = RegQueryValueEx(unit_key,
"ComponentId", NULL,
&value_type, comp_id, &len);
if (status != ERROR_SUCCESS || value_type != REG_SZ) {
RegCloseKey(unit_key);
continue;
}
len = sizeof(guid);
status = RegQueryValueEx(unit_key,
"NetCfgInstanceId", NULL,
&value_type, guid, &len);
if (status != ERROR_SUCCESS || value_type != REG_SZ) {
RegCloseKey(unit_key);
continue;
}
int j = 0;
while (TAP_COMPONENT_ID[j]) {
if (!strcmp(comp_id, TAP_COMPONENT_ID[j])) {
break;
}
j++;
}
if (!TAP_COMPONENT_ID[j]) {
RegCloseKey(unit_key);
continue;
}
/*
* Let's try to open this device
*/
search_if(dev, guid, SEARCH_IF_NAME_FROM_GUID);
fd = open_tun_device(guid, dev, mode);
if (fd != -1) {
found = TRUE;
}
RegCloseKey(unit_key);
}
RegCloseKey(adapter_key);
return fd;
}
#elif defined(IFF_TUN)
int tun_open(char *dev, enum if_mode_enum mode)
{
struct ifreq ifr;
int fd, err;
if ((fd = open("/dev/net/tun", O_RDWR)) < 0) {
error(0, errno,
"can't open /dev/net/tun, check that it is either device char 10 200 or (with DevFS) a symlink to ../misc/net/tun (not misc/net/tun)");
return -1;
}
memset(&ifr, 0, sizeof(ifr));
ifr.ifr_flags = ((mode == IF_MODE_TUN) ? IFF_TUN : IFF_TAP) | IFF_NO_PI;
if (*dev)
strncpy(ifr.ifr_name, dev, IFNAMSIZ);
if ((err = ioctl(fd, TUNSETIFF, (void *)&ifr)) < 0) {
close(fd);
return err;
}
strcpy(dev, ifr.ifr_name);
return fd;
}
#else
int tun_open(char *dev, enum if_mode_enum mode)
{
char tunname[IFNAMSIZ];
int i, fd;
if (*dev) {
if (strncmp(dev, ((mode == IF_MODE_TUN) ? "tun" : "tap"), 3))
error(1, 0,
"error: arbitrary naming tunnel interface is not supported in this version\n");
snprintf(tunname, sizeof(tunname), "/dev/%s", dev);
return open(tunname, O_RDWR);
}
#if defined(__APPLE__)
//default to using utun if possible.
if(mode == IF_MODE_TUN) {
fd = utun_open(dev);
if(fd >= 0) return fd;
}
#endif
for (i = 0; i < 255; i++) {
snprintf(tunname, sizeof(tunname), "/dev/%s%d",
((mode == IF_MODE_TUN) ? "tun" : "tap"), i);
/* Open device */
if ((fd = open(tunname, O_RDWR)) > 0) {
snprintf(dev, IFNAMSIZ, "%s%d",
((mode == IF_MODE_TUN) ? "tun" : "tap"), i);
return fd;
}
}
return -1;
}
#endif /* New driver support */
/*
* Close TUN device.
*/
#if defined(__sun__)
int tun_close(int fd, char *dev)
{
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
strcpy(ifr.ifr_name, dev);
if (ioctl(ip_fd, SIOCGIFFLAGS, &ifr) < 0) {
logmsg(LOG_ERR, "Can't get iface flags");
return 0;
}
if (ioctl(ip_fd, I_PUNLINK, muxid) < 0) {
logmsg(LOG_ERR, "Can't unlink interface");
return 0;
}
close(ip_fd);
ip_fd = -1;
close(fd);
return 0;
}
#elif defined(__CYGWIN__)
int tun_close(int fd, char *dev)
{
dev = NULL; /* unused */
return CloseHandle((HANDLE) get_osfhandle(fd));
}
#else
int tun_close(int fd, char *dev)
{
dev = NULL; /*unused */
return close(fd);
}
#endif
#if defined(__APPLE__)
//remove the IP version header from the result of bytes read or written.
static inline ssize_t header_modify_read_write_return (ssize_t len)
{
if (len > 0)
return len > (ssize_t) sizeof(u_int32_t) ? len - sizeof(u_int32_t) : 0;
else
return len;
}
//read from utun
ssize_t utun_read(int fd, uint8_t *buf, int len) {
u_int32_t type;
struct iovec iv[2];
struct ip *iph;
iph = (struct ip *) buf;
if(iph->ip_v == 6)
type = htonl(AF_INET6);
else
type = htonl(AF_INET);
iv[0].iov_base = (char *)&type;
iv[0].iov_len = sizeof (type);
iv[1].iov_base = buf;
iv[1].iov_len = len;
return header_modify_read_write_return(readv(fd, iv, 2));
}
//write to utun
ssize_t utun_write(int fd, uint8_t *buf, int len)
{
u_int32_t type;
struct iovec iv[2];
struct ip *iph;
iph = (struct ip *) buf;
if(iph->ip_v == 6)
type = htonl(AF_INET6);
else
type = htonl(AF_INET);
iv[0].iov_base = (char *)&type;
iv[0].iov_len = sizeof (type);
iv[1].iov_base = buf;
iv[1].iov_len = len;
return header_modify_read_write_return(writev(fd, iv, 2));
}
#endif
#if defined(__sun__)
int tun_write(int fd, unsigned char *buf, int len)
{
struct strbuf sbuf;
sbuf.len = len;
sbuf.buf = buf;
return putmsg(fd, NULL, &sbuf, 0) >= 0 ? sbuf.len : -1;
}
int tun_read(int fd, unsigned char *buf, int len)
{
struct strbuf sbuf;
int f = 0;
sbuf.maxlen = len;
sbuf.buf = buf;
return getmsg(fd, NULL, &sbuf, &f) >= 0 ? sbuf.len : -1;
}
#elif defined(__CYGWIN__)
int tun_read(int fd, unsigned char *buf, int len)
{
DWORD read_size;
ResetEvent(overlap_read.hEvent);
if (ReadFile((HANDLE) get_osfhandle(fd), buf, len, &read_size, &overlap_read)) {
return read_size;
}
switch (GetLastError()) {
case ERROR_IO_PENDING:
WaitForSingleObject(overlap_read.hEvent, INFINITE);
GetOverlappedResult((HANDLE) get_osfhandle(fd), &overlap_read, &read_size, FALSE);
return read_size;
break;
default:
break;
}
return -1;
}
int tun_write(int fd, unsigned char *buf, int len)
{
DWORD write_size;
ResetEvent(overlap_write.hEvent);
if (WriteFile((HANDLE) get_osfhandle(fd),
buf,
len,
&write_size,
&overlap_write)) {
return write_size;
}
switch (GetLastError()) {
case ERROR_IO_PENDING:
WaitForSingleObject(overlap_write.hEvent, INFINITE);
GetOverlappedResult((HANDLE) get_osfhandle(fd), &overlap_write,
&write_size, FALSE);
return write_size;
break;
default:
break;
}
return -1;
}
#elif defined(NEW_TUN)
#define MAX_MRU 2048
struct tun_data {
union {
uint32_t family;
uint32_t timeout;
} header;
u_char data[MAX_MRU];
};
/* Read/write frames from TUN device */
int tun_write(int fd, unsigned char *buf, int len)
{
char *data;
struct tun_data tun;
if (len > (int)sizeof(tun.data))
return -1;
memcpy(tun.data, buf, len);
tun.header.family = htonl(AF_INET);
len += (sizeof(tun) - sizeof(tun.data));
data = (char *)&tun;
return write(fd, data, len) - (sizeof(tun) - sizeof(tun.data));
}
int tun_read(int fd, unsigned char *buf, int len)
{
struct tun_data tun;
char *data;
size_t sz;
int pack;
data = (char *)&tun;
sz = sizeof(tun);
pack = read(fd, data, sz);
if (pack == -1)
return -1;
pack -= sz - sizeof(tun.data);
if (pack > len)
pack = len; /* truncate packet */
memcpy(buf, tun.data, pack);
return pack;
}
#else
int tun_write(int fd, unsigned char *buf, int len)
{
return write(fd, buf, len);
}
int tun_read(int fd, unsigned char *buf, int len)
{
return read(fd, buf, len);
}
#endif
/*
* Get HW addr
*/
int tun_get_hwaddr(int fd, char *dev, uint8_t *hwaddr)
{
#if defined(__CYGWIN__)
ULONG len;
dev = NULL; /* unused */
if (!DeviceIoControl((HANDLE) get_osfhandle(fd), TAP_IOCTL_GET_MAC,
hwaddr, ETH_ALEN, hwaddr, ETH_ALEN, &len, NULL)) {
printf("Cannot get HW address\n");
return -1;
}
return 0;
#elif defined(SIOCGIFHWADDR)
struct ifreq ifr;
/* Use a new socket fd! */
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
return -1;
}
memset(&ifr, 0, sizeof(struct ifreq));
strncpy(ifr.ifr_name, dev, IFNAMSIZ);
if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) {
return -1;
}
memcpy(hwaddr, &ifr.ifr_hwaddr.sa_data, ETH_ALEN);
return 0;
#else
/* todo: implement using SIOCGLIFADDR */
fd = 0;
dev = 0;
hwaddr = 0;
errno = ENOSYS;
return -1;
#endif
}
/***********************************************************************/
/* other support functions */
#ifndef HAVE_VASPRINTF
int vasprintf(char **strp, const char *fmt, va_list ap)
{
int ret;
char *strbuf;
ret = vsnprintf(NULL, 0, fmt, ap);
strbuf = (char *)malloc(ret + 1);
if (strbuf == NULL) {
errno = ENOMEM;
ret = -1;
}
vsnprintf(strbuf, ret + 1, fmt, ap);
*strp = strbuf;
return ret;
}
#endif
#ifndef HAVE_ASPRINTF
int asprintf(char **strp, const char *fmt, ...)
{
int ret;
va_list ap;
va_start(ap, fmt);
ret = vasprintf(strp, fmt, ap);
va_end(ap);
return ret;
}
#endif
#ifndef HAVE_ERROR
void error(int status, int errornum, const char *fmt, ...)
{
char *buf2;
va_list ap;
va_start(ap, fmt);
vasprintf(&buf2, fmt, ap);
va_end(ap);
fprintf(stderr, "%s", buf2);
if (errornum)
fprintf(stderr, ": %s\n", strerror(errornum));
else
fprintf(stderr, "\n");
free(buf2);
if (status)
exit(status);
}
#endif
#ifndef HAVE_UNSETENV
int unsetenv(const char *name)
{
int i, len;
len = strlen(name);
for (i = 0; environ[i]; i++)
if (!strncmp(name, environ[i], len))
if (environ[i][len] == '=')
break;
for (; environ[i] && environ[i + 1]; i++)
environ[i] = environ[i + 1];
return 0;
}
#endif
#ifndef HAVE_SETENV
int setenv(const char *name, const char *value, int overwrite)
{
int ret;
char *newenv;
if (overwrite == 0)
if (getenv(name) != NULL)
return 0;
newenv = malloc(strlen(name) + 1 + strlen(value) + 1);
if (newenv == NULL)
return -1;
*newenv = '\0';
strcat(newenv, name);
strcat(newenv, "=");
strcat(newenv, value);
ret = putenv(newenv);
if (ret == -1)
free(newenv);
return ret;
}
#endif