From 14d8c34e6066bbe0cc132fa95a497cef8c30b14e Mon Sep 17 00:00:00 2001 From: Nikos Mavrogiannopoulos Date: Fri, 13 Feb 2015 23:30:29 +0100 Subject: [PATCH] Attempted to simplify the BSD tun handling code --- src/tun.c | 60 +++++++++++++++++++++++++++---------------------------- 1 file changed, 30 insertions(+), 30 deletions(-) diff --git a/src/tun.c b/src/tun.c index 46b833cd..9e3f900b 100644 --- a/src/tun.c +++ b/src/tun.c @@ -322,38 +322,46 @@ static int set_network_info(main_server_st * s, struct proc_st *proc) #include #ifndef __linux__ -# ifdef SIOCIFCREATE -static int bsd_open_tun(char *tun_name) +static int bsd_open_tun(void) { int fd; int s; + char tun_name[80]; struct ifreq ifr; + int unit_nr = 0; - fd = open(tun_name, O_RDWR); + fd = open("/dev/tun", O_RDWR); if (fd == -1) { - s = socket(AF_INET, SOCK_DGRAM, 0); - if (s < 0) - return -1; + /* try iterating */ + for (unit_nr = 0; unit_nr < 255; unit_nr++) { + snprintf(tun_name, sizeof(tun_name), "/dev/tun%d", unit_nr); + fd = open(tun_name, O_RDWR); +# ifdef SIOCIFCREATE + if (fd == -1) { + /* cannot open tunXX, try creating it */ + s = socket(AF_INET, SOCK_DGRAM, 0); + if (s < 0) + return -1; - memset(&ifr, 0, sizeof(ifr)); - strncpy(ifr.ifr_name, tun_name + 5, sizeof(ifr.ifr_name) - 1); - if (!ioctl(s, SIOCIFCREATE, &ifr)) - fd = open(tun_name, O_RDWR); - - close(s); + memset(&ifr, 0, sizeof(ifr)); + strncpy(ifr.ifr_name, tun_name + 5, sizeof(ifr.ifr_name) - 1); + if (!ioctl(s, SIOCIFCREATE, &ifr)) + fd = open(tun_name, O_RDWR); + close(s); + } +# endif + if (fd >= 0) + break; + } } + return fd; } -# else -# define bsd_open_tun(tun_name) open(tun_name, O_RDWR) -# endif #endif int open_tun(main_server_st * s, struct proc_st *proc) { int tunfd, ret, e; - static char tun_name[80]; - int unit_nr = 0; struct ifreq ifr; unsigned int t; @@ -424,20 +432,12 @@ int open_tun(main_server_st * s, struct proc_st *proc) } #endif #else /* freebsd */ - tunfd = bsd_open_tun("/dev/tun"); + tunfd = bsd_open_tun() if (tunfd < 0) { - for (unit_nr = 0; unit_nr < 255; unit_nr++) { - sprintf(tun_name, "/dev/tun%d", unit_nr); - tunfd = bsd_open_tun(tun_name); - if (tunfd >= 0) - break; - } - if (tunfd < 0) { - int e = errno; - mslog(s, NULL, LOG_ERR, "Can't open /dev/tun: %s\n", - strerror(e)); - return -1; - } + int e = errno; + mslog(s, NULL, LOG_ERR, "Can't open /dev/tun: %s\n", + strerror(e)); + return -1; } /* find device name */