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