aboutsummaryrefslogtreecommitdiffstats
path: root/lib/tun.c
blob: bf956309d909e017bc562162faae4e8b44301240 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
/* 
 * TUN interface functions.
 * Copyright (C) 2002, 2003, 2004 Mondru AB.
 * Copyright (C) 2017 by Harald Welte <laforge@gnumonks.org>
 * 
 * The contents of this file may be used under the terms of the GNU
 * General Public License Version 2, provided that the above copyright
 * notice and this permission notice is included in all copies or
 * substantial portions of the software.
 * 
 */

/*
 * tun.c: Contains all TUN functionality. Is able to handle multiple
 * tunnels in the same program. Each tunnel is identified by the struct,
 * which is passed to functions.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <errno.h>
#include <net/route.h>
#include <net/if.h>

#if defined(__linux__)
#include <linux/if_tun.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>

#elif defined (__FreeBSD__)
#include <net/if_tun.h>
#include <net/if_var.h>
#include <netinet/in_var.h>

#elif defined (__APPLE__)
#include <net/if.h>

#elif defined (__sun__)
#include <stropts.h>
#include <sys/sockio.h>
#include <net/if.h>
#include <net/if_tun.h>
/*#include "sun_if_tun.h"*/

#else
#error  "Unknown platform!"
#endif

#include "tun.h"
#include "syserr.h"

static int tun_setaddr4(struct tun_t *this, struct in_addr *addr,
			struct in_addr *dstaddr, struct in_addr *netmask);

#if defined(__linux__)

#include <linux/ipv6.h>

int tun_nlattr(struct nlmsghdr *n, int nsize, int type, void *d, int dlen)
{
	int len = RTA_LENGTH(dlen);
	int alen = NLMSG_ALIGN(n->nlmsg_len);
	struct rtattr *rta = (struct rtattr *)(((void *)n) + alen);
	if (alen + len > nsize)
		return -1;
	rta->rta_len = len;
	rta->rta_type = type;
	memcpy(RTA_DATA(rta), d, dlen);
	n->nlmsg_len = alen + len;
	return 0;
}
#endif

int tun_sifflags(struct tun_t *this, int flags)
{
	struct ifreq ifr;
	int fd;

	memset(&ifr, '\0', sizeof(ifr));
	ifr.ifr_flags = flags;
	strncpy(ifr.ifr_name, this->devname, IFNAMSIZ);
	ifr.ifr_name[IFNAMSIZ - 1] = 0;	/* Make sure to terminate */
	if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
		SYS_ERR(DTUN, LOGL_ERROR, errno, "socket() failed");
		return -1;
	}
	if (ioctl(fd, SIOCSIFFLAGS, &ifr)) {
		SYS_ERR(DTUN, LOGL_ERROR, errno,
			"ioctl(SIOCSIFFLAGS) failed");
		close(fd);
		return -1;
	}
	close(fd);
	return 0;
}

