Home | History | Annotate | Line # | Download | only in librumphijack
hijack.c revision 1.40
      1 /*      $NetBSD: hijack.c,v 1.40 2011/02/15 13:59:28 pooka Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2011 Antti Kantee.  All Rights Reserved.
      5  *
      6  * Redistribution and use in source and binary forms, with or without
      7  * modification, are permitted provided that the following conditions
      8  * are met:
      9  * 1. Redistributions of source code must retain the above copyright
     10  *    notice, this list of conditions and the following disclaimer.
     11  * 2. Redistributions in binary form must reproduce the above copyright
     12  *    notice, this list of conditions and the following disclaimer in the
     13  *    documentation and/or other materials provided with the distribution.
     14  *
     15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
     16  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
     17  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
     18  * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
     21  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     25  * SUCH DAMAGE.
     26  */
     27 
     28 #include <sys/cdefs.h>
     29 __RCSID("$NetBSD: hijack.c,v 1.40 2011/02/15 13:59:28 pooka Exp $");
     30 
     31 #define __ssp_weak_name(fun) _hijack_ ## fun
     32 
     33 #include <sys/param.h>
     34 #include <sys/types.h>
     35 #include <sys/event.h>
     36 #include <sys/ioctl.h>
     37 #include <sys/socket.h>
     38 #include <sys/poll.h>
     39 
     40 #include <rump/rumpclient.h>
     41 #include <rump/rump_syscalls.h>
     42 
     43 #include <assert.h>
     44 #include <dlfcn.h>
     45 #include <err.h>
     46 #include <errno.h>
     47 #include <fcntl.h>
     48 #include <poll.h>
     49 #include <pthread.h>
     50 #include <signal.h>
     51 #include <stdarg.h>
     52 #include <stdbool.h>
     53 #include <stdio.h>
     54 #include <stdlib.h>
     55 #include <string.h>
     56 #include <time.h>
     57 #include <unistd.h>
     58 
     59 enum dualcall {
     60 	DUALCALL_WRITE, DUALCALL_WRITEV,
     61 	DUALCALL_IOCTL, DUALCALL_FCNTL,
     62 	DUALCALL_SOCKET, DUALCALL_ACCEPT, DUALCALL_BIND, DUALCALL_CONNECT,
     63 	DUALCALL_GETPEERNAME, DUALCALL_GETSOCKNAME, DUALCALL_LISTEN,
     64 	DUALCALL_RECVFROM, DUALCALL_RECVMSG,
     65 	DUALCALL_SENDTO, DUALCALL_SENDMSG,
     66 	DUALCALL_GETSOCKOPT, DUALCALL_SETSOCKOPT,
     67 	DUALCALL_SHUTDOWN,
     68 	DUALCALL_READ, DUALCALL_READV,
     69 	DUALCALL_DUP, DUALCALL_DUP2,
     70 	DUALCALL_CLOSE,
     71 	DUALCALL_POLLTS,
     72 	DUALCALL_KEVENT,
     73 	DUALCALL__NUM
     74 };
     75 
     76 #define RSYS_STRING(a) __STRING(a)
     77 #define RSYS_NAME(a) RSYS_STRING(__CONCAT(RUMP_SYS_RENAME_,a))
     78 
     79 /*
     80  * Would be nice to get this automatically in sync with libc.
     81  * Also, this does not work for compat-using binaries!
     82  */
     83 #if !__NetBSD_Prereq__(5,99,7)
     84 #define REALSELECT select
     85 #define REALPOLLTS pollts
     86 #define REALKEVENT kevent
     87 #else
     88 #define REALSELECT _sys___select50
     89 #define REALPOLLTS _sys___pollts50
     90 #define REALKEVENT _sys___kevent50
     91 #endif
     92 #define REALREAD _sys_read
     93 
     94 int REALSELECT(int, fd_set *, fd_set *, fd_set *, struct timeval *);
     95 int REALPOLLTS(struct pollfd *, nfds_t,
     96 	       const struct timespec *, const sigset_t *);
     97 int REALKEVENT(int, const struct kevent *, size_t, struct kevent *, size_t,
     98 	       const struct timespec *);
     99 ssize_t REALREAD(int, void *, size_t);
    100 
    101 #define S(a) __STRING(a)
    102 struct sysnames {
    103 	enum dualcall scm_callnum;
    104 	const char *scm_hostname;
    105 	const char *scm_rumpname;
    106 } syscnames[] = {
    107 	{ DUALCALL_SOCKET,	"__socket30",	RSYS_NAME(SOCKET)	},
    108 	{ DUALCALL_ACCEPT,	"accept",	RSYS_NAME(ACCEPT)	},
    109 	{ DUALCALL_BIND,	"bind",		RSYS_NAME(BIND)		},
    110 	{ DUALCALL_CONNECT,	"connect",	RSYS_NAME(CONNECT)	},
    111 	{ DUALCALL_GETPEERNAME,	"getpeername",	RSYS_NAME(GETPEERNAME)	},
    112 	{ DUALCALL_GETSOCKNAME,	"getsockname",	RSYS_NAME(GETSOCKNAME)	},
    113 	{ DUALCALL_LISTEN,	"listen",	RSYS_NAME(LISTEN)	},
    114 	{ DUALCALL_RECVFROM,	"recvfrom",	RSYS_NAME(RECVFROM)	},
    115 	{ DUALCALL_RECVMSG,	"recvmsg",	RSYS_NAME(RECVMSG)	},
    116 	{ DUALCALL_SENDTO,	"sendto",	RSYS_NAME(SENDTO)	},
    117 	{ DUALCALL_SENDMSG,	"sendmsg",	RSYS_NAME(SENDMSG)	},
    118 	{ DUALCALL_GETSOCKOPT,	"getsockopt",	RSYS_NAME(GETSOCKOPT)	},
    119 	{ DUALCALL_SETSOCKOPT,	"setsockopt",	RSYS_NAME(SETSOCKOPT)	},
    120 	{ DUALCALL_SHUTDOWN,	"shutdown",	RSYS_NAME(SHUTDOWN)	},
    121 	{ DUALCALL_READ,	S(REALREAD),	RSYS_NAME(READ)		},
    122 	{ DUALCALL_READV,	"readv",	RSYS_NAME(READV)	},
    123 	{ DUALCALL_WRITE,	"write",	RSYS_NAME(WRITE)	},
    124 	{ DUALCALL_WRITEV,	"writev",	RSYS_NAME(WRITEV)	},
    125 	{ DUALCALL_IOCTL,	"ioctl",	RSYS_NAME(IOCTL)	},
    126 	{ DUALCALL_FCNTL,	"fcntl",	RSYS_NAME(FCNTL)	},
    127 	{ DUALCALL_DUP,		"dup",		RSYS_NAME(DUP)		},
    128 	{ DUALCALL_DUP2,	"dup2",		RSYS_NAME(DUP2)		},
    129 	{ DUALCALL_CLOSE,	"close",	RSYS_NAME(CLOSE)	},
    130 	{ DUALCALL_POLLTS,	S(REALPOLLTS),	RSYS_NAME(POLLTS)	},
    131 	{ DUALCALL_KEVENT,	S(REALKEVENT),	RSYS_NAME(KEVENT)	},
    132 };
    133 #undef S
    134 
    135 struct bothsys {
    136 	void *bs_host;
    137 	void *bs_rump;
    138 } syscalls[DUALCALL__NUM];
    139 #define GETSYSCALL(which, name) syscalls[DUALCALL_##name].bs_##which
    140 
    141 pid_t	(*host_fork)(void);
    142 int	(*host_daemon)(int, int);
    143 int	(*host_execve)(const char *, char *const[], char *const[]);
    144 
    145 static uint32_t dup2mask;
    146 #define ISDUP2D(fd) (((fd) < 32) && (1<<(fd) & dup2mask))
    147 #define SETDUP2(fd) \
    148     do { if ((fd) < 32) dup2mask |= (1<<(fd)); } while (/*CONSTCOND*/0)
    149 #define CLRDUP2(fd) \
    150     do { if ((fd) < 32) dup2mask &= ~(1<<(fd)); } while (/*CONSTCOND*/0)
    151 
    152 //#define DEBUGJACK
    153 #ifdef DEBUGJACK
    154 #define DPRINTF(x) mydprintf x
    155 static void
    156 mydprintf(const char *fmt, ...)
    157 {
    158 	va_list ap;
    159 
    160 	if (ISDUP2D(STDERR_FILENO))
    161 		return;
    162 
    163 	va_start(ap, fmt);
    164 	vfprintf(stderr, fmt, ap);
    165 	va_end(ap);
    166 }
    167 
    168 #else
    169 #define DPRINTF(x)
    170 #endif
    171 
    172 #define FDCALL(type, name, rcname, args, proto, vars)			\
    173 type name args								\
    174 {									\
    175 	type (*fun) proto;						\
    176 									\
    177 	DPRINTF(("%s -> %d\n", __STRING(name), fd));			\
    178 	if (fd_isrump(fd)) {						\
    179 		fun = syscalls[rcname].bs_rump;				\
    180 		fd = fd_host2rump(fd);					\
    181 	} else {							\
    182 		fun = syscalls[rcname].bs_host;				\
    183 	}								\
    184 									\
    185 	return fun vars;						\
    186 }
    187 
    188 /*
    189  * This is called from librumpclient in case of LD_PRELOAD.
    190  * It ensures correct RTLD_NEXT.
    191  *
    192  * ... except, it's apparently extremely difficult to force
    193  * at least gcc to generate an actual stack frame here.  So
    194  * sprinkle some volatile foobar and baz to throw the optimizer
    195  * off the scent and generate a variable assignment with the
    196  * return value.  The posterboy for this meltdown is amd64
    197  * with -O2.  At least with gcc 4.1.3 i386 works regardless of
    198  * optimization.
    199  */
    200 volatile int rumphijack_unrope; /* there, unhang yourself */
    201 static void *
    202 hijackdlsym(void *handle, const char *symbol)
    203 {
    204 	void *rv;
    205 
    206 	rv = dlsym(handle, symbol);
    207 	rumphijack_unrope = *(volatile int *)rv;
    208 
    209 	return (void *)rv;
    210 }
    211 
    212 /* low calorie sockets? */
    213 static bool hostlocalsockets = true;
    214 
    215 static void __attribute__((constructor))
    216 rcinit(void)
    217 {
    218 	char buf[64];
    219 	extern void *(*rumpclient_dlsym)(void *, const char *);
    220 	unsigned i, j;
    221 
    222 	rumpclient_dlsym = hijackdlsym;
    223 	host_fork = dlsym(RTLD_NEXT, "fork");
    224 	host_daemon = dlsym(RTLD_NEXT, "daemon");
    225 	host_execve = dlsym(RTLD_NEXT, "execve");
    226 
    227 	/*
    228 	 * In theory cannot print anything during lookups because
    229 	 * we might not have the call vector set up.  so, the errx()
    230 	 * is a bit of a strech, but it might work.
    231 	 */
    232 
    233 	for (i = 0; i < DUALCALL__NUM; i++) {
    234 		/* build runtime O(1) access */
    235 		for (j = 0; j < __arraycount(syscnames); j++) {
    236 			if (syscnames[j].scm_callnum == i)
    237 				break;
    238 		}
    239 
    240 		if (j == __arraycount(syscnames))
    241 			errx(1, "rumphijack error: syscall pos %d missing", i);
    242 
    243 		syscalls[i].bs_host = dlsym(RTLD_NEXT,
    244 		    syscnames[j].scm_hostname);
    245 		if (syscalls[i].bs_host == NULL)
    246 			errx(1, "hostcall %s not found missing",
    247 			    syscnames[j].scm_hostname);
    248 
    249 		syscalls[i].bs_rump = dlsym(RTLD_NEXT,
    250 		    syscnames[j].scm_rumpname);
    251 		if (syscalls[i].bs_rump == NULL)
    252 			errx(1, "rumpcall %s not found missing",
    253 			    syscnames[j].scm_rumpname);
    254 	}
    255 
    256 	if (rumpclient_init() == -1)
    257 		err(1, "rumpclient init");
    258 
    259 	/* set client persistence level */
    260 	if (getenv_r("RUMPHIJACK_RETRY", buf, sizeof(buf)) == -1) {
    261 		if (errno == ERANGE)
    262 			err(1, "invalid RUMPHIJACK_RETRY");
    263 		rumpclient_setconnretry(RUMPCLIENT_RETRYCONN_INFTIME);
    264 	} else {
    265 		if (strcmp(buf, "die") == 0)
    266 			rumpclient_setconnretry(RUMPCLIENT_RETRYCONN_DIE);
    267 		else if (strcmp(buf, "inftime") == 0)
    268 			rumpclient_setconnretry(RUMPCLIENT_RETRYCONN_INFTIME);
    269 		else if (strcmp(buf, "once") == 0)
    270 			rumpclient_setconnretry(RUMPCLIENT_RETRYCONN_ONCE);
    271 		else {
    272 			time_t timeout;
    273 
    274 			timeout = (time_t)strtoll(buf, NULL, 10);
    275 			if (timeout <= 0)
    276 				errx(1, "RUMPHIJACK_RETRY must be keyword "
    277 				    "or a positive integer, got: %s", buf);
    278 
    279 			rumpclient_setconnretry(timeout);
    280 		}
    281 	}
    282 
    283 	if (getenv_r("RUMPHIJACK__DUP2MASK", buf, sizeof(buf)) == 0) {
    284 		dup2mask = strtoul(buf, NULL, 10);
    285 	}
    286 }
    287 
    288 /* XXX: need runtime selection.  low for now due to FD_SETSIZE */
    289 #define HIJACK_FDOFF 128
    290 static int
    291 fd_rump2host(int fd)
    292 {
    293 
    294 	if (fd == -1)
    295 		return fd;
    296 
    297 	if (!ISDUP2D(fd))
    298 		fd += HIJACK_FDOFF;
    299 
    300 	return fd;
    301 }
    302 
    303 static int
    304 fd_host2rump(int fd)
    305 {
    306 
    307 	if (!ISDUP2D(fd))
    308 		fd -= HIJACK_FDOFF;
    309 	return fd;
    310 }
    311 
    312 static bool
    313 fd_isrump(int fd)
    314 {
    315 
    316 	return ISDUP2D(fd) || fd >= HIJACK_FDOFF;
    317 }
    318 
    319 #define assertfd(_fd_) assert(ISDUP2D(_fd_) || (_fd_) >= HIJACK_FDOFF)
    320 
    321 static int
    322 dodup(int oldd, int minfd)
    323 {
    324 	int (*op_fcntl)(int, int, ...);
    325 	int newd;
    326 	int isrump;
    327 
    328 	DPRINTF(("dup -> %d (minfd %d)\n", oldd, minfd));
    329 	if (fd_isrump(oldd)) {
    330 		op_fcntl = GETSYSCALL(rump, FCNTL);
    331 		oldd = fd_host2rump(oldd);
    332 		isrump = 1;
    333 	} else {
    334 		op_fcntl = GETSYSCALL(host, FCNTL);
    335 		isrump = 0;
    336 	}
    337 
    338 	newd = op_fcntl(oldd, F_DUPFD, minfd);
    339 
    340 	if (isrump)
    341 		newd = fd_rump2host(newd);
    342 	DPRINTF(("dup <- %d\n", newd));
    343 
    344 	return newd;
    345 }
    346 
    347 int __socket30(int, int, int);
    348 int
    349 __socket30(int domain, int type, int protocol)
    350 {
    351 	int (*op_socket)(int, int, int);
    352 	int fd;
    353 	bool dohost;
    354 
    355 	dohost = hostlocalsockets && (domain == AF_LOCAL);
    356 
    357 	if (dohost)
    358 		op_socket = GETSYSCALL(host, SOCKET);
    359 	else
    360 		op_socket = GETSYSCALL(rump, SOCKET);
    361 	fd = op_socket(domain, type, protocol);
    362 
    363 	if (!dohost)
    364 		fd = fd_rump2host(fd);
    365 	DPRINTF(("socket <- %d\n", fd));
    366 
    367 	return fd;
    368 }
    369 
    370 int
    371 accept(int s, struct sockaddr *addr, socklen_t *addrlen)
    372 {
    373 	int (*op_accept)(int, struct sockaddr *, socklen_t *);
    374 	int fd;
    375 	bool isrump;
    376 
    377 	isrump = fd_isrump(s);
    378 
    379 	DPRINTF(("accept -> %d", s));
    380 	if (isrump) {
    381 		op_accept = GETSYSCALL(rump, ACCEPT);
    382 		s = fd_host2rump(s);
    383 	} else {
    384 		op_accept = GETSYSCALL(host, ACCEPT);
    385 	}
    386 	fd = op_accept(s, addr, addrlen);
    387 	if (fd != -1 && isrump)
    388 		fd = fd_rump2host(fd);
    389 
    390 	DPRINTF((" <- %d\n", fd));
    391 
    392 	return fd;
    393 }
    394 
    395 /*
    396  * ioctl and fcntl are varargs calls and need special treatment
    397  */
    398 int
    399 ioctl(int fd, unsigned long cmd, ...)
    400 {
    401 	int (*op_ioctl)(int, unsigned long cmd, ...);
    402 	va_list ap;
    403 	int rv;
    404 
    405 	DPRINTF(("ioctl -> %d\n", fd));
    406 	if (fd_isrump(fd)) {
    407 		fd = fd_host2rump(fd);
    408 		op_ioctl = GETSYSCALL(rump, IOCTL);
    409 	} else {
    410 		op_ioctl = GETSYSCALL(host, IOCTL);
    411 	}
    412 
    413 	va_start(ap, cmd);
    414 	rv = op_ioctl(fd, cmd, va_arg(ap, void *));
    415 	va_end(ap);
    416 	return rv;
    417 }
    418 
    419 #include <syslog.h>
    420 int
    421 fcntl(int fd, int cmd, ...)
    422 {
    423 	int (*op_fcntl)(int, int, ...);
    424 	va_list ap;
    425 	int rv, minfd, i;
    426 
    427 	DPRINTF(("fcntl -> %d (cmd %d)\n", fd, cmd));
    428 
    429 	switch (cmd) {
    430 	case F_DUPFD:
    431 		va_start(ap, cmd);
    432 		minfd = va_arg(ap, int);
    433 		va_end(ap);
    434 		return dodup(fd, minfd);
    435 
    436 	case F_CLOSEM:
    437 		/*
    438 		 * So, if fd < HIJACKOFF, we want to do a host closem.
    439 		 */
    440 
    441 		if (fd < HIJACK_FDOFF) {
    442 			int closemfd = fd;
    443 
    444 			if (rumpclient__closenotify(&closemfd,
    445 			    RUMPCLIENT_CLOSE_FCLOSEM) == -1)
    446 				return -1;
    447 			op_fcntl = GETSYSCALL(host, FCNTL);
    448 			rv = op_fcntl(closemfd, cmd);
    449 			if (rv)
    450 				return rv;
    451 		}
    452 
    453 		/*
    454 		 * Additionally, we want to do a rump closem, but only
    455 		 * for the file descriptors not within the dup2mask.
    456 		 */
    457 
    458 		/* why don't we offer fls()? */
    459 		for (i = 31; i >= 0; i--) {
    460 			if (dup2mask & 1<<i)
    461 				break;
    462 		}
    463 
    464 		if (fd >= HIJACK_FDOFF)
    465 			fd -= HIJACK_FDOFF;
    466 		else
    467 			fd = 0;
    468 		fd = MAX(i+1, fd);
    469 
    470 		/* hmm, maybe we should close rump fd's not within dup2mask? */
    471 
    472 		return rump_sys_fcntl(fd, F_CLOSEM);
    473 
    474 	case F_MAXFD:
    475 		/*
    476 		 * For maxfd, if there's a rump kernel fd, return
    477 		 * it hostified.  Otherwise, return host's MAXFD
    478 		 * return value.
    479 		 */
    480 		if ((rv = rump_sys_fcntl(fd, F_MAXFD)) != -1) {
    481 			/*
    482 			 * This might go a little wrong in case
    483 			 * of dup2 to [012], but I'm not sure if
    484 			 * there's a justification for tracking
    485 			 * that info.  Consider e.g.
    486 			 * dup2(rumpfd, 2) followed by rump_sys_open()
    487 			 * returning 1.  We should return 1+HIJACKOFF,
    488 			 * not 2+HIJACKOFF.  However, if [01] is not
    489 			 * open, the correct return value is 2.
    490 			 */
    491 			return fd_rump2host(fd);
    492 		} else {
    493 			op_fcntl = GETSYSCALL(host, FCNTL);
    494 			return op_fcntl(fd, F_MAXFD);
    495 		}
    496 		/*NOTREACHED*/
    497 
    498 	default:
    499 		if (fd_isrump(fd)) {
    500 			fd = fd_host2rump(fd);
    501 			op_fcntl = GETSYSCALL(rump, FCNTL);
    502 		} else {
    503 			op_fcntl = GETSYSCALL(host, FCNTL);
    504 		}
    505 
    506 		va_start(ap, cmd);
    507 		rv = op_fcntl(fd, cmd, va_arg(ap, void *));
    508 		va_end(ap);
    509 		return rv;
    510 	}
    511 	/*NOTREACHED*/
    512 }
    513 
    514 int
    515 close(int fd)
    516 {
    517 	int (*op_close)(int);
    518 	int rv;
    519 
    520 	DPRINTF(("close -> %d\n", fd));
    521 	if (fd_isrump(fd)) {
    522 		int undup2 = 0;
    523 
    524 		if (ISDUP2D(fd))
    525 			undup2 = 1;
    526 		fd = fd_host2rump(fd);
    527 		op_close = GETSYSCALL(rump, CLOSE);
    528 		rv = op_close(fd);
    529 		if (rv == 0 && undup2)
    530 			CLRDUP2(fd);
    531 	} else {
    532 		if (rumpclient__closenotify(&fd, RUMPCLIENT_CLOSE_CLOSE) == -1)
    533 			return -1;
    534 		op_close = GETSYSCALL(host, CLOSE);
    535 		rv = op_close(fd);
    536 	}
    537 
    538 	return rv;
    539 }
    540 
    541 /*
    542  * write cannot issue a standard debug printf due to recursion
    543  */
    544 ssize_t
    545 write(int fd, const void *buf, size_t blen)
    546 {
    547 	ssize_t (*op_write)(int, const void *, size_t);
    548 
    549 	if (fd_isrump(fd)) {
    550 		fd = fd_host2rump(fd);
    551 		op_write = GETSYSCALL(rump, WRITE);
    552 	} else {
    553 		op_write = GETSYSCALL(host, WRITE);
    554 	}
    555 
    556 	return op_write(fd, buf, blen);
    557 }
    558 
    559 /*
    560  * dup2 is special.  we allow dup2 of a rump kernel fd to 0-2 since
    561  * many programs do that.  dup2 of a rump kernel fd to another value
    562  * not >= fdoff is an error.
    563  *
    564  * Note: cannot rump2host newd, because it is often hardcoded.
    565  */
    566 int
    567 dup2(int oldd, int newd)
    568 {
    569 	int (*host_dup2)(int, int);
    570 	int rv;
    571 
    572 	DPRINTF(("dup2 -> %d (o) -> %d (n)\n", oldd, newd));
    573 
    574 	if (fd_isrump(oldd)) {
    575 		if (!(newd >= 0 && newd <= 2))
    576 			return EBADF;
    577 		oldd = fd_host2rump(oldd);
    578 		rv = rump_sys_dup2(oldd, newd);
    579 		if (rv != -1)
    580 			SETDUP2(newd);
    581 	} else {
    582 		host_dup2 = syscalls[DUALCALL_DUP2].bs_host;
    583 		if (rumpclient__closenotify(&newd, RUMPCLIENT_CLOSE_DUP2) == -1)
    584 			return -1;
    585 		rv = host_dup2(oldd, newd);
    586 	}
    587 
    588 	return rv;
    589 }
    590 
    591 int
    592 dup(int oldd)
    593 {
    594 
    595 	return dodup(oldd, 0);
    596 }
    597 
    598 /*
    599  * We just wrap fork the appropriate rump client calls to preserve
    600  * the file descriptors of the forked parent in the child, but
    601  * prevent double use of connection fd.
    602  */
    603 pid_t
    604 fork()
    605 {
    606 	struct rumpclient_fork *rf;
    607 	pid_t rv;
    608 
    609 	DPRINTF(("fork\n"));
    610 
    611 	if ((rf = rumpclient_prefork()) == NULL)
    612 		return -1;
    613 
    614 	switch ((rv = host_fork())) {
    615 	case -1:
    616 		/* XXX: cancel rf */
    617 		break;
    618 	case 0:
    619 		if (rumpclient_fork_init(rf) == -1)
    620 			rv = -1;
    621 		break;
    622 	default:
    623 		break;
    624 	}
    625 
    626 	DPRINTF(("fork returns %d\n", rv));
    627 	return rv;
    628 }
    629 
    630 int
    631 daemon(int nochdir, int noclose)
    632 {
    633 	struct rumpclient_fork *rf;
    634 
    635 	if ((rf = rumpclient_prefork()) == NULL)
    636 		return -1;
    637 
    638 	if (host_daemon(nochdir, noclose) == -1)
    639 		return -1;
    640 
    641 	if (rumpclient_fork_init(rf) == -1)
    642 		return -1;
    643 
    644 	return 0;
    645 }
    646 
    647 int
    648 execve(const char *path, char *const argv[], char *const oenvp[])
    649 {
    650 	char buf[128];
    651 	char **env;
    652 	char *dup2maskenv[2];
    653 	char *dup2str;
    654 	int rv;
    655 
    656 	snprintf(buf, sizeof(buf), "RUMPHIJACK__DUP2MASK=%u", dup2mask);
    657 	dup2str = malloc(strlen(buf)+1);
    658 	if (dup2str == NULL)
    659 		return ENOMEM;
    660 	strcpy(dup2str, buf);
    661 	dup2maskenv[0] = dup2str;
    662 	dup2maskenv[1] = NULL;
    663 
    664 	rv = rumpclient__exec_augmentenv(oenvp, dup2maskenv, &env);
    665 	if (rv)
    666 		return rv;
    667 
    668 	rv = host_execve(path, argv, env);
    669 	if (rv != 0) {
    670 		free(dup2str);
    671 		free(env); /* XXX missing some strings within env */
    672 	}
    673 	return rv;
    674 }
    675 
    676 /*
    677  * select is done by calling poll.
    678  */
    679 int
    680 REALSELECT(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
    681 	struct timeval *timeout)
    682 {
    683 	struct pollfd *pfds;
    684 	struct timespec ts, *tsp = NULL;
    685 	nfds_t realnfds;
    686 	int i, j;
    687 	int rv, incr;
    688 
    689 	DPRINTF(("select\n"));
    690 
    691 	/*
    692 	 * Well, first we must scan the fds to figure out how many
    693 	 * fds there really are.  This is because up to and including
    694 	 * nb5 poll() silently refuses nfds > process_maxopen_fds.
    695 	 * Seems to be fixed in current, thank the maker.
    696 	 * god damn cluster...bomb.
    697 	 */
    698 
    699 	for (i = 0, realnfds = 0; i < nfds; i++) {
    700 		if (readfds && FD_ISSET(i, readfds)) {
    701 			realnfds++;
    702 			continue;
    703 		}
    704 		if (writefds && FD_ISSET(i, writefds)) {
    705 			realnfds++;
    706 			continue;
    707 		}
    708 		if (exceptfds && FD_ISSET(i, exceptfds)) {
    709 			realnfds++;
    710 			continue;
    711 		}
    712 	}
    713 
    714 	if (realnfds) {
    715 		pfds = calloc(realnfds, sizeof(*pfds));
    716 		if (!pfds)
    717 			return -1;
    718 	} else {
    719 		pfds = NULL;
    720 	}
    721 
    722 	for (i = 0, j = 0; i < nfds; i++) {
    723 		incr = 0;
    724 		if (readfds && FD_ISSET(i, readfds)) {
    725 			pfds[j].fd = i;
    726 			pfds[j].events |= POLLIN;
    727 			incr=1;
    728 		}
    729 		if (writefds && FD_ISSET(i, writefds)) {
    730 			pfds[j].fd = i;
    731 			pfds[j].events |= POLLOUT;
    732 			incr=1;
    733 		}
    734 		if (exceptfds && FD_ISSET(i, exceptfds)) {
    735 			pfds[j].fd = i;
    736 			pfds[j].events |= POLLHUP|POLLERR;
    737 			incr=1;
    738 		}
    739 		if (incr)
    740 			j++;
    741 	}
    742 	assert(j == (int)realnfds);
    743 
    744 	if (timeout) {
    745 		TIMEVAL_TO_TIMESPEC(timeout, &ts);
    746 		tsp = &ts;
    747 	}
    748 	rv = REALPOLLTS(pfds, realnfds, tsp, NULL);
    749 	/*
    750 	 * "If select() returns with an error the descriptor sets
    751 	 * will be unmodified"
    752 	 */
    753 	if (rv < 0)
    754 		goto out;
    755 
    756 	/*
    757 	 * zero out results (can't use FD_ZERO for the
    758 	 * obvious select-me-not reason).  whee.
    759 	 *
    760 	 * We do this here since some software ignores the return
    761 	 * value of select, and hence if the timeout expires, it may
    762 	 * assume all input descriptors have activity.
    763 	 */
    764 	for (i = 0; i < nfds; i++) {
    765 		if (readfds)
    766 			FD_CLR(i, readfds);
    767 		if (writefds)
    768 			FD_CLR(i, writefds);
    769 		if (exceptfds)
    770 			FD_CLR(i, exceptfds);
    771 	}
    772 	if (rv == 0)
    773 		goto out;
    774 
    775 	/*
    776 	 * We have >0 fds with activity.  Harvest the results.
    777 	 */
    778 	for (i = 0; i < (int)realnfds; i++) {
    779 		if (readfds) {
    780 			if (pfds[i].revents & POLLIN) {
    781 				FD_SET(pfds[i].fd, readfds);
    782 			}
    783 		}
    784 		if (writefds) {
    785 			if (pfds[i].revents & POLLOUT) {
    786 				FD_SET(pfds[i].fd, writefds);
    787 			}
    788 		}
    789 		if (exceptfds) {
    790 			if (pfds[i].revents & (POLLHUP|POLLERR)) {
    791 				FD_SET(pfds[i].fd, exceptfds);
    792 			}
    793 		}
    794 	}
    795 
    796  out:
    797 	free(pfds);
    798 	return rv;
    799 }
    800 
    801 static void
    802 checkpoll(struct pollfd *fds, nfds_t nfds, int *hostcall, int *rumpcall)
    803 {
    804 	nfds_t i;
    805 
    806 	for (i = 0; i < nfds; i++) {
    807 		if (fds[i].fd == -1)
    808 			continue;
    809 
    810 		if (fd_isrump(fds[i].fd))
    811 			(*rumpcall)++;
    812 		else
    813 			(*hostcall)++;
    814 	}
    815 }
    816 
    817 static void
    818 adjustpoll(struct pollfd *fds, nfds_t nfds, int (*fdadj)(int))
    819 {
    820 	nfds_t i;
    821 
    822 	for (i = 0; i < nfds; i++) {
    823 		fds[i].fd = fdadj(fds[i].fd);
    824 	}
    825 }
    826 
    827 /*
    828  * poll is easy as long as the call comes in the fds only in one
    829  * kernel.  otherwise its quite tricky...
    830  */
    831 struct pollarg {
    832 	struct pollfd *pfds;
    833 	nfds_t nfds;
    834 	const struct timespec *ts;
    835 	const sigset_t *sigmask;
    836 	int pipefd;
    837 	int errnum;
    838 };
    839 
    840 static void *
    841 hostpoll(void *arg)
    842 {
    843 	int (*op_pollts)(struct pollfd *, nfds_t, const struct timespec *,
    844 			 const sigset_t *);
    845 	struct pollarg *parg = arg;
    846 	intptr_t rv;
    847 
    848 	op_pollts = GETSYSCALL(host, POLLTS);
    849 	rv = op_pollts(parg->pfds, parg->nfds, parg->ts, parg->sigmask);
    850 	if (rv == -1)
    851 		parg->errnum = errno;
    852 	rump_sys_write(parg->pipefd, &rv, sizeof(rv));
    853 
    854 	return (void *)(intptr_t)rv;
    855 }
    856 
    857 int
    858 REALPOLLTS(struct pollfd *fds, nfds_t nfds, const struct timespec *ts,
    859 	const sigset_t *sigmask)
    860 {
    861 	int (*op_pollts)(struct pollfd *, nfds_t, const struct timespec *,
    862 			 const sigset_t *);
    863 	int (*host_close)(int);
    864 	int hostcall = 0, rumpcall = 0;
    865 	pthread_t pt;
    866 	nfds_t i;
    867 	int rv;
    868 
    869 	DPRINTF(("poll\n"));
    870 	checkpoll(fds, nfds, &hostcall, &rumpcall);
    871 
    872 	if (hostcall && rumpcall) {
    873 		struct pollfd *pfd_host = NULL, *pfd_rump = NULL;
    874 		int rpipe[2] = {-1,-1}, hpipe[2] = {-1,-1};
    875 		struct pollarg parg;
    876 		uintptr_t lrv;
    877 		int sverrno = 0, trv;
    878 
    879 		/*
    880 		 * ok, this is where it gets tricky.  We must support
    881 		 * this since it's a very common operation in certain
    882 		 * types of software (telnet, netcat, etc).  We allocate
    883 		 * two vectors and run two poll commands in separate
    884 		 * threads.  Whichever returns first "wins" and the
    885 		 * other kernel's fds won't show activity.
    886 		 */
    887 		rv = -1;
    888 
    889 		/* allocate full vector for O(n) joining after call */
    890 		pfd_host = malloc(sizeof(*pfd_host)*(nfds+1));
    891 		if (!pfd_host)
    892 			goto out;
    893 		pfd_rump = malloc(sizeof(*pfd_rump)*(nfds+1));
    894 		if (!pfd_rump) {
    895 			goto out;
    896 		}
    897 
    898 		/* split vectors */
    899 		for (i = 0; i < nfds; i++) {
    900 			if (fds[i].fd == -1) {
    901 				pfd_host[i].fd = -1;
    902 				pfd_rump[i].fd = -1;
    903 			} else if (fd_isrump(fds[i].fd)) {
    904 				pfd_host[i].fd = -1;
    905 				pfd_rump[i].fd = fd_host2rump(fds[i].fd);
    906 				pfd_rump[i].events = fds[i].events;
    907 			} else {
    908 				pfd_rump[i].fd = -1;
    909 				pfd_host[i].fd = fds[i].fd;
    910 				pfd_host[i].events = fds[i].events;
    911 			}
    912 			pfd_rump[i].revents = pfd_host[i].revents = 0;
    913 			fds[i].revents = 0;
    914 		}
    915 
    916 		/*
    917 		 * then, open two pipes, one for notifications
    918 		 * to each kernel.
    919 		 */
    920 		if (rump_sys_pipe(rpipe) == -1)
    921 			goto out;
    922 		if (pipe(hpipe) == -1)
    923 			goto out;
    924 
    925 		pfd_host[nfds].fd = hpipe[0];
    926 		pfd_host[nfds].events = POLLIN;
    927 		pfd_rump[nfds].fd = rpipe[0];
    928 		pfd_rump[nfds].events = POLLIN;
    929 
    930 		/*
    931 		 * then, create a thread to do host part and meanwhile
    932 		 * do rump kernel part right here
    933 		 */
    934 
    935 		parg.pfds = pfd_host;
    936 		parg.nfds = nfds+1;
    937 		parg.ts = ts;
    938 		parg.sigmask = sigmask;
    939 		parg.pipefd = rpipe[1];
    940 		pthread_create(&pt, NULL, hostpoll, &parg);
    941 
    942 		op_pollts = GETSYSCALL(rump, POLLTS);
    943 		lrv = op_pollts(pfd_rump, nfds+1, ts, NULL);
    944 		sverrno = errno;
    945 		write(hpipe[1], &rv, sizeof(rv));
    946 		pthread_join(pt, (void *)&trv);
    947 
    948 		/* check who "won" and merge results */
    949 		if (lrv != 0 && pfd_host[nfds].revents & POLLIN) {
    950 			rv = trv;
    951 
    952 			for (i = 0; i < nfds; i++) {
    953 				if (pfd_rump[i].fd != -1)
    954 					fds[i].revents = pfd_rump[i].revents;
    955 			}
    956 			sverrno = parg.errnum;
    957 		} else if (trv != 0 && pfd_rump[nfds].revents & POLLIN) {
    958 			rv = trv;
    959 
    960 			for (i = 0; i < nfds; i++) {
    961 				if (pfd_host[i].fd != -1)
    962 					fds[i].revents = pfd_host[i].revents;
    963 			}
    964 		} else {
    965 			rv = 0;
    966 		}
    967 
    968  out:
    969 		host_close = GETSYSCALL(host, CLOSE);
    970 		if (rpipe[0] != -1)
    971 			rump_sys_close(rpipe[0]);
    972 		if (rpipe[1] != -1)
    973 			rump_sys_close(rpipe[1]);
    974 		if (hpipe[0] != -1)
    975 			host_close(hpipe[0]);
    976 		if (hpipe[1] != -1)
    977 			host_close(hpipe[1]);
    978 		free(pfd_host);
    979 		free(pfd_rump);
    980 		errno = sverrno;
    981 	} else {
    982 		if (hostcall) {
    983 			op_pollts = GETSYSCALL(host, POLLTS);
    984 		} else {
    985 			op_pollts = GETSYSCALL(rump, POLLTS);
    986 			adjustpoll(fds, nfds, fd_host2rump);
    987 		}
    988 
    989 		rv = op_pollts(fds, nfds, ts, sigmask);
    990 		if (rumpcall)
    991 			adjustpoll(fds, nfds, fd_rump2host);
    992 	}
    993 
    994 	return rv;
    995 }
    996 
    997 int
    998 poll(struct pollfd *fds, nfds_t nfds, int timeout)
    999 {
   1000 	struct timespec ts;
   1001 	struct timespec *tsp = NULL;
   1002 
   1003 	if (timeout != INFTIM) {
   1004 		ts.tv_sec = timeout / 1000;
   1005 		ts.tv_nsec = (timeout % 1000) * 1000*1000;
   1006 
   1007 		tsp = &ts;
   1008 	}
   1009 
   1010 	return REALPOLLTS(fds, nfds, tsp, NULL);
   1011 }
   1012 
   1013 int
   1014 REALKEVENT(int kq, const struct kevent *changelist, size_t nchanges,
   1015 	struct kevent *eventlist, size_t nevents,
   1016 	const struct timespec *timeout)
   1017 {
   1018 	int (*op_kevent)(int, const struct kevent *, size_t,
   1019 		struct kevent *, size_t, const struct timespec *);
   1020 	const struct kevent *ev;
   1021 	size_t i;
   1022 
   1023 	/*
   1024 	 * Check that we don't attempt to kevent rump kernel fd's.
   1025 	 * That needs similar treatment to select/poll, but is slightly
   1026 	 * trickier since we need to manage to different kq descriptors.
   1027 	 * (TODO, in case you're wondering).
   1028 	 */
   1029 	for (i = 0; i < nchanges; i++) {
   1030 		ev = &changelist[i];
   1031 		if (ev->filter == EVFILT_READ || ev->filter == EVFILT_WRITE ||
   1032 		    ev->filter == EVFILT_VNODE) {
   1033 			if (fd_isrump((int)ev->ident))
   1034 				return ENOTSUP;
   1035 		}
   1036 	}
   1037 
   1038 	op_kevent = GETSYSCALL(host, KEVENT);
   1039 	return op_kevent(kq, changelist, nchanges, eventlist, nevents, timeout);
   1040 }
   1041 
   1042 /*
   1043  * Rest are std type calls.
   1044  */
   1045 
   1046 FDCALL(int, bind, DUALCALL_BIND,					\
   1047 	(int fd, const struct sockaddr *name, socklen_t namelen),	\
   1048 	(int, const struct sockaddr *, socklen_t),			\
   1049 	(fd, name, namelen))
   1050 
   1051 FDCALL(int, connect, DUALCALL_CONNECT,					\
   1052 	(int fd, const struct sockaddr *name, socklen_t namelen),	\
   1053 	(int, const struct sockaddr *, socklen_t),			\
   1054 	(fd, name, namelen))
   1055 
   1056 FDCALL(int, getpeername, DUALCALL_GETPEERNAME,				\
   1057 	(int fd, struct sockaddr *name, socklen_t *namelen),		\
   1058 	(int, struct sockaddr *, socklen_t *),				\
   1059 	(fd, name, namelen))
   1060 
   1061 FDCALL(int, getsockname, DUALCALL_GETSOCKNAME, 				\
   1062 	(int fd, struct sockaddr *name, socklen_t *namelen),		\
   1063 	(int, struct sockaddr *, socklen_t *),				\
   1064 	(fd, name, namelen))
   1065 
   1066 FDCALL(int, listen, DUALCALL_LISTEN,	 				\
   1067 	(int fd, int backlog),						\
   1068 	(int, int),							\
   1069 	(fd, backlog))
   1070 
   1071 FDCALL(ssize_t, recvfrom, DUALCALL_RECVFROM, 				\
   1072 	(int fd, void *buf, size_t len, int flags,			\
   1073 	    struct sockaddr *from, socklen_t *fromlen),			\
   1074 	(int, void *, size_t, int, struct sockaddr *, socklen_t *),	\
   1075 	(fd, buf, len, flags, from, fromlen))
   1076 
   1077 FDCALL(ssize_t, sendto, DUALCALL_SENDTO, 				\
   1078 	(int fd, const void *buf, size_t len, int flags,		\
   1079 	    const struct sockaddr *to, socklen_t tolen),		\
   1080 	(int, const void *, size_t, int,				\
   1081 	    const struct sockaddr *, socklen_t),			\
   1082 	(fd, buf, len, flags, to, tolen))
   1083 
   1084 FDCALL(ssize_t, recvmsg, DUALCALL_RECVMSG, 				\
   1085 	(int fd, struct msghdr *msg, int flags),			\
   1086 	(int, struct msghdr *, int),					\
   1087 	(fd, msg, flags))
   1088 
   1089 FDCALL(ssize_t, sendmsg, DUALCALL_SENDMSG, 				\
   1090 	(int fd, const struct msghdr *msg, int flags),			\
   1091 	(int, const struct msghdr *, int),				\
   1092 	(fd, msg, flags))
   1093 
   1094 FDCALL(int, getsockopt, DUALCALL_GETSOCKOPT, 				\
   1095 	(int fd, int level, int optn, void *optval, socklen_t *optlen),	\
   1096 	(int, int, int, void *, socklen_t *),				\
   1097 	(fd, level, optn, optval, optlen))
   1098 
   1099 FDCALL(int, setsockopt, DUALCALL_SETSOCKOPT, 				\
   1100 	(int fd, int level, int optn,					\
   1101 	    const void *optval, socklen_t optlen),			\
   1102 	(int, int, int, const void *, socklen_t),			\
   1103 	(fd, level, optn, optval, optlen))
   1104 
   1105 FDCALL(int, shutdown, DUALCALL_SHUTDOWN, 				\
   1106 	(int fd, int how),						\
   1107 	(int, int),							\
   1108 	(fd, how))
   1109 
   1110 #if _FORTIFY_SOURCE > 0
   1111 #define STUB(fun) __ssp_weak_name(fun)
   1112 ssize_t _sys_readlink(const char * __restrict, char * __restrict, size_t);
   1113 ssize_t
   1114 STUB(readlink)(const char * __restrict path, char * __restrict buf,
   1115     size_t bufsiz)
   1116 {
   1117 	return _sys_readlink(path, buf, bufsiz);
   1118 }
   1119 
   1120 char *_sys_getcwd(char *, size_t);
   1121 char *
   1122 STUB(getcwd)(char *buf, size_t size)
   1123 {
   1124 	return _sys_getcwd(buf, size);
   1125 }
   1126 #else
   1127 #define STUB(fun) fun
   1128 #endif
   1129 
   1130 FDCALL(ssize_t, REALREAD, DUALCALL_READ,				\
   1131 	(int fd, void *buf, size_t buflen),				\
   1132 	(int, void *, size_t),						\
   1133 	(fd, buf, buflen))
   1134 
   1135 FDCALL(ssize_t, readv, DUALCALL_READV, 					\
   1136 	(int fd, const struct iovec *iov, int iovcnt),			\
   1137 	(int, const struct iovec *, int),				\
   1138 	(fd, iov, iovcnt))
   1139 
   1140 FDCALL(ssize_t, writev, DUALCALL_WRITEV, 				\
   1141 	(int fd, const struct iovec *iov, int iovcnt),			\
   1142 	(int, const struct iovec *, int),				\
   1143 	(fd, iov, iovcnt))
   1144