1 /*
2     VTun - Virtual Tunnel over TCP/IP network.
3 
4     Copyright (C) 1998-2000  Maxim Krasnyansky <max_mk@yahoo.com>
5 
6     VTun has been derived from VPPP package by Maxim Krasnyansky.
7 
8     This program is free software; you can redistribute it and/or modify
9     it under the terms of the GNU General Public License as published by
10     the Free Software Foundation; either version 2 of the License, or
11     (at your option) any later version.
12 
13     This program is distributed in the hope that it will be useful,
14     but WITHOUT ANY WARRANTY; without even the implied warranty of
15     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16     GNU General Public License for more details.
17  */
18 
19 /*
20  * tun_dev.c,v 1.2.2.1.2.1 2006/11/16 04:04:23 mtbishop Exp
21  */
22 
23 /* #include "config.h" */
24 
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <stdlib.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <syslog.h>
31 #include <errno.h>
32 
33 #include <sys/ioctl.h>
34 #ifdef __DragonFly__
35 #include <net/tun/if_tun.h>
36 #else
37 #include <net/if_tun.h>
38 #endif
39 
40 /* #include "vtun.h"
41 #include "lib.h" */
42 
43 /*
44  * Allocate TUN device, returns opened fd.
45  * Stores dev name in the first arg(must be large enough).
46  */
tun_open(char * dev)47 int tun_open(char *dev)
48 {
49     char tunname[14];
50     int i, fd = -1;
51 
52     if( *dev ){
53        sprintf(tunname, "/dev/%s", dev);
54        fd = open(tunname, O_RDWR);
55     } else {
56        for(i=0; i < 255; i++){
57           sprintf(tunname, "/dev/tun%d", i);
58           /* Open device */
59           if( (fd=open(tunname, O_RDWR)) > 0 ){
60              sprintf(dev, "tun%d", i);
61              break;
62           }
63        }
64     }
65     if( fd > -1 ){
66        i=0;
67        /* Disable extended modes */
68        ioctl(fd, TUNSLMODE, &i);
69        ioctl(fd, TUNSIFHEAD, &i);
70     }
71     return fd;
72 }
73 
tun_close(int fd,char * dev)74 int tun_close(int fd, char *dev)
75 {
76     return close(fd);
77 }
78 
79 /* Read/write frames from/to TUN device */
tun_write(int fd,char * buf,int len)80 int tun_write(int fd, char *buf, int len)
81 {
82     return write(fd, buf, len);
83 }
84 
tun_read(int fd,char * buf,int len)85 int tun_read(int fd, char *buf, int len)
86 {
87     return read(fd, buf, len);
88 }
89 
tun_last_error()90 const char *tun_last_error()
91 {
92     return strerror(errno);
93 }
94