1 /* tunctl.c - Control tap/tun network devices.
2 *
3 * Copyright 2016 Rob Landley <rob@landley.net>
4 *
5 * See http://kernel.org/doc/Documentation/networking/tuntap.txt
6 *
7 * This is useful for things like "kvm -netdev tap" and containers.
8 * See https://landley.net/lxc/02-networking.html for example usage.
9 *
10 * todo: bridge mode
11 * -b bridge daemon (forwards packets between NAME and NAME2 interfaces)
12
13
14 USE_TUNCTL(NEWTOY(tunctl, "<1>1t|d|u:T[!td]", TOYFLAG_USR|TOYFLAG_BIN))
15
16 config TUNCTL
17 bool "tunctl"
18 default y
19 help
20 usage: tunctl [-dtT] [-u USER] NAME
21
22 Create and delete tun/tap virtual ethernet devices.
23
24 -T Use tap (ethernet frames) instead of tun (ip packets)
25 -d Delete tun/tap device
26 -t Create tun/tap device
27 -u Set owner (user who can read/write device without root access)
28 */
29
30 #define FOR_tunctl
31 #include "toys.h"
32 #include <linux/if_tun.h>
33
GLOBALS(char * user;)34 GLOBALS(
35 char *user;
36 )
37
38 void tunctl_main(void)
39 {
40 struct ifreq *ifr = (void *)toybuf;
41 uid_t u = TT.user ? xgetuid(TT.user) : 0;
42 int fd = xopen("/dev/net/tun", O_RDWR);
43
44 // Associate filehandle with device
45 ifr->ifr_flags = ((toys.optflags&FLAG_T) ? IFF_TUN : IFF_TAP)|IFF_NO_PI;
46 strncpy(ifr->ifr_name, *toys.optargs, sizeof(ifr->ifr_name));
47 xioctl(fd, TUNSETIFF, toybuf);
48
49 if (toys.optflags&FLAG_t) {
50 xioctl(fd, TUNSETPERSIST, (void *)1);
51 xioctl(fd, TUNSETOWNER, (void *)(long)u);
52 } else xioctl(fd, TUNSETPERSIST, (void *)0);
53 }
54