tunctl.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. USE_TUNCTL(NEWTOY(tunctl, "<1>1t|d|u:T[!td]", TOYFLAG_USR|TOYFLAG_BIN))
  13. config TUNCTL
  14. bool "tunctl"
  15. default y
  16. help
  17. usage: tunctl [-dtT] [-u USER] NAME
  18. Create and delete tun/tap virtual ethernet devices.
  19. -T Use tap (ethernet frames) instead of tun (ip packets)
  20. -d Delete tun/tap device
  21. -t Create tun/tap device
  22. -u Set owner (user who can read/write device without root access)
  23. */
  24. #define FOR_tunctl
  25. #include "toys.h"
  26. #include <linux/if_tun.h>
  27. GLOBALS(
  28. char *u;
  29. )
  30. void tunctl_main(void)
  31. {
  32. struct ifreq *ifr = (void *)toybuf;
  33. uid_t u = TT.u ? xgetuid(TT.u) : 0;
  34. int fd = xopen("/dev/net/tun", O_RDWR);
  35. // Associate filehandle with device
  36. ifr->ifr_flags = ((toys.optflags&FLAG_T) ? IFF_TUN : IFF_TAP)|IFF_NO_PI;
  37. strncpy(ifr->ifr_name, *toys.optargs, sizeof(ifr->ifr_name));
  38. xioctl(fd, TUNSETIFF, toybuf);
  39. if (toys.optflags&FLAG_t) {
  40. xioctl(fd, TUNSETPERSIST, (void *)1);
  41. xioctl(fd, TUNSETOWNER, (void *)(long)u);
  42. } else xioctl(fd, TUNSETPERSIST, (void *)0);
  43. }