• Home
  • History
  • Annotate
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2014 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  * tun.c - tun device functions
17  */
18 #include <arpa/inet.h>
19 #include <fcntl.h>
20 #include <linux/if.h>
21 #include <linux/if_tun.h>
22 #include <string.h>
23 #include <sys/ioctl.h>
24 #include <unistd.h>
25 
26 #include "common.h"
27 
28 /* function: tun_open
29  * tries to open the tunnel device in non-blocking mode
30  */
tun_open()31 int tun_open() {
32   int fd;
33 
34   fd = open("/dev/tun", O_RDWR | O_NONBLOCK | O_CLOEXEC);
35   if (fd < 0) {
36     fd = open("/dev/net/tun", O_RDWR | O_NONBLOCK | O_CLOEXEC);
37   }
38 
39   return fd;
40 }
41 
42 /* function: tun_alloc
43  * creates a tun interface and names it
44  * dev - the name for the new tun device
45  * fd - an open fd to the tun device node
46  * len - the length of the buffer pointed to by dev
47  */
tun_alloc(char * dev,int fd,size_t len)48 int tun_alloc(char *dev, int fd, size_t len) {
49   struct ifreq ifr;
50   int err;
51 
52   memset(&ifr, 0, sizeof(ifr));
53 
54   ifr.ifr_flags = IFF_TUN;
55   if (*dev) {
56     strncpy(ifr.ifr_name, dev, IFNAMSIZ);
57     ifr.ifr_name[IFNAMSIZ - 1] = '\0';
58   }
59 
60   if ((err = ioctl(fd, TUNSETIFF, (void *)&ifr)) < 0) {
61     close(fd);
62     return err;
63   }
64   strlcpy(dev, ifr.ifr_name, len);
65   return 0;
66 }
67