xref: /openbsd-src/usr.bin/ssh/misc.c (revision c020cf82e0cc147236f01a8dca7052034cf9d30d)
1 /* $OpenBSD: misc.c,v 1.152 2020/05/29 11:17:56 dtucker 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 <poll.h>
44 #include <signal.h>
45 #include <stdarg.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <unistd.h>
50 
51 #include "xmalloc.h"
52 #include "misc.h"
53 #include "log.h"
54 #include "ssh.h"
55 #include "sshbuf.h"
56 #include "ssherr.h"
57 
58 /* remove newline at end of string */
59 char *
60 chop(char *s)
61 {
62 	char *t = s;
63 	while (*t) {
64 		if (*t == '\n' || *t == '\r') {
65 			*t = '\0';
66 			return s;
67 		}
68 		t++;
69 	}
70 	return s;
71 
72 }
73 
74 /* set/unset filedescriptor to non-blocking */
75 int
76 set_nonblock(int fd)
77 {
78 	int val;
79 
80 	val = fcntl(fd, F_GETFL);
81 	if (val == -1) {
82 		error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
83 		return (-1);
84 	}
85 	if (val & O_NONBLOCK) {
86 		debug3("fd %d is O_NONBLOCK", fd);
87 		return (0);
88 	}
89 	debug2("fd %d setting O_NONBLOCK", fd);
90 	val |= O_NONBLOCK;
91 	if (fcntl(fd, F_SETFL, val) == -1) {
92 		debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
93 		    strerror(errno));
94 		return (-1);
95 	}
96 	return (0);
97 }
98 
99 int
100 unset_nonblock(int fd)
101 {
102 	int val;
103 
104 	val = fcntl(fd, F_GETFL);
105 	if (val == -1) {
106 		error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
107 		return (-1);
108 	}
109 	if (!(val & O_NONBLOCK)) {
110 		debug3("fd %d is not O_NONBLOCK", fd);
111 		return (0);
112 	}
113 	debug("fd %d clearing O_NONBLOCK", fd);
114 	val &= ~O_NONBLOCK;
115 	if (fcntl(fd, F_SETFL, val) == -1) {
116 		debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
117 		    fd, strerror(errno));
118 		return (-1);
119 	}
120 	return (0);
121 }
122 
123 const char *
124 ssh_gai_strerror(int gaierr)
125 {
126 	if (gaierr == EAI_SYSTEM && errno != 0)
127 		return strerror(errno);
128 	return gai_strerror(gaierr);
129 }
130 
131 /* disable nagle on socket */
132 void
133 set_nodelay(int fd)
134 {
135 	int opt;
136 	socklen_t optlen;
137 
138 	optlen = sizeof opt;
139 	if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
140 		debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
141 		return;
142 	}
143 	if (opt == 1) {
144 		debug2("fd %d is TCP_NODELAY", fd);
145 		return;
146 	}
147 	opt = 1;
148 	debug2("fd %d setting TCP_NODELAY", fd);
149 	if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
150 		error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
151 }
152 
153 /* Allow local port reuse in TIME_WAIT */
154 int
155 set_reuseaddr(int fd)
156 {
157 	int on = 1;
158 
159 	if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
160 		error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
161 		return -1;
162 	}
163 	return 0;
164 }
165 
166 /* Get/set routing domain */
167 char *
168 get_rdomain(int fd)
169 {
170 	int rtable;
171 	char *ret;
172 	socklen_t len = sizeof(rtable);
173 
174 	if (getsockopt(fd, SOL_SOCKET, SO_RTABLE, &rtable, &len) == -1) {
175 		error("Failed to get routing domain for fd %d: %s",
176 		    fd, strerror(errno));
177 		return NULL;
178 	}
179 	xasprintf(&ret, "%d", rtable);
180 	return ret;
181 }
182 
183 int
184 set_rdomain(int fd, const char *name)
185 {
186 	int rtable;
187 	const char *errstr;
188 
189 	if (name == NULL)
190 		return 0; /* default table */
191 
192 	rtable = (int)strtonum(name, 0, 255, &errstr);
193 	if (errstr != NULL) {
194 		/* Shouldn't happen */
195 		error("Invalid routing domain \"%s\": %s", name, errstr);
196 		return -1;
197 	}
198 	if (setsockopt(fd, SOL_SOCKET, SO_RTABLE,
199 	    &rtable, sizeof(rtable)) == -1) {
200 		error("Failed to set routing domain %d on fd %d: %s",
201 		    rtable, fd, strerror(errno));
202 		return -1;
203 	}
204 	return 0;
205 }
206 
207 /*
208  * Wait up to *timeoutp milliseconds for events on fd. Updates
209  * *timeoutp with time remaining.
210  * Returns 0 if fd ready or -1 on timeout or error (see errno).
211  */
212 static int
213 waitfd(int fd, int *timeoutp, short events)
214 {
215 	struct pollfd pfd;
216 	struct timeval t_start;
217 	int oerrno, r;
218 
219 	monotime_tv(&t_start);
220 	pfd.fd = fd;
221 	pfd.events = events;
222 	for (; *timeoutp >= 0;) {
223 		r = poll(&pfd, 1, *timeoutp);
224 		oerrno = errno;
225 		ms_subtract_diff(&t_start, timeoutp);
226 		errno = oerrno;
227 		if (r > 0)
228 			return 0;
229 		else if (r == -1 && errno != EAGAIN)
230 			return -1;
231 		else if (r == 0)
232 			break;
233 	}
234 	/* timeout */
235 	errno = ETIMEDOUT;
236 	return -1;
237 }
238 
239 /*
240  * Wait up to *timeoutp milliseconds for fd to be readable. Updates
241  * *timeoutp with time remaining.
242  * Returns 0 if fd ready or -1 on timeout or error (see errno).
243  */
244 int
245 waitrfd(int fd, int *timeoutp) {
246 	return waitfd(fd, timeoutp, POLLIN);
247 }
248 
249 /*
250  * Attempt a non-blocking connect(2) to the specified address, waiting up to
251  * *timeoutp milliseconds for the connection to complete. If the timeout is
252  * <=0, then wait indefinitely.
253  *
254  * Returns 0 on success or -1 on failure.
255  */
256 int
257 timeout_connect(int sockfd, const struct sockaddr *serv_addr,
258     socklen_t addrlen, int *timeoutp)
259 {
260 	int optval = 0;
261 	socklen_t optlen = sizeof(optval);
262 
263 	/* No timeout: just do a blocking connect() */
264 	if (timeoutp == NULL || *timeoutp <= 0)
265 		return connect(sockfd, serv_addr, addrlen);
266 
267 	set_nonblock(sockfd);
268 	if (connect(sockfd, serv_addr, addrlen) == 0) {
269 		/* Succeeded already? */
270 		unset_nonblock(sockfd);
271 		return 0;
272 	} else if (errno != EINPROGRESS)
273 		return -1;
274 
275 	if (waitfd(sockfd, timeoutp, POLLIN | POLLOUT) == -1)
276 		return -1;
277 
278 	/* Completed or failed */
279 	if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval, &optlen) == -1) {
280 		debug("getsockopt: %s", strerror(errno));
281 		return -1;
282 	}
283 	if (optval != 0) {
284 		errno = optval;
285 		return -1;
286 	}
287 	unset_nonblock(sockfd);
288 	return 0;
289 }
290 
291 /* Characters considered whitespace in strsep calls. */
292 #define WHITESPACE " \t\r\n"
293 #define QUOTE	"\""
294 
295 /* return next token in configuration line */
296 static char *
297 strdelim_internal(char **s, int split_equals)
298 {
299 	char *old;
300 	int wspace = 0;
301 
302 	if (*s == NULL)
303 		return NULL;
304 
305 	old = *s;
306 
307 	*s = strpbrk(*s,
308 	    split_equals ? WHITESPACE QUOTE "=" : WHITESPACE QUOTE);
309 	if (*s == NULL)
310 		return (old);
311 
312 	if (*s[0] == '\"') {
313 		memmove(*s, *s + 1, strlen(*s)); /* move nul too */
314 		/* Find matching quote */
315 		if ((*s = strpbrk(*s, QUOTE)) == NULL) {
316 			return (NULL);		/* no matching quote */
317 		} else {
318 			*s[0] = '\0';
319 			*s += strspn(*s + 1, WHITESPACE) + 1;
320 			return (old);
321 		}
322 	}
323 
324 	/* Allow only one '=' to be skipped */
325 	if (split_equals && *s[0] == '=')
326 		wspace = 1;
327 	*s[0] = '\0';
328 
329 	/* Skip any extra whitespace after first token */
330 	*s += strspn(*s + 1, WHITESPACE) + 1;
331 	if (split_equals && *s[0] == '=' && !wspace)
332 		*s += strspn(*s + 1, WHITESPACE) + 1;
333 
334 	return (old);
335 }
336 
337 /*
338  * Return next token in configuration line; splts on whitespace or a
339  * single '=' character.
340  */
341 char *
342 strdelim(char **s)
343 {
344 	return strdelim_internal(s, 1);
345 }
346 
347 /*
348  * Return next token in configuration line; splts on whitespace only.
349  */
350 char *
351 strdelimw(char **s)
352 {
353 	return strdelim_internal(s, 0);
354 }
355 
356 struct passwd *
357 pwcopy(struct passwd *pw)
358 {
359 	struct passwd *copy = xcalloc(1, sizeof(*copy));
360 
361 	copy->pw_name = xstrdup(pw->pw_name);
362 	copy->pw_passwd = xstrdup(pw->pw_passwd);
363 	copy->pw_gecos = xstrdup(pw->pw_gecos);
364 	copy->pw_uid = pw->pw_uid;
365 	copy->pw_gid = pw->pw_gid;
366 	copy->pw_expire = pw->pw_expire;
367 	copy->pw_change = pw->pw_change;
368 	copy->pw_class = xstrdup(pw->pw_class);
369 	copy->pw_dir = xstrdup(pw->pw_dir);
370 	copy->pw_shell = xstrdup(pw->pw_shell);
371 	return copy;
372 }
373 
374 /*
375  * Convert ASCII string to TCP/IP port number.
376  * Port must be >=0 and <=65535.
377  * Return -1 if invalid.
378  */
379 int
380 a2port(const char *s)
381 {
382 	struct servent *se;
383 	long long port;
384 	const char *errstr;
385 
386 	port = strtonum(s, 0, 65535, &errstr);
387 	if (errstr == NULL)
388 		return (int)port;
389 	if ((se = getservbyname(s, "tcp")) != NULL)
390 		return ntohs(se->s_port);
391 	return -1;
392 }
393 
394 int
395 a2tun(const char *s, int *remote)
396 {
397 	const char *errstr = NULL;
398 	char *sp, *ep;
399 	int tun;
400 
401 	if (remote != NULL) {
402 		*remote = SSH_TUNID_ANY;
403 		sp = xstrdup(s);
404 		if ((ep = strchr(sp, ':')) == NULL) {
405 			free(sp);
406 			return (a2tun(s, NULL));
407 		}
408 		ep[0] = '\0'; ep++;
409 		*remote = a2tun(ep, NULL);
410 		tun = a2tun(sp, NULL);
411 		free(sp);
412 		return (*remote == SSH_TUNID_ERR ? *remote : tun);
413 	}
414 
415 	if (strcasecmp(s, "any") == 0)
416 		return (SSH_TUNID_ANY);
417 
418 	tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
419 	if (errstr != NULL)
420 		return (SSH_TUNID_ERR);
421 
422 	return (tun);
423 }
424 
425 #define SECONDS		1
426 #define MINUTES		(SECONDS * 60)
427 #define HOURS		(MINUTES * 60)
428 #define DAYS		(HOURS * 24)
429 #define WEEKS		(DAYS * 7)
430 
431 /*
432  * Convert a time string into seconds; format is
433  * a sequence of:
434  *      time[qualifier]
435  *
436  * Valid time qualifiers are:
437  *      <none>  seconds
438  *      s|S     seconds
439  *      m|M     minutes
440  *      h|H     hours
441  *      d|D     days
442  *      w|W     weeks
443  *
444  * Examples:
445  *      90m     90 minutes
446  *      1h30m   90 minutes
447  *      2d      2 days
448  *      1w      1 week
449  *
450  * Return -1 if time string is invalid.
451  */
452 long
453 convtime(const char *s)
454 {
455 	long total, secs, multiplier;
456 	const char *p;
457 	char *endp;
458 
459 	errno = 0;
460 	total = 0;
461 	p = s;
462 
463 	if (p == NULL || *p == '\0')
464 		return -1;
465 
466 	while (*p) {
467 		secs = strtol(p, &endp, 10);
468 		if (p == endp ||
469 		    (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
470 		    secs < 0)
471 			return -1;
472 
473 		multiplier = 1;
474 		switch (*endp++) {
475 		case '\0':
476 			endp--;
477 			break;
478 		case 's':
479 		case 'S':
480 			break;
481 		case 'm':
482 		case 'M':
483 			multiplier = MINUTES;
484 			break;
485 		case 'h':
486 		case 'H':
487 			multiplier = HOURS;
488 			break;
489 		case 'd':
490 		case 'D':
491 			multiplier = DAYS;
492 			break;
493 		case 'w':
494 		case 'W':
495 			multiplier = WEEKS;
496 			break;
497 		default:
498 			return -1;
499 		}
500 		if (secs >= LONG_MAX / multiplier)
501 			return -1;
502 		secs *= multiplier;
503 		if  (total >= LONG_MAX - secs)
504 			return -1;
505 		total += secs;
506 		if (total < 0)
507 			return -1;
508 		p = endp;
509 	}
510 
511 	return total;
512 }
513 
514 #define TF_BUFS	8
515 #define TF_LEN	9
516 
517 const char *
518 fmt_timeframe(time_t t)
519 {
520 	char		*buf;
521 	static char	 tfbuf[TF_BUFS][TF_LEN];	/* ring buffer */
522 	static int	 idx = 0;
523 	unsigned int	 sec, min, hrs, day;
524 	unsigned long long	week;
525 
526 	buf = tfbuf[idx++];
527 	if (idx == TF_BUFS)
528 		idx = 0;
529 
530 	week = t;
531 
532 	sec = week % 60;
533 	week /= 60;
534 	min = week % 60;
535 	week /= 60;
536 	hrs = week % 24;
537 	week /= 24;
538 	day = week % 7;
539 	week /= 7;
540 
541 	if (week > 0)
542 		snprintf(buf, TF_LEN, "%02lluw%01ud%02uh", week, day, hrs);
543 	else if (day > 0)
544 		snprintf(buf, TF_LEN, "%01ud%02uh%02um", day, hrs, min);
545 	else
546 		snprintf(buf, TF_LEN, "%02u:%02u:%02u", hrs, min, sec);
547 
548 	return (buf);
549 }
550 
551 /*
552  * Returns a standardized host+port identifier string.
553  * Caller must free returned string.
554  */
555 char *
556 put_host_port(const char *host, u_short port)
557 {
558 	char *hoststr;
559 
560 	if (port == 0 || port == SSH_DEFAULT_PORT)
561 		return(xstrdup(host));
562 	if (asprintf(&hoststr, "[%s]:%d", host, (int)port) == -1)
563 		fatal("put_host_port: asprintf: %s", strerror(errno));
564 	debug3("put_host_port: %s", hoststr);
565 	return hoststr;
566 }
567 
568 /*
569  * Search for next delimiter between hostnames/addresses and ports.
570  * Argument may be modified (for termination).
571  * Returns *cp if parsing succeeds.
572  * *cp is set to the start of the next field, if one was found.
573  * The delimiter char, if present, is stored in delim.
574  * If this is the last field, *cp is set to NULL.
575  */
576 char *
577 hpdelim2(char **cp, char *delim)
578 {
579 	char *s, *old;
580 
581 	if (cp == NULL || *cp == NULL)
582 		return NULL;
583 
584 	old = s = *cp;
585 	if (*s == '[') {
586 		if ((s = strchr(s, ']')) == NULL)
587 			return NULL;
588 		else
589 			s++;
590 	} else if ((s = strpbrk(s, ":/")) == NULL)
591 		s = *cp + strlen(*cp); /* skip to end (see first case below) */
592 
593 	switch (*s) {
594 	case '\0':
595 		*cp = NULL;	/* no more fields*/
596 		break;
597 
598 	case ':':
599 	case '/':
600 		if (delim != NULL)
601 			*delim = *s;
602 		*s = '\0';	/* terminate */
603 		*cp = s + 1;
604 		break;
605 
606 	default:
607 		return NULL;
608 	}
609 
610 	return old;
611 }
612 
613 char *
614 hpdelim(char **cp)
615 {
616 	return hpdelim2(cp, NULL);
617 }
618 
619 char *
620 cleanhostname(char *host)
621 {
622 	if (*host == '[' && host[strlen(host) - 1] == ']') {
623 		host[strlen(host) - 1] = '\0';
624 		return (host + 1);
625 	} else
626 		return host;
627 }
628 
629 char *
630 colon(char *cp)
631 {
632 	int flag = 0;
633 
634 	if (*cp == ':')		/* Leading colon is part of file name. */
635 		return NULL;
636 	if (*cp == '[')
637 		flag = 1;
638 
639 	for (; *cp; ++cp) {
640 		if (*cp == '@' && *(cp+1) == '[')
641 			flag = 1;
642 		if (*cp == ']' && *(cp+1) == ':' && flag)
643 			return (cp+1);
644 		if (*cp == ':' && !flag)
645 			return (cp);
646 		if (*cp == '/')
647 			return NULL;
648 	}
649 	return NULL;
650 }
651 
652 /*
653  * Parse a [user@]host:[path] string.
654  * Caller must free returned user, host and path.
655  * Any of the pointer return arguments may be NULL (useful for syntax checking).
656  * If user was not specified then *userp will be set to NULL.
657  * If host was not specified then *hostp will be set to NULL.
658  * If path was not specified then *pathp will be set to ".".
659  * Returns 0 on success, -1 on failure.
660  */
661 int
662 parse_user_host_path(const char *s, char **userp, char **hostp, char **pathp)
663 {
664 	char *user = NULL, *host = NULL, *path = NULL;
665 	char *sdup, *tmp;
666 	int ret = -1;
667 
668 	if (userp != NULL)
669 		*userp = NULL;
670 	if (hostp != NULL)
671 		*hostp = NULL;
672 	if (pathp != NULL)
673 		*pathp = NULL;
674 
675 	sdup = xstrdup(s);
676 
677 	/* Check for remote syntax: [user@]host:[path] */
678 	if ((tmp = colon(sdup)) == NULL)
679 		goto out;
680 
681 	/* Extract optional path */
682 	*tmp++ = '\0';
683 	if (*tmp == '\0')
684 		tmp = ".";
685 	path = xstrdup(tmp);
686 
687 	/* Extract optional user and mandatory host */
688 	tmp = strrchr(sdup, '@');
689 	if (tmp != NULL) {
690 		*tmp++ = '\0';
691 		host = xstrdup(cleanhostname(tmp));
692 		if (*sdup != '\0')
693 			user = xstrdup(sdup);
694 	} else {
695 		host = xstrdup(cleanhostname(sdup));
696 		user = NULL;
697 	}
698 
699 	/* Success */
700 	if (userp != NULL) {
701 		*userp = user;
702 		user = NULL;
703 	}
704 	if (hostp != NULL) {
705 		*hostp = host;
706 		host = NULL;
707 	}
708 	if (pathp != NULL) {
709 		*pathp = path;
710 		path = NULL;
711 	}
712 	ret = 0;
713 out:
714 	free(sdup);
715 	free(user);
716 	free(host);
717 	free(path);
718 	return ret;
719 }
720 
721 /*
722  * Parse a [user@]host[:port] string.
723  * Caller must free returned user and host.
724  * Any of the pointer return arguments may be NULL (useful for syntax checking).
725  * If user was not specified then *userp will be set to NULL.
726  * If port was not specified then *portp will be -1.
727  * Returns 0 on success, -1 on failure.
728  */
729 int
730 parse_user_host_port(const char *s, char **userp, char **hostp, int *portp)
731 {
732 	char *sdup, *cp, *tmp;
733 	char *user = NULL, *host = NULL;
734 	int port = -1, ret = -1;
735 
736 	if (userp != NULL)
737 		*userp = NULL;
738 	if (hostp != NULL)
739 		*hostp = NULL;
740 	if (portp != NULL)
741 		*portp = -1;
742 
743 	if ((sdup = tmp = strdup(s)) == NULL)
744 		return -1;
745 	/* Extract optional username */
746 	if ((cp = strrchr(tmp, '@')) != NULL) {
747 		*cp = '\0';
748 		if (*tmp == '\0')
749 			goto out;
750 		if ((user = strdup(tmp)) == NULL)
751 			goto out;
752 		tmp = cp + 1;
753 	}
754 	/* Extract mandatory hostname */
755 	if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0')
756 		goto out;
757 	host = xstrdup(cleanhostname(cp));
758 	/* Convert and verify optional port */
759 	if (tmp != NULL && *tmp != '\0') {
760 		if ((port = a2port(tmp)) <= 0)
761 			goto out;
762 	}
763 	/* Success */
764 	if (userp != NULL) {
765 		*userp = user;
766 		user = NULL;
767 	}
768 	if (hostp != NULL) {
769 		*hostp = host;
770 		host = NULL;
771 	}
772 	if (portp != NULL)
773 		*portp = port;
774 	ret = 0;
775  out:
776 	free(sdup);
777 	free(user);
778 	free(host);
779 	return ret;
780 }
781 
782 /*
783  * Converts a two-byte hex string to decimal.
784  * Returns the decimal value or -1 for invalid input.
785  */
786 static int
787 hexchar(const char *s)
788 {
789 	unsigned char result[2];
790 	int i;
791 
792 	for (i = 0; i < 2; i++) {
793 		if (s[i] >= '0' && s[i] <= '9')
794 			result[i] = (unsigned char)(s[i] - '0');
795 		else if (s[i] >= 'a' && s[i] <= 'f')
796 			result[i] = (unsigned char)(s[i] - 'a') + 10;
797 		else if (s[i] >= 'A' && s[i] <= 'F')
798 			result[i] = (unsigned char)(s[i] - 'A') + 10;
799 		else
800 			return -1;
801 	}
802 	return (result[0] << 4) | result[1];
803 }
804 
805 /*
806  * Decode an url-encoded string.
807  * Returns a newly allocated string on success or NULL on failure.
808  */
809 static char *
810 urldecode(const char *src)
811 {
812 	char *ret, *dst;
813 	int ch;
814 
815 	ret = xmalloc(strlen(src) + 1);
816 	for (dst = ret; *src != '\0'; src++) {
817 		switch (*src) {
818 		case '+':
819 			*dst++ = ' ';
820 			break;
821 		case '%':
822 			if (!isxdigit((unsigned char)src[1]) ||
823 			    !isxdigit((unsigned char)src[2]) ||
824 			    (ch = hexchar(src + 1)) == -1) {
825 				free(ret);
826 				return NULL;
827 			}
828 			*dst++ = ch;
829 			src += 2;
830 			break;
831 		default:
832 			*dst++ = *src;
833 			break;
834 		}
835 	}
836 	*dst = '\0';
837 
838 	return ret;
839 }
840 
841 /*
842  * Parse an (scp|ssh|sftp)://[user@]host[:port][/path] URI.
843  * See https://tools.ietf.org/html/draft-ietf-secsh-scp-sftp-ssh-uri-04
844  * Either user or path may be url-encoded (but not host or port).
845  * Caller must free returned user, host and path.
846  * Any of the pointer return arguments may be NULL (useful for syntax checking)
847  * but the scheme must always be specified.
848  * If user was not specified then *userp will be set to NULL.
849  * If port was not specified then *portp will be -1.
850  * If path was not specified then *pathp will be set to NULL.
851  * Returns 0 on success, 1 if non-uri/wrong scheme, -1 on error/invalid uri.
852  */
853 int
854 parse_uri(const char *scheme, const char *uri, char **userp, char **hostp,
855     int *portp, char **pathp)
856 {
857 	char *uridup, *cp, *tmp, ch;
858 	char *user = NULL, *host = NULL, *path = NULL;
859 	int port = -1, ret = -1;
860 	size_t len;
861 
862 	len = strlen(scheme);
863 	if (strncmp(uri, scheme, len) != 0 || strncmp(uri + len, "://", 3) != 0)
864 		return 1;
865 	uri += len + 3;
866 
867 	if (userp != NULL)
868 		*userp = NULL;
869 	if (hostp != NULL)
870 		*hostp = NULL;
871 	if (portp != NULL)
872 		*portp = -1;
873 	if (pathp != NULL)
874 		*pathp = NULL;
875 
876 	uridup = tmp = xstrdup(uri);
877 
878 	/* Extract optional ssh-info (username + connection params) */
879 	if ((cp = strchr(tmp, '@')) != NULL) {
880 		char *delim;
881 
882 		*cp = '\0';
883 		/* Extract username and connection params */
884 		if ((delim = strchr(tmp, ';')) != NULL) {
885 			/* Just ignore connection params for now */
886 			*delim = '\0';
887 		}
888 		if (*tmp == '\0') {
889 			/* Empty username */
890 			goto out;
891 		}
892 		if ((user = urldecode(tmp)) == NULL)
893 			goto out;
894 		tmp = cp + 1;
895 	}
896 
897 	/* Extract mandatory hostname */
898 	if ((cp = hpdelim2(&tmp, &ch)) == NULL || *cp == '\0')
899 		goto out;
900 	host = xstrdup(cleanhostname(cp));
901 	if (!valid_domain(host, 0, NULL))
902 		goto out;
903 
904 	if (tmp != NULL && *tmp != '\0') {
905 		if (ch == ':') {
906 			/* Convert and verify port. */
907 			if ((cp = strchr(tmp, '/')) != NULL)
908 				*cp = '\0';
909 			if ((port = a2port(tmp)) <= 0)
910 				goto out;
911 			tmp = cp ? cp + 1 : NULL;
912 		}
913 		if (tmp != NULL && *tmp != '\0') {
914 			/* Extract optional path */
915 			if ((path = urldecode(tmp)) == NULL)
916 				goto out;
917 		}
918 	}
919 
920 	/* Success */
921 	if (userp != NULL) {
922 		*userp = user;
923 		user = NULL;
924 	}
925 	if (hostp != NULL) {
926 		*hostp = host;
927 		host = NULL;
928 	}
929 	if (portp != NULL)
930 		*portp = port;
931 	if (pathp != NULL) {
932 		*pathp = path;
933 		path = NULL;
934 	}
935 	ret = 0;
936  out:
937 	free(uridup);
938 	free(user);
939 	free(host);
940 	free(path);
941 	return ret;
942 }
943 
944 /* function to assist building execv() arguments */
945 void
946 addargs(arglist *args, char *fmt, ...)
947 {
948 	va_list ap;
949 	char *cp;
950 	u_int nalloc;
951 	int r;
952 
953 	va_start(ap, fmt);
954 	r = vasprintf(&cp, fmt, ap);
955 	va_end(ap);
956 	if (r == -1)
957 		fatal("addargs: argument too long");
958 
959 	nalloc = args->nalloc;
960 	if (args->list == NULL) {
961 		nalloc = 32;
962 		args->num = 0;
963 	} else if (args->num+2 >= nalloc)
964 		nalloc *= 2;
965 
966 	args->list = xrecallocarray(args->list, args->nalloc, nalloc, sizeof(char *));
967 	args->nalloc = nalloc;
968 	args->list[args->num++] = cp;
969 	args->list[args->num] = NULL;
970 }
971 
972 void
973 replacearg(arglist *args, u_int which, char *fmt, ...)
974 {
975 	va_list ap;
976 	char *cp;
977 	int r;
978 
979 	va_start(ap, fmt);
980 	r = vasprintf(&cp, fmt, ap);
981 	va_end(ap);
982 	if (r == -1)
983 		fatal("replacearg: argument too long");
984 
985 	if (which >= args->num)
986 		fatal("replacearg: tried to replace invalid arg %d >= %d",
987 		    which, args->num);
988 	free(args->list[which]);
989 	args->list[which] = cp;
990 }
991 
992 void
993 freeargs(arglist *args)
994 {
995 	u_int i;
996 
997 	if (args->list != NULL) {
998 		for (i = 0; i < args->num; i++)
999 			free(args->list[i]);
1000 		free(args->list);
1001 		args->nalloc = args->num = 0;
1002 		args->list = NULL;
1003 	}
1004 }
1005 
1006 /*
1007  * Expands tildes in the file name.  Returns data allocated by xmalloc.
1008  * Warning: this calls getpw*.
1009  */
1010 char *
1011 tilde_expand_filename(const char *filename, uid_t uid)
1012 {
1013 	const char *path, *sep;
1014 	char user[128], *ret;
1015 	struct passwd *pw;
1016 	u_int len, slash;
1017 
1018 	if (*filename != '~')
1019 		return (xstrdup(filename));
1020 	filename++;
1021 
1022 	path = strchr(filename, '/');
1023 	if (path != NULL && path > filename) {		/* ~user/path */
1024 		slash = path - filename;
1025 		if (slash > sizeof(user) - 1)
1026 			fatal("tilde_expand_filename: ~username too long");
1027 		memcpy(user, filename, slash);
1028 		user[slash] = '\0';
1029 		if ((pw = getpwnam(user)) == NULL)
1030 			fatal("tilde_expand_filename: No such user %s", user);
1031 	} else if ((pw = getpwuid(uid)) == NULL)	/* ~/path */
1032 		fatal("tilde_expand_filename: No such uid %ld", (long)uid);
1033 
1034 	/* Make sure directory has a trailing '/' */
1035 	len = strlen(pw->pw_dir);
1036 	if (len == 0 || pw->pw_dir[len - 1] != '/')
1037 		sep = "/";
1038 	else
1039 		sep = "";
1040 
1041 	/* Skip leading '/' from specified path */
1042 	if (path != NULL)
1043 		filename = path + 1;
1044 
1045 	if (xasprintf(&ret, "%s%s%s", pw->pw_dir, sep, filename) >= PATH_MAX)
1046 		fatal("tilde_expand_filename: Path too long");
1047 
1048 	return (ret);
1049 }
1050 
1051 /*
1052  * Expand a string with a set of %[char] escapes and/or ${ENVIRONMENT}
1053  * substitutions.  A number of escapes may be specified as
1054  * (char *escape_chars, char *replacement) pairs. The list must be terminated
1055  * by a NULL escape_char. Returns replaced string in memory allocated by
1056  * xmalloc which the caller must free.
1057  */
1058 static char *
1059 vdollar_percent_expand(int *parseerror, int dollar, int percent,
1060     const char *string, va_list ap)
1061 {
1062 #define EXPAND_MAX_KEYS	16
1063 	u_int num_keys = 0, i;
1064 	struct {
1065 		const char *key;
1066 		const char *repl;
1067 	} keys[EXPAND_MAX_KEYS];
1068 	struct sshbuf *buf;
1069 	int r, missingvar = 0;
1070 	char *ret = NULL, *var, *varend, *val;
1071 	size_t len;
1072 
1073 	if ((buf = sshbuf_new()) == NULL)
1074 		fatal("%s: sshbuf_new failed", __func__);
1075 	if (parseerror == NULL)
1076 		fatal("%s: null parseerror arg", __func__);
1077 	*parseerror = 1;
1078 
1079 	/* Gather keys if we're doing percent expansion. */
1080 	if (percent) {
1081 		for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
1082 			keys[num_keys].key = va_arg(ap, char *);
1083 			if (keys[num_keys].key == NULL)
1084 				break;
1085 			keys[num_keys].repl = va_arg(ap, char *);
1086 			if (keys[num_keys].repl == NULL)
1087 				fatal("%s: NULL replacement for token %s", __func__, keys[num_keys].key);
1088 		}
1089 		if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
1090 			fatal("%s: too many keys", __func__);
1091 		if (num_keys == 0)
1092 			fatal("%s: percent expansion without token list",
1093 			    __func__);
1094 	}
1095 
1096 	/* Expand string */
1097 	for (i = 0; *string != '\0'; string++) {
1098 		/* Optionally process ${ENVIRONMENT} expansions. */
1099 		if (dollar && string[0] == '$' && string[1] == '{') {
1100 			string += 2;  /* skip over '${' */
1101 			if ((varend = strchr(string, '}')) == NULL) {
1102 				error("%s: environment variable '%s' missing "
1103 				   "closing '}'", __func__, string);
1104 				goto out;
1105 			}
1106 			len = varend - string;
1107 			if (len == 0) {
1108 				error("%s: zero-length environment variable",
1109 				    __func__);
1110 				goto out;
1111 			}
1112 			var = xmalloc(len + 1);
1113 			(void)strlcpy(var, string, len + 1);
1114 			if ((val = getenv(var)) == NULL) {
1115 				error("%s: env var ${%s} has no value",
1116 				    __func__, var);
1117 				missingvar = 1;
1118 			} else {
1119 				debug3("%s: expand ${%s} -> '%s'", __func__,
1120 				    var, val);
1121 				if ((r = sshbuf_put(buf, val, strlen(val))) !=0)
1122 					fatal("%s: sshbuf_put: %s", __func__,
1123 					    ssh_err(r));
1124 			}
1125 			free(var);
1126 			string += len;
1127 			continue;
1128 		}
1129 
1130 		/*
1131 		 * Process percent expansions if we have a list of TOKENs.
1132 		 * If we're not doing percent expansion everything just gets
1133 		 * appended here.
1134 		 */
1135 		if (*string != '%' || !percent) {
1136  append:
1137 			if ((r = sshbuf_put_u8(buf, *string)) != 0) {
1138 				fatal("%s: sshbuf_put_u8: %s",
1139 				    __func__, ssh_err(r));
1140 			}
1141 			continue;
1142 		}
1143 		string++;
1144 		/* %% case */
1145 		if (*string == '%')
1146 			goto append;
1147 		if (*string == '\0') {
1148 			error("%s: invalid format", __func__);
1149 			goto out;
1150 		}
1151 		for (i = 0; i < num_keys; i++) {
1152 			if (strchr(keys[i].key, *string) != NULL) {
1153 				if ((r = sshbuf_put(buf, keys[i].repl,
1154 				    strlen(keys[i].repl))) != 0) {
1155 					fatal("%s: sshbuf_put: %s",
1156 					    __func__, ssh_err(r));
1157 				}
1158 				break;
1159 			}
1160 		}
1161 		if (i >= num_keys) {
1162 			error("%s: unknown key %%%c", __func__, *string);
1163 			goto out;
1164 		}
1165 	}
1166 	if (!missingvar && (ret = sshbuf_dup_string(buf)) == NULL)
1167 		fatal("%s: sshbuf_dup_string failed", __func__);
1168 	*parseerror = 0;
1169  out:
1170 	sshbuf_free(buf);
1171 	return *parseerror ? NULL : ret;
1172 #undef EXPAND_MAX_KEYS
1173 }
1174 
1175 /*
1176  * Expand only environment variables.
1177  * Note that although this function is variadic like the other similar
1178  * functions, any such arguments will be unused.
1179  */
1180 
1181 char *
1182 dollar_expand(int *parseerr, const char *string, ...)
1183 {
1184 	char *ret;
1185 	int err;
1186 	va_list ap;
1187 
1188 	va_start(ap, string);
1189 	ret = vdollar_percent_expand(&err, 1, 0, string, ap);
1190 	va_end(ap);
1191 	if (parseerr != NULL)
1192 		*parseerr = err;
1193 	return ret;
1194 }
1195 
1196 /*
1197  * Returns expanded string or NULL if a specified environment variable is
1198  * not defined, or calls fatal if the string is invalid.
1199  */
1200 char *
1201 percent_expand(const char *string, ...)
1202 {
1203 	char *ret;
1204 	int err;
1205 	va_list ap;
1206 
1207 	va_start(ap, string);
1208 	ret = vdollar_percent_expand(&err, 0, 1, string, ap);
1209 	va_end(ap);
1210 	if (err)
1211 		fatal("%s failed", __func__);
1212 	return ret;
1213 }
1214 
1215 /*
1216  * Returns expanded string or NULL if a specified environment variable is
1217  * not defined, or calls fatal if the string is invalid.
1218  */
1219 char *
1220 percent_dollar_expand(const char *string, ...)
1221 {
1222 	char *ret;
1223 	int err;
1224 	va_list ap;
1225 
1226 	va_start(ap, string);
1227 	ret = vdollar_percent_expand(&err, 1, 1, string, ap);
1228 	va_end(ap);
1229 	if (err)
1230 		fatal("%s failed", __func__);
1231 	return ret;
1232 }
1233 
1234 int
1235 tun_open(int tun, int mode, char **ifname)
1236 {
1237 	struct ifreq ifr;
1238 	char name[100];
1239 	int fd = -1, sock;
1240 	const char *tunbase = "tun";
1241 
1242 	if (ifname != NULL)
1243 		*ifname = NULL;
1244 
1245 	if (mode == SSH_TUNMODE_ETHERNET)
1246 		tunbase = "tap";
1247 
1248 	/* Open the tunnel device */
1249 	if (tun <= SSH_TUNID_MAX) {
1250 		snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
1251 		fd = open(name, O_RDWR);
1252 	} else if (tun == SSH_TUNID_ANY) {
1253 		for (tun = 100; tun >= 0; tun--) {
1254 			snprintf(name, sizeof(name), "/dev/%s%d",
1255 			    tunbase, tun);
1256 			if ((fd = open(name, O_RDWR)) >= 0)
1257 				break;
1258 		}
1259 	} else {
1260 		debug("%s: invalid tunnel %u", __func__, tun);
1261 		return -1;
1262 	}
1263 
1264 	if (fd == -1) {
1265 		debug("%s: %s open: %s", __func__, name, strerror(errno));
1266 		return -1;
1267 	}
1268 
1269 	debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
1270 
1271 	/* Bring interface up if it is not already */
1272 	snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
1273 	if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
1274 		goto failed;
1275 
1276 	if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
1277 		debug("%s: get interface %s flags: %s", __func__,
1278 		    ifr.ifr_name, strerror(errno));
1279 		goto failed;
1280 	}
1281 
1282 	if (!(ifr.ifr_flags & IFF_UP)) {
1283 		ifr.ifr_flags |= IFF_UP;
1284 		if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
1285 			debug("%s: activate interface %s: %s", __func__,
1286 			    ifr.ifr_name, strerror(errno));
1287 			goto failed;
1288 		}
1289 	}
1290 
1291 	if (ifname != NULL)
1292 		*ifname = xstrdup(ifr.ifr_name);
1293 
1294 	close(sock);
1295 	return fd;
1296 
1297  failed:
1298 	if (fd >= 0)
1299 		close(fd);
1300 	if (sock >= 0)
1301 		close(sock);
1302 	return -1;
1303 }
1304 
1305 void
1306 sanitise_stdfd(void)
1307 {
1308 	int nullfd, dupfd;
1309 
1310 	if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1311 		fprintf(stderr, "Couldn't open /dev/null: %s\n",
1312 		    strerror(errno));
1313 		exit(1);
1314 	}
1315 	while (++dupfd <= STDERR_FILENO) {
1316 		/* Only populate closed fds. */
1317 		if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
1318 			if (dup2(nullfd, dupfd) == -1) {
1319 				fprintf(stderr, "dup2: %s\n", strerror(errno));
1320 				exit(1);
1321 			}
1322 		}
1323 	}
1324 	if (nullfd > STDERR_FILENO)
1325 		close(nullfd);
1326 }
1327 
1328 char *
1329 tohex(const void *vp, size_t l)
1330 {
1331 	const u_char *p = (const u_char *)vp;
1332 	char b[3], *r;
1333 	size_t i, hl;
1334 
1335 	if (l > 65536)
1336 		return xstrdup("tohex: length > 65536");
1337 
1338 	hl = l * 2 + 1;
1339 	r = xcalloc(1, hl);
1340 	for (i = 0; i < l; i++) {
1341 		snprintf(b, sizeof(b), "%02x", p[i]);
1342 		strlcat(r, b, hl);
1343 	}
1344 	return (r);
1345 }
1346 
1347 /*
1348  * Extend string *sp by the specified format. If *sp is not NULL (or empty),
1349  * then the separator 'sep' will be prepended before the formatted arguments.
1350  * Extended strings are heap allocated.
1351  */
1352 void
1353 xextendf(char **sp, const char *sep, const char *fmt, ...)
1354 {
1355 	va_list ap;
1356 	char *tmp1, *tmp2;
1357 
1358 	va_start(ap, fmt);
1359 	xvasprintf(&tmp1, fmt, ap);
1360 	va_end(ap);
1361 
1362 	if (*sp == NULL || **sp == '\0') {
1363 		free(*sp);
1364 		*sp = tmp1;
1365 		return;
1366 	}
1367 	xasprintf(&tmp2, "%s%s%s", *sp, sep == NULL ? "" : sep, tmp1);
1368 	free(tmp1);
1369 	free(*sp);
1370 	*sp = tmp2;
1371 }
1372 
1373 
1374 u_int64_t
1375 get_u64(const void *vp)
1376 {
1377 	const u_char *p = (const u_char *)vp;
1378 	u_int64_t v;
1379 
1380 	v  = (u_int64_t)p[0] << 56;
1381 	v |= (u_int64_t)p[1] << 48;
1382 	v |= (u_int64_t)p[2] << 40;
1383 	v |= (u_int64_t)p[3] << 32;
1384 	v |= (u_int64_t)p[4] << 24;
1385 	v |= (u_int64_t)p[5] << 16;
1386 	v |= (u_int64_t)p[6] << 8;
1387 	v |= (u_int64_t)p[7];
1388 
1389 	return (v);
1390 }
1391 
1392 u_int32_t
1393 get_u32(const void *vp)
1394 {
1395 	const u_char *p = (const u_char *)vp;
1396 	u_int32_t v;
1397 
1398 	v  = (u_int32_t)p[0] << 24;
1399 	v |= (u_int32_t)p[1] << 16;
1400 	v |= (u_int32_t)p[2] << 8;
1401 	v |= (u_int32_t)p[3];
1402 
1403 	return (v);
1404 }
1405 
1406 u_int32_t
1407 get_u32_le(const void *vp)
1408 {
1409 	const u_char *p = (const u_char *)vp;
1410 	u_int32_t v;
1411 
1412 	v  = (u_int32_t)p[0];
1413 	v |= (u_int32_t)p[1] << 8;
1414 	v |= (u_int32_t)p[2] << 16;
1415 	v |= (u_int32_t)p[3] << 24;
1416 
1417 	return (v);
1418 }
1419 
1420 u_int16_t
1421 get_u16(const void *vp)
1422 {
1423 	const u_char *p = (const u_char *)vp;
1424 	u_int16_t v;
1425 
1426 	v  = (u_int16_t)p[0] << 8;
1427 	v |= (u_int16_t)p[1];
1428 
1429 	return (v);
1430 }
1431 
1432 void
1433 put_u64(void *vp, u_int64_t v)
1434 {
1435 	u_char *p = (u_char *)vp;
1436 
1437 	p[0] = (u_char)(v >> 56) & 0xff;
1438 	p[1] = (u_char)(v >> 48) & 0xff;
1439 	p[2] = (u_char)(v >> 40) & 0xff;
1440 	p[3] = (u_char)(v >> 32) & 0xff;
1441 	p[4] = (u_char)(v >> 24) & 0xff;
1442 	p[5] = (u_char)(v >> 16) & 0xff;
1443 	p[6] = (u_char)(v >> 8) & 0xff;
1444 	p[7] = (u_char)v & 0xff;
1445 }
1446 
1447 void
1448 put_u32(void *vp, u_int32_t v)
1449 {
1450 	u_char *p = (u_char *)vp;
1451 
1452 	p[0] = (u_char)(v >> 24) & 0xff;
1453 	p[1] = (u_char)(v >> 16) & 0xff;
1454 	p[2] = (u_char)(v >> 8) & 0xff;
1455 	p[3] = (u_char)v & 0xff;
1456 }
1457 
1458 void
1459 put_u32_le(void *vp, u_int32_t v)
1460 {
1461 	u_char *p = (u_char *)vp;
1462 
1463 	p[0] = (u_char)v & 0xff;
1464 	p[1] = (u_char)(v >> 8) & 0xff;
1465 	p[2] = (u_char)(v >> 16) & 0xff;
1466 	p[3] = (u_char)(v >> 24) & 0xff;
1467 }
1468 
1469 void
1470 put_u16(void *vp, u_int16_t v)
1471 {
1472 	u_char *p = (u_char *)vp;
1473 
1474 	p[0] = (u_char)(v >> 8) & 0xff;
1475 	p[1] = (u_char)v & 0xff;
1476 }
1477 
1478 void
1479 ms_subtract_diff(struct timeval *start, int *ms)
1480 {
1481 	struct timeval diff, finish;
1482 
1483 	monotime_tv(&finish);
1484 	timersub(&finish, start, &diff);
1485 	*ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
1486 }
1487 
1488 void
1489 ms_to_timeval(struct timeval *tv, int ms)
1490 {
1491 	if (ms < 0)
1492 		ms = 0;
1493 	tv->tv_sec = ms / 1000;
1494 	tv->tv_usec = (ms % 1000) * 1000;
1495 }
1496 
1497 void
1498 monotime_ts(struct timespec *ts)
1499 {
1500 	if (clock_gettime(CLOCK_MONOTONIC, ts) != 0)
1501 		fatal("clock_gettime: %s", strerror(errno));
1502 }
1503 
1504 void
1505 monotime_tv(struct timeval *tv)
1506 {
1507 	struct timespec ts;
1508 
1509 	monotime_ts(&ts);
1510 	tv->tv_sec = ts.tv_sec;
1511 	tv->tv_usec = ts.tv_nsec / 1000;
1512 }
1513 
1514 time_t
1515 monotime(void)
1516 {
1517 	struct timespec ts;
1518 
1519 	monotime_ts(&ts);
1520 	return (ts.tv_sec);
1521 }
1522 
1523 double
1524 monotime_double(void)
1525 {
1526 	struct timespec ts;
1527 
1528 	monotime_ts(&ts);
1529 	return (double)ts.tv_sec + (double)ts.tv_nsec / 1000000000.0;
1530 }
1531 
1532 void
1533 bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
1534 {
1535 	bw->buflen = buflen;
1536 	bw->rate = kbps;
1537 	bw->thresh = buflen;
1538 	bw->lamt = 0;
1539 	timerclear(&bw->bwstart);
1540 	timerclear(&bw->bwend);
1541 }
1542 
1543 /* Callback from read/write loop to insert bandwidth-limiting delays */
1544 void
1545 bandwidth_limit(struct bwlimit *bw, size_t read_len)
1546 {
1547 	u_int64_t waitlen;
1548 	struct timespec ts, rm;
1549 
1550 	bw->lamt += read_len;
1551 	if (!timerisset(&bw->bwstart)) {
1552 		monotime_tv(&bw->bwstart);
1553 		return;
1554 	}
1555 	if (bw->lamt < bw->thresh)
1556 		return;
1557 
1558 	monotime_tv(&bw->bwend);
1559 	timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
1560 	if (!timerisset(&bw->bwend))
1561 		return;
1562 
1563 	bw->lamt *= 8;
1564 	waitlen = (double)1000000L * bw->lamt / bw->rate;
1565 
1566 	bw->bwstart.tv_sec = waitlen / 1000000L;
1567 	bw->bwstart.tv_usec = waitlen % 1000000L;
1568 
1569 	if (timercmp(&bw->bwstart, &bw->bwend, >)) {
1570 		timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
1571 
1572 		/* Adjust the wait time */
1573 		if (bw->bwend.tv_sec) {
1574 			bw->thresh /= 2;
1575 			if (bw->thresh < bw->buflen / 4)
1576 				bw->thresh = bw->buflen / 4;
1577 		} else if (bw->bwend.tv_usec < 10000) {
1578 			bw->thresh *= 2;
1579 			if (bw->thresh > bw->buflen * 8)
1580 				bw->thresh = bw->buflen * 8;
1581 		}
1582 
1583 		TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
1584 		while (nanosleep(&ts, &rm) == -1) {
1585 			if (errno != EINTR)
1586 				break;
1587 			ts = rm;
1588 		}
1589 	}
1590 
1591 	bw->lamt = 0;
1592 	monotime_tv(&bw->bwstart);
1593 }
1594 
1595 /* Make a template filename for mk[sd]temp() */
1596 void
1597 mktemp_proto(char *s, size_t len)
1598 {
1599 	const char *tmpdir;
1600 	int r;
1601 
1602 	if ((tmpdir = getenv("TMPDIR")) != NULL) {
1603 		r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
1604 		if (r > 0 && (size_t)r < len)
1605 			return;
1606 	}
1607 	r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
1608 	if (r < 0 || (size_t)r >= len)
1609 		fatal("%s: template string too short", __func__);
1610 }
1611 
1612 static const struct {
1613 	const char *name;
1614 	int value;
1615 } ipqos[] = {
1616 	{ "none", INT_MAX },		/* can't use 0 here; that's CS0 */
1617 	{ "af11", IPTOS_DSCP_AF11 },
1618 	{ "af12", IPTOS_DSCP_AF12 },
1619 	{ "af13", IPTOS_DSCP_AF13 },
1620 	{ "af21", IPTOS_DSCP_AF21 },
1621 	{ "af22", IPTOS_DSCP_AF22 },
1622 	{ "af23", IPTOS_DSCP_AF23 },
1623 	{ "af31", IPTOS_DSCP_AF31 },
1624 	{ "af32", IPTOS_DSCP_AF32 },
1625 	{ "af33", IPTOS_DSCP_AF33 },
1626 	{ "af41", IPTOS_DSCP_AF41 },
1627 	{ "af42", IPTOS_DSCP_AF42 },
1628 	{ "af43", IPTOS_DSCP_AF43 },
1629 	{ "cs0", IPTOS_DSCP_CS0 },
1630 	{ "cs1", IPTOS_DSCP_CS1 },
1631 	{ "cs2", IPTOS_DSCP_CS2 },
1632 	{ "cs3", IPTOS_DSCP_CS3 },
1633 	{ "cs4", IPTOS_DSCP_CS4 },
1634 	{ "cs5", IPTOS_DSCP_CS5 },
1635 	{ "cs6", IPTOS_DSCP_CS6 },
1636 	{ "cs7", IPTOS_DSCP_CS7 },
1637 	{ "ef", IPTOS_DSCP_EF },
1638 	{ "le", IPTOS_DSCP_LE },
1639 	{ "lowdelay", IPTOS_LOWDELAY },
1640 	{ "throughput", IPTOS_THROUGHPUT },
1641 	{ "reliability", IPTOS_RELIABILITY },
1642 	{ NULL, -1 }
1643 };
1644 
1645 int
1646 parse_ipqos(const char *cp)
1647 {
1648 	u_int i;
1649 	char *ep;
1650 	long val;
1651 
1652 	if (cp == NULL)
1653 		return -1;
1654 	for (i = 0; ipqos[i].name != NULL; i++) {
1655 		if (strcasecmp(cp, ipqos[i].name) == 0)
1656 			return ipqos[i].value;
1657 	}
1658 	/* Try parsing as an integer */
1659 	val = strtol(cp, &ep, 0);
1660 	if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1661 		return -1;
1662 	return val;
1663 }
1664 
1665 const char *
1666 iptos2str(int iptos)
1667 {
1668 	int i;
1669 	static char iptos_str[sizeof "0xff"];
1670 
1671 	for (i = 0; ipqos[i].name != NULL; i++) {
1672 		if (ipqos[i].value == iptos)
1673 			return ipqos[i].name;
1674 	}
1675 	snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1676 	return iptos_str;
1677 }
1678 
1679 void
1680 lowercase(char *s)
1681 {
1682 	for (; *s; s++)
1683 		*s = tolower((u_char)*s);
1684 }
1685 
1686 int
1687 unix_listener(const char *path, int backlog, int unlink_first)
1688 {
1689 	struct sockaddr_un sunaddr;
1690 	int saved_errno, sock;
1691 
1692 	memset(&sunaddr, 0, sizeof(sunaddr));
1693 	sunaddr.sun_family = AF_UNIX;
1694 	if (strlcpy(sunaddr.sun_path, path,
1695 	    sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1696 		error("%s: path \"%s\" too long for Unix domain socket",
1697 		    __func__, path);
1698 		errno = ENAMETOOLONG;
1699 		return -1;
1700 	}
1701 
1702 	sock = socket(PF_UNIX, SOCK_STREAM, 0);
1703 	if (sock == -1) {
1704 		saved_errno = errno;
1705 		error("%s: socket: %.100s", __func__, strerror(errno));
1706 		errno = saved_errno;
1707 		return -1;
1708 	}
1709 	if (unlink_first == 1) {
1710 		if (unlink(path) != 0 && errno != ENOENT)
1711 			error("unlink(%s): %.100s", path, strerror(errno));
1712 	}
1713 	if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1714 		saved_errno = errno;
1715 		error("%s: cannot bind to path %s: %s",
1716 		    __func__, path, strerror(errno));
1717 		close(sock);
1718 		errno = saved_errno;
1719 		return -1;
1720 	}
1721 	if (listen(sock, backlog) == -1) {
1722 		saved_errno = errno;
1723 		error("%s: cannot listen on path %s: %s",
1724 		    __func__, path, strerror(errno));
1725 		close(sock);
1726 		unlink(path);
1727 		errno = saved_errno;
1728 		return -1;
1729 	}
1730 	return sock;
1731 }
1732 
1733 /*
1734  * Compares two strings that maybe be NULL. Returns non-zero if strings
1735  * are both NULL or are identical, returns zero otherwise.
1736  */
1737 static int
1738 strcmp_maybe_null(const char *a, const char *b)
1739 {
1740 	if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1741 		return 0;
1742 	if (a != NULL && strcmp(a, b) != 0)
1743 		return 0;
1744 	return 1;
1745 }
1746 
1747 /*
1748  * Compare two forwards, returning non-zero if they are identical or
1749  * zero otherwise.
1750  */
1751 int
1752 forward_equals(const struct Forward *a, const struct Forward *b)
1753 {
1754 	if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
1755 		return 0;
1756 	if (a->listen_port != b->listen_port)
1757 		return 0;
1758 	if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
1759 		return 0;
1760 	if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
1761 		return 0;
1762 	if (a->connect_port != b->connect_port)
1763 		return 0;
1764 	if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
1765 		return 0;
1766 	/* allocated_port and handle are not checked */
1767 	return 1;
1768 }
1769 
1770 /* returns 1 if process is already daemonized, 0 otherwise */
1771 int
1772 daemonized(void)
1773 {
1774 	int fd;
1775 
1776 	if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
1777 		close(fd);
1778 		return 0;	/* have controlling terminal */
1779 	}
1780 	if (getppid() != 1)
1781 		return 0;	/* parent is not init */
1782 	if (getsid(0) != getpid())
1783 		return 0;	/* not session leader */
1784 	debug3("already daemonized");
1785 	return 1;
1786 }
1787 
1788 
1789 /*
1790  * Splits 's' into an argument vector. Handles quoted string and basic
1791  * escape characters (\\, \", \'). Caller must free the argument vector
1792  * and its members.
1793  */
1794 int
1795 argv_split(const char *s, int *argcp, char ***argvp)
1796 {
1797 	int r = SSH_ERR_INTERNAL_ERROR;
1798 	int argc = 0, quote, i, j;
1799 	char *arg, **argv = xcalloc(1, sizeof(*argv));
1800 
1801 	*argvp = NULL;
1802 	*argcp = 0;
1803 
1804 	for (i = 0; s[i] != '\0'; i++) {
1805 		/* Skip leading whitespace */
1806 		if (s[i] == ' ' || s[i] == '\t')
1807 			continue;
1808 
1809 		/* Start of a token */
1810 		quote = 0;
1811 		if (s[i] == '\\' &&
1812 		    (s[i + 1] == '\'' || s[i + 1] == '\"' || s[i + 1] == '\\'))
1813 			i++;
1814 		else if (s[i] == '\'' || s[i] == '"')
1815 			quote = s[i++];
1816 
1817 		argv = xreallocarray(argv, (argc + 2), sizeof(*argv));
1818 		arg = argv[argc++] = xcalloc(1, strlen(s + i) + 1);
1819 		argv[argc] = NULL;
1820 
1821 		/* Copy the token in, removing escapes */
1822 		for (j = 0; s[i] != '\0'; i++) {
1823 			if (s[i] == '\\') {
1824 				if (s[i + 1] == '\'' ||
1825 				    s[i + 1] == '\"' ||
1826 				    s[i + 1] == '\\') {
1827 					i++; /* Skip '\' */
1828 					arg[j++] = s[i];
1829 				} else {
1830 					/* Unrecognised escape */
1831 					arg[j++] = s[i];
1832 				}
1833 			} else if (quote == 0 && (s[i] == ' ' || s[i] == '\t'))
1834 				break; /* done */
1835 			else if (quote != 0 && s[i] == quote)
1836 				break; /* done */
1837 			else
1838 				arg[j++] = s[i];
1839 		}
1840 		if (s[i] == '\0') {
1841 			if (quote != 0) {
1842 				/* Ran out of string looking for close quote */
1843 				r = SSH_ERR_INVALID_FORMAT;
1844 				goto out;
1845 			}
1846 			break;
1847 		}
1848 	}
1849 	/* Success */
1850 	*argcp = argc;
1851 	*argvp = argv;
1852 	argc = 0;
1853 	argv = NULL;
1854 	r = 0;
1855  out:
1856 	if (argc != 0 && argv != NULL) {
1857 		for (i = 0; i < argc; i++)
1858 			free(argv[i]);
1859 		free(argv);
1860 	}
1861 	return r;
1862 }
1863 
1864 /*
1865  * Reassemble an argument vector into a string, quoting and escaping as
1866  * necessary. Caller must free returned string.
1867  */
1868 char *
1869 argv_assemble(int argc, char **argv)
1870 {
1871 	int i, j, ws, r;
1872 	char c, *ret;
1873 	struct sshbuf *buf, *arg;
1874 
1875 	if ((buf = sshbuf_new()) == NULL || (arg = sshbuf_new()) == NULL)
1876 		fatal("%s: sshbuf_new failed", __func__);
1877 
1878 	for (i = 0; i < argc; i++) {
1879 		ws = 0;
1880 		sshbuf_reset(arg);
1881 		for (j = 0; argv[i][j] != '\0'; j++) {
1882 			r = 0;
1883 			c = argv[i][j];
1884 			switch (c) {
1885 			case ' ':
1886 			case '\t':
1887 				ws = 1;
1888 				r = sshbuf_put_u8(arg, c);
1889 				break;
1890 			case '\\':
1891 			case '\'':
1892 			case '"':
1893 				if ((r = sshbuf_put_u8(arg, '\\')) != 0)
1894 					break;
1895 				/* FALLTHROUGH */
1896 			default:
1897 				r = sshbuf_put_u8(arg, c);
1898 				break;
1899 			}
1900 			if (r != 0)
1901 				fatal("%s: sshbuf_put_u8: %s",
1902 				    __func__, ssh_err(r));
1903 		}
1904 		if ((i != 0 && (r = sshbuf_put_u8(buf, ' ')) != 0) ||
1905 		    (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0) ||
1906 		    (r = sshbuf_putb(buf, arg)) != 0 ||
1907 		    (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0))
1908 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
1909 	}
1910 	if ((ret = malloc(sshbuf_len(buf) + 1)) == NULL)
1911 		fatal("%s: malloc failed", __func__);
1912 	memcpy(ret, sshbuf_ptr(buf), sshbuf_len(buf));
1913 	ret[sshbuf_len(buf)] = '\0';
1914 	sshbuf_free(buf);
1915 	sshbuf_free(arg);
1916 	return ret;
1917 }
1918 
1919 /* Returns 0 if pid exited cleanly, non-zero otherwise */
1920 int
1921 exited_cleanly(pid_t pid, const char *tag, const char *cmd, int quiet)
1922 {
1923 	int status;
1924 
1925 	while (waitpid(pid, &status, 0) == -1) {
1926 		if (errno != EINTR) {
1927 			error("%s: waitpid: %s", tag, strerror(errno));
1928 			return -1;
1929 		}
1930 	}
1931 	if (WIFSIGNALED(status)) {
1932 		error("%s %s exited on signal %d", tag, cmd, WTERMSIG(status));
1933 		return -1;
1934 	} else if (WEXITSTATUS(status) != 0) {
1935 		do_log2(quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_INFO,
1936 		    "%s %s failed, status %d", tag, cmd, WEXITSTATUS(status));
1937 		return -1;
1938 	}
1939 	return 0;
1940 }
1941 
1942 /*
1943  * Check a given path for security. This is defined as all components
1944  * of the path to the file must be owned by either the owner of
1945  * of the file or root and no directories must be group or world writable.
1946  *
1947  * XXX Should any specific check be done for sym links ?
1948  *
1949  * Takes a file name, its stat information (preferably from fstat() to
1950  * avoid races), the uid of the expected owner, their home directory and an
1951  * error buffer plus max size as arguments.
1952  *
1953  * Returns 0 on success and -1 on failure
1954  */
1955 int
1956 safe_path(const char *name, struct stat *stp, const char *pw_dir,
1957     uid_t uid, char *err, size_t errlen)
1958 {
1959 	char buf[PATH_MAX], homedir[PATH_MAX];
1960 	char *cp;
1961 	int comparehome = 0;
1962 	struct stat st;
1963 
1964 	if (realpath(name, buf) == NULL) {
1965 		snprintf(err, errlen, "realpath %s failed: %s", name,
1966 		    strerror(errno));
1967 		return -1;
1968 	}
1969 	if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL)
1970 		comparehome = 1;
1971 
1972 	if (!S_ISREG(stp->st_mode)) {
1973 		snprintf(err, errlen, "%s is not a regular file", buf);
1974 		return -1;
1975 	}
1976 	if ((stp->st_uid != 0 && stp->st_uid != uid) ||
1977 	    (stp->st_mode & 022) != 0) {
1978 		snprintf(err, errlen, "bad ownership or modes for file %s",
1979 		    buf);
1980 		return -1;
1981 	}
1982 
1983 	/* for each component of the canonical path, walking upwards */
1984 	for (;;) {
1985 		if ((cp = dirname(buf)) == NULL) {
1986 			snprintf(err, errlen, "dirname() failed");
1987 			return -1;
1988 		}
1989 		strlcpy(buf, cp, sizeof(buf));
1990 
1991 		if (stat(buf, &st) == -1 ||
1992 		    (st.st_uid != 0 && st.st_uid != uid) ||
1993 		    (st.st_mode & 022) != 0) {
1994 			snprintf(err, errlen,
1995 			    "bad ownership or modes for directory %s", buf);
1996 			return -1;
1997 		}
1998 
1999 		/* If are past the homedir then we can stop */
2000 		if (comparehome && strcmp(homedir, buf) == 0)
2001 			break;
2002 
2003 		/*
2004 		 * dirname should always complete with a "/" path,
2005 		 * but we can be paranoid and check for "." too
2006 		 */
2007 		if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
2008 			break;
2009 	}
2010 	return 0;
2011 }
2012 
2013 /*
2014  * Version of safe_path() that accepts an open file descriptor to
2015  * avoid races.
2016  *
2017  * Returns 0 on success and -1 on failure
2018  */
2019 int
2020 safe_path_fd(int fd, const char *file, struct passwd *pw,
2021     char *err, size_t errlen)
2022 {
2023 	struct stat st;
2024 
2025 	/* check the open file to avoid races */
2026 	if (fstat(fd, &st) == -1) {
2027 		snprintf(err, errlen, "cannot stat file %s: %s",
2028 		    file, strerror(errno));
2029 		return -1;
2030 	}
2031 	return safe_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen);
2032 }
2033 
2034 /*
2035  * Sets the value of the given variable in the environment.  If the variable
2036  * already exists, its value is overridden.
2037  */
2038 void
2039 child_set_env(char ***envp, u_int *envsizep, const char *name,
2040 	const char *value)
2041 {
2042 	char **env;
2043 	u_int envsize;
2044 	u_int i, namelen;
2045 
2046 	if (strchr(name, '=') != NULL) {
2047 		error("Invalid environment variable \"%.100s\"", name);
2048 		return;
2049 	}
2050 
2051 	/*
2052 	 * Find the slot where the value should be stored.  If the variable
2053 	 * already exists, we reuse the slot; otherwise we append a new slot
2054 	 * at the end of the array, expanding if necessary.
2055 	 */
2056 	env = *envp;
2057 	namelen = strlen(name);
2058 	for (i = 0; env[i]; i++)
2059 		if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
2060 			break;
2061 	if (env[i]) {
2062 		/* Reuse the slot. */
2063 		free(env[i]);
2064 	} else {
2065 		/* New variable.  Expand if necessary. */
2066 		envsize = *envsizep;
2067 		if (i >= envsize - 1) {
2068 			if (envsize >= 1000)
2069 				fatal("child_set_env: too many env vars");
2070 			envsize += 50;
2071 			env = (*envp) = xreallocarray(env, envsize, sizeof(char *));
2072 			*envsizep = envsize;
2073 		}
2074 		/* Need to set the NULL pointer at end of array beyond the new slot. */
2075 		env[i + 1] = NULL;
2076 	}
2077 
2078 	/* Allocate space and format the variable in the appropriate slot. */
2079 	/* XXX xasprintf */
2080 	env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
2081 	snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
2082 }
2083 
2084 /*
2085  * Check and optionally lowercase a domain name, also removes trailing '.'
2086  * Returns 1 on success and 0 on failure, storing an error message in errstr.
2087  */
2088 int
2089 valid_domain(char *name, int makelower, const char **errstr)
2090 {
2091 	size_t i, l = strlen(name);
2092 	u_char c, last = '\0';
2093 	static char errbuf[256];
2094 
2095 	if (l == 0) {
2096 		strlcpy(errbuf, "empty domain name", sizeof(errbuf));
2097 		goto bad;
2098 	}
2099 	if (!isalpha((u_char)name[0]) && !isdigit((u_char)name[0])) {
2100 		snprintf(errbuf, sizeof(errbuf), "domain name \"%.100s\" "
2101 		    "starts with invalid character", name);
2102 		goto bad;
2103 	}
2104 	for (i = 0; i < l; i++) {
2105 		c = tolower((u_char)name[i]);
2106 		if (makelower)
2107 			name[i] = (char)c;
2108 		if (last == '.' && c == '.') {
2109 			snprintf(errbuf, sizeof(errbuf), "domain name "
2110 			    "\"%.100s\" contains consecutive separators", name);
2111 			goto bad;
2112 		}
2113 		if (c != '.' && c != '-' && !isalnum(c) &&
2114 		    c != '_') /* technically invalid, but common */ {
2115 			snprintf(errbuf, sizeof(errbuf), "domain name "
2116 			    "\"%.100s\" contains invalid characters", name);
2117 			goto bad;
2118 		}
2119 		last = c;
2120 	}
2121 	if (name[l - 1] == '.')
2122 		name[l - 1] = '\0';
2123 	if (errstr != NULL)
2124 		*errstr = NULL;
2125 	return 1;
2126 bad:
2127 	if (errstr != NULL)
2128 		*errstr = errbuf;
2129 	return 0;
2130 }
2131 
2132 /*
2133  * Verify that a environment variable name (not including initial '$') is
2134  * valid; consisting of one or more alphanumeric or underscore characters only.
2135  * Returns 1 on valid, 0 otherwise.
2136  */
2137 int
2138 valid_env_name(const char *name)
2139 {
2140 	const char *cp;
2141 
2142 	if (name[0] == '\0')
2143 		return 0;
2144 	for (cp = name; *cp != '\0'; cp++) {
2145 		if (!isalnum((u_char)*cp) && *cp != '_')
2146 			return 0;
2147 	}
2148 	return 1;
2149 }
2150 
2151 const char *
2152 atoi_err(const char *nptr, int *val)
2153 {
2154 	const char *errstr = NULL;
2155 	long long num;
2156 
2157 	if (nptr == NULL || *nptr == '\0')
2158 		return "missing";
2159 	num = strtonum(nptr, 0, INT_MAX, &errstr);
2160 	if (errstr == NULL)
2161 		*val = (int)num;
2162 	return errstr;
2163 }
2164 
2165 int
2166 parse_absolute_time(const char *s, uint64_t *tp)
2167 {
2168 	struct tm tm;
2169 	time_t tt;
2170 	char buf[32], *fmt;
2171 
2172 	*tp = 0;
2173 
2174 	/*
2175 	 * POSIX strptime says "The application shall ensure that there
2176 	 * is white-space or other non-alphanumeric characters between
2177 	 * any two conversion specifications" so arrange things this way.
2178 	 */
2179 	switch (strlen(s)) {
2180 	case 8: /* YYYYMMDD */
2181 		fmt = "%Y-%m-%d";
2182 		snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
2183 		break;
2184 	case 12: /* YYYYMMDDHHMM */
2185 		fmt = "%Y-%m-%dT%H:%M";
2186 		snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s",
2187 		    s, s + 4, s + 6, s + 8, s + 10);
2188 		break;
2189 	case 14: /* YYYYMMDDHHMMSS */
2190 		fmt = "%Y-%m-%dT%H:%M:%S";
2191 		snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
2192 		    s, s + 4, s + 6, s + 8, s + 10, s + 12);
2193 		break;
2194 	default:
2195 		return SSH_ERR_INVALID_FORMAT;
2196 	}
2197 
2198 	memset(&tm, 0, sizeof(tm));
2199 	if (strptime(buf, fmt, &tm) == NULL)
2200 		return SSH_ERR_INVALID_FORMAT;
2201 	if ((tt = mktime(&tm)) < 0)
2202 		return SSH_ERR_INVALID_FORMAT;
2203 	/* success */
2204 	*tp = (uint64_t)tt;
2205 	return 0;
2206 }
2207 
2208 void
2209 format_absolute_time(uint64_t t, char *buf, size_t len)
2210 {
2211 	time_t tt = t > INT_MAX ? INT_MAX : t; /* XXX revisit in 2038 :P */
2212 	struct tm tm;
2213 
2214 	localtime_r(&tt, &tm);
2215 	strftime(buf, len, "%Y-%m-%dT%H:%M:%S", &tm);
2216 }
2217 
2218 /* check if path is absolute */
2219 int
2220 path_absolute(const char *path)
2221 {
2222 	return (*path == '/') ? 1 : 0;
2223 }
2224 
2225 void
2226 skip_space(char **cpp)
2227 {
2228 	char *cp;
2229 
2230 	for (cp = *cpp; *cp == ' ' || *cp == '\t'; cp++)
2231 		;
2232 	*cpp = cp;
2233 }
2234 
2235 /* authorized_key-style options parsing helpers */
2236 
2237 /*
2238  * Match flag 'opt' in *optsp, and if allow_negate is set then also match
2239  * 'no-opt'. Returns -1 if option not matched, 1 if option matches or 0
2240  * if negated option matches.
2241  * If the option or negated option matches, then *optsp is updated to
2242  * point to the first character after the option.
2243  */
2244 int
2245 opt_flag(const char *opt, int allow_negate, const char **optsp)
2246 {
2247 	size_t opt_len = strlen(opt);
2248 	const char *opts = *optsp;
2249 	int negate = 0;
2250 
2251 	if (allow_negate && strncasecmp(opts, "no-", 3) == 0) {
2252 		opts += 3;
2253 		negate = 1;
2254 	}
2255 	if (strncasecmp(opts, opt, opt_len) == 0) {
2256 		*optsp = opts + opt_len;
2257 		return negate ? 0 : 1;
2258 	}
2259 	return -1;
2260 }
2261 
2262 char *
2263 opt_dequote(const char **sp, const char **errstrp)
2264 {
2265 	const char *s = *sp;
2266 	char *ret;
2267 	size_t i;
2268 
2269 	*errstrp = NULL;
2270 	if (*s != '"') {
2271 		*errstrp = "missing start quote";
2272 		return NULL;
2273 	}
2274 	s++;
2275 	if ((ret = malloc(strlen((s)) + 1)) == NULL) {
2276 		*errstrp = "memory allocation failed";
2277 		return NULL;
2278 	}
2279 	for (i = 0; *s != '\0' && *s != '"';) {
2280 		if (s[0] == '\\' && s[1] == '"')
2281 			s++;
2282 		ret[i++] = *s++;
2283 	}
2284 	if (*s == '\0') {
2285 		*errstrp = "missing end quote";
2286 		free(ret);
2287 		return NULL;
2288 	}
2289 	ret[i] = '\0';
2290 	s++;
2291 	*sp = s;
2292 	return ret;
2293 }
2294 
2295 int
2296 opt_match(const char **opts, const char *term)
2297 {
2298 	if (strncasecmp((*opts), term, strlen(term)) == 0 &&
2299 	    (*opts)[strlen(term)] == '=') {
2300 		*opts += strlen(term) + 1;
2301 		return 1;
2302 	}
2303 	return 0;
2304 }
2305 
2306 sshsig_t
2307 ssh_signal(int signum, sshsig_t handler)
2308 {
2309 	struct sigaction sa, osa;
2310 
2311 	/* mask all other signals while in handler */
2312 	memset(&sa, 0, sizeof(sa));
2313 	sa.sa_handler = handler;
2314 	sigfillset(&sa.sa_mask);
2315 	if (signum != SIGALRM)
2316 		sa.sa_flags = SA_RESTART;
2317 	if (sigaction(signum, &sa, &osa) == -1) {
2318 		debug3("sigaction(%s): %s", strsignal(signum), strerror(errno));
2319 		return SIG_ERR;
2320 	}
2321 	return osa.sa_handler;
2322 }
2323