12c2a70e27accd15353b5b125a2f83914f0da1e4
[sliver-openvswitch.git] / lib / tunalloc.c
1 /* Slice-side code to allocate tuntap interface in root slice
2  * Based on bmsocket.c
3  *  Thom Haddow - 08/10/09
4  *
5  * Call tun_alloc() with IFFTUN or IFFTAP as an argument to get back fd to
6  * new tuntap interface. Interface name can be acquired via TUNGETIFF ioctl.
7  */
8
9 #include <sys/un.h>
10 #include <stdlib.h>
11 #include <stdio.h>
12 #include <string.h>
13 #include <errno.h>
14 #include <unistd.h>
15 #include <sys/socket.h>
16 #include <linux/if.h>
17 #include <linux/if_tun.h>
18
19 #include "tunalloc.h"
20
21 #define VSYS_TUNTAP "/var/run/pl-ovs.control"
22
23 /* Reads vif FD from "fd", writes interface name to vif_name, and returns vif FD.
24  * vif_name should be IFNAMSIZ chars long. */
25 static int receive_vif_fd(int fd, char *vif_name)
26 {
27         struct msghdr msg;
28         struct iovec iov;
29         int rv;
30         size_t ccmsg[CMSG_SPACE(sizeof(int)) / sizeof(size_t)];
31         struct cmsghdr *cmsg;
32
33     /* Use IOV to read interface name */
34         iov.iov_base = vif_name;
35         iov.iov_len = IFNAMSIZ;
36
37         msg.msg_name = 0;
38         msg.msg_namelen = 0;
39         msg.msg_iov = &iov;
40         msg.msg_iovlen = 1;
41         /* old BSD implementations should use msg_accrights instead of
42          * msg_control; the interface is different. */
43         msg.msg_control = ccmsg;
44         msg.msg_controllen = sizeof(ccmsg);
45
46         while(((rv = recvmsg(fd, &msg, 0)) == -1) && errno == EINTR);
47         if (rv == -1) {
48                 return -1;
49         }
50         if(!rv) {
51                 /* EOF */
52                 return -1;
53         }
54
55         cmsg = CMSG_FIRSTHDR(&msg);
56         if (!cmsg->cmsg_type == SCM_RIGHTS) {
57                 return -1;
58         }
59         return *(int*)CMSG_DATA(cmsg);
60 }
61
62
63 int tun_alloc(int iftype, char *if_name)
64 {
65     int control_fd;
66     struct sockaddr_un addr;
67     int remotefd;
68
69     control_fd = socket(AF_UNIX, SOCK_STREAM, 0);
70     if (control_fd == -1) {
71         return -1;
72     }
73
74     memset(&addr, 0, sizeof(struct sockaddr_un));
75     /* Clear structure */
76     addr.sun_family = AF_UNIX;
77     strncpy(addr.sun_path, VSYS_TUNTAP,
78             sizeof(addr.sun_path) - 1);
79
80     if (connect(control_fd, (struct sockaddr *) &addr,
81                 sizeof(struct sockaddr_un)) == -1) {
82         return -1;
83     }
84
85     remotefd = receive_vif_fd(control_fd, if_name);
86
87     close(control_fd);
88
89     return remotefd;
90 }