Attempted to simplify the BSD tun handling code

This commit is contained in:
Nikos Mavrogiannopoulos
2015-02-13 23:30:29 +01:00
parent 2c0849c8a9
commit 14d8c34e60

View File

@@ -322,38 +322,46 @@ static int set_network_info(main_server_st * s, struct proc_st *proc)
#include <ccan/hash/hash.h>
#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 */