xref: /openbsd-src/usr.bin/ssh/misc.c (revision 1ad61ae0a79a724d2d3ec69e69c8e1d1ff6b53a0)
1 /* $OpenBSD: misc.c,v 1.189 2023/10/12 03:36:32 djm Exp $ */
2 /*
3  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
4  * Copyright (c) 2005-2020 Damien Miller.  All rights reserved.
5  * Copyright (c) 2004 Henning Brauer <henning@openbsd.org>
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 
21 #include <sys/types.h>
22 #include <sys/ioctl.h>
23 #include <sys/socket.h>
24 #include <sys/stat.h>
25 #include <sys/time.h>
26 #include <sys/wait.h>
27 #include <sys/un.h>
28 
29 #include <net/if.h>
30 #include <netinet/in.h>
31 #include <netinet/ip.h>
32 #include <netinet/tcp.h>
33 #include <arpa/inet.h>
34 
35 #include <ctype.h>
36 #include <errno.h>
37 #include <fcntl.h>
38 #include <netdb.h>
39 #include <paths.h>
40 #include <pwd.h>
41 #include <libgen.h>
42 #include <limits.h>
43 #include <nlist.h>
44 #include <poll.h>
45 #include <signal.h>
46 #include <stdarg.h>
47 #include <stdio.h>
48 #include <stdint.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <unistd.h>
52 
53 #include "xmalloc.h"
54 #include "misc.h"
55 #include "log.h"
56 #include "ssh.h"
57 #include "sshbuf.h"
58 #include "ssherr.h"
59 
60 /* remove newline at end of string */
61 char *
62 chop(char *s)
63 {
64 	char *t = s;
65 	while (*t) {
66 		if (*t == '\n' || *t == '\r') {
67 			*t = '\0';
68 			return s;
69 		}
70 		t++;
71 	}
72 	return s;
73 
74 }
75 
76 /* remove whitespace from end of string */
77 void
78 rtrim(char *s)
79 {
80 	size_t i;
81 
82 	if ((i = strlen(s)) == 0)
83 		return;
84 	for (i--; i > 0; i--) {
85 		if (isspace((unsigned char)s[i]))
86 			s[i] = '\0';
87 	}
88 }
89 
90 /* set/unset filedescriptor to non-blocking */
91 int
92 set_nonblock(int fd)
93 {
94 	int val;
95 
96 	val = fcntl(fd, F_GETFL);
97 	if (val == -1) {
98 		error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
99 		return (-1);
100 	}
101 	if (val & O_NONBLOCK) {
102 		debug3("fd %d is O_NONBLOCK", fd);
103 		return (0);
104 	}
105 	debug2("fd %d setting O_NONBLOCK", fd);
106 	val |= O_NONBLOCK;
107 	if (fcntl(fd, F_SETFL, val) == -1) {
108 		debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
109 		    strerror(errno));
110 		return (-1);
111 	}
112 	return (0);
113 }
114 
115 int
116 unset_nonblock(int fd)
117 {
118 	int val;
119 
120 	val = fcntl(fd, F_GETFL);
121 	if (val == -1) {
122 		error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
123 		return (-1);
124 	}
125 	if (!(val & O_NONBLOCK)) {
126 		debug3("fd %d is not O_NONBLOCK", fd);
127 		return (0);
128 	}
129 	debug("fd %d clearing O_NONBLOCK", fd);
130 	val &= ~O_NONBLOCK;
131 	if (fcntl(fd, F_SETFL, val) == -1) {
132 		debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
133 		    fd, strerror(errno));
134 		return (-1);
135 	}
136 	return (0);
137 }
138 
139 const char *
140 ssh_gai_strerror(int gaierr)
141 {
142 	if (gaierr == EAI_SYSTEM && errno != 0)
143 		return strerror(errno);
144 	return gai_strerror(gaierr);
145 }
146 
147 /* disable nagle on socket */
148 void
149 set_nodelay(int fd)
150 {
151 	int opt;
152 	socklen_t optlen;
153 
154 	optlen = sizeof opt;
155 	if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
156 		debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
157 		return;
158 	}
159 	if (opt == 1) {
160 		debug2("fd %d is TCP_NODELAY", fd);
161 		return;
162 	}
163 	opt = 1;
164 	debug2("fd %d setting TCP_NODELAY", fd);
165 	if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
166 		error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
167 }
168 
169 /* Allow local port reuse in TIME_WAIT */
170 int
171 set_reuseaddr(int fd)
172 {
173 	int on = 1;
174 
175 	if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
176 		error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
177 		return -1;
178 	}
179 	return 0;
180 }
181 
182 /* Get/set routing domain */
183 char *
184 get_rdomain(int fd)
185 {
186 	int rtable;
187 	char *ret;
188 	socklen_t len = sizeof(rtable);
189 
190 	if (getsockopt(fd, SOL_SOCKET, SO_RTABLE, &rtable, &len) == -1) {
191 		error("Failed to get routing domain for fd %d: %s",
192 		    fd, strerror(errno));
193 		return NULL;
194 	}
195 	xasprintf(&ret, "%d", rtable);
196 	return ret;
197 }
198 
199 int
200 set_rdomain(int fd, const char *name)
201 {
202 	int rtable;
203 	const char *errstr;
204 
205 	if (name == NULL)
206 		return 0; /* default table */
207 
208 	rtable = (int)strtonum(name, 0, 255, &errstr);
209 	if (errstr != NULL) {
210 		/* Shouldn't happen */
211 		error("Invalid routing domain \"%s\": %s", name, errstr);
212 		return -1;
213 	}
214 	if (setsockopt(fd, SOL_SOCKET, SO_RTABLE,
215 	    &rtable, sizeof(rtable)) == -1) {
216 		error("Failed to set routing domain %d on fd %d: %s",
217 		    rtable, fd, strerror(errno));
218 		return -1;
219 	}
220 	return 0;
221 }
222 
223 int
224 get_sock_af(int fd)
225 {
226 	struct sockaddr_storage to;
227 	socklen_t tolen = sizeof(to);
228 
229 	memset(&to, 0, sizeof(to));
230 	if (getsockname(fd, (struct sockaddr *)&to, &tolen) == -1)
231 		return -1;
232 	return to.ss_family;
233 }
234 
235 void
236 set_sock_tos(int fd, int tos)
237 {
238 	int af;
239 
240 	switch ((af = get_sock_af(fd))) {
241 	case -1:
242 		/* assume not a socket */
243 		break;
244 	case AF_INET:
245 		debug3_f("set socket %d IP_TOS 0x%02x", fd, tos);
246 		if (setsockopt(fd, IPPROTO_IP, IP_TOS,
247 		    &tos, sizeof(tos)) == -1) {
248 			error("setsockopt socket %d IP_TOS %d: %s",
249 			    fd, tos, strerror(errno));
250 		}
251 		break;
252 	case AF_INET6:
253 		debug3_f("set socket %d IPV6_TCLASS 0x%02x", fd, tos);
254 		if (setsockopt(fd, IPPROTO_IPV6, IPV6_TCLASS,
255 		    &tos, sizeof(tos)) == -1) {
256 			error("setsockopt socket %d IPV6_TCLASS %d: %s",
257 			    fd, tos, strerror(errno));
258 		}
259 		break;
260 	default:
261 		debug2_f("unsupported socket family %d", af);
262 		break;
263 	}
264 }
265 
266 /*
267  * Wait up to *timeoutp milliseconds for events on fd. Updates
268  * *timeoutp with time remaining.
269  * Returns 0 if fd ready or -1 on timeout or error (see errno).
270  */
271 static int
272 waitfd(int fd, int *timeoutp, short events, volatile sig_atomic_t *stop)
273 {
274 	struct pollfd pfd;
275 	struct timespec timeout;
276 	int oerrno, r;
277 	sigset_t nsigset, osigset;
278 
279 	if (timeoutp && *timeoutp == -1)
280 		timeoutp = NULL;
281 	pfd.fd = fd;
282 	pfd.events = events;
283 	ptimeout_init(&timeout);
284 	if (timeoutp != NULL)
285 		ptimeout_deadline_ms(&timeout, *timeoutp);
286 	if (stop != NULL)
287 		sigfillset(&nsigset);
288 	for (; timeoutp == NULL || *timeoutp >= 0;) {
289 		if (stop != NULL) {
290 			sigprocmask(SIG_BLOCK, &nsigset, &osigset);
291 			if (*stop) {
292 				sigprocmask(SIG_SETMASK, &osigset, NULL);
293 				errno = EINTR;
294 				return -1;
295 			}
296 		}
297 		r = ppoll(&pfd, 1, ptimeout_get_tsp(&timeout),
298 		    stop != NULL ? &osigset : NULL);
299 		oerrno = errno;
300 		if (stop != NULL)
301 			sigprocmask(SIG_SETMASK, &osigset, NULL);
302 		if (timeoutp)
303 			*timeoutp = ptimeout_get_ms(&timeout);
304 		errno = oerrno;
305 		if (r > 0)
306 			return 0;
307 		else if (r == -1 && errno != EAGAIN && errno != EINTR)
308 			return -1;
309 		else if (r == 0)
310 			break;
311 	}
312 	/* timeout */
313 	errno = ETIMEDOUT;
314 	return -1;
315 }
316 
317 /*
318  * Wait up to *timeoutp milliseconds for fd to be readable. Updates
319  * *timeoutp with time remaining.
320  * Returns 0 if fd ready or -1 on timeout or error (see errno).
321  */
322 int
323 waitrfd(int fd, int *timeoutp, volatile sig_atomic_t *stop) {
324 	return waitfd(fd, timeoutp, POLLIN, stop);
325 }
326 
327 /*
328  * Attempt a non-blocking connect(2) to the specified address, waiting up to
329  * *timeoutp milliseconds for the connection to complete. If the timeout is
330  * <=0, then wait indefinitely.
331  *
332  * Returns 0 on success or -1 on failure.
333  */
334 int
335 timeout_connect(int sockfd, const struct sockaddr *serv_addr,
336     socklen_t addrlen, int *timeoutp)
337 {
338 	int optval = 0;
339 	socklen_t optlen = sizeof(optval);
340 
341 	/* No timeout: just do a blocking connect() */
342 	if (timeoutp == NULL || *timeoutp <= 0)
343 		return connect(sockfd, serv_addr, addrlen);
344 
345 	set_nonblock(sockfd);
346 	for (;;) {
347 		if (connect(sockfd, serv_addr, addrlen) == 0) {
348 			/* Succeeded already? */
349 			unset_nonblock(sockfd);
350 			return 0;
351 		} else if (errno == EINTR)
352 			continue;
353 		else if (errno != EINPROGRESS)
354 			return -1;
355 		break;
356 	}
357 
358 	if (waitfd(sockfd, timeoutp, POLLIN | POLLOUT, NULL) == -1)
359 		return -1;
360 
361 	/* Completed or failed */
362 	if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval, &optlen) == -1) {
363 		debug("getsockopt: %s", strerror(errno));
364 		return -1;
365 	}
366 	if (optval != 0) {
367 		errno = optval;
368 		return -1;
369 	}
370 	unset_nonblock(sockfd);
371 	return 0;
372 }
373 
374 /* Characters considered whitespace in strsep calls. */
375 #define WHITESPACE " \t\r\n"
376 #define QUOTE	"\""
377 
378 /* return next token in configuration line */
379 static char *
380 strdelim_internal(char **s, int split_equals)
381 {
382 	char *old;
383 	int wspace = 0;
384 
385 	if (*s == NULL)
386 		return NULL;
387 
388 	old = *s;
389 
390 	*s = strpbrk(*s,
391 	    split_equals ? WHITESPACE QUOTE "=" : WHITESPACE QUOTE);
392 	if (*s == NULL)
393 		return (old);
394 
395 	if (*s[0] == '\"') {
396 		memmove(*s, *s + 1, strlen(*s)); /* move nul too */
397 		/* Find matching quote */
398 		if ((*s = strpbrk(*s, QUOTE)) == NULL) {
399 			return (NULL);		/* no matching quote */
400 		} else {
401 			*s[0] = '\0';
402 			*s += strspn(*s + 1, WHITESPACE) + 1;
403 			return (old);
404 		}
405 	}
406 
407 	/* Allow only one '=' to be skipped */
408 	if (split_equals && *s[0] == '=')
409 		wspace = 1;
410 	*s[0] = '\0';
411 
412 	/* Skip any extra whitespace after first token */
413 	*s += strspn(*s + 1, WHITESPACE) + 1;
414 	if (split_equals && *s[0] == '=' && !wspace)
415 		*s += strspn(*s + 1, WHITESPACE) + 1;
416 
417 	return (old);
418 }
419 
420 /*
421  * Return next token in configuration line; splts on whitespace or a
422  * single '=' character.
423  */
424 char *
425 strdelim(char **s)
426 {
427 	return strdelim_internal(s, 1);
428 }
429 
430 /*
431  * Return next token in configuration line; splts on whitespace only.
432  */
433 char *
434 strdelimw(char **s)
435 {
436 	return strdelim_internal(s, 0);
437 }
438 
439 struct passwd *
440 pwcopy(struct passwd *pw)
441 {
442 	struct passwd *copy = xcalloc(1, sizeof(*copy));
443 
444 	copy->pw_name = xstrdup(pw->pw_name);
445 	copy->pw_passwd = xstrdup(pw->pw_passwd);
446 	copy->pw_gecos = xstrdup(pw->pw_gecos);
447 	copy->pw_uid = pw->pw_uid;
448 	copy->pw_gid = pw->pw_gid;
449 	copy->pw_expire = pw->pw_expire;
450 	copy->pw_change = pw->pw_change;
451 	copy->pw_class = xstrdup(pw->pw_class);
452 	copy->pw_dir = xstrdup(pw->pw_dir);
453 	copy->pw_shell = xstrdup(pw->pw_shell);
454 	return copy;
455 }
456 
457 /*
458  * Convert ASCII string to TCP/IP port number.
459  * Port must be >=0 and <=65535.
460  * Return -1 if invalid.
461  */
462 int
463 a2port(const char *s)
464 {
465 	struct servent *se;
466 	long long port;
467 	const char *errstr;
468 
469 	port = strtonum(s, 0, 65535, &errstr);
470 	if (errstr == NULL)
471 		return (int)port;
472 	if ((se = getservbyname(s, "tcp")) != NULL)
473 		return ntohs(se->s_port);
474 	return -1;
475 }
476 
477 int
478 a2tun(const char *s, int *remote)
479 {
480 	const char *errstr = NULL;
481 	char *sp, *ep;
482 	int tun;
483 
484 	if (remote != NULL) {
485 		*remote = SSH_TUNID_ANY;
486 		sp = xstrdup(s);
487 		if ((ep = strchr(sp, ':')) == NULL) {
488 			free(sp);
489 			return (a2tun(s, NULL));
490 		}
491 		ep[0] = '\0'; ep++;
492 		*remote = a2tun(ep, NULL);
493 		tun = a2tun(sp, NULL);
494 		free(sp);
495 		return (*remote == SSH_TUNID_ERR ? *remote : tun);
496 	}
497 
498 	if (strcasecmp(s, "any") == 0)
499 		return (SSH_TUNID_ANY);
500 
501 	tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
502 	if (errstr != NULL)
503 		return (SSH_TUNID_ERR);
504 
505 	return (tun);
506 }
507 
508 #define SECONDS		1
509 #define MINUTES		(SECONDS * 60)
510 #define HOURS		(MINUTES * 60)
511 #define DAYS		(HOURS * 24)
512 #define WEEKS		(DAYS * 7)
513 
514 /*
515  * Convert a time string into seconds; format is
516  * a sequence of:
517  *      time[qualifier]
518  *
519  * Valid time qualifiers are:
520  *      <none>  seconds
521  *      s|S     seconds
522  *      m|M     minutes
523  *      h|H     hours
524  *      d|D     days
525  *      w|W     weeks
526  *
527  * Examples:
528  *      90m     90 minutes
529  *      1h30m   90 minutes
530  *      2d      2 days
531  *      1w      1 week
532  *
533  * Return -1 if time string is invalid.
534  */
535 int
536 convtime(const char *s)
537 {
538 	long total, secs, multiplier;
539 	const char *p;
540 	char *endp;
541 
542 	errno = 0;
543 	total = 0;
544 	p = s;
545 
546 	if (p == NULL || *p == '\0')
547 		return -1;
548 
549 	while (*p) {
550 		secs = strtol(p, &endp, 10);
551 		if (p == endp ||
552 		    (errno == ERANGE && (secs == INT_MIN || secs == INT_MAX)) ||
553 		    secs < 0)
554 			return -1;
555 
556 		multiplier = 1;
557 		switch (*endp++) {
558 		case '\0':
559 			endp--;
560 			break;
561 		case 's':
562 		case 'S':
563 			break;
564 		case 'm':
565 		case 'M':
566 			multiplier = MINUTES;
567 			break;
568 		case 'h':
569 		case 'H':
570 			multiplier = HOURS;
571 			break;
572 		case 'd':
573 		case 'D':
574 			multiplier = DAYS;
575 			break;
576 		case 'w':
577 		case 'W':
578 			multiplier = WEEKS;
579 			break;
580 		default:
581 			return -1;
582 		}
583 		if (secs > INT_MAX / multiplier)
584 			return -1;
585 		secs *= multiplier;
586 		if  (total > INT_MAX - secs)
587 			return -1;
588 		total += secs;
589 		if (total < 0)
590 			return -1;
591 		p = endp;
592 	}
593 
594 	return total;
595 }
596 
597 #define TF_BUFS	8
598 #define TF_LEN	9
599 
600 const char *
601 fmt_timeframe(time_t t)
602 {
603 	char		*buf;
604 	static char	 tfbuf[TF_BUFS][TF_LEN];	/* ring buffer */
605 	static int	 idx = 0;
606 	unsigned int	 sec, min, hrs, day;
607 	unsigned long long	week;
608 
609 	buf = tfbuf[idx++];
610 	if (idx == TF_BUFS)
611 		idx = 0;
612 
613 	week = t;
614 
615 	sec = week % 60;
616 	week /= 60;
617 	min = week % 60;
618 	week /= 60;
619 	hrs = week % 24;
620 	week /= 24;
621 	day = week % 7;
622 	week /= 7;
623 
624 	if (week > 0)
625 		snprintf(buf, TF_LEN, "%02lluw%01ud%02uh", week, day, hrs);
626 	else if (day > 0)
627 		snprintf(buf, TF_LEN, "%01ud%02uh%02um", day, hrs, min);
628 	else
629 		snprintf(buf, TF_LEN, "%02u:%02u:%02u", hrs, min, sec);
630 
631 	return (buf);
632 }
633 
634 /*
635  * Returns a standardized host+port identifier string.
636  * Caller must free returned string.
637  */
638 char *
639 put_host_port(const char *host, u_short port)
640 {
641 	char *hoststr;
642 
643 	if (port == 0 || port == SSH_DEFAULT_PORT)
644 		return(xstrdup(host));
645 	if (asprintf(&hoststr, "[%s]:%d", host, (int)port) == -1)
646 		fatal("put_host_port: asprintf: %s", strerror(errno));
647 	debug3("put_host_port: %s", hoststr);
648 	return hoststr;
649 }
650 
651 /*
652  * Search for next delimiter between hostnames/addresses and ports.
653  * Argument may be modified (for termination).
654  * Returns *cp if parsing succeeds.
655  * *cp is set to the start of the next field, if one was found.
656  * The delimiter char, if present, is stored in delim.
657  * If this is the last field, *cp is set to NULL.
658  */
659 char *
660 hpdelim2(char **cp, char *delim)
661 {
662 	char *s, *old;
663 
664 	if (cp == NULL || *cp == NULL)
665 		return NULL;
666 
667 	old = s = *cp;
668 	if (*s == '[') {
669 		if ((s = strchr(s, ']')) == NULL)
670 			return NULL;
671 		else
672 			s++;
673 	} else if ((s = strpbrk(s, ":/")) == NULL)
674 		s = *cp + strlen(*cp); /* skip to end (see first case below) */
675 
676 	switch (*s) {
677 	case '\0':
678 		*cp = NULL;	/* no more fields*/
679 		break;
680 
681 	case ':':
682 	case '/':
683 		if (delim != NULL)
684 			*delim = *s;
685 		*s = '\0';	/* terminate */
686 		*cp = s + 1;
687 		break;
688 
689 	default:
690 		return NULL;
691 	}
692 
693 	return old;
694 }
695 
696 /* The common case: only accept colon as delimiter. */
697 char *
698 hpdelim(char **cp)
699 {
700 	char *r, delim = '\0';
701 
702 	r =  hpdelim2(cp, &delim);
703 	if (delim == '/')
704 		return NULL;
705 	return r;
706 }
707 
708 char *
709 cleanhostname(char *host)
710 {
711 	if (*host == '[' && host[strlen(host) - 1] == ']') {
712 		host[strlen(host) - 1] = '\0';
713 		return (host + 1);
714 	} else
715 		return host;
716 }
717 
718 char *
719 colon(char *cp)
720 {
721 	int flag = 0;
722 
723 	if (*cp == ':')		/* Leading colon is part of file name. */
724 		return NULL;
725 	if (*cp == '[')
726 		flag = 1;
727 
728 	for (; *cp; ++cp) {
729 		if (*cp == '@' && *(cp+1) == '[')
730 			flag = 1;
731 		if (*cp == ']' && *(cp+1) == ':' && flag)
732 			return (cp+1);
733 		if (*cp == ':' && !flag)
734 			return (cp);
735 		if (*cp == '/')
736 			return NULL;
737 	}
738 	return NULL;
739 }
740 
741 /*
742  * Parse a [user@]host:[path] string.
743  * Caller must free returned user, host and path.
744  * Any of the pointer return arguments may be NULL (useful for syntax checking).
745  * If user was not specified then *userp will be set to NULL.
746  * If host was not specified then *hostp will be set to NULL.
747  * If path was not specified then *pathp will be set to ".".
748  * Returns 0 on success, -1 on failure.
749  */
750 int
751 parse_user_host_path(const char *s, char **userp, char **hostp, char **pathp)
752 {
753 	char *user = NULL, *host = NULL, *path = NULL;
754 	char *sdup, *tmp;
755 	int ret = -1;
756 
757 	if (userp != NULL)
758 		*userp = NULL;
759 	if (hostp != NULL)
760 		*hostp = NULL;
761 	if (pathp != NULL)
762 		*pathp = NULL;
763 
764 	sdup = xstrdup(s);
765 
766 	/* Check for remote syntax: [user@]host:[path] */
767 	if ((tmp = colon(sdup)) == NULL)
768 		goto out;
769 
770 	/* Extract optional path */
771 	*tmp++ = '\0';
772 	if (*tmp == '\0')
773 		tmp = ".";
774 	path = xstrdup(tmp);
775 
776 	/* Extract optional user and mandatory host */
777 	tmp = strrchr(sdup, '@');
778 	if (tmp != NULL) {
779 		*tmp++ = '\0';
780 		host = xstrdup(cleanhostname(tmp));
781 		if (*sdup != '\0')
782 			user = xstrdup(sdup);
783 	} else {
784 		host = xstrdup(cleanhostname(sdup));
785 		user = NULL;
786 	}
787 
788 	/* Success */
789 	if (userp != NULL) {
790 		*userp = user;
791 		user = NULL;
792 	}
793 	if (hostp != NULL) {
794 		*hostp = host;
795 		host = NULL;
796 	}
797 	if (pathp != NULL) {
798 		*pathp = path;
799 		path = NULL;
800 	}
801 	ret = 0;
802 out:
803 	free(sdup);
804 	free(user);
805 	free(host);
806 	free(path);
807 	return ret;
808 }
809 
810 /*
811  * Parse a [user@]host[:port] string.
812  * Caller must free returned user and host.
813  * Any of the pointer return arguments may be NULL (useful for syntax checking).
814  * If user was not specified then *userp will be set to NULL.
815  * If port was not specified then *portp will be -1.
816  * Returns 0 on success, -1 on failure.
817  */
818 int
819 parse_user_host_port(const char *s, char **userp, char **hostp, int *portp)
820 {
821 	char *sdup, *cp, *tmp;
822 	char *user = NULL, *host = NULL;
823 	int port = -1, ret = -1;
824 
825 	if (userp != NULL)
826 		*userp = NULL;
827 	if (hostp != NULL)
828 		*hostp = NULL;
829 	if (portp != NULL)
830 		*portp = -1;
831 
832 	if ((sdup = tmp = strdup(s)) == NULL)
833 		return -1;
834 	/* Extract optional username */
835 	if ((cp = strrchr(tmp, '@')) != NULL) {
836 		*cp = '\0';
837 		if (*tmp == '\0')
838 			goto out;
839 		if ((user = strdup(tmp)) == NULL)
840 			goto out;
841 		tmp = cp + 1;
842 	}
843 	/* Extract mandatory hostname */
844 	if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0')
845 		goto out;
846 	host = xstrdup(cleanhostname(cp));
847 	/* Convert and verify optional port */
848 	if (tmp != NULL && *tmp != '\0') {
849 		if ((port = a2port(tmp)) <= 0)
850 			goto out;
851 	}
852 	/* Success */
853 	if (userp != NULL) {
854 		*userp = user;
855 		user = NULL;
856 	}
857 	if (hostp != NULL) {
858 		*hostp = host;
859 		host = NULL;
860 	}
861 	if (portp != NULL)
862 		*portp = port;
863 	ret = 0;
864  out:
865 	free(sdup);
866 	free(user);
867 	free(host);
868 	return ret;
869 }
870 
871 /*
872  * Converts a two-byte hex string to decimal.
873  * Returns the decimal value or -1 for invalid input.
874  */
875 static int
876 hexchar(const char *s)
877 {
878 	unsigned char result[2];
879 	int i;
880 
881 	for (i = 0; i < 2; i++) {
882 		if (s[i] >= '0' && s[i] <= '9')
883 			result[i] = (unsigned char)(s[i] - '0');
884 		else if (s[i] >= 'a' && s[i] <= 'f')
885 			result[i] = (unsigned char)(s[i] - 'a') + 10;
886 		else if (s[i] >= 'A' && s[i] <= 'F')
887 			result[i] = (unsigned char)(s[i] - 'A') + 10;
888 		else
889 			return -1;
890 	}
891 	return (result[0] << 4) | result[1];
892 }
893 
894 /*
895  * Decode an url-encoded string.
896  * Returns a newly allocated string on success or NULL on failure.
897  */
898 static char *
899 urldecode(const char *src)
900 {
901 	char *ret, *dst;
902 	int ch;
903 	size_t srclen;
904 
905 	if ((srclen = strlen(src)) >= SIZE_MAX)
906 		fatal_f("input too large");
907 	ret = xmalloc(srclen + 1);
908 	for (dst = ret; *src != '\0'; src++) {
909 		switch (*src) {
910 		case '+':
911 			*dst++ = ' ';
912 			break;
913 		case '%':
914 			if (!isxdigit((unsigned char)src[1]) ||
915 			    !isxdigit((unsigned char)src[2]) ||
916 			    (ch = hexchar(src + 1)) == -1) {
917 				free(ret);
918 				return NULL;
919 			}
920 			*dst++ = ch;
921 			src += 2;
922 			break;
923 		default:
924 			*dst++ = *src;
925 			break;
926 		}
927 	}
928 	*dst = '\0';
929 
930 	return ret;
931 }
932 
933 /*
934  * Parse an (scp|ssh|sftp)://[user@]host[:port][/path] URI.
935  * See https://tools.ietf.org/html/draft-ietf-secsh-scp-sftp-ssh-uri-04
936  * Either user or path may be url-encoded (but not host or port).
937  * Caller must free returned user, host and path.
938  * Any of the pointer return arguments may be NULL (useful for syntax checking)
939  * but the scheme must always be specified.
940  * If user was not specified then *userp will be set to NULL.
941  * If port was not specified then *portp will be -1.
942  * If path was not specified then *pathp will be set to NULL.
943  * Returns 0 on success, 1 if non-uri/wrong scheme, -1 on error/invalid uri.
944  */
945 int
946 parse_uri(const char *scheme, const char *uri, char **userp, char **hostp,
947     int *portp, char **pathp)
948 {
949 	char *uridup, *cp, *tmp, ch;
950 	char *user = NULL, *host = NULL, *path = NULL;
951 	int port = -1, ret = -1;
952 	size_t len;
953 
954 	len = strlen(scheme);
955 	if (strncmp(uri, scheme, len) != 0 || strncmp(uri + len, "://", 3) != 0)
956 		return 1;
957 	uri += len + 3;
958 
959 	if (userp != NULL)
960 		*userp = NULL;
961 	if (hostp != NULL)
962 		*hostp = NULL;
963 	if (portp != NULL)
964 		*portp = -1;
965 	if (pathp != NULL)
966 		*pathp = NULL;
967 
968 	uridup = tmp = xstrdup(uri);
969 
970 	/* Extract optional ssh-info (username + connection params) */
971 	if ((cp = strchr(tmp, '@')) != NULL) {
972 		char *delim;
973 
974 		*cp = '\0';
975 		/* Extract username and connection params */
976 		if ((delim = strchr(tmp, ';')) != NULL) {
977 			/* Just ignore connection params for now */
978 			*delim = '\0';
979 		}
980 		if (*tmp == '\0') {
981 			/* Empty username */
982 			goto out;
983 		}
984 		if ((user = urldecode(tmp)) == NULL)
985 			goto out;
986 		tmp = cp + 1;
987 	}
988 
989 	/* Extract mandatory hostname */
990 	if ((cp = hpdelim2(&tmp, &ch)) == NULL || *cp == '\0')
991 		goto out;
992 	host = xstrdup(cleanhostname(cp));
993 	if (!valid_domain(host, 0, NULL))
994 		goto out;
995 
996 	if (tmp != NULL && *tmp != '\0') {
997 		if (ch == ':') {
998 			/* Convert and verify port. */
999 			if ((cp = strchr(tmp, '/')) != NULL)
1000 				*cp = '\0';
1001 			if ((port = a2port(tmp)) <= 0)
1002 				goto out;
1003 			tmp = cp ? cp + 1 : NULL;
1004 		}
1005 		if (tmp != NULL && *tmp != '\0') {
1006 			/* Extract optional path */
1007 			if ((path = urldecode(tmp)) == NULL)
1008 				goto out;
1009 		}
1010 	}
1011 
1012 	/* Success */
1013 	if (userp != NULL) {
1014 		*userp = user;
1015 		user = NULL;
1016 	}
1017 	if (hostp != NULL) {
1018 		*hostp = host;
1019 		host = NULL;
1020 	}
1021 	if (portp != NULL)
1022 		*portp = port;
1023 	if (pathp != NULL) {
1024 		*pathp = path;
1025 		path = NULL;
1026 	}
1027 	ret = 0;
1028  out:
1029 	free(uridup);
1030 	free(user);
1031 	free(host);
1032 	free(path);
1033 	return ret;
1034 }
1035 
1036 /* function to assist building execv() arguments */
1037 void
1038 addargs(arglist *args, char *fmt, ...)
1039 {
1040 	va_list ap;
1041 	char *cp;
1042 	u_int nalloc;
1043 	int r;
1044 
1045 	va_start(ap, fmt);
1046 	r = vasprintf(&cp, fmt, ap);
1047 	va_end(ap);
1048 	if (r == -1)
1049 		fatal_f("argument too long");
1050 
1051 	nalloc = args->nalloc;
1052 	if (args->list == NULL) {
1053 		nalloc = 32;
1054 		args->num = 0;
1055 	} else if (args->num > (256 * 1024))
1056 		fatal_f("too many arguments");
1057 	else if (args->num >= args->nalloc)
1058 		fatal_f("arglist corrupt");
1059 	else if (args->num+2 >= nalloc)
1060 		nalloc *= 2;
1061 
1062 	args->list = xrecallocarray(args->list, args->nalloc,
1063 	    nalloc, sizeof(char *));
1064 	args->nalloc = nalloc;
1065 	args->list[args->num++] = cp;
1066 	args->list[args->num] = NULL;
1067 }
1068 
1069 void
1070 replacearg(arglist *args, u_int which, char *fmt, ...)
1071 {
1072 	va_list ap;
1073 	char *cp;
1074 	int r;
1075 
1076 	va_start(ap, fmt);
1077 	r = vasprintf(&cp, fmt, ap);
1078 	va_end(ap);
1079 	if (r == -1)
1080 		fatal_f("argument too long");
1081 	if (args->list == NULL || args->num >= args->nalloc)
1082 		fatal_f("arglist corrupt");
1083 
1084 	if (which >= args->num)
1085 		fatal_f("tried to replace invalid arg %d >= %d",
1086 		    which, args->num);
1087 	free(args->list[which]);
1088 	args->list[which] = cp;
1089 }
1090 
1091 void
1092 freeargs(arglist *args)
1093 {
1094 	u_int i;
1095 
1096 	if (args == NULL)
1097 		return;
1098 	if (args->list != NULL && args->num < args->nalloc) {
1099 		for (i = 0; i < args->num; i++)
1100 			free(args->list[i]);
1101 		free(args->list);
1102 	}
1103 	args->nalloc = args->num = 0;
1104 	args->list = NULL;
1105 }
1106 
1107 /*
1108  * Expands tildes in the file name.  Returns data allocated by xmalloc.
1109  * Warning: this calls getpw*.
1110  */
1111 int
1112 tilde_expand(const char *filename, uid_t uid, char **retp)
1113 {
1114 	char *ocopy = NULL, *copy, *s = NULL;
1115 	const char *path = NULL, *user = NULL;
1116 	struct passwd *pw;
1117 	size_t len;
1118 	int ret = -1, r, slash;
1119 
1120 	*retp = NULL;
1121 	if (*filename != '~') {
1122 		*retp = xstrdup(filename);
1123 		return 0;
1124 	}
1125 	ocopy = copy = xstrdup(filename + 1);
1126 
1127 	if (*copy == '\0')				/* ~ */
1128 		path = NULL;
1129 	else if (*copy == '/') {
1130 		copy += strspn(copy, "/");
1131 		if (*copy == '\0')
1132 			path = NULL;			/* ~/ */
1133 		else
1134 			path = copy;			/* ~/path */
1135 	} else {
1136 		user = copy;
1137 		if ((path = strchr(copy, '/')) != NULL) {
1138 			copy[path - copy] = '\0';
1139 			path++;
1140 			path += strspn(path, "/");
1141 			if (*path == '\0')		/* ~user/ */
1142 				path = NULL;
1143 			/* else				 ~user/path */
1144 		}
1145 		/* else					~user */
1146 	}
1147 	if (user != NULL) {
1148 		if ((pw = getpwnam(user)) == NULL) {
1149 			error_f("No such user %s", user);
1150 			goto out;
1151 		}
1152 	} else if ((pw = getpwuid(uid)) == NULL) {
1153 		error_f("No such uid %ld", (long)uid);
1154 		goto out;
1155 	}
1156 
1157 	/* Make sure directory has a trailing '/' */
1158 	slash = (len = strlen(pw->pw_dir)) == 0 || pw->pw_dir[len - 1] != '/';
1159 
1160 	if ((r = xasprintf(&s, "%s%s%s", pw->pw_dir,
1161 	    slash ? "/" : "", path != NULL ? path : "")) <= 0) {
1162 		error_f("xasprintf failed");
1163 		goto out;
1164 	}
1165 	if (r >= PATH_MAX) {
1166 		error_f("Path too long");
1167 		goto out;
1168 	}
1169 	/* success */
1170 	ret = 0;
1171 	*retp = s;
1172 	s = NULL;
1173  out:
1174 	free(s);
1175 	free(ocopy);
1176 	return ret;
1177 }
1178 
1179 char *
1180 tilde_expand_filename(const char *filename, uid_t uid)
1181 {
1182 	char *ret;
1183 
1184 	if (tilde_expand(filename, uid, &ret) != 0)
1185 		cleanup_exit(255);
1186 	return ret;
1187 }
1188 
1189 /*
1190  * Expand a string with a set of %[char] escapes and/or ${ENVIRONMENT}
1191  * substitutions.  A number of escapes may be specified as
1192  * (char *escape_chars, char *replacement) pairs. The list must be terminated
1193  * by a NULL escape_char. Returns replaced string in memory allocated by
1194  * xmalloc which the caller must free.
1195  */
1196 static char *
1197 vdollar_percent_expand(int *parseerror, int dollar, int percent,
1198     const char *string, va_list ap)
1199 {
1200 #define EXPAND_MAX_KEYS	64
1201 	u_int num_keys = 0, i;
1202 	struct {
1203 		const char *key;
1204 		const char *repl;
1205 	} keys[EXPAND_MAX_KEYS];
1206 	struct sshbuf *buf;
1207 	int r, missingvar = 0;
1208 	char *ret = NULL, *var, *varend, *val;
1209 	size_t len;
1210 
1211 	if ((buf = sshbuf_new()) == NULL)
1212 		fatal_f("sshbuf_new failed");
1213 	if (parseerror == NULL)
1214 		fatal_f("null parseerror arg");
1215 	*parseerror = 1;
1216 
1217 	/* Gather keys if we're doing percent expansion. */
1218 	if (percent) {
1219 		for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
1220 			keys[num_keys].key = va_arg(ap, char *);
1221 			if (keys[num_keys].key == NULL)
1222 				break;
1223 			keys[num_keys].repl = va_arg(ap, char *);
1224 			if (keys[num_keys].repl == NULL) {
1225 				fatal_f("NULL replacement for token %s",
1226 				    keys[num_keys].key);
1227 			}
1228 		}
1229 		if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
1230 			fatal_f("too many keys");
1231 		if (num_keys == 0)
1232 			fatal_f("percent expansion without token list");
1233 	}
1234 
1235 	/* Expand string */
1236 	for (i = 0; *string != '\0'; string++) {
1237 		/* Optionally process ${ENVIRONMENT} expansions. */
1238 		if (dollar && string[0] == '$' && string[1] == '{') {
1239 			string += 2;  /* skip over '${' */
1240 			if ((varend = strchr(string, '}')) == NULL) {
1241 				error_f("environment variable '%s' missing "
1242 				    "closing '}'", string);
1243 				goto out;
1244 			}
1245 			len = varend - string;
1246 			if (len == 0) {
1247 				error_f("zero-length environment variable");
1248 				goto out;
1249 			}
1250 			var = xmalloc(len + 1);
1251 			(void)strlcpy(var, string, len + 1);
1252 			if ((val = getenv(var)) == NULL) {
1253 				error_f("env var ${%s} has no value", var);
1254 				missingvar = 1;
1255 			} else {
1256 				debug3_f("expand ${%s} -> '%s'", var, val);
1257 				if ((r = sshbuf_put(buf, val, strlen(val))) !=0)
1258 					fatal_fr(r, "sshbuf_put ${}");
1259 			}
1260 			free(var);
1261 			string += len;
1262 			continue;
1263 		}
1264 
1265 		/*
1266 		 * Process percent expansions if we have a list of TOKENs.
1267 		 * If we're not doing percent expansion everything just gets
1268 		 * appended here.
1269 		 */
1270 		if (*string != '%' || !percent) {
1271  append:
1272 			if ((r = sshbuf_put_u8(buf, *string)) != 0)
1273 				fatal_fr(r, "sshbuf_put_u8 %%");
1274 			continue;
1275 		}
1276 		string++;
1277 		/* %% case */
1278 		if (*string == '%')
1279 			goto append;
1280 		if (*string == '\0') {
1281 			error_f("invalid format");
1282 			goto out;
1283 		}
1284 		for (i = 0; i < num_keys; i++) {
1285 			if (strchr(keys[i].key, *string) != NULL) {
1286 				if ((r = sshbuf_put(buf, keys[i].repl,
1287 				    strlen(keys[i].repl))) != 0)
1288 					fatal_fr(r, "sshbuf_put %%-repl");
1289 				break;
1290 			}
1291 		}
1292 		if (i >= num_keys) {
1293 			error_f("unknown key %%%c", *string);
1294 			goto out;
1295 		}
1296 	}
1297 	if (!missingvar && (ret = sshbuf_dup_string(buf)) == NULL)
1298 		fatal_f("sshbuf_dup_string failed");
1299 	*parseerror = 0;
1300  out:
1301 	sshbuf_free(buf);
1302 	return *parseerror ? NULL : ret;
1303 #undef EXPAND_MAX_KEYS
1304 }
1305 
1306 /*
1307  * Expand only environment variables.
1308  * Note that although this function is variadic like the other similar
1309  * functions, any such arguments will be unused.
1310  */
1311 
1312 char *
1313 dollar_expand(int *parseerr, const char *string, ...)
1314 {
1315 	char *ret;
1316 	int err;
1317 	va_list ap;
1318 
1319 	va_start(ap, string);
1320 	ret = vdollar_percent_expand(&err, 1, 0, string, ap);
1321 	va_end(ap);
1322 	if (parseerr != NULL)
1323 		*parseerr = err;
1324 	return ret;
1325 }
1326 
1327 /*
1328  * Returns expanded string or NULL if a specified environment variable is
1329  * not defined, or calls fatal if the string is invalid.
1330  */
1331 char *
1332 percent_expand(const char *string, ...)
1333 {
1334 	char *ret;
1335 	int err;
1336 	va_list ap;
1337 
1338 	va_start(ap, string);
1339 	ret = vdollar_percent_expand(&err, 0, 1, string, ap);
1340 	va_end(ap);
1341 	if (err)
1342 		fatal_f("failed");
1343 	return ret;
1344 }
1345 
1346 /*
1347  * Returns expanded string or NULL if a specified environment variable is
1348  * not defined, or calls fatal if the string is invalid.
1349  */
1350 char *
1351 percent_dollar_expand(const char *string, ...)
1352 {
1353 	char *ret;
1354 	int err;
1355 	va_list ap;
1356 
1357 	va_start(ap, string);
1358 	ret = vdollar_percent_expand(&err, 1, 1, string, ap);
1359 	va_end(ap);
1360 	if (err)
1361 		fatal_f("failed");
1362 	return ret;
1363 }
1364 
1365 int
1366 tun_open(int tun, int mode, char **ifname)
1367 {
1368 	struct ifreq ifr;
1369 	char name[100];
1370 	int fd = -1, sock;
1371 	const char *tunbase = "tun";
1372 
1373 	if (ifname != NULL)
1374 		*ifname = NULL;
1375 
1376 	if (mode == SSH_TUNMODE_ETHERNET)
1377 		tunbase = "tap";
1378 
1379 	/* Open the tunnel device */
1380 	if (tun <= SSH_TUNID_MAX) {
1381 		snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
1382 		fd = open(name, O_RDWR);
1383 	} else if (tun == SSH_TUNID_ANY) {
1384 		for (tun = 100; tun >= 0; tun--) {
1385 			snprintf(name, sizeof(name), "/dev/%s%d",
1386 			    tunbase, tun);
1387 			if ((fd = open(name, O_RDWR)) >= 0)
1388 				break;
1389 		}
1390 	} else {
1391 		debug_f("invalid tunnel %u", tun);
1392 		return -1;
1393 	}
1394 
1395 	if (fd == -1) {
1396 		debug_f("%s open: %s", name, strerror(errno));
1397 		return -1;
1398 	}
1399 
1400 	debug_f("%s mode %d fd %d", name, mode, fd);
1401 
1402 	/* Bring interface up if it is not already */
1403 	snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
1404 	if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
1405 		goto failed;
1406 
1407 	if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
1408 		debug_f("get interface %s flags: %s", ifr.ifr_name,
1409 		    strerror(errno));
1410 		goto failed;
1411 	}
1412 
1413 	if (!(ifr.ifr_flags & IFF_UP)) {
1414 		ifr.ifr_flags |= IFF_UP;
1415 		if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
1416 			debug_f("activate interface %s: %s", ifr.ifr_name,
1417 			    strerror(errno));
1418 			goto failed;
1419 		}
1420 	}
1421 
1422 	if (ifname != NULL)
1423 		*ifname = xstrdup(ifr.ifr_name);
1424 
1425 	close(sock);
1426 	return fd;
1427 
1428  failed:
1429 	if (fd >= 0)
1430 		close(fd);
1431 	if (sock >= 0)
1432 		close(sock);
1433 	return -1;
1434 }
1435 
1436 void
1437 sanitise_stdfd(void)
1438 {
1439 	int nullfd, dupfd;
1440 
1441 	if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1442 		fprintf(stderr, "Couldn't open /dev/null: %s\n",
1443 		    strerror(errno));
1444 		exit(1);
1445 	}
1446 	while (++dupfd <= STDERR_FILENO) {
1447 		/* Only populate closed fds. */
1448 		if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
1449 			if (dup2(nullfd, dupfd) == -1) {
1450 				fprintf(stderr, "dup2: %s\n", strerror(errno));
1451 				exit(1);
1452 			}
1453 		}
1454 	}
1455 	if (nullfd > STDERR_FILENO)
1456 		close(nullfd);
1457 }
1458 
1459 char *
1460 tohex(const void *vp, size_t l)
1461 {
1462 	const u_char *p = (const u_char *)vp;
1463 	char b[3], *r;
1464 	size_t i, hl;
1465 
1466 	if (l > 65536)
1467 		return xstrdup("tohex: length > 65536");
1468 
1469 	hl = l * 2 + 1;
1470 	r = xcalloc(1, hl);
1471 	for (i = 0; i < l; i++) {
1472 		snprintf(b, sizeof(b), "%02x", p[i]);
1473 		strlcat(r, b, hl);
1474 	}
1475 	return (r);
1476 }
1477 
1478 /*
1479  * Extend string *sp by the specified format. If *sp is not NULL (or empty),
1480  * then the separator 'sep' will be prepended before the formatted arguments.
1481  * Extended strings are heap allocated.
1482  */
1483 void
1484 xextendf(char **sp, const char *sep, const char *fmt, ...)
1485 {
1486 	va_list ap;
1487 	char *tmp1, *tmp2;
1488 
1489 	va_start(ap, fmt);
1490 	xvasprintf(&tmp1, fmt, ap);
1491 	va_end(ap);
1492 
1493 	if (*sp == NULL || **sp == '\0') {
1494 		free(*sp);
1495 		*sp = tmp1;
1496 		return;
1497 	}
1498 	xasprintf(&tmp2, "%s%s%s", *sp, sep == NULL ? "" : sep, tmp1);
1499 	free(tmp1);
1500 	free(*sp);
1501 	*sp = tmp2;
1502 }
1503 
1504 
1505 u_int64_t
1506 get_u64(const void *vp)
1507 {
1508 	const u_char *p = (const u_char *)vp;
1509 	u_int64_t v;
1510 
1511 	v  = (u_int64_t)p[0] << 56;
1512 	v |= (u_int64_t)p[1] << 48;
1513 	v |= (u_int64_t)p[2] << 40;
1514 	v |= (u_int64_t)p[3] << 32;
1515 	v |= (u_int64_t)p[4] << 24;
1516 	v |= (u_int64_t)p[5] << 16;
1517 	v |= (u_int64_t)p[6] << 8;
1518 	v |= (u_int64_t)p[7];
1519 
1520 	return (v);
1521 }
1522 
1523 u_int32_t
1524 get_u32(const void *vp)
1525 {
1526 	const u_char *p = (const u_char *)vp;
1527 	u_int32_t v;
1528 
1529 	v  = (u_int32_t)p[0] << 24;
1530 	v |= (u_int32_t)p[1] << 16;
1531 	v |= (u_int32_t)p[2] << 8;
1532 	v |= (u_int32_t)p[3];
1533 
1534 	return (v);
1535 }
1536 
1537 u_int32_t
1538 get_u32_le(const void *vp)
1539 {
1540 	const u_char *p = (const u_char *)vp;
1541 	u_int32_t v;
1542 
1543 	v  = (u_int32_t)p[0];
1544 	v |= (u_int32_t)p[1] << 8;
1545 	v |= (u_int32_t)p[2] << 16;
1546 	v |= (u_int32_t)p[3] << 24;
1547 
1548 	return (v);
1549 }
1550 
1551 u_int16_t
1552 get_u16(const void *vp)
1553 {
1554 	const u_char *p = (const u_char *)vp;
1555 	u_int16_t v;
1556 
1557 	v  = (u_int16_t)p[0] << 8;
1558 	v |= (u_int16_t)p[1];
1559 
1560 	return (v);
1561 }
1562 
1563 void
1564 put_u64(void *vp, u_int64_t v)
1565 {
1566 	u_char *p = (u_char *)vp;
1567 
1568 	p[0] = (u_char)(v >> 56) & 0xff;
1569 	p[1] = (u_char)(v >> 48) & 0xff;
1570 	p[2] = (u_char)(v >> 40) & 0xff;
1571 	p[3] = (u_char)(v >> 32) & 0xff;
1572 	p[4] = (u_char)(v >> 24) & 0xff;
1573 	p[5] = (u_char)(v >> 16) & 0xff;
1574 	p[6] = (u_char)(v >> 8) & 0xff;
1575 	p[7] = (u_char)v & 0xff;
1576 }
1577 
1578 void
1579 put_u32(void *vp, u_int32_t v)
1580 {
1581 	u_char *p = (u_char *)vp;
1582 
1583 	p[0] = (u_char)(v >> 24) & 0xff;
1584 	p[1] = (u_char)(v >> 16) & 0xff;
1585 	p[2] = (u_char)(v >> 8) & 0xff;
1586 	p[3] = (u_char)v & 0xff;
1587 }
1588 
1589 void
1590 put_u32_le(void *vp, u_int32_t v)
1591 {
1592 	u_char *p = (u_char *)vp;
1593 
1594 	p[0] = (u_char)v & 0xff;
1595 	p[1] = (u_char)(v >> 8) & 0xff;
1596 	p[2] = (u_char)(v >> 16) & 0xff;
1597 	p[3] = (u_char)(v >> 24) & 0xff;
1598 }
1599 
1600 void
1601 put_u16(void *vp, u_int16_t v)
1602 {
1603 	u_char *p = (u_char *)vp;
1604 
1605 	p[0] = (u_char)(v >> 8) & 0xff;
1606 	p[1] = (u_char)v & 0xff;
1607 }
1608 
1609 void
1610 ms_subtract_diff(struct timeval *start, int *ms)
1611 {
1612 	struct timeval diff, finish;
1613 
1614 	monotime_tv(&finish);
1615 	timersub(&finish, start, &diff);
1616 	*ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
1617 }
1618 
1619 void
1620 ms_to_timespec(struct timespec *ts, int ms)
1621 {
1622 	if (ms < 0)
1623 		ms = 0;
1624 	ts->tv_sec = ms / 1000;
1625 	ts->tv_nsec = (ms % 1000) * 1000 * 1000;
1626 }
1627 
1628 void
1629 monotime_ts(struct timespec *ts)
1630 {
1631 	if (clock_gettime(CLOCK_MONOTONIC, ts) != 0)
1632 		fatal("clock_gettime: %s", strerror(errno));
1633 }
1634 
1635 void
1636 monotime_tv(struct timeval *tv)
1637 {
1638 	struct timespec ts;
1639 
1640 	monotime_ts(&ts);
1641 	tv->tv_sec = ts.tv_sec;
1642 	tv->tv_usec = ts.tv_nsec / 1000;
1643 }
1644 
1645 time_t
1646 monotime(void)
1647 {
1648 	struct timespec ts;
1649 
1650 	monotime_ts(&ts);
1651 	return (ts.tv_sec);
1652 }
1653 
1654 double
1655 monotime_double(void)
1656 {
1657 	struct timespec ts;
1658 
1659 	monotime_ts(&ts);
1660 	return (double)ts.tv_sec + (double)ts.tv_nsec / 1000000000.0;
1661 }
1662 
1663 void
1664 bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
1665 {
1666 	bw->buflen = buflen;
1667 	bw->rate = kbps;
1668 	bw->thresh = buflen;
1669 	bw->lamt = 0;
1670 	timerclear(&bw->bwstart);
1671 	timerclear(&bw->bwend);
1672 }
1673 
1674 /* Callback from read/write loop to insert bandwidth-limiting delays */
1675 void
1676 bandwidth_limit(struct bwlimit *bw, size_t read_len)
1677 {
1678 	u_int64_t waitlen;
1679 	struct timespec ts, rm;
1680 
1681 	bw->lamt += read_len;
1682 	if (!timerisset(&bw->bwstart)) {
1683 		monotime_tv(&bw->bwstart);
1684 		return;
1685 	}
1686 	if (bw->lamt < bw->thresh)
1687 		return;
1688 
1689 	monotime_tv(&bw->bwend);
1690 	timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
1691 	if (!timerisset(&bw->bwend))
1692 		return;
1693 
1694 	bw->lamt *= 8;
1695 	waitlen = (double)1000000L * bw->lamt / bw->rate;
1696 
1697 	bw->bwstart.tv_sec = waitlen / 1000000L;
1698 	bw->bwstart.tv_usec = waitlen % 1000000L;
1699 
1700 	if (timercmp(&bw->bwstart, &bw->bwend, >)) {
1701 		timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
1702 
1703 		/* Adjust the wait time */
1704 		if (bw->bwend.tv_sec) {
1705 			bw->thresh /= 2;
1706 			if (bw->thresh < bw->buflen / 4)
1707 				bw->thresh = bw->buflen / 4;
1708 		} else if (bw->bwend.tv_usec < 10000) {
1709 			bw->thresh *= 2;
1710 			if (bw->thresh > bw->buflen * 8)
1711 				bw->thresh = bw->buflen * 8;
1712 		}
1713 
1714 		TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
1715 		while (nanosleep(&ts, &rm) == -1) {
1716 			if (errno != EINTR)
1717 				break;
1718 			ts = rm;
1719 		}
1720 	}
1721 
1722 	bw->lamt = 0;
1723 	monotime_tv(&bw->bwstart);
1724 }
1725 
1726 /* Make a template filename for mk[sd]temp() */
1727 void
1728 mktemp_proto(char *s, size_t len)
1729 {
1730 	const char *tmpdir;
1731 	int r;
1732 
1733 	if ((tmpdir = getenv("TMPDIR")) != NULL) {
1734 		r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
1735 		if (r > 0 && (size_t)r < len)
1736 			return;
1737 	}
1738 	r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
1739 	if (r < 0 || (size_t)r >= len)
1740 		fatal_f("template string too short");
1741 }
1742 
1743 static const struct {
1744 	const char *name;
1745 	int value;
1746 } ipqos[] = {
1747 	{ "none", INT_MAX },		/* can't use 0 here; that's CS0 */
1748 	{ "af11", IPTOS_DSCP_AF11 },
1749 	{ "af12", IPTOS_DSCP_AF12 },
1750 	{ "af13", IPTOS_DSCP_AF13 },
1751 	{ "af21", IPTOS_DSCP_AF21 },
1752 	{ "af22", IPTOS_DSCP_AF22 },
1753 	{ "af23", IPTOS_DSCP_AF23 },
1754 	{ "af31", IPTOS_DSCP_AF31 },
1755 	{ "af32", IPTOS_DSCP_AF32 },
1756 	{ "af33", IPTOS_DSCP_AF33 },
1757 	{ "af41", IPTOS_DSCP_AF41 },
1758 	{ "af42", IPTOS_DSCP_AF42 },
1759 	{ "af43", IPTOS_DSCP_AF43 },
1760 	{ "cs0", IPTOS_DSCP_CS0 },
1761 	{ "cs1", IPTOS_DSCP_CS1 },
1762 	{ "cs2", IPTOS_DSCP_CS2 },
1763 	{ "cs3", IPTOS_DSCP_CS3 },
1764 	{ "cs4", IPTOS_DSCP_CS4 },
1765 	{ "cs5", IPTOS_DSCP_CS5 },
1766 	{ "cs6", IPTOS_DSCP_CS6 },
1767 	{ "cs7", IPTOS_DSCP_CS7 },
1768 	{ "ef", IPTOS_DSCP_EF },
1769 	{ "le", IPTOS_DSCP_LE },
1770 	{ "lowdelay", IPTOS_LOWDELAY },
1771 	{ "throughput", IPTOS_THROUGHPUT },
1772 	{ "reliability", IPTOS_RELIABILITY },
1773 	{ NULL, -1 }
1774 };
1775 
1776 int
1777 parse_ipqos(const char *cp)
1778 {
1779 	u_int i;
1780 	char *ep;
1781 	long val;
1782 
1783 	if (cp == NULL)
1784 		return -1;
1785 	for (i = 0; ipqos[i].name != NULL; i++) {
1786 		if (strcasecmp(cp, ipqos[i].name) == 0)
1787 			return ipqos[i].value;
1788 	}
1789 	/* Try parsing as an integer */
1790 	val = strtol(cp, &ep, 0);
1791 	if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1792 		return -1;
1793 	return val;
1794 }
1795 
1796 const char *
1797 iptos2str(int iptos)
1798 {
1799 	int i;
1800 	static char iptos_str[sizeof "0xff"];
1801 
1802 	for (i = 0; ipqos[i].name != NULL; i++) {
1803 		if (ipqos[i].value == iptos)
1804 			return ipqos[i].name;
1805 	}
1806 	snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1807 	return iptos_str;
1808 }
1809 
1810 void
1811 lowercase(char *s)
1812 {
1813 	for (; *s; s++)
1814 		*s = tolower((u_char)*s);
1815 }
1816 
1817 int
1818 unix_listener(const char *path, int backlog, int unlink_first)
1819 {
1820 	struct sockaddr_un sunaddr;
1821 	int saved_errno, sock;
1822 
1823 	memset(&sunaddr, 0, sizeof(sunaddr));
1824 	sunaddr.sun_family = AF_UNIX;
1825 	if (strlcpy(sunaddr.sun_path, path,
1826 	    sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1827 		error_f("path \"%s\" too long for Unix domain socket", path);
1828 		errno = ENAMETOOLONG;
1829 		return -1;
1830 	}
1831 
1832 	sock = socket(PF_UNIX, SOCK_STREAM, 0);
1833 	if (sock == -1) {
1834 		saved_errno = errno;
1835 		error_f("socket: %.100s", strerror(errno));
1836 		errno = saved_errno;
1837 		return -1;
1838 	}
1839 	if (unlink_first == 1) {
1840 		if (unlink(path) != 0 && errno != ENOENT)
1841 			error("unlink(%s): %.100s", path, strerror(errno));
1842 	}
1843 	if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1844 		saved_errno = errno;
1845 		error_f("cannot bind to path %s: %s", path, strerror(errno));
1846 		close(sock);
1847 		errno = saved_errno;
1848 		return -1;
1849 	}
1850 	if (listen(sock, backlog) == -1) {
1851 		saved_errno = errno;
1852 		error_f("cannot listen on path %s: %s", path, strerror(errno));
1853 		close(sock);
1854 		unlink(path);
1855 		errno = saved_errno;
1856 		return -1;
1857 	}
1858 	return sock;
1859 }
1860 
1861 /*
1862  * Compares two strings that maybe be NULL. Returns non-zero if strings
1863  * are both NULL or are identical, returns zero otherwise.
1864  */
1865 static int
1866 strcmp_maybe_null(const char *a, const char *b)
1867 {
1868 	if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1869 		return 0;
1870 	if (a != NULL && strcmp(a, b) != 0)
1871 		return 0;
1872 	return 1;
1873 }
1874 
1875 /*
1876  * Compare two forwards, returning non-zero if they are identical or
1877  * zero otherwise.
1878  */
1879 int
1880 forward_equals(const struct Forward *a, const struct Forward *b)
1881 {
1882 	if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
1883 		return 0;
1884 	if (a->listen_port != b->listen_port)
1885 		return 0;
1886 	if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
1887 		return 0;
1888 	if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
1889 		return 0;
1890 	if (a->connect_port != b->connect_port)
1891 		return 0;
1892 	if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
1893 		return 0;
1894 	/* allocated_port and handle are not checked */
1895 	return 1;
1896 }
1897 
1898 /* returns 1 if process is already daemonized, 0 otherwise */
1899 int
1900 daemonized(void)
1901 {
1902 	int fd;
1903 
1904 	if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
1905 		close(fd);
1906 		return 0;	/* have controlling terminal */
1907 	}
1908 	if (getppid() != 1)
1909 		return 0;	/* parent is not init */
1910 	if (getsid(0) != getpid())
1911 		return 0;	/* not session leader */
1912 	debug3("already daemonized");
1913 	return 1;
1914 }
1915 
1916 /*
1917  * Splits 's' into an argument vector. Handles quoted string and basic
1918  * escape characters (\\, \", \'). Caller must free the argument vector
1919  * and its members.
1920  */
1921 int
1922 argv_split(const char *s, int *argcp, char ***argvp, int terminate_on_comment)
1923 {
1924 	int r = SSH_ERR_INTERNAL_ERROR;
1925 	int argc = 0, quote, i, j;
1926 	char *arg, **argv = xcalloc(1, sizeof(*argv));
1927 
1928 	*argvp = NULL;
1929 	*argcp = 0;
1930 
1931 	for (i = 0; s[i] != '\0'; i++) {
1932 		/* Skip leading whitespace */
1933 		if (s[i] == ' ' || s[i] == '\t')
1934 			continue;
1935 		if (terminate_on_comment && s[i] == '#')
1936 			break;
1937 		/* Start of a token */
1938 		quote = 0;
1939 
1940 		argv = xreallocarray(argv, (argc + 2), sizeof(*argv));
1941 		arg = argv[argc++] = xcalloc(1, strlen(s + i) + 1);
1942 		argv[argc] = NULL;
1943 
1944 		/* Copy the token in, removing escapes */
1945 		for (j = 0; s[i] != '\0'; i++) {
1946 			if (s[i] == '\\') {
1947 				if (s[i + 1] == '\'' ||
1948 				    s[i + 1] == '\"' ||
1949 				    s[i + 1] == '\\' ||
1950 				    (quote == 0 && s[i + 1] == ' ')) {
1951 					i++; /* Skip '\' */
1952 					arg[j++] = s[i];
1953 				} else {
1954 					/* Unrecognised escape */
1955 					arg[j++] = s[i];
1956 				}
1957 			} else if (quote == 0 && (s[i] == ' ' || s[i] == '\t'))
1958 				break; /* done */
1959 			else if (quote == 0 && (s[i] == '\"' || s[i] == '\''))
1960 				quote = s[i]; /* quote start */
1961 			else if (quote != 0 && s[i] == quote)
1962 				quote = 0; /* quote end */
1963 			else
1964 				arg[j++] = s[i];
1965 		}
1966 		if (s[i] == '\0') {
1967 			if (quote != 0) {
1968 				/* Ran out of string looking for close quote */
1969 				r = SSH_ERR_INVALID_FORMAT;
1970 				goto out;
1971 			}
1972 			break;
1973 		}
1974 	}
1975 	/* Success */
1976 	*argcp = argc;
1977 	*argvp = argv;
1978 	argc = 0;
1979 	argv = NULL;
1980 	r = 0;
1981  out:
1982 	if (argc != 0 && argv != NULL) {
1983 		for (i = 0; i < argc; i++)
1984 			free(argv[i]);
1985 		free(argv);
1986 	}
1987 	return r;
1988 }
1989 
1990 /*
1991  * Reassemble an argument vector into a string, quoting and escaping as
1992  * necessary. Caller must free returned string.
1993  */
1994 char *
1995 argv_assemble(int argc, char **argv)
1996 {
1997 	int i, j, ws, r;
1998 	char c, *ret;
1999 	struct sshbuf *buf, *arg;
2000 
2001 	if ((buf = sshbuf_new()) == NULL || (arg = sshbuf_new()) == NULL)
2002 		fatal_f("sshbuf_new failed");
2003 
2004 	for (i = 0; i < argc; i++) {
2005 		ws = 0;
2006 		sshbuf_reset(arg);
2007 		for (j = 0; argv[i][j] != '\0'; j++) {
2008 			r = 0;
2009 			c = argv[i][j];
2010 			switch (c) {
2011 			case ' ':
2012 			case '\t':
2013 				ws = 1;
2014 				r = sshbuf_put_u8(arg, c);
2015 				break;
2016 			case '\\':
2017 			case '\'':
2018 			case '"':
2019 				if ((r = sshbuf_put_u8(arg, '\\')) != 0)
2020 					break;
2021 				/* FALLTHROUGH */
2022 			default:
2023 				r = sshbuf_put_u8(arg, c);
2024 				break;
2025 			}
2026 			if (r != 0)
2027 				fatal_fr(r, "sshbuf_put_u8");
2028 		}
2029 		if ((i != 0 && (r = sshbuf_put_u8(buf, ' ')) != 0) ||
2030 		    (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0) ||
2031 		    (r = sshbuf_putb(buf, arg)) != 0 ||
2032 		    (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0))
2033 			fatal_fr(r, "assemble");
2034 	}
2035 	if ((ret = malloc(sshbuf_len(buf) + 1)) == NULL)
2036 		fatal_f("malloc failed");
2037 	memcpy(ret, sshbuf_ptr(buf), sshbuf_len(buf));
2038 	ret[sshbuf_len(buf)] = '\0';
2039 	sshbuf_free(buf);
2040 	sshbuf_free(arg);
2041 	return ret;
2042 }
2043 
2044 char *
2045 argv_next(int *argcp, char ***argvp)
2046 {
2047 	char *ret = (*argvp)[0];
2048 
2049 	if (*argcp > 0 && ret != NULL) {
2050 		(*argcp)--;
2051 		(*argvp)++;
2052 	}
2053 	return ret;
2054 }
2055 
2056 void
2057 argv_consume(int *argcp)
2058 {
2059 	*argcp = 0;
2060 }
2061 
2062 void
2063 argv_free(char **av, int ac)
2064 {
2065 	int i;
2066 
2067 	if (av == NULL)
2068 		return;
2069 	for (i = 0; i < ac; i++)
2070 		free(av[i]);
2071 	free(av);
2072 }
2073 
2074 /* Returns 0 if pid exited cleanly, non-zero otherwise */
2075 int
2076 exited_cleanly(pid_t pid, const char *tag, const char *cmd, int quiet)
2077 {
2078 	int status;
2079 
2080 	while (waitpid(pid, &status, 0) == -1) {
2081 		if (errno != EINTR) {
2082 			error("%s waitpid: %s", tag, strerror(errno));
2083 			return -1;
2084 		}
2085 	}
2086 	if (WIFSIGNALED(status)) {
2087 		error("%s %s exited on signal %d", tag, cmd, WTERMSIG(status));
2088 		return -1;
2089 	} else if (WEXITSTATUS(status) != 0) {
2090 		do_log2(quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_INFO,
2091 		    "%s %s failed, status %d", tag, cmd, WEXITSTATUS(status));
2092 		return -1;
2093 	}
2094 	return 0;
2095 }
2096 
2097 /*
2098  * Check a given path for security. This is defined as all components
2099  * of the path to the file must be owned by either the owner of
2100  * of the file or root and no directories must be group or world writable.
2101  *
2102  * XXX Should any specific check be done for sym links ?
2103  *
2104  * Takes a file name, its stat information (preferably from fstat() to
2105  * avoid races), the uid of the expected owner, their home directory and an
2106  * error buffer plus max size as arguments.
2107  *
2108  * Returns 0 on success and -1 on failure
2109  */
2110 int
2111 safe_path(const char *name, struct stat *stp, const char *pw_dir,
2112     uid_t uid, char *err, size_t errlen)
2113 {
2114 	char buf[PATH_MAX], homedir[PATH_MAX];
2115 	char *cp;
2116 	int comparehome = 0;
2117 	struct stat st;
2118 
2119 	if (realpath(name, buf) == NULL) {
2120 		snprintf(err, errlen, "realpath %s failed: %s", name,
2121 		    strerror(errno));
2122 		return -1;
2123 	}
2124 	if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL)
2125 		comparehome = 1;
2126 
2127 	if (!S_ISREG(stp->st_mode)) {
2128 		snprintf(err, errlen, "%s is not a regular file", buf);
2129 		return -1;
2130 	}
2131 	if ((stp->st_uid != 0 && stp->st_uid != uid) ||
2132 	    (stp->st_mode & 022) != 0) {
2133 		snprintf(err, errlen, "bad ownership or modes for file %s",
2134 		    buf);
2135 		return -1;
2136 	}
2137 
2138 	/* for each component of the canonical path, walking upwards */
2139 	for (;;) {
2140 		if ((cp = dirname(buf)) == NULL) {
2141 			snprintf(err, errlen, "dirname() failed");
2142 			return -1;
2143 		}
2144 		strlcpy(buf, cp, sizeof(buf));
2145 
2146 		if (stat(buf, &st) == -1 ||
2147 		    (st.st_uid != 0 && st.st_uid != uid) ||
2148 		    (st.st_mode & 022) != 0) {
2149 			snprintf(err, errlen,
2150 			    "bad ownership or modes for directory %s", buf);
2151 			return -1;
2152 		}
2153 
2154 		/* If are past the homedir then we can stop */
2155 		if (comparehome && strcmp(homedir, buf) == 0)
2156 			break;
2157 
2158 		/*
2159 		 * dirname should always complete with a "/" path,
2160 		 * but we can be paranoid and check for "." too
2161 		 */
2162 		if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
2163 			break;
2164 	}
2165 	return 0;
2166 }
2167 
2168 /*
2169  * Version of safe_path() that accepts an open file descriptor to
2170  * avoid races.
2171  *
2172  * Returns 0 on success and -1 on failure
2173  */
2174 int
2175 safe_path_fd(int fd, const char *file, struct passwd *pw,
2176     char *err, size_t errlen)
2177 {
2178 	struct stat st;
2179 
2180 	/* check the open file to avoid races */
2181 	if (fstat(fd, &st) == -1) {
2182 		snprintf(err, errlen, "cannot stat file %s: %s",
2183 		    file, strerror(errno));
2184 		return -1;
2185 	}
2186 	return safe_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen);
2187 }
2188 
2189 /*
2190  * Sets the value of the given variable in the environment.  If the variable
2191  * already exists, its value is overridden.
2192  */
2193 void
2194 child_set_env(char ***envp, u_int *envsizep, const char *name,
2195 	const char *value)
2196 {
2197 	char **env;
2198 	u_int envsize;
2199 	u_int i, namelen;
2200 
2201 	if (strchr(name, '=') != NULL) {
2202 		error("Invalid environment variable \"%.100s\"", name);
2203 		return;
2204 	}
2205 
2206 	/*
2207 	 * Find the slot where the value should be stored.  If the variable
2208 	 * already exists, we reuse the slot; otherwise we append a new slot
2209 	 * at the end of the array, expanding if necessary.
2210 	 */
2211 	env = *envp;
2212 	namelen = strlen(name);
2213 	for (i = 0; env[i]; i++)
2214 		if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
2215 			break;
2216 	if (env[i]) {
2217 		/* Reuse the slot. */
2218 		free(env[i]);
2219 	} else {
2220 		/* New variable.  Expand if necessary. */
2221 		envsize = *envsizep;
2222 		if (i >= envsize - 1) {
2223 			if (envsize >= 1000)
2224 				fatal("child_set_env: too many env vars");
2225 			envsize += 50;
2226 			env = (*envp) = xreallocarray(env, envsize, sizeof(char *));
2227 			*envsizep = envsize;
2228 		}
2229 		/* Need to set the NULL pointer at end of array beyond the new slot. */
2230 		env[i + 1] = NULL;
2231 	}
2232 
2233 	/* Allocate space and format the variable in the appropriate slot. */
2234 	/* XXX xasprintf */
2235 	env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
2236 	snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
2237 }
2238 
2239 /*
2240  * Check and optionally lowercase a domain name, also removes trailing '.'
2241  * Returns 1 on success and 0 on failure, storing an error message in errstr.
2242  */
2243 int
2244 valid_domain(char *name, int makelower, const char **errstr)
2245 {
2246 	size_t i, l = strlen(name);
2247 	u_char c, last = '\0';
2248 	static char errbuf[256];
2249 
2250 	if (l == 0) {
2251 		strlcpy(errbuf, "empty domain name", sizeof(errbuf));
2252 		goto bad;
2253 	}
2254 	if (!isalpha((u_char)name[0]) && !isdigit((u_char)name[0])) {
2255 		snprintf(errbuf, sizeof(errbuf), "domain name \"%.100s\" "
2256 		    "starts with invalid character", name);
2257 		goto bad;
2258 	}
2259 	for (i = 0; i < l; i++) {
2260 		c = tolower((u_char)name[i]);
2261 		if (makelower)
2262 			name[i] = (char)c;
2263 		if (last == '.' && c == '.') {
2264 			snprintf(errbuf, sizeof(errbuf), "domain name "
2265 			    "\"%.100s\" contains consecutive separators", name);
2266 			goto bad;
2267 		}
2268 		if (c != '.' && c != '-' && !isalnum(c) &&
2269 		    c != '_') /* technically invalid, but common */ {
2270 			snprintf(errbuf, sizeof(errbuf), "domain name "
2271 			    "\"%.100s\" contains invalid characters", name);
2272 			goto bad;
2273 		}
2274 		last = c;
2275 	}
2276 	if (name[l - 1] == '.')
2277 		name[l - 1] = '\0';
2278 	if (errstr != NULL)
2279 		*errstr = NULL;
2280 	return 1;
2281 bad:
2282 	if (errstr != NULL)
2283 		*errstr = errbuf;
2284 	return 0;
2285 }
2286 
2287 /*
2288  * Verify that a environment variable name (not including initial '$') is
2289  * valid; consisting of one or more alphanumeric or underscore characters only.
2290  * Returns 1 on valid, 0 otherwise.
2291  */
2292 int
2293 valid_env_name(const char *name)
2294 {
2295 	const char *cp;
2296 
2297 	if (name[0] == '\0')
2298 		return 0;
2299 	for (cp = name; *cp != '\0'; cp++) {
2300 		if (!isalnum((u_char)*cp) && *cp != '_')
2301 			return 0;
2302 	}
2303 	return 1;
2304 }
2305 
2306 const char *
2307 atoi_err(const char *nptr, int *val)
2308 {
2309 	const char *errstr = NULL;
2310 	long long num;
2311 
2312 	if (nptr == NULL || *nptr == '\0')
2313 		return "missing";
2314 	num = strtonum(nptr, 0, INT_MAX, &errstr);
2315 	if (errstr == NULL)
2316 		*val = (int)num;
2317 	return errstr;
2318 }
2319 
2320 int
2321 parse_absolute_time(const char *s, uint64_t *tp)
2322 {
2323 	struct tm tm;
2324 	time_t tt;
2325 	char buf[32], *fmt;
2326 	const char *cp;
2327 	size_t l;
2328 	int is_utc = 0;
2329 
2330 	*tp = 0;
2331 
2332 	l = strlen(s);
2333 	if (l > 1 && strcasecmp(s + l - 1, "Z") == 0) {
2334 		is_utc = 1;
2335 		l--;
2336 	} else if (l > 3 && strcasecmp(s + l - 3, "UTC") == 0) {
2337 		is_utc = 1;
2338 		l -= 3;
2339 	}
2340 	/*
2341 	 * POSIX strptime says "The application shall ensure that there
2342 	 * is white-space or other non-alphanumeric characters between
2343 	 * any two conversion specifications" so arrange things this way.
2344 	 */
2345 	switch (l) {
2346 	case 8: /* YYYYMMDD */
2347 		fmt = "%Y-%m-%d";
2348 		snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
2349 		break;
2350 	case 12: /* YYYYMMDDHHMM */
2351 		fmt = "%Y-%m-%dT%H:%M";
2352 		snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s",
2353 		    s, s + 4, s + 6, s + 8, s + 10);
2354 		break;
2355 	case 14: /* YYYYMMDDHHMMSS */
2356 		fmt = "%Y-%m-%dT%H:%M:%S";
2357 		snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
2358 		    s, s + 4, s + 6, s + 8, s + 10, s + 12);
2359 		break;
2360 	default:
2361 		return SSH_ERR_INVALID_FORMAT;
2362 	}
2363 
2364 	memset(&tm, 0, sizeof(tm));
2365 	if ((cp = strptime(buf, fmt, &tm)) == NULL || *cp != '\0')
2366 		return SSH_ERR_INVALID_FORMAT;
2367 	if (is_utc) {
2368 		if ((tt = timegm(&tm)) < 0)
2369 			return SSH_ERR_INVALID_FORMAT;
2370 	} else {
2371 		if ((tt = mktime(&tm)) < 0)
2372 			return SSH_ERR_INVALID_FORMAT;
2373 	}
2374 	/* success */
2375 	*tp = (uint64_t)tt;
2376 	return 0;
2377 }
2378 
2379 void
2380 format_absolute_time(uint64_t t, char *buf, size_t len)
2381 {
2382 	time_t tt = t > SSH_TIME_T_MAX ? SSH_TIME_T_MAX : t;
2383 	struct tm tm;
2384 
2385 	localtime_r(&tt, &tm);
2386 	strftime(buf, len, "%Y-%m-%dT%H:%M:%S", &tm);
2387 }
2388 
2389 /*
2390  * Parse a "pattern=interval" clause (e.g. a ChannelTimeout).
2391  * Returns 0 on success or non-zero on failure.
2392  * Caller must free *typep.
2393  */
2394 int
2395 parse_pattern_interval(const char *s, char **typep, int *secsp)
2396 {
2397 	char *cp, *sdup;
2398 	int secs;
2399 
2400 	if (typep != NULL)
2401 		*typep = NULL;
2402 	if (secsp != NULL)
2403 		*secsp = 0;
2404 	if (s == NULL)
2405 		return -1;
2406 	sdup = xstrdup(s);
2407 
2408 	if ((cp = strchr(sdup, '=')) == NULL || cp == sdup) {
2409 		free(sdup);
2410 		return -1;
2411 	}
2412 	*cp++ = '\0';
2413 	if ((secs = convtime(cp)) < 0) {
2414 		free(sdup);
2415 		return -1;
2416 	}
2417 	/* success */
2418 	if (typep != NULL)
2419 		*typep = xstrdup(sdup);
2420 	if (secsp != NULL)
2421 		*secsp = secs;
2422 	free(sdup);
2423 	return 0;
2424 }
2425 
2426 /* check if path is absolute */
2427 int
2428 path_absolute(const char *path)
2429 {
2430 	return (*path == '/') ? 1 : 0;
2431 }
2432 
2433 void
2434 skip_space(char **cpp)
2435 {
2436 	char *cp;
2437 
2438 	for (cp = *cpp; *cp == ' ' || *cp == '\t'; cp++)
2439 		;
2440 	*cpp = cp;
2441 }
2442 
2443 /* authorized_key-style options parsing helpers */
2444 
2445 /*
2446  * Match flag 'opt' in *optsp, and if allow_negate is set then also match
2447  * 'no-opt'. Returns -1 if option not matched, 1 if option matches or 0
2448  * if negated option matches.
2449  * If the option or negated option matches, then *optsp is updated to
2450  * point to the first character after the option.
2451  */
2452 int
2453 opt_flag(const char *opt, int allow_negate, const char **optsp)
2454 {
2455 	size_t opt_len = strlen(opt);
2456 	const char *opts = *optsp;
2457 	int negate = 0;
2458 
2459 	if (allow_negate && strncasecmp(opts, "no-", 3) == 0) {
2460 		opts += 3;
2461 		negate = 1;
2462 	}
2463 	if (strncasecmp(opts, opt, opt_len) == 0) {
2464 		*optsp = opts + opt_len;
2465 		return negate ? 0 : 1;
2466 	}
2467 	return -1;
2468 }
2469 
2470 char *
2471 opt_dequote(const char **sp, const char **errstrp)
2472 {
2473 	const char *s = *sp;
2474 	char *ret;
2475 	size_t i;
2476 
2477 	*errstrp = NULL;
2478 	if (*s != '"') {
2479 		*errstrp = "missing start quote";
2480 		return NULL;
2481 	}
2482 	s++;
2483 	if ((ret = malloc(strlen((s)) + 1)) == NULL) {
2484 		*errstrp = "memory allocation failed";
2485 		return NULL;
2486 	}
2487 	for (i = 0; *s != '\0' && *s != '"';) {
2488 		if (s[0] == '\\' && s[1] == '"')
2489 			s++;
2490 		ret[i++] = *s++;
2491 	}
2492 	if (*s == '\0') {
2493 		*errstrp = "missing end quote";
2494 		free(ret);
2495 		return NULL;
2496 	}
2497 	ret[i] = '\0';
2498 	s++;
2499 	*sp = s;
2500 	return ret;
2501 }
2502 
2503 int
2504 opt_match(const char **opts, const char *term)
2505 {
2506 	if (strncasecmp((*opts), term, strlen(term)) == 0 &&
2507 	    (*opts)[strlen(term)] == '=') {
2508 		*opts += strlen(term) + 1;
2509 		return 1;
2510 	}
2511 	return 0;
2512 }
2513 
2514 void
2515 opt_array_append2(const char *file, const int line, const char *directive,
2516     char ***array, int **iarray, u_int *lp, const char *s, int i)
2517 {
2518 
2519 	if (*lp >= INT_MAX)
2520 		fatal("%s line %d: Too many %s entries", file, line, directive);
2521 
2522 	if (iarray != NULL) {
2523 		*iarray = xrecallocarray(*iarray, *lp, *lp + 1,
2524 		    sizeof(**iarray));
2525 		(*iarray)[*lp] = i;
2526 	}
2527 
2528 	*array = xrecallocarray(*array, *lp, *lp + 1, sizeof(**array));
2529 	(*array)[*lp] = xstrdup(s);
2530 	(*lp)++;
2531 }
2532 
2533 void
2534 opt_array_append(const char *file, const int line, const char *directive,
2535     char ***array, u_int *lp, const char *s)
2536 {
2537 	opt_array_append2(file, line, directive, array, NULL, lp, s, 0);
2538 }
2539 
2540 sshsig_t
2541 ssh_signal(int signum, sshsig_t handler)
2542 {
2543 	struct sigaction sa, osa;
2544 
2545 	/* mask all other signals while in handler */
2546 	memset(&sa, 0, sizeof(sa));
2547 	sa.sa_handler = handler;
2548 	sigfillset(&sa.sa_mask);
2549 	if (signum != SIGALRM)
2550 		sa.sa_flags = SA_RESTART;
2551 	if (sigaction(signum, &sa, &osa) == -1) {
2552 		debug3("sigaction(%s): %s", strsignal(signum), strerror(errno));
2553 		return SIG_ERR;
2554 	}
2555 	return osa.sa_handler;
2556 }
2557 
2558 int
2559 stdfd_devnull(int do_stdin, int do_stdout, int do_stderr)
2560 {
2561 	int devnull, ret = 0;
2562 
2563 	if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
2564 		error_f("open %s: %s", _PATH_DEVNULL,
2565 		    strerror(errno));
2566 		return -1;
2567 	}
2568 	if ((do_stdin && dup2(devnull, STDIN_FILENO) == -1) ||
2569 	    (do_stdout && dup2(devnull, STDOUT_FILENO) == -1) ||
2570 	    (do_stderr && dup2(devnull, STDERR_FILENO) == -1)) {
2571 		error_f("dup2: %s", strerror(errno));
2572 		ret = -1;
2573 	}
2574 	if (devnull > STDERR_FILENO)
2575 		close(devnull);
2576 	return ret;
2577 }
2578 
2579 /*
2580  * Runs command in a subprocess with a minimal environment.
2581  * Returns pid on success, 0 on failure.
2582  * The child stdout and stderr maybe captured, left attached or sent to
2583  * /dev/null depending on the contents of flags.
2584  * "tag" is prepended to log messages.
2585  * NB. "command" is only used for logging; the actual command executed is
2586  * av[0].
2587  */
2588 pid_t
2589 subprocess(const char *tag, const char *command,
2590     int ac, char **av, FILE **child, u_int flags,
2591     struct passwd *pw, privdrop_fn *drop_privs, privrestore_fn *restore_privs)
2592 {
2593 	FILE *f = NULL;
2594 	struct stat st;
2595 	int fd, devnull, p[2], i;
2596 	pid_t pid;
2597 	char *cp, errmsg[512];
2598 	u_int nenv = 0;
2599 	char **env = NULL;
2600 
2601 	/* If dropping privs, then must specify user and restore function */
2602 	if (drop_privs != NULL && (pw == NULL || restore_privs == NULL)) {
2603 		error("%s: inconsistent arguments", tag); /* XXX fatal? */
2604 		return 0;
2605 	}
2606 	if (pw == NULL && (pw = getpwuid(getuid())) == NULL) {
2607 		error("%s: no user for current uid", tag);
2608 		return 0;
2609 	}
2610 	if (child != NULL)
2611 		*child = NULL;
2612 
2613 	debug3_f("%s command \"%s\" running as %s (flags 0x%x)",
2614 	    tag, command, pw->pw_name, flags);
2615 
2616 	/* Check consistency */
2617 	if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
2618 	    (flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0) {
2619 		error_f("inconsistent flags");
2620 		return 0;
2621 	}
2622 	if (((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0) != (child == NULL)) {
2623 		error_f("inconsistent flags/output");
2624 		return 0;
2625 	}
2626 
2627 	/*
2628 	 * If executing an explicit binary, then verify the it exists
2629 	 * and appears safe-ish to execute
2630 	 */
2631 	if (!path_absolute(av[0])) {
2632 		error("%s path is not absolute", tag);
2633 		return 0;
2634 	}
2635 	if (drop_privs != NULL)
2636 		drop_privs(pw);
2637 	if (stat(av[0], &st) == -1) {
2638 		error("Could not stat %s \"%s\": %s", tag,
2639 		    av[0], strerror(errno));
2640 		goto restore_return;
2641 	}
2642 	if ((flags & SSH_SUBPROCESS_UNSAFE_PATH) == 0 &&
2643 	    safe_path(av[0], &st, NULL, 0, errmsg, sizeof(errmsg)) != 0) {
2644 		error("Unsafe %s \"%s\": %s", tag, av[0], errmsg);
2645 		goto restore_return;
2646 	}
2647 	/* Prepare to keep the child's stdout if requested */
2648 	if (pipe(p) == -1) {
2649 		error("%s: pipe: %s", tag, strerror(errno));
2650  restore_return:
2651 		if (restore_privs != NULL)
2652 			restore_privs();
2653 		return 0;
2654 	}
2655 	if (restore_privs != NULL)
2656 		restore_privs();
2657 
2658 	switch ((pid = fork())) {
2659 	case -1: /* error */
2660 		error("%s: fork: %s", tag, strerror(errno));
2661 		close(p[0]);
2662 		close(p[1]);
2663 		return 0;
2664 	case 0: /* child */
2665 		/* Prepare a minimal environment for the child. */
2666 		if ((flags & SSH_SUBPROCESS_PRESERVE_ENV) == 0) {
2667 			nenv = 5;
2668 			env = xcalloc(sizeof(*env), nenv);
2669 			child_set_env(&env, &nenv, "PATH", _PATH_STDPATH);
2670 			child_set_env(&env, &nenv, "USER", pw->pw_name);
2671 			child_set_env(&env, &nenv, "LOGNAME", pw->pw_name);
2672 			child_set_env(&env, &nenv, "HOME", pw->pw_dir);
2673 			if ((cp = getenv("LANG")) != NULL)
2674 				child_set_env(&env, &nenv, "LANG", cp);
2675 		}
2676 
2677 		for (i = 1; i < NSIG; i++)
2678 			ssh_signal(i, SIG_DFL);
2679 
2680 		if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
2681 			error("%s: open %s: %s", tag, _PATH_DEVNULL,
2682 			    strerror(errno));
2683 			_exit(1);
2684 		}
2685 		if (dup2(devnull, STDIN_FILENO) == -1) {
2686 			error("%s: dup2: %s", tag, strerror(errno));
2687 			_exit(1);
2688 		}
2689 
2690 		/* Set up stdout as requested; leave stderr in place for now. */
2691 		fd = -1;
2692 		if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0)
2693 			fd = p[1];
2694 		else if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0)
2695 			fd = devnull;
2696 		if (fd != -1 && dup2(fd, STDOUT_FILENO) == -1) {
2697 			error("%s: dup2: %s", tag, strerror(errno));
2698 			_exit(1);
2699 		}
2700 		closefrom(STDERR_FILENO + 1);
2701 
2702 		if (geteuid() == 0 &&
2703 		    initgroups(pw->pw_name, pw->pw_gid) == -1) {
2704 			error("%s: initgroups(%s, %u): %s", tag,
2705 			    pw->pw_name, (u_int)pw->pw_gid, strerror(errno));
2706 			_exit(1);
2707 		}
2708 		if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1) {
2709 			error("%s: setresgid %u: %s", tag, (u_int)pw->pw_gid,
2710 			    strerror(errno));
2711 			_exit(1);
2712 		}
2713 		if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1) {
2714 			error("%s: setresuid %u: %s", tag, (u_int)pw->pw_uid,
2715 			    strerror(errno));
2716 			_exit(1);
2717 		}
2718 		/* stdin is pointed to /dev/null at this point */
2719 		if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
2720 		    dup2(STDIN_FILENO, STDERR_FILENO) == -1) {
2721 			error("%s: dup2: %s", tag, strerror(errno));
2722 			_exit(1);
2723 		}
2724 		if (env != NULL)
2725 			execve(av[0], av, env);
2726 		else
2727 			execv(av[0], av);
2728 		error("%s %s \"%s\": %s", tag, env == NULL ? "execv" : "execve",
2729 		    command, strerror(errno));
2730 		_exit(127);
2731 	default: /* parent */
2732 		break;
2733 	}
2734 
2735 	close(p[1]);
2736 	if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0)
2737 		close(p[0]);
2738 	else if ((f = fdopen(p[0], "r")) == NULL) {
2739 		error("%s: fdopen: %s", tag, strerror(errno));
2740 		close(p[0]);
2741 		/* Don't leave zombie child */
2742 		kill(pid, SIGTERM);
2743 		while (waitpid(pid, NULL, 0) == -1 && errno == EINTR)
2744 			;
2745 		return 0;
2746 	}
2747 	/* Success */
2748 	debug3_f("%s pid %ld", tag, (long)pid);
2749 	if (child != NULL)
2750 		*child = f;
2751 	return pid;
2752 }
2753 
2754 const char *
2755 lookup_env_in_list(const char *env, char * const *envs, size_t nenvs)
2756 {
2757 	size_t i, envlen;
2758 
2759 	envlen = strlen(env);
2760 	for (i = 0; i < nenvs; i++) {
2761 		if (strncmp(envs[i], env, envlen) == 0 &&
2762 		    envs[i][envlen] == '=') {
2763 			return envs[i] + envlen + 1;
2764 		}
2765 	}
2766 	return NULL;
2767 }
2768 
2769 const char *
2770 lookup_setenv_in_list(const char *env, char * const *envs, size_t nenvs)
2771 {
2772 	char *name, *cp;
2773 	const char *ret;
2774 
2775 	name = xstrdup(env);
2776 	if ((cp = strchr(name, '=')) == NULL) {
2777 		free(name);
2778 		return NULL; /* not env=val */
2779 	}
2780 	*cp = '\0';
2781 	ret = lookup_env_in_list(name, envs, nenvs);
2782 	free(name);
2783 	return ret;
2784 }
2785 
2786 /*
2787  * Helpers for managing poll(2)/ppoll(2) timeouts
2788  * Will remember the earliest deadline and return it for use in poll/ppoll.
2789  */
2790 
2791 /* Initialise a poll/ppoll timeout with an indefinite deadline */
2792 void
2793 ptimeout_init(struct timespec *pt)
2794 {
2795 	/*
2796 	 * Deliberately invalid for ppoll(2).
2797 	 * Will be converted to NULL in ptimeout_get_tspec() later.
2798 	 */
2799 	pt->tv_sec = -1;
2800 	pt->tv_nsec = 0;
2801 }
2802 
2803 /* Specify a poll/ppoll deadline of at most 'sec' seconds */
2804 void
2805 ptimeout_deadline_sec(struct timespec *pt, long sec)
2806 {
2807 	if (pt->tv_sec == -1 || pt->tv_sec >= sec) {
2808 		pt->tv_sec = sec;
2809 		pt->tv_nsec = 0;
2810 	}
2811 }
2812 
2813 /* Specify a poll/ppoll deadline of at most 'p' (timespec) */
2814 static void
2815 ptimeout_deadline_tsp(struct timespec *pt, struct timespec *p)
2816 {
2817 	if (pt->tv_sec == -1 || timespeccmp(pt, p, >=))
2818 		*pt = *p;
2819 }
2820 
2821 /* Specify a poll/ppoll deadline of at most 'ms' milliseconds */
2822 void
2823 ptimeout_deadline_ms(struct timespec *pt, long ms)
2824 {
2825 	struct timespec p;
2826 
2827 	p.tv_sec = ms / 1000;
2828 	p.tv_nsec = (ms % 1000) * 1000000;
2829 	ptimeout_deadline_tsp(pt, &p);
2830 }
2831 
2832 /* Specify a poll/ppoll deadline at wall clock monotime 'when' (timespec) */
2833 void
2834 ptimeout_deadline_monotime_tsp(struct timespec *pt, struct timespec *when)
2835 {
2836 	struct timespec now, t;
2837 
2838 	monotime_ts(&now);
2839 
2840 	if (timespeccmp(&now, when, >=)) {
2841 		/* 'when' is now or in the past. Timeout ASAP */
2842 		pt->tv_sec = 0;
2843 		pt->tv_nsec = 0;
2844 	} else {
2845 		timespecsub(when, &now, &t);
2846 		ptimeout_deadline_tsp(pt, &t);
2847 	}
2848 }
2849 
2850 /* Specify a poll/ppoll deadline at wall clock monotime 'when' */
2851 void
2852 ptimeout_deadline_monotime(struct timespec *pt, time_t when)
2853 {
2854 	struct timespec t;
2855 
2856 	t.tv_sec = when;
2857 	t.tv_nsec = 0;
2858 	ptimeout_deadline_monotime_tsp(pt, &t);
2859 }
2860 
2861 /* Get a poll(2) timeout value in milliseconds */
2862 int
2863 ptimeout_get_ms(struct timespec *pt)
2864 {
2865 	if (pt->tv_sec == -1)
2866 		return -1;
2867 	if (pt->tv_sec >= (INT_MAX - (pt->tv_nsec / 1000000)) / 1000)
2868 		return INT_MAX;
2869 	return (pt->tv_sec * 1000) + (pt->tv_nsec / 1000000);
2870 }
2871 
2872 /* Get a ppoll(2) timeout value as a timespec pointer */
2873 struct timespec *
2874 ptimeout_get_tsp(struct timespec *pt)
2875 {
2876 	return pt->tv_sec == -1 ? NULL : pt;
2877 }
2878 
2879 /* Returns non-zero if a timeout has been set (i.e. is not indefinite) */
2880 int
2881 ptimeout_isset(struct timespec *pt)
2882 {
2883 	return pt->tv_sec != -1;
2884 }
2885 
2886 /*
2887  * Returns zero if the library at 'path' contains symbol 's', nonzero
2888  * otherwise.
2889  */
2890 int
2891 lib_contains_symbol(const char *path, const char *s)
2892 {
2893 	struct nlist nl[2];
2894 	int ret = -1, r;
2895 
2896 	memset(nl, 0, sizeof(nl));
2897 	nl[0].n_name = xstrdup(s);
2898 	nl[1].n_name = NULL;
2899 	if ((r = nlist(path, nl)) == -1) {
2900 		error_f("nlist failed for %s", path);
2901 		goto out;
2902 	}
2903 	if (r != 0 || nl[0].n_value == 0 || nl[0].n_type == 0) {
2904 		error_f("library %s does not contain symbol %s", path, s);
2905 		goto out;
2906 	}
2907 	/* success */
2908 	ret = 0;
2909  out:
2910 	free(nl[0].n_name);
2911 	return ret;
2912 }
2913