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