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_TUN;
41 ifr->ifr_flags |= IFF_TAP;
43 if (netdev->packet_info)
44 ifr->ifr_flags &= ~IFF_NO_PI;
46 ifr->ifr_flags |= IFF_NO_PI;
48 if (netdev->one_queue)
49 ifr->ifr_flags |= IFF_ONE_QUEUE;
51 if (netdev->multi_queue)
52 ifr->ifr_flags |= IFF_MULTI_QUEUE;
54 strncpy(ifr->ifr_name, netdev->ifname, IFNAMSIZ-1);
59 static int netdev_tuntap_add(NetDev *netdev, struct ifreq *ifr) {
60 _cleanup_close_ int fd;
67 fd = open(TUN_DEV, O_RDWR);
69 log_error_netdev(netdev,
70 "Failed to open tun dev: %s",
75 r = ioctl(fd, TUNSETIFF, ifr);
77 log_error_netdev(netdev,
78 "TUNSETIFF failed on tun dev: %s",
83 if(netdev->user_name) {
85 user = netdev->user_name;
87 r = get_user_creds(&user, &uid, NULL, NULL, NULL);
89 log_error("Cannot resolve user name %s: %s",
90 netdev->user_name, strerror(-r));
94 r = ioctl(fd, TUNSETOWNER, uid);
96 log_error_netdev(netdev,
97 "TUNSETOWNER failed on tun dev: %s",
102 if(netdev->group_name) {
104 group = netdev->group_name;
106 r = get_group_creds(&group, &gid);
108 log_error("Cannot resolve group name %s: %s",
109 netdev->group_name, strerror(-r));
113 r = ioctl(fd, TUNSETGROUP, gid);
115 log_error_netdev(netdev,
116 "TUNSETGROUP failed on tun dev: %s",
123 r = ioctl(fd, TUNSETPERSIST, 1);
125 log_error_netdev(netdev,
126 "TUNSETPERSIST failed on tun dev: %s",
134 int netdev_create_tuntap(NetDev *netdev) {
139 assert(netdev->ifname);
141 switch(netdev->kind) {
142 case NETDEV_KIND_TUN:
143 case NETDEV_KIND_TAP:
149 r = netdev_fill_tuntap_message(netdev, &ifr);
153 log_debug_netdev(netdev, "Creating tuntap netdev: %s",
154 netdev_kind_to_string(netdev->kind));
156 return netdev_tuntap_add(netdev, &ifr);