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