/* Currently unused 
int tun_addroute2(struct tun_t *this,
		  struct in_addr *dst,
		  struct in_addr *gateway,
		  struct in_addr *mask) {
  
  struct {
    struct nlmsghdr 	n;
    struct rtmsg 	r;
    char buf[TUN_NLBUFSIZE];
  } req;
  
  struct sockaddr_nl local;
  int addr_len;
  int fd;
  int status;
  struct sockaddr_nl nladdr;
  struct iovec iov;
  struct msghdr msg;

  memset(&req, 0, sizeof(req));
  req.n.nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
  req.n.nlmsg_flags = NLM_F_REQUEST | NLM_F_CREATE;
  req.n.nlmsg_type = RTM_NEWROUTE;
  req.r.rtm_family = AF_INET;
  req.r.rtm_table  = RT_TABLE_MAIN;
  req.r.rtm_protocol = RTPROT_BOOT;
  req.r.rtm_scope  = RT_SCOPE_UNIVERSE;
  req.r.rtm_type  = RTN_UNICAST;
  tun_nlattr(&req.n, sizeof(req), RTA_DST, dst, 4);
  tun_nlattr(&req.n, sizeof(req), RTA_GATEWAY, gateway, 4);
  
  if ((fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE)) < 0) {
    SYS_ERR(DTUN, LOGL_ERROR, errno,
	    "socket() failed");
    return -1;
  }

  memset(&local, 0, sizeof(local));
  local.nl_family = AF_NETLINK;
  local.nl_groups = 0;
  
  if (bind(fd, (struct sockaddr*)&local, sizeof(local)) < 0) {
    SYS_ERR(DTUN, LOGL_ERROR, errno,
	    "bind() failed");
    close(fd);
    return -1;
  }

  addr_len = sizeof(local);
  if (getsockname(fd, (struct sockaddr*)&local, &addr_len) < 0) {
    SYS_ERR(DTUN, LOGL_ERROR, errno,
	    "getsockname() failed");
    close(fd);
    return -1;
  }

  if (addr_len != sizeof(local)) {
    SYS_ERR(DTUN, LOGL_ERROR, 0,
	    "Wrong address length %d", addr_len);
    close(fd);
    return -1;
  }

  if (local.nl_family != AF_NETLINK) {
    SYS_ERR(DTUN, LOGL_ERROR, 0,
	    "Wrong address family %d", local.nl_family);
    close(fd);
    return -1;
  }
  
  iov.iov_base = (void*)&req.n;
  iov.iov_len = req.n.nlmsg_len;

  msg.msg_name = (void*)&nladdr;
  msg.msg_namelen = sizeof(nladdr),
  msg.msg_iov = &iov;
  msg.msg_iovlen = 1;
  msg.msg_control = NULL;
  msg.msg_controllen = 0;
  msg.msg_flags = 0;

  memset(&nladdr, 0, sizeof(nladdr));
  nladdr.nl_family = AF_NETLINK;
  nladdr.nl_pid = 0;
  nladdr.nl_groups = 0;

  req.n.nlmsg_seq = 0;
  req.n.nlmsg_flags |= NLM_F_ACK;

  status = sendmsg(fd, &msg, 0);  * TODO: Error check *
  close(fd);
  return 0;
}
*/

int tun_addaddr(struct tun_t *this,
		struct in_addr *addr,
		struct in_addr *dstaddr, struct in_addr *netmask)
{

#if defined(__linux__)
	struct {
		struct nlmsghdr n;
		struct ifaddrmsg i;
		char buf[TUN_NLBUFSIZE];
	} req;

	struct sockaddr_nl local;
	socklen_t addr_len;
	int fd;
	int status;

	struct sockaddr_nl nladdr;
	struct iovec iov;
	struct msghdr msg;

	if (!this->addrs)	/* Use ioctl for first addr to make ping work */
		return tun_setaddr4(this, addr, dstaddr, netmask);

	memset(&req, 0, sizeof(req));
	req.n.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifaddrmsg));
	req.n.nlmsg_flags = NLM_F_REQUEST | NLM_F_CREATE;
	req.n.nlmsg_type = RTM_NEWADDR;
	req.i.ifa_family = AF_INET;
	req.i.ifa_prefixlen = 32;	/* 32 FOR IPv4 */
	req.i.ifa_flags = 0;
	req.i.ifa_scope = RT_SCOPE_HOST;	/* TODO or 0 */
	req.i.ifa_index = if_nametoindex(this->devname);
	if (!req.i.ifa_index) {
		SYS_ERR(DTUN, LOGL_ERROR, errno, "Unable to get ifindex for %s", this->devname);
		return -1;
	}

	tun_nlattr(&req.n, sizeof(req), IFA_ADDRESS, addr, sizeof(addr));
	tun_nlattr(&req.n, sizeof(req), IFA_LOCAL, dstaddr, sizeof(dstaddr));

	if ((fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE)) < 0) {
		SYS_ERR(DTUN, LOGL_ERROR, errno, "socket() failed");
		return -1;
	}

	memset(&local, 0, sizeof(local));
	local.nl_family = AF_NETLINK;
	local.nl_groups = 0;

	if (bind(fd, (struct sockaddr *)&local, sizeof(local)) < 0) {
		SYS_ERR(DTUN, LOGL_ERROR, errno, "bind() failed");
		close(fd);
		return -1;
	}

	addr_len = sizeof(local);
	if (getsockname(fd, (struct sockaddr *)&local, &addr_len) < 0) {
		SYS_ERR(DTUN, LOGL_ERROR, errno,
			"getsockname() failed");
		close(fd);
		return -1;
	}

	if (addr_len != sizeof(local)) {
		SYS_ERR(DTUN, LOGL_ERROR, 0,
			"Wrong address length %d", addr_len);
		close(fd);
		return -1;
	}

	if (local.nl_family != AF_NETLINK) {
		SYS_ERR(DTUN, LOGL_ERROR, 0,
			"Wrong address family %d", local.nl_family);
		close(fd);
		return -1;
	}

	iov.iov_base = (void *)&req.n;
	iov.iov_len = req.n.nlmsg_len;

	msg.msg_name = (void *)&nladdr;
	msg.msg_namelen = sizeof(nladdr);
	msg.msg_iov = &iov;
	msg.msg_iovlen = 1;
	msg.msg_control = NULL;
	msg.msg_controllen = 0;
	msg.msg_flags = 0;

	memset(&nladdr, 0, sizeof(nladdr));
	nladdr.nl_family = AF_NETLINK;
	nladdr.nl_pid = 0;
	nladdr.nl_groups = 0;

	req.n.nlmsg_seq = 0;
	req.n.nlmsg_flags |= NLM_F_ACK;

	status = sendmsg(fd, &msg, 0);
	if (status != req.n.nlmsg_len) {
		SYS_ERR(DTUN, LOGL_ERROR, errno, "sendmsg() failed, returned %d", status);
		close(fd);
		return -1;
	}

	status = tun_sifflags(this, IFF_UP | IFF_RUNNING);
	if (status == -1) {
		close(fd);
		return -1;
	}


	close(fd);
	this->addrs++;
	return 0;

