From 4fb0f88d53fc60395a4a87b7a9ca1245ba033ee7 Mon Sep 17 00:00:00 2001 From: Ian Jackson Date: Mon, 22 Sep 2014 15:51:30 +0100 Subject: [PATCH] fds: Provide cloexec() and use it in udp.c and tun.c Signed-off-by: Ian Jackson --- secnet.h | 4 ++++ tun.c | 4 ++++ udp.c | 5 +---- util.c | 7 +++++++ 4 files changed, 16 insertions(+), 4 deletions(-) diff --git a/secnet.h b/secnet.h index 194341c..ce01d24 100644 --- a/secnet.h +++ b/secnet.h @@ -9,6 +9,8 @@ #include #include #include +#include +#include #include #include #include @@ -136,6 +138,8 @@ extern char *safe_strdup(const char *string, const char *message); extern void *safe_malloc(size_t size, const char *message); extern void *safe_malloc_ary(size_t size, size_t count, const char *message); +void setcloexec(int fd); /* cannot fail */ + extern int sys_cmd(const char *file, const char *argc, ...); extern uint64_t now_global; diff --git a/tun.c b/tun.c index d4070f2..ffc195c 100644 --- a/tun.c +++ b/tun.c @@ -340,6 +340,8 @@ static void tun_phase_hook(void *sst, uint32_t newphase) st->interface_name=safe_malloc(10,"tun_apply"); sprintf(st->interface_name,"tun%d",ppa); st->fd=tun_fd; + setcloexec(if_ifd); + setcloexec(ip_ifd); #else fatal("tun_phase_hook: TUN_FLAVOUR_STREAMS unexpected"); #endif /* HAVE_TUN_STREAMS */ @@ -350,6 +352,8 @@ static void tun_phase_hook(void *sst, uint32_t newphase) to set the TUN device's address, and route to add routes to all our networks. */ + setcloexec(st->fd); + hostaddr=ipaddr_to_string(st->nl.local_address); secnetaddr=ipaddr_to_string(st->nl.secnet_address); snprintf(mtu,sizeof(mtu),"%d",st->nl.mtu); diff --git a/udp.c b/udp.c index 552a58e..bb82026 100644 --- a/udp.c +++ b/udp.c @@ -224,10 +224,7 @@ static void udp_phase_hook(void *sst, uint32_t new_phase) fatal_perror("udp (%s:%d): fcntl(set O_NONBLOCK)", st->loc.file,st->loc.line); } - if (fcntl(st->fd, F_SETFD, FD_CLOEXEC)==-1) { - fatal_perror("udp (%s:%d): fcntl(set FD_CLOEXEC)", - st->loc.file,st->loc.line); - } + setcloexec(st->fd); FILLZERO(addr); addr.sin_family=AF_INET; diff --git a/util.c b/util.c index 094870f..fc6f626 100644 --- a/util.c +++ b/util.c @@ -162,6 +162,13 @@ int32_t write_mpbin(MP_INT *a, uint8_t *buffer, int32_t buflen) return i; } +void setcloexec(int fd) { + int r=fcntl(fd, F_GETFD); + if (r<0) fatal_perror("fcntl(,F_GETFD) failed"); + r=fcntl(fd, F_SETFD, r|FD_CLOEXEC); + if (r<0) fatal_perror("fcntl(,F_SETFD,|FD_CLOEXEC) failed"); +} + static const char *phases[NR_PHASES]={ "PHASE_INIT", "PHASE_GETOPTS", -- 2.30.2