blob: 7e62e44a68e63edac65e3ebfc148090a0c3a5dd4 [file] [log] [blame]
xf.lif1aed282024-02-06 00:31:51 -08001/*
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 <fcntl.h>
19#include <string.h>
20#include <unistd.h>
21#include <arpa/inet.h>
22//#include <linux/if.h>
23#include <net/if.h>
24#include <linux/if_tun.h>
25#include <sys/ioctl.h>
26#include <sys/uio.h>
27
28#include "clatd.h"
29
30/* function: tun_open
31 * tries to open the tunnel device
32 */
33int tun_open() {
34 int fd;
35
36 fd = open("/dev/tun", O_RDWR);
37 if(fd < 0) {
38 fd = open("/dev/net/tun", O_RDWR);
39 }
40
41 return fd;
42}
43
44/* function: tun_alloc
45 * creates a tun interface and names it
46 * dev - the name for the new tun device
47 */
48int tun_alloc(char *dev, int fd) {
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 strcpy(dev, ifr.ifr_name);
65 return 0;
66}
67
68/* function: set_nonblocking
69 * sets a filedescriptor to non-blocking mode
70 * fd - the filedescriptor
71 * returns: 0 on success, -1 on failure
72 */
73int set_nonblocking(int fd) {
74 int flags = fcntl(fd, F_GETFL);
75 if (flags == -1) {
76 return flags;
77 }
78 return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
79}
80
81/* function: send_tun
82 * sends a clat_packet to a tun interface
83 * fd - the tun filedescriptor
84 * out - the packet to send
85 * iov_len - the number of entries in the clat_packet
86 * returns: number of bytes read on success, -1 on failure
87 */
88int send_tun(int fd, clat_packet out, int iov_len) {
89 return writev(fd, out, iov_len);
90}