aruu

[MIRROR] Actual replacement for Busybox | suckless
git clone https://git.daat.foo/aruu.git
Log | Files | Refs | README | LICENSE

tunctl.c (1930B)


      1 /* see LICENSE file for copyright and license details */
      2 
      3 #include <sys/types.h>
      4 
      5 #include <limits.h>
      6 #include <pwd.h>
      7 #include <stdio.h>
      8 #include <stdlib.h>
      9 #include <string.h>
     10 #include <unistd.h>
     11 
     12 #include "net.h"
     13 #include "util.h"
     14 
     15 static int   dflag;
     16 static int   tflag = 1;
     17 static int   Tflag;
     18 static char *owner;
     19 
     20 static void
     21 usage(void)
     22 {
     23   eprintf("usage: %s [-dtT] [-u owner] [device]\n", argv0);
     24 }
     25 
     26 // ?man tunctl: configure tun/tap interfaces
     27 // ?man arguments: device
     28 // ?man create or destroy tun/tap network interfaces
     29 int
     30 main(int argc, char *argv[])
     31 {
     32   char           name[NET_IFNAME_MAX] = "";
     33   struct passwd *pw;
     34   uid_t          owner_uid = 0;
     35   int            fd;
     36 
     37   ARGBEGIN
     38   {
     39     // ?man -d: specify directory
     40     case 'd':
     41       dflag = 1;
     42       tflag = 0;
     43       break;
     44     // ?man -t: sort or specify timestamp
     45     case 't':
     46       tflag = 1;
     47       dflag = 0;
     48       break;
     49     // ?man -T: specify option flag
     50     case 'T':
     51       Tflag = 1;
     52       break;
     53     // ?man -u:str: unbuffered output
     54     case 'u':
     55       owner = EARGF(usage());
     56       break;
     57     default:
     58       usage();
     59   }
     60   ARGEND
     61 
     62   if (owner) {
     63     pw = getpwnam(owner);
     64     if (!pw)
     65       owner_uid = estrtonum(owner, 0, UINT_MAX);
     66     else
     67       owner_uid = pw->pw_uid;
     68   }
     69 
     70   fd = net_tun_open();
     71   if (fd < 0)
     72     eprintf("open /dev/net/tun:");
     73 
     74   if (argc > 0)
     75     estrlcpy(name, argv[0], sizeof(name));
     76 
     77   if (net_tun_attach(fd, name, sizeof(name), Tflag) < 0)
     78     eprintf("ioctl TUNSETIFF:");
     79 
     80   if (tflag) {
     81     if (net_tun_persist(fd, 1) < 0)
     82       eprintf("ioctl TUNSETPERSIST:");
     83     if (owner) {
     84       if (net_tun_owner(fd, owner_uid) < 0)
     85         eprintf("ioctl TUNSETOWNER:");
     86     }
     87     printf("Set '%s' persistent and owned by %u\n", name, owner_uid);
     88   } else if (dflag) {
     89     if (net_tun_persist(fd, 0) < 0)
     90       eprintf("ioctl TUNSETPERSIST:");
     91     printf("Set '%s' non-persistent\n", name);
     92   }
     93 
     94   close(fd);
     95   return 0;
     96 }