1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2014 Susant Sahani <susant@redhat.com>
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
22 #include <sys/ioctl.h>
24 #include <linux/if_tun.h>
28 #define TUN_DEV "/dev/net/tun"
31 static int netdev_fill_tuntap_message(NetDev *netdev, struct ifreq *ifr) {
36 memset(ifr, 0, sizeof(*ifr));
38 if (netdev->kind == NETDEV_KIND_TAP)
39 ifr->ifr_flags |= IFF_TAP;
41 ifr->ifr_flags |= IFF_TUN;
43 if (!netdev->packet_info)
44 ifr->ifr_flags |= IFF_NO_PI;
46 if (netdev->one_queue)
47 ifr->ifr_flags |= IFF_ONE_QUEUE;
49 if (netdev->multi_queue)
50 ifr->ifr_flags |= IFF_MULTI_QUEUE;
52 strncpy(ifr->ifr_name, netdev->ifname, IFNAMSIZ-1);
57 static int netdev_tuntap_add(NetDev *netdev, struct ifreq *ifr) {
58 _cleanup_close_ int fd;
65 fd = open(TUN_DEV, O_RDWR);
67 log_error_netdev(netdev,
68 "Failed to open tun dev: %s",
73 r = ioctl(fd, TUNSETIFF, ifr);
75 log_error_netdev(netdev,
76 "TUNSETIFF failed on tun dev: %s",
81 if(netdev->user_name) {
83 user = netdev->user_name;
85 r = get_user_creds(&user, &uid, NULL, NULL, NULL);
87 log_error("Cannot resolve user name %s: %s",
88 netdev->user_name, strerror(-r));
92 r = ioctl(fd, TUNSETOWNER, uid);
94 log_error_netdev(netdev,
95 "TUNSETOWNER failed on tun dev: %s",
100 if(netdev->group_name) {
102 group = netdev->group_name;
104 r = get_group_creds(&group, &gid);
106 log_error("Cannot resolve group name %s: %s",
107 netdev->group_name, strerror(-r));
111 r = ioctl(fd, TUNSETGROUP, gid);
113 log_error_netdev(netdev,
114 "TUNSETGROUP failed on tun dev: %s",
121 r = ioctl(fd, TUNSETPERSIST, 1);
123 log_error_netdev(netdev,
124 "TUNSETPERSIST failed on tun dev: %s",
132 int netdev_create_tuntap(NetDev *netdev) {
137 assert(netdev->ifname);
139 switch(netdev->kind) {
140 case NETDEV_KIND_TUN:
141 case NETDEV_KIND_TAP:
147 r = netdev_fill_tuntap_message(netdev, &ifr);
151 log_debug_netdev(netdev, "Creating tuntap netdev: %s",
152 netdev_kind_to_string(netdev->kind));
154 return netdev_tuntap_add(netdev, &ifr);