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