Skip to contentSkip to conversation

-tun-fd option

PATCH New Rusty Russell 1 participant 1 message Sep 18, 2003

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 -tun-fd option

Hi all,

Played a bit with getting qemu to work with uml_switch, but I
found it too baroque. This approach worked really well for me: get a helper to open and configure the tun file descriptor and hand it off to vl.

Like so: (in practice I use a variant of this which takes a uid, since I ended up running it as root from an init script).

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <net/if.h>
#include <linux/if_tun.h>

/* Tiny code to open tap/tun device, and hand the fd to vl.
Run setuid root, drops privs. */
int main(int argc, char *argv[])

{
	struct ifreq ifr;
	int fd;

	if (argc == 1) {
		fprintf(stderr, "Usage: tundev vl <vl options>...\n");
		exit(1);
	}

	fd = open("/dev/net/tun", O_RDWR);
	if (fd < 0) {
		perror("Could not open /dev/net/tun");
		exit(1);
	}

	memset(&ifr, 0, sizeof(ifr));
	ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
	strncpy(ifr.ifr_name, "tun%d", IFNAMSIZ);
	if (ioctl(fd, TUNSETIFF, (void *) &ifr) != 0) {
		perror("Could not get tun device");
		exit(1);
	}
	printf("Got tun device %s on fd %i\n", ifr.ifr_name, fd);

	/* Drop effective uid. */
	setuid(getuid());

	/* Insert -tun-fd=3 arg. */
	argv[0] = argv[1];
	asprintf(&argv[1], "-tun-fd=%d", fd);
	execvp(argv[0], argv);
	perror("Exec of vl failed");
	exit(1);
}

--
Anyone who quotes me in their sig is an idiot. -- Rusty Russell.

vl.c +7 -1
diff -ur qemu-0.4.3/vl.c qemu-0.4.3-umlswitch/qemu-0.4.3-umlswitch/vl.c
@@ -2635,6 +2639,7 @@
 	   "-snapshot      write to temporary files instead of disk image files\n"
            "-m megs        set virtual RAM size to megs MB\n"
            "-n script      set network init script [default=%s]\n"
+           "-tun-fd=fd     this fd talks to tap/tun, use it.\n"
            "\n"
            "Debug options:\n"
            "-s             wait gdb connection to port %d\n"
@@ -2652,6 +2657,7 @@
     { "hda", 1, NULL, 0, },
     { "hdb", 1, NULL, 0, },
     { "snapshot", 0, NULL, 0, },
+    { "tun-fd", 1, NULL, 0, },
     { NULL, 0, NULL, 0 },
 };
 
@@ -2695,6 +2702,9 @@
             case 3:
                 snapshot = 1;
                 break;
+	    case 4:
+		net_fd = atoi(optarg);
+		break;
             }
             break;
         case 'h':
@@ -2739,7 +2749,8 @@
     }
 
     /* init network tun interface */
-    net_init();
+    if (net_fd < 0)
+	net_init();
 
     /* init the memory */
     tmpdir = getenv("VLTMPDIR");