#elif defined (__FreeBSD__) || defined (__APPLE__)

	int fd;
	struct ifaliasreq areq;

	/* TODO: Is this needed on FreeBSD? */
	if (!this->addrs)	/* Use ioctl for first addr to make ping work */
		return tun_setaddr4(this, addr, dstaddr, netmask);	/* TODO dstaddr */

	memset(&areq, 0, sizeof(areq));

	/* Set up interface name */
	strncpy(areq.ifra_name, this->devname, IFNAMSIZ);
	areq.ifra_name[IFNAMSIZ - 1] = 0;	/* Make sure to terminate */

	((struct sockaddr_in *)&areq.ifra_addr)->sin_family = AF_INET;
	((struct sockaddr_in *)&areq.ifra_addr)->sin_len =
	    sizeof(areq.ifra_addr);
	((struct sockaddr_in *)&areq.ifra_addr)->sin_addr.s_addr = addr->s_addr;

	((struct sockaddr_in *)&areq.ifra_mask)->sin_family = AF_INET;
	((struct sockaddr_in *)&areq.ifra_mask)->sin_len =
	    sizeof(areq.ifra_mask);
	((struct sockaddr_in *)&areq.ifra_mask)->sin_addr.s_addr =
	    netmask->s_addr;

	/* For some reason FreeBSD uses ifra_broadcast for specifying dstaddr */
	((struct sockaddr_in *)&areq.ifra_broadaddr)->sin_family = AF_INET;
	((struct sockaddr_in *)&areq.ifra_broadaddr)->sin_len =
	    sizeof(areq.ifra_broadaddr);
	((struct sockaddr_in *)&areq.ifra_broadaddr)->sin_addr.s_addr =
	    dstaddr->s_addr;

	/* Create a channel to the NET kernel. */
	if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
		SYS_ERR(DTUN, LOGL_ERROR, errno, "socket() failed");
		return -1;
	}

	if (ioctl(fd, SIOCAIFADDR, (void *)&areq) < 0) {
		SYS_ERR(DTUN, LOGL_ERROR, errno,
			"ioctl(SIOCAIFADDR) failed");
		close(fd);
		return -1;
	}

	close(fd);
	this->addrs++;
	return 0;

#elif defined (__sun__)

	if (!this->addrs)	/* Use ioctl for first addr to make ping work */
		return tun_setaddr4(this, addr, dstaddr, netmask);

	SYS_ERR(DTUN, LOGL_ERROR, errno,
		"Setting multiple addresses not possible on Solaris");
	return -1;

#else
#error  "Unknown platform!"
#endif

}

static int tun_setaddr4(struct tun_t *this, struct in_addr *addr,
			struct in_addr *dstaddr, struct in_addr *netmask)
{
	struct ifreq ifr;
	int fd;

	memset(&ifr, '\0', sizeof(ifr));
	ifr.ifr_addr.sa_family = AF_INET;
	ifr.ifr_dstaddr.sa_family = AF_INET;

#if defined(__linux__)
	ifr.ifr_netmask.sa_family = AF_INET;

#elif defined(__FreeBSD__) || defined (__APPLE__)
	((struct sockaddr_in *)&ifr.ifr_addr)->sin_len =
	    sizeof(struct sockaddr_in);
	((struct sockaddr_in *)&ifr.ifr_dstaddr)->sin_len =
	    sizeof(struct sockaddr_in);
#endif

	strncpy(ifr.ifr_name, this->devname, IFNAMSIZ);
	ifr.ifr_name[IFNAMSIZ - 1] = 0;	/* Make sure to terminate */

	/* Create a channel to the NET kernel. */
	if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
		SYS_ERR(DTUN, LOGL_ERROR, errno, "socket() failed");
		return -1;
	}

	if (addr) {		/* Set the interface address */
		this->addr.s_addr = addr->s_addr;
		memcpy(&((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr, addr,
		       sizeof(*addr));
		if (ioctl(fd, SIOCSIFADDR, (void *)&ifr) < 0) {
			if (errno != EEXIST) {
				SYS_ERR(DTUN, LOGL_ERROR, errno,
					"ioctl(SIOCSIFADDR) failed");
			} else {
				SYS_ERR(DTUN, LOGL_NOTICE, errno,
					"ioctl(SIOCSIFADDR): Address already exists");
			}
			close(fd);
			return -1;
		}
	}

	if (dstaddr) {		/* Set the destination address */
		this->dstaddr.s_addr = dstaddr->s_addr;
		memcpy(&((struct sockaddr_in *)&ifr.ifr_dstaddr)->sin_addr,
		       dstaddr, sizeof(*dstaddr));
		if (ioctl(fd, SIOCSIFDSTADDR, (caddr_t) & ifr) < 0) {
			SYS_ERR(DTUN, LOGL_ERROR, errno,
				"ioctl(SIOCSIFDSTADDR) failed");
			close(fd);
			return -1;
		}
	}

	if (netmask) {		/* Set the netmask */
		this->netmask.s_addr = netmask->s_addr;
#if defined(__linux__)
		memcpy(&((struct sockaddr_in *)&ifr.ifr_netmask)->sin_addr,
		       netmask, sizeof(*netmask));

#elif defined(__FreeBSD__) || defined (__APPLE__)
		((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr.s_addr =
		    netmask->s_addr;

#elif defined(__sun__)
		((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr.s_addr =
		    netmask->s_addr;
#else
#error  "Unknown platform!"
#endif

		if (ioctl(fd, SIOCSIFNETMASK, (void *)&ifr) < 0) {
			SYS_ERR(DTUN, LOGL_ERROR, errno,
				"ioctl(SIOCSIFNETMASK) failed");
			close(fd);
			return -1;
		}
	}

	close(fd);
	this->addrs++;

	/* On linux the route to the interface is set automatically
	   on FreeBSD we have to do this manually */

	/* TODO: How does it work on Solaris? */

	tun_sifflags(this, IFF_UP | IFF_RUNNING);

#if defined(__FreeBSD__) || defined (__APPLE__)
	tun_addroute(this, dstaddr, addr, &this->netmask);
	this->routes = 1;
#endif

	return 0;
}

static int tun_setaddr6(struct tun_t *this, struct in6_addr *addr, struct in6_addr *dstaddr,
			size_t prefixlen)
{
	struct in6_ifreq ifr;
	int fd;

	memset(&ifr, 0, sizeof(ifr));

#if defined(__linux__)
	ifr.ifr6_prefixlen = prefixlen;
	ifr.ifr6_ifindex = if_nametoindex(this->devname);
	if (ifr.ifr6_ifindex == 0) {
		SYS_ERR(DTUN, LOGL_ERROR, 0, "Error getting ifindex for %s\n", this->devname);
		return -1;
	}
#elif defined(__FreeBSD__) || defined (__APPLE__)
	strncpy(ifr.ifr_name, this->devname, IFNAMSIZ);
#endif

	/* Create a channel to the NET kernel */
	if ((fd = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
		SYS_ERR(DTUN, LOGL_ERROR, 0, "socket() failed");
		return -1;
	}

#if defined(__linux__)
	if (addr) {
		memcpy(&this->addr, addr, sizeof(*addr));
		memcpy(&ifr.ifr6_addr, addr, sizeof(*addr));
		if (ioctl(fd, SIOCSIFADDR, (void *) &ifr) < 0) {
			if (errno != EEXIST) {
				SYS_ERR(DTUN, LOGL_ERROR, 0, "ioctl(SIOCSIFADDR) failed");
			} else {
				SYS_ERR(DTUN, LOGL_NOTICE, 0, "ioctl(SIOCSIFADDR): Address alreadsy exists");
			}
			close(fd);
			return -1;
		}
	}

#if 0
	/* FIXME: looks like this is not possible/necessary for IPv6? */
	if (dstaddr) {
		memcpy(&this->dstaddr, dstaddr, sizeof(*dstaddr));
		memcpy(&ifr.ifr6_addr, dstaddr, sizeof(*dstaddr));
		if (ioctl(fd, SIOCSIFDSTADDR, (caddr_t *) &ifr) < 0) {
			SYS_ERR(DTUN, LOGL_ERROR, "ioctl(SIOCSIFDSTADDR) failed");
			close(fd);
			return -1;
		}
	}
#endif

#elif defined(__FreeBSD__) || defined (__APPLE__)
	if (addr)
		memcpy(&ifr.ifr_ifru.ifru_addr, addr, sizeof(ifr.ifr_ifru.ifru_addr));
	if (dstaddr)
		memcpy(&ifr.ifr_ifru.ifru_dstaddr, dstaddr, sizeof(ifr.ifr_ifru.ifru_dstaddr));

	if (ioctl(fd, SIOCSIFADDR_IN6, (struct ifreq *)&ifr) < 0) {
		SYS_ERR(DTUN, LOGL_ERROR, 0, "ioctl(SIOCSIFADDR_IN6) failed");
		close(fd);
		return -1;
	}
#endif

	close(fd);
	this->addrs++;

	/* On linux the route to the interface is set automatically
	   on FreeBSD we have to do this manually */

	/* TODO: How does it work on Solaris? */

	tun_sifflags(this, IFF_UP | IFF_RUNNING);

#if 0	/* FIXME */
//#if defined(__FreeBSD__) || defined (__APPLE__)
	tun_addroute6(this, dstaddr, addr, prefixlen);
	this->routes = 1;
#endif

	return 0;
}

int tun_setaddr(struct tun_t *this, struct in46_addr *addr, struct in46_addr *dstaddr, size_t prefixlen)
{
	struct in_addr netmask;
	switch (addr->len) {
	case 4:
		netmask.s_addr = htonl(0xffffffff << (32 - prefixlen));
		return tun_setaddr4(this, &addr->v4, dstaddr ? &dstaddr->v4 : NULL, &netmask);
	case 16:
		return tun_setaddr6(this, &addr->v6, dstaddr ? &dstaddr->v6 : NULL, prefixlen);
	default:
		return -1;
	}
}

int tun_route(struct tun_t *this,
	      struct in_addr *dst,
	      struct in_addr *gateway, struct in_addr *mask, int delete)
{

	/* TODO: Learn how to set routing table on sun  */

#if defined(__linux__)

	struct rtentry r;
	int fd;

	memset(&r, '\0', sizeof(r));
	r.rt_flags = RTF_UP | RTF_GATEWAY;	/* RTF_HOST not set */

	/* Create a channel to the NET kernel. */
	if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
		SYS_ERR(DTUN, LOGL_ERROR, errno, "socket() failed");
		return -1;
	}

	r.rt_dst.sa_family = AF_INET;
	r.rt_gateway.sa_family = AF_INET;
	r.rt_genmask.sa_family = AF_INET;
	memcpy(&((struct sockaddr_in *)&r.rt_dst)->sin_addr, dst, sizeof(*dst));
	memcpy(&((struct sockaddr_in *)&r.rt_gateway)->sin_addr, gateway,
	       sizeof(*gateway));
	memcpy(&((struct sockaddr_in *)&r.rt_genmask)->sin_addr, mask,
	       sizeof(*mask));

	if (delete) {
		if (ioctl(fd, SIOCDELRT, (void *)&r) < 0) {
			SYS_ERR(DTUN, LOGL_ERROR, errno,
				"ioctl(SIOCDELRT) failed");
			close(fd);
			return -1;
		}
	} else {
		if (ioctl(fd, SIOCADDRT, (void *)&r) < 0) {
			SYS_ERR(DTUN, LOGL_ERROR, errno,
				"ioctl(SIOCADDRT) failed");
			close(fd);
			return -1;
		}
	}
	close(fd);
	return 0;

#elif defined(__FreeBSD__) || defined (__APPLE__)

	struct {
		struct rt_msghdr rt;
		struct sockaddr_in dst;
		struct sockaddr_in gate;
		struct sockaddr_in mask;
	} req;

	int fd;
	struct rt_msghdr *rtm;

	if ((fd = socket(AF_ROUTE, SOCK_RAW, 0)) == -1) {
		SYS_ERR(DTUN, LOGL_ERROR, errno, "socket() failed");
		return -1;
	}

	memset(&req, 0x00, sizeof(req));

	rtm = &req.rt;

	rtm->rtm_msglen = sizeof(req);
	rtm->rtm_version = RTM_VERSION;
	if (delete) {
		rtm->rtm_type = RTM_DELETE;
	} else {
		rtm->rtm_type = RTM_ADD;
	}
	rtm->rtm_flags = RTF_UP | RTF_GATEWAY | RTF_STATIC;	/* TODO */
	rtm->rtm_addrs = RTA_DST | RTA_GATEWAY | RTA_NETMASK;
	rtm->rtm_pid = getpid();
	rtm->rtm_seq = 0044;	/* TODO */

	req.dst.sin_family = AF_INET;
	req.dst.sin_len = sizeof(req.dst);
	req.mask.sin_family = AF_INET;
	req.mask.sin_len = sizeof(req.mask);
	req.gate.sin_family = AF_INET;
	req.gate.sin_len = sizeof(req.gate);

	req.dst.sin_addr.s_addr = dst->s_addr;
	req.mask.sin_addr.s_addr = mask->s_addr;
	req.gate.sin_addr.s_addr = gateway->s_addr;

	if (write(fd, rtm, rtm->rtm_msglen) < 0) {
		SYS_ERR(DTUN, LOGL_ERROR, errno, "write() failed");
		close(fd);
		return -1;
	}
	close(fd);
	return 0;

#elif defined(__sun__)
	SYS_ERR(DTUN, LOGL_NOTICE, errno,
		"Could not set up routing on Solaris. Please add route manually.");
	return 0;

#else
#error  "Unknown platform!"
#endif

}

int tun_addroute(struct tun_t *this,
		 struct in_addr *dst,
		 struct in_addr *gateway, struct in_addr *mask)
{
	return tun_route(this, dst, gateway, mask, 0);
}

int tun_delroute(struct tun_t *this,
		 struct in_addr *dst,
		 struct in_addr *gateway, struct in_addr *mask)
{
	return tun_route(this, dst, gateway, mask, 1);
}

int tun_new(struct tun_t **tun, const char *dev_name)
{

#if defined(__linux__)
	struct ifreq ifr;

#elif defined(__FreeBSD__) || defined (__APPLE__)
	char devname[IFNAMSIZ + 5];	/* "/dev/" + ifname */
	int devnum;
	struct ifaliasreq areq;
	int fd;

#elif defined(__sun__)
	int if_fd, ppa = -1;
	static int ip_fd = 0;
	int muxid;
	struct ifreq ifr;

#else
#error  "Unknown platform!"
#endif

	if (!(*tun = calloc(1, sizeof(struct tun_t)))) {
		SYS_ERR(DTUN, LOGL_ERROR, errno, "calloc() failed");
		return EOF;
	}

	(*tun)->cb_ind = NULL;
	(*tun)->addrs = 0;
	(*tun)->routes = 0;

#if defined(__linux__)
	/* Open the actual tun device */
	if (((*tun)->fd = open("/dev/net/tun", O_RDWR)) < 0) {
		SYS_ERR(DTUN, LOGL_ERROR, errno, "open() failed");
		goto err_free;
	}

	/* Set device flags. For some weird reason this is also the method
	   used to obtain the network interface name */
	memset(&ifr, 0, sizeof(ifr));
	if (dev_name)
		strcpy(ifr.ifr_name, dev_name);
	ifr.ifr_flags = IFF_TUN | IFF_NO_PI;	/* Tun device, no packet info */
	if (ioctl((*tun)->fd, TUNSETIFF, (void *)&ifr) < 0) {
		SYS_ERR(DTUN, LOGL_ERROR, errno, "ioctl() failed");
		goto err_close;
	}

	strncpy((*tun)->devname, ifr.ifr_name, IFNAMSIZ);
	(*tun)->devname[IFNAMSIZ - 1] = 0;

	ioctl((*tun)->fd, TUNSETNOCSUM, 1);	/* Disable checksums */
	return 0;

#elif defined(__FreeBSD__) || defined (__APPLE__)

	/* Find suitable device */
	for (devnum = 0; devnum < 255; devnum++) {	/* TODO 255 */
		snprintf(devname, sizeof(devname), "/dev/tun%d", devnum);
		if (((*tun)->fd = open(devname, O_RDWR)) >= 0)
			break;
		if (errno != EBUSY)
			break;
	}
	if ((*tun)->fd < 0) {
		SYS_ERR(DTUN, LOGL_ERROR, errno,
			"Can't find tunnel device");
		goto err_free;
	}

	snprintf((*tun)->devname, sizeof((*tun)->devname), "tun%d", devnum);
	(*tun)->devname[sizeof((*tun)->devname)-1] = 0;

	/* The tun device we found might have "old" IP addresses allocated */
	/* We need to delete those. This problem is not present on Linux */

	memset(&areq, 0, sizeof(areq));

	/* Set up interface name */
	strncpy(areq.ifra_name, (*tun)->devname, IFNAMSIZ);
	areq.ifra_name[IFNAMSIZ - 1] = 0;	/* Make sure to terminate */

	/* Create a channel to the NET kernel. */
	if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
		SYS_ERR(DTUN, LOGL_ERROR, errno, "socket() failed");
		goto err_close;
	}

	/* Delete any IP addresses until SIOCDIFADDR fails */
	while (ioctl(fd, SIOCDIFADDR, (void *)&areq) != -1) ;

	close(fd);
	return 0;

#elif defined(__sun__)

	if ((ip_fd = open("/dev/udp", O_RDWR, 0)) < 0) {
		SYS_ERR(DTUN, LOGL_ERROR, errno,
			"Can't open /dev/udp");
		goto err_free;
	}

	if (((*tun)->fd = open("/dev/tun", O_RDWR, 0)) < 0) {
		SYS_ERR(DTUN, LOGL_ERROR, errno,
			"Can't open /dev/tun");
		close(ip_fd);
		goto err_free;
	}

	/* Assign a new PPA and get its unit number. */
	if ((ppa = ioctl((*tun)->fd, TUNNEWPPA, -1)) < 0) {
		SYS_ERR(DTUN, LOGL_ERROR, errno,
			"Can't assign new interface");
		goto sun_close_ip;
	}

	if ((if_fd = open("/dev/tun", O_RDWR, 0)) < 0) {
		SYS_ERR(DTUN, LOGL_ERROR, errno,
			"Can't open /dev/tun (2)");
		goto sun_close_ip;
	}
	if (ioctl(if_fd, I_PUSH, "ip") < 0) {
		SYS_ERR(DTUN, LOGL_ERROR, errno,
			"Can't push IP module");
		goto sun_close_if;
	}

	/* Assign ppa according to the unit number returned by tun device */
	if (ioctl(if_fd, IF_UNITSEL, (char *)&ppa) < 0) {
		SYS_ERR(DTUN, LOGL_ERROR, errno, "Can't set PPA %d",
			ppa);
		goto sun_close_if;
	}

	/* Link the two streams */
	if ((muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0) {
		SYS_ERR(DTUN, LOGL_ERROR, errno,
			"Can't link TUN device to IP");
		goto sun_close_if;
	}

	/* Link the two streams */
	if ((muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0) {
		SYS_ERR(DTUN, LOGL_ERROR, errno,
			"Can't link TUN device to IP");
		goto sun_close_if;
	}

	close(if_fd);

	snprintf((*tun)->devname, sizeof((*tun)->devname), "tun%d", ppa);
	(*tun)->devname[sizeof((*tun)->devname)] = 0;

	memset(&ifr, 0, sizeof(ifr));
	strcpy(ifr.ifr_name, (*tun)->devname);
	ifr.ifr_ip_muxid = muxid;

	if (ioctl(ip_fd, SIOCSIFMUXID, &ifr) < 0) {
		ioctl(ip_fd, I_PUNLINK, muxid);
		SYS_ERR(DTUN, LOGL_ERROR, errno,
			"Can't set multiplexor id");
		goto sun_close_ip;
	}

	/*  if (fcntl (fd, F_SETFL, O_NONBLOCK) < 0)
	   msg (M_ERR, "Set file descriptor to non-blocking failed"); */

	return 0;

sun_close_if:
	close(if_fd);
sun_close_ip:
	close(ip_fd);
	goto err_close;

#else
#error  "Unknown platform!"
#endif

err_close:
	close((*tun)->fd);
err_free:
	free(*tun);
	*tun = NULL;
	return -1;
}

int tun_free(struct tun_t *tun)
{

	if (tun->routes) {
		tun_delroute(tun, &tun->dstaddr, &tun->addr, &tun->netmask);
	}

	if (close(tun->fd)) {
		SYS_ERR(DTUN, LOGL_ERROR, errno, "close() failed");
	}

	/* TODO: For solaris we need to unlink streams */

	free(tun);
	return 0;
}

int tun_set_cb_ind(struct tun_t *this,
		   int (*cb_ind) (struct tun_t * tun, void *pack, unsigned len))
{
	this->cb_ind = cb_ind;
	return 0;
}

int tun_decaps(struct tun_t *this)
{

#if defined(__linux__) || defined (__FreeBSD__) || defined (__APPLE__)

	unsigned char buffer[PACKET_MAX];
	int status;

	if ((status = read(this->fd, buffer, sizeof(buffer))) <= 0) {
		SYS_ERR(DTUN, LOGL_ERROR, errno, "read() failed");
		return -1;
	}

	if (this->cb_ind)
		return this->cb_ind(this, buffer, status);

	return 0;

#elif defined (__sun__)

	unsigned char buffer[PACKET_MAX];
	struct strbuf sbuf;
	int f = 0;

	sbuf.maxlen = PACKET_MAX;
	sbuf.buf = buffer;
	if (getmsg(this->fd, NULL, &sbuf, &f) < 0) {
		SYS_ERR(DTUN, LOGL_ERROR, errno, "getmsg() failed");
		return -1;
	}

	if (this->cb_ind)
		return this->cb_ind(this, buffer, sbuf.len);

	return 0;

#endif

}

int tun_encaps(struct tun_t *tun, void *pack, unsigned len)
{

#if defined(__linux__) || defined (__FreeBSD__) || defined (__APPLE__)

	return write(tun->fd, pack, len);

#elif defined (__sun__)

	struct strbuf sbuf;
	sbuf.len = len;
	sbuf.buf = pack;
	return putmsg(tun->fd, NULL, &sbuf, 0);

#endif
}

int tun_runscript(struct tun_t *tun, char *script)
{

	char buf[TUN_SCRIPTSIZE];
	char snet[TUN_ADDRSIZE];
	char smask[TUN_ADDRSIZE];
	int rc;

	strncpy(snet, inet_ntoa(tun->addr), sizeof(snet));
	snet[sizeof(snet) - 1] = 0;
	strncpy(smask, inet_ntoa(tun->netmask), sizeof(smask));
	smask[sizeof(smask) - 1] = 0;

	/* system("ipup /dev/tun0 192.168.0.10 255.255.255.0"); */
	snprintf(buf, sizeof(buf), "%s %s %s %s",
		 script, tun->devname, snet, smask);
	buf[sizeof(buf) - 1] = 0;
	rc = system(buf);
	if (rc == -1) {
		SYS_ERR(DTUN, LOGL_ERROR, errno,
			"Error executing command %s", buf);
		return -1;
	}
	return 0;
}