1 /*
2 VTun - Virtual Tunnel over TCP/IP network.
3
4 Copyright (C) 1998-2016 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 * $Id: tun_dev.c,v 1.5.2.3 2016/10/01 21:46:01 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
32 #include <sys/ioctl.h>
33 #include <net/if_tun.h>
34
35 #include "vtun.h"
36 #include "lib.h"
37
38 extern int extended_mode;
39
40 /*
41 * Allocate TUN device, returns opened fd.
42 * Stores dev name in the first arg(must be large enough).
43 */
tun_open(char * dev)44 int tun_open(char *dev)
45 {
46 char tunname[14];
47 int i, fd = -1;
48
49 if( *dev ){
50 sprintf(tunname, "/dev/%s", dev);
51 fd = open(tunname, O_RDWR);
52 } else {
53 for(i=0; i < 255; i++){
54 sprintf(tunname, "/dev/tun%d", i);
55 /* Open device */
56 if( (fd=open(tunname, O_RDWR)) > 0 ){
57 sprintf(dev, "tun%d", i);
58 break;
59 }
60 }
61 }
62 if( fd > -1 ){
63 ioctl(fd, TUNSLMODE, &extended_mode);
64 ioctl(fd, TUNSIFHEAD, &extended_mode);
65 }
66 return fd;
67 }
68
tun_close(int fd,char * dev)69 int tun_close(int fd, char *dev)
70 {
71 return close(fd);
72 }
73
74 /* Read/write frames from/to TUN device */
tun_write(int fd,char * buf,int len)75 int tun_write(int fd, char *buf, int len)
76 {
77 return write(fd, buf, len);
78 }
79
tun_read(int fd,char * buf,int len)80 int tun_read(int fd, char *buf, int len)
81 {
82 return read(fd, buf, len);
83 }
84