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