xref: /openssh-portable/misc.c (revision f85b118d)
1 /* $OpenBSD: misc.c,v 1.151 2020/05/29 09:02:44 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 and/or ${ENVIRONMENT}
1088  * substitutions.  A number of escapes may be specified as
1089  * (char *escape_chars, char *replacement) pairs. The list must be terminated
1090  * by a NULL escape_char. Returns replaced string in memory allocated by
1091  * xmalloc which the caller must free.
1092  */
1093 static char *
1094 vdollar_percent_expand(int *parseerror, int dollar, int percent,
1095     const char *string, va_list ap)
1096 {
1097 #define EXPAND_MAX_KEYS	16
1098 	u_int num_keys = 0, i;
1099 	struct {
1100 		const char *key;
1101 		const char *repl;
1102 	} keys[EXPAND_MAX_KEYS];
1103 	struct sshbuf *buf;
1104 	int r, missingvar = 0;
1105 	char *ret = NULL, *var, *varend, *val;
1106 	size_t len;
1107 
1108 	if ((buf = sshbuf_new()) == NULL)
1109 		fatal("%s: sshbuf_new failed", __func__);
1110 	if (parseerror == NULL)
1111 		fatal("%s: null parseerror arg", __func__);
1112 	*parseerror = 1;
1113 
1114 	/* Gather keys if we're doing percent expansion. */
1115 	if (percent) {
1116 		for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
1117 			keys[num_keys].key = va_arg(ap, char *);
1118 			if (keys[num_keys].key == NULL)
1119 				break;
1120 			keys[num_keys].repl = va_arg(ap, char *);
1121 			if (keys[num_keys].repl == NULL)
1122 				fatal("%s: NULL replacement for token %s", __func__, keys[num_keys].key);
1123 		}
1124 		if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
1125 			fatal("%s: too many keys", __func__);
1126 		if (num_keys == 0)
1127 			fatal("%s: percent expansion without token list",
1128 			    __func__);
1129 	}
1130 
1131 	/* Expand string */
1132 	for (i = 0; *string != '\0'; string++) {
1133 		/* Optionally process ${ENVIRONMENT} expansions. */
1134 		if (dollar && string[0] == '$' && string[1] == '{') {
1135 			string += 2;  /* skip over '${' */
1136 			if ((varend = strchr(string, '}')) == NULL) {
1137 				error("%s: environment variable '%s' missing "
1138 				   "closing '}'", __func__, string);
1139 				goto out;
1140 			}
1141 			len = varend - string;
1142 			if (len == 0) {
1143 				error("%s: zero-length environment variable",
1144 				    __func__);
1145 				goto out;
1146 			}
1147 			var = xmalloc(len + 1);
1148 			(void)strlcpy(var, string, len + 1);
1149 			if ((val = getenv(var)) == NULL) {
1150 				error("%s: env var ${%s} has no value",
1151 				    __func__, var);
1152 				missingvar = 1;
1153 			} else {
1154 				debug3("%s: expand ${%s} -> '%s'", __func__,
1155 				    var, val);
1156 				if ((r = sshbuf_put(buf, val, strlen(val))) !=0)
1157 					fatal("%s: sshbuf_put: %s", __func__,
1158 					    ssh_err(r));
1159 			}
1160 			free(var);
1161 			string += len;
1162 			continue;
1163 		}
1164 
1165 		/*
1166 		 * Process percent expansions if we have a list of TOKENs.
1167 		 * If we're not doing percent expansion everything just gets
1168 		 * appended here.
1169 		 */
1170 		if (*string != '%' || !percent) {
1171  append:
1172 			if ((r = sshbuf_put_u8(buf, *string)) != 0) {
1173 				fatal("%s: sshbuf_put_u8: %s",
1174 				    __func__, ssh_err(r));
1175 			}
1176 			continue;
1177 		}
1178 		string++;
1179 		/* %% case */
1180 		if (*string == '%')
1181 			goto append;
1182 		if (*string == '\0') {
1183 			error("%s: invalid format", __func__);
1184 			goto out;
1185 		}
1186 		for (i = 0; i < num_keys; i++) {
1187 			if (strchr(keys[i].key, *string) != NULL) {
1188 				if ((r = sshbuf_put(buf, keys[i].repl,
1189 				    strlen(keys[i].repl))) != 0) {
1190 					fatal("%s: sshbuf_put: %s",
1191 					    __func__, ssh_err(r));
1192 				}
1193 				break;
1194 			}
1195 		}
1196 		if (i >= num_keys) {
1197 			error("%s: unknown key %%%c", __func__, *string);
1198 			goto out;
1199 		}
1200 	}
1201 	if (!missingvar && (ret = sshbuf_dup_string(buf)) == NULL)
1202 		fatal("%s: sshbuf_dup_string failed", __func__);
1203 	*parseerror = 0;
1204  out:
1205 	sshbuf_free(buf);
1206 	return *parseerror ? NULL : ret;
1207 #undef EXPAND_MAX_KEYS
1208 }
1209 
1210 char *
1211 dollar_expand(int *parseerr, const char *string)
1212 {
1213 	char *ret;
1214 	int err;
1215 
1216 	ret = vdollar_percent_expand(&err, 1, 0, string, NULL);
1217 	if (parseerr != NULL)
1218 		*parseerr = err;
1219 	return ret;
1220 }
1221 
1222 /*
1223  * Returns expanded string or NULL if a specified environment variable is
1224  * not defined, or calls fatal if the string is invalid.
1225  */
1226 char *
1227 percent_expand(const char *string, ...)
1228 {
1229 	char *ret;
1230 	int err;
1231 	va_list ap;
1232 
1233 	va_start(ap, string);
1234 	ret = vdollar_percent_expand(&err, 0, 1, string, ap);
1235 	va_end(ap);
1236 	if (err)
1237 		fatal("%s failed", __func__);
1238 	return ret;
1239 }
1240 
1241 /*
1242  * Returns expanded string or NULL if a specified environment variable is
1243  * not defined, or calls fatal if the string is invalid.
1244  */
1245 char *
1246 percent_dollar_expand(const char *string, ...)
1247 {
1248 	char *ret;
1249 	int err;
1250 	va_list ap;
1251 
1252 	va_start(ap, string);
1253 	ret = vdollar_percent_expand(&err, 1, 1, string, ap);
1254 	va_end(ap);
1255 	if (err)
1256 		fatal("%s failed", __func__);
1257 	return ret;
1258 }
1259 
1260 int
1261 tun_open(int tun, int mode, char **ifname)
1262 {
1263 #if defined(CUSTOM_SYS_TUN_OPEN)
1264 	return (sys_tun_open(tun, mode, ifname));
1265 #elif defined(SSH_TUN_OPENBSD)
1266 	struct ifreq ifr;
1267 	char name[100];
1268 	int fd = -1, sock;
1269 	const char *tunbase = "tun";
1270 
1271 	if (ifname != NULL)
1272 		*ifname = NULL;
1273 
1274 	if (mode == SSH_TUNMODE_ETHERNET)
1275 		tunbase = "tap";
1276 
1277 	/* Open the tunnel device */
1278 	if (tun <= SSH_TUNID_MAX) {
1279 		snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
1280 		fd = open(name, O_RDWR);
1281 	} else if (tun == SSH_TUNID_ANY) {
1282 		for (tun = 100; tun >= 0; tun--) {
1283 			snprintf(name, sizeof(name), "/dev/%s%d",
1284 			    tunbase, tun);
1285 			if ((fd = open(name, O_RDWR)) >= 0)
1286 				break;
1287 		}
1288 	} else {
1289 		debug("%s: invalid tunnel %u", __func__, tun);
1290 		return -1;
1291 	}
1292 
1293 	if (fd == -1) {
1294 		debug("%s: %s open: %s", __func__, name, strerror(errno));
1295 		return -1;
1296 	}
1297 
1298 	debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
1299 
1300 	/* Bring interface up if it is not already */
1301 	snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
1302 	if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
1303 		goto failed;
1304 
1305 	if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
1306 		debug("%s: get interface %s flags: %s", __func__,
1307 		    ifr.ifr_name, strerror(errno));
1308 		goto failed;
1309 	}
1310 
1311 	if (!(ifr.ifr_flags & IFF_UP)) {
1312 		ifr.ifr_flags |= IFF_UP;
1313 		if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
1314 			debug("%s: activate interface %s: %s", __func__,
1315 			    ifr.ifr_name, strerror(errno));
1316 			goto failed;
1317 		}
1318 	}
1319 
1320 	if (ifname != NULL)
1321 		*ifname = xstrdup(ifr.ifr_name);
1322 
1323 	close(sock);
1324 	return fd;
1325 
1326  failed:
1327 	if (fd >= 0)
1328 		close(fd);
1329 	if (sock >= 0)
1330 		close(sock);
1331 	return -1;
1332 #else
1333 	error("Tunnel interfaces are not supported on this platform");
1334 	return (-1);
1335 #endif
1336 }
1337 
1338 void
1339 sanitise_stdfd(void)
1340 {
1341 	int nullfd, dupfd;
1342 
1343 	if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1344 		fprintf(stderr, "Couldn't open /dev/null: %s\n",
1345 		    strerror(errno));
1346 		exit(1);
1347 	}
1348 	while (++dupfd <= STDERR_FILENO) {
1349 		/* Only populate closed fds. */
1350 		if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
1351 			if (dup2(nullfd, dupfd) == -1) {
1352 				fprintf(stderr, "dup2: %s\n", strerror(errno));
1353 				exit(1);
1354 			}
1355 		}
1356 	}
1357 	if (nullfd > STDERR_FILENO)
1358 		close(nullfd);
1359 }
1360 
1361 char *
1362 tohex(const void *vp, size_t l)
1363 {
1364 	const u_char *p = (const u_char *)vp;
1365 	char b[3], *r;
1366 	size_t i, hl;
1367 
1368 	if (l > 65536)
1369 		return xstrdup("tohex: length > 65536");
1370 
1371 	hl = l * 2 + 1;
1372 	r = xcalloc(1, hl);
1373 	for (i = 0; i < l; i++) {
1374 		snprintf(b, sizeof(b), "%02x", p[i]);
1375 		strlcat(r, b, hl);
1376 	}
1377 	return (r);
1378 }
1379 
1380 /*
1381  * Extend string *sp by the specified format. If *sp is not NULL (or empty),
1382  * then the separator 'sep' will be prepended before the formatted arguments.
1383  * Extended strings are heap allocated.
1384  */
1385 void
1386 xextendf(char **sp, const char *sep, const char *fmt, ...)
1387 {
1388 	va_list ap;
1389 	char *tmp1, *tmp2;
1390 
1391 	va_start(ap, fmt);
1392 	xvasprintf(&tmp1, fmt, ap);
1393 	va_end(ap);
1394 
1395 	if (*sp == NULL || **sp == '\0') {
1396 		free(*sp);
1397 		*sp = tmp1;
1398 		return;
1399 	}
1400 	xasprintf(&tmp2, "%s%s%s", *sp, sep == NULL ? "" : sep, tmp1);
1401 	free(tmp1);
1402 	free(*sp);
1403 	*sp = tmp2;
1404 }
1405 
1406 
1407 u_int64_t
1408 get_u64(const void *vp)
1409 {
1410 	const u_char *p = (const u_char *)vp;
1411 	u_int64_t v;
1412 
1413 	v  = (u_int64_t)p[0] << 56;
1414 	v |= (u_int64_t)p[1] << 48;
1415 	v |= (u_int64_t)p[2] << 40;
1416 	v |= (u_int64_t)p[3] << 32;
1417 	v |= (u_int64_t)p[4] << 24;
1418 	v |= (u_int64_t)p[5] << 16;
1419 	v |= (u_int64_t)p[6] << 8;
1420 	v |= (u_int64_t)p[7];
1421 
1422 	return (v);
1423 }
1424 
1425 u_int32_t
1426 get_u32(const void *vp)
1427 {
1428 	const u_char *p = (const u_char *)vp;
1429 	u_int32_t v;
1430 
1431 	v  = (u_int32_t)p[0] << 24;
1432 	v |= (u_int32_t)p[1] << 16;
1433 	v |= (u_int32_t)p[2] << 8;
1434 	v |= (u_int32_t)p[3];
1435 
1436 	return (v);
1437 }
1438 
1439 u_int32_t
1440 get_u32_le(const void *vp)
1441 {
1442 	const u_char *p = (const u_char *)vp;
1443 	u_int32_t v;
1444 
1445 	v  = (u_int32_t)p[0];
1446 	v |= (u_int32_t)p[1] << 8;
1447 	v |= (u_int32_t)p[2] << 16;
1448 	v |= (u_int32_t)p[3] << 24;
1449 
1450 	return (v);
1451 }
1452 
1453 u_int16_t
1454 get_u16(const void *vp)
1455 {
1456 	const u_char *p = (const u_char *)vp;
1457 	u_int16_t v;
1458 
1459 	v  = (u_int16_t)p[0] << 8;
1460 	v |= (u_int16_t)p[1];
1461 
1462 	return (v);
1463 }
1464 
1465 void
1466 put_u64(void *vp, u_int64_t v)
1467 {
1468 	u_char *p = (u_char *)vp;
1469 
1470 	p[0] = (u_char)(v >> 56) & 0xff;
1471 	p[1] = (u_char)(v >> 48) & 0xff;
1472 	p[2] = (u_char)(v >> 40) & 0xff;
1473 	p[3] = (u_char)(v >> 32) & 0xff;
1474 	p[4] = (u_char)(v >> 24) & 0xff;
1475 	p[5] = (u_char)(v >> 16) & 0xff;
1476 	p[6] = (u_char)(v >> 8) & 0xff;
1477 	p[7] = (u_char)v & 0xff;
1478 }
1479 
1480 void
1481 put_u32(void *vp, u_int32_t v)
1482 {
1483 	u_char *p = (u_char *)vp;
1484 
1485 	p[0] = (u_char)(v >> 24) & 0xff;
1486 	p[1] = (u_char)(v >> 16) & 0xff;
1487 	p[2] = (u_char)(v >> 8) & 0xff;
1488 	p[3] = (u_char)v & 0xff;
1489 }
1490 
1491 void
1492 put_u32_le(void *vp, u_int32_t v)
1493 {
1494 	u_char *p = (u_char *)vp;
1495 
1496 	p[0] = (u_char)v & 0xff;
1497 	p[1] = (u_char)(v >> 8) & 0xff;
1498 	p[2] = (u_char)(v >> 16) & 0xff;
1499 	p[3] = (u_char)(v >> 24) & 0xff;
1500 }
1501 
1502 void
1503 put_u16(void *vp, u_int16_t v)
1504 {
1505 	u_char *p = (u_char *)vp;
1506 
1507 	p[0] = (u_char)(v >> 8) & 0xff;
1508 	p[1] = (u_char)v & 0xff;
1509 }
1510 
1511 void
1512 ms_subtract_diff(struct timeval *start, int *ms)
1513 {
1514 	struct timeval diff, finish;
1515 
1516 	monotime_tv(&finish);
1517 	timersub(&finish, start, &diff);
1518 	*ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
1519 }
1520 
1521 void
1522 ms_to_timeval(struct timeval *tv, int ms)
1523 {
1524 	if (ms < 0)
1525 		ms = 0;
1526 	tv->tv_sec = ms / 1000;
1527 	tv->tv_usec = (ms % 1000) * 1000;
1528 }
1529 
1530 void
1531 monotime_ts(struct timespec *ts)
1532 {
1533 	struct timeval tv;
1534 #if defined(HAVE_CLOCK_GETTIME) && (defined(CLOCK_BOOTTIME) || \
1535     defined(CLOCK_MONOTONIC) || defined(CLOCK_REALTIME))
1536 	static int gettime_failed = 0;
1537 
1538 	if (!gettime_failed) {
1539 # ifdef CLOCK_BOOTTIME
1540 		if (clock_gettime(CLOCK_BOOTTIME, ts) == 0)
1541 			return;
1542 # endif /* CLOCK_BOOTTIME */
1543 # ifdef CLOCK_MONOTONIC
1544 		if (clock_gettime(CLOCK_MONOTONIC, ts) == 0)
1545 			return;
1546 # endif /* CLOCK_MONOTONIC */
1547 # ifdef CLOCK_REALTIME
1548 		/* Not monotonic, but we're almost out of options here. */
1549 		if (clock_gettime(CLOCK_REALTIME, ts) == 0)
1550 			return;
1551 # endif /* CLOCK_REALTIME */
1552 		debug3("clock_gettime: %s", strerror(errno));
1553 		gettime_failed = 1;
1554 	}
1555 #endif /* HAVE_CLOCK_GETTIME && (BOOTTIME || MONOTONIC || REALTIME) */
1556 	gettimeofday(&tv, NULL);
1557 	ts->tv_sec = tv.tv_sec;
1558 	ts->tv_nsec = (long)tv.tv_usec * 1000;
1559 }
1560 
1561 void
1562 monotime_tv(struct timeval *tv)
1563 {
1564 	struct timespec ts;
1565 
1566 	monotime_ts(&ts);
1567 	tv->tv_sec = ts.tv_sec;
1568 	tv->tv_usec = ts.tv_nsec / 1000;
1569 }
1570 
1571 time_t
1572 monotime(void)
1573 {
1574 	struct timespec ts;
1575 
1576 	monotime_ts(&ts);
1577 	return ts.tv_sec;
1578 }
1579 
1580 double
1581 monotime_double(void)
1582 {
1583 	struct timespec ts;
1584 
1585 	monotime_ts(&ts);
1586 	return ts.tv_sec + ((double)ts.tv_nsec / 1000000000);
1587 }
1588 
1589 void
1590 bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
1591 {
1592 	bw->buflen = buflen;
1593 	bw->rate = kbps;
1594 	bw->thresh = buflen;
1595 	bw->lamt = 0;
1596 	timerclear(&bw->bwstart);
1597 	timerclear(&bw->bwend);
1598 }
1599 
1600 /* Callback from read/write loop to insert bandwidth-limiting delays */
1601 void
1602 bandwidth_limit(struct bwlimit *bw, size_t read_len)
1603 {
1604 	u_int64_t waitlen;
1605 	struct timespec ts, rm;
1606 
1607 	bw->lamt += read_len;
1608 	if (!timerisset(&bw->bwstart)) {
1609 		monotime_tv(&bw->bwstart);
1610 		return;
1611 	}
1612 	if (bw->lamt < bw->thresh)
1613 		return;
1614 
1615 	monotime_tv(&bw->bwend);
1616 	timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
1617 	if (!timerisset(&bw->bwend))
1618 		return;
1619 
1620 	bw->lamt *= 8;
1621 	waitlen = (double)1000000L * bw->lamt / bw->rate;
1622 
1623 	bw->bwstart.tv_sec = waitlen / 1000000L;
1624 	bw->bwstart.tv_usec = waitlen % 1000000L;
1625 
1626 	if (timercmp(&bw->bwstart, &bw->bwend, >)) {
1627 		timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
1628 
1629 		/* Adjust the wait time */
1630 		if (bw->bwend.tv_sec) {
1631 			bw->thresh /= 2;
1632 			if (bw->thresh < bw->buflen / 4)
1633 				bw->thresh = bw->buflen / 4;
1634 		} else if (bw->bwend.tv_usec < 10000) {
1635 			bw->thresh *= 2;
1636 			if (bw->thresh > bw->buflen * 8)
1637 				bw->thresh = bw->buflen * 8;
1638 		}
1639 
1640 		TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
1641 		while (nanosleep(&ts, &rm) == -1) {
1642 			if (errno != EINTR)
1643 				break;
1644 			ts = rm;
1645 		}
1646 	}
1647 
1648 	bw->lamt = 0;
1649 	monotime_tv(&bw->bwstart);
1650 }
1651 
1652 /* Make a template filename for mk[sd]temp() */
1653 void
1654 mktemp_proto(char *s, size_t len)
1655 {
1656 	const char *tmpdir;
1657 	int r;
1658 
1659 	if ((tmpdir = getenv("TMPDIR")) != NULL) {
1660 		r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
1661 		if (r > 0 && (size_t)r < len)
1662 			return;
1663 	}
1664 	r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
1665 	if (r < 0 || (size_t)r >= len)
1666 		fatal("%s: template string too short", __func__);
1667 }
1668 
1669 static const struct {
1670 	const char *name;
1671 	int value;
1672 } ipqos[] = {
1673 	{ "none", INT_MAX },		/* can't use 0 here; that's CS0 */
1674 	{ "af11", IPTOS_DSCP_AF11 },
1675 	{ "af12", IPTOS_DSCP_AF12 },
1676 	{ "af13", IPTOS_DSCP_AF13 },
1677 	{ "af21", IPTOS_DSCP_AF21 },
1678 	{ "af22", IPTOS_DSCP_AF22 },
1679 	{ "af23", IPTOS_DSCP_AF23 },
1680 	{ "af31", IPTOS_DSCP_AF31 },
1681 	{ "af32", IPTOS_DSCP_AF32 },
1682 	{ "af33", IPTOS_DSCP_AF33 },
1683 	{ "af41", IPTOS_DSCP_AF41 },
1684 	{ "af42", IPTOS_DSCP_AF42 },
1685 	{ "af43", IPTOS_DSCP_AF43 },
1686 	{ "cs0", IPTOS_DSCP_CS0 },
1687 	{ "cs1", IPTOS_DSCP_CS1 },
1688 	{ "cs2", IPTOS_DSCP_CS2 },
1689 	{ "cs3", IPTOS_DSCP_CS3 },
1690 	{ "cs4", IPTOS_DSCP_CS4 },
1691 	{ "cs5", IPTOS_DSCP_CS5 },
1692 	{ "cs6", IPTOS_DSCP_CS6 },
1693 	{ "cs7", IPTOS_DSCP_CS7 },
1694 	{ "ef", IPTOS_DSCP_EF },
1695 	{ "le", IPTOS_DSCP_LE },
1696 	{ "lowdelay", IPTOS_LOWDELAY },
1697 	{ "throughput", IPTOS_THROUGHPUT },
1698 	{ "reliability", IPTOS_RELIABILITY },
1699 	{ NULL, -1 }
1700 };
1701 
1702 int
1703 parse_ipqos(const char *cp)
1704 {
1705 	u_int i;
1706 	char *ep;
1707 	long val;
1708 
1709 	if (cp == NULL)
1710 		return -1;
1711 	for (i = 0; ipqos[i].name != NULL; i++) {
1712 		if (strcasecmp(cp, ipqos[i].name) == 0)
1713 			return ipqos[i].value;
1714 	}
1715 	/* Try parsing as an integer */
1716 	val = strtol(cp, &ep, 0);
1717 	if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1718 		return -1;
1719 	return val;
1720 }
1721 
1722 const char *
1723 iptos2str(int iptos)
1724 {
1725 	int i;
1726 	static char iptos_str[sizeof "0xff"];
1727 
1728 	for (i = 0; ipqos[i].name != NULL; i++) {
1729 		if (ipqos[i].value == iptos)
1730 			return ipqos[i].name;
1731 	}
1732 	snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1733 	return iptos_str;
1734 }
1735 
1736 void
1737 lowercase(char *s)
1738 {
1739 	for (; *s; s++)
1740 		*s = tolower((u_char)*s);
1741 }
1742 
1743 int
1744 unix_listener(const char *path, int backlog, int unlink_first)
1745 {
1746 	struct sockaddr_un sunaddr;
1747 	int saved_errno, sock;
1748 
1749 	memset(&sunaddr, 0, sizeof(sunaddr));
1750 	sunaddr.sun_family = AF_UNIX;
1751 	if (strlcpy(sunaddr.sun_path, path,
1752 	    sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1753 		error("%s: path \"%s\" too long for Unix domain socket",
1754 		    __func__, path);
1755 		errno = ENAMETOOLONG;
1756 		return -1;
1757 	}
1758 
1759 	sock = socket(PF_UNIX, SOCK_STREAM, 0);
1760 	if (sock == -1) {
1761 		saved_errno = errno;
1762 		error("%s: socket: %.100s", __func__, strerror(errno));
1763 		errno = saved_errno;
1764 		return -1;
1765 	}
1766 	if (unlink_first == 1) {
1767 		if (unlink(path) != 0 && errno != ENOENT)
1768 			error("unlink(%s): %.100s", path, strerror(errno));
1769 	}
1770 	if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1771 		saved_errno = errno;
1772 		error("%s: cannot bind to path %s: %s",
1773 		    __func__, path, strerror(errno));
1774 		close(sock);
1775 		errno = saved_errno;
1776 		return -1;
1777 	}
1778 	if (listen(sock, backlog) == -1) {
1779 		saved_errno = errno;
1780 		error("%s: cannot listen on path %s: %s",
1781 		    __func__, path, strerror(errno));
1782 		close(sock);
1783 		unlink(path);
1784 		errno = saved_errno;
1785 		return -1;
1786 	}
1787 	return sock;
1788 }
1789 
1790 void
1791 sock_set_v6only(int s)
1792 {
1793 #if defined(IPV6_V6ONLY) && !defined(__OpenBSD__)
1794 	int on = 1;
1795 
1796 	debug3("%s: set socket %d IPV6_V6ONLY", __func__, s);
1797 	if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1)
1798 		error("setsockopt IPV6_V6ONLY: %s", strerror(errno));
1799 #endif
1800 }
1801 
1802 /*
1803  * Compares two strings that maybe be NULL. Returns non-zero if strings
1804  * are both NULL or are identical, returns zero otherwise.
1805  */
1806 static int
1807 strcmp_maybe_null(const char *a, const char *b)
1808 {
1809 	if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1810 		return 0;
1811 	if (a != NULL && strcmp(a, b) != 0)
1812 		return 0;
1813 	return 1;
1814 }
1815 
1816 /*
1817  * Compare two forwards, returning non-zero if they are identical or
1818  * zero otherwise.
1819  */
1820 int
1821 forward_equals(const struct Forward *a, const struct Forward *b)
1822 {
1823 	if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
1824 		return 0;
1825 	if (a->listen_port != b->listen_port)
1826 		return 0;
1827 	if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
1828 		return 0;
1829 	if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
1830 		return 0;
1831 	if (a->connect_port != b->connect_port)
1832 		return 0;
1833 	if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
1834 		return 0;
1835 	/* allocated_port and handle are not checked */
1836 	return 1;
1837 }
1838 
1839 /* returns 1 if process is already daemonized, 0 otherwise */
1840 int
1841 daemonized(void)
1842 {
1843 	int fd;
1844 
1845 	if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
1846 		close(fd);
1847 		return 0;	/* have controlling terminal */
1848 	}
1849 	if (getppid() != 1)
1850 		return 0;	/* parent is not init */
1851 	if (getsid(0) != getpid())
1852 		return 0;	/* not session leader */
1853 	debug3("already daemonized");
1854 	return 1;
1855 }
1856 
1857 
1858 /*
1859  * Splits 's' into an argument vector. Handles quoted string and basic
1860  * escape characters (\\, \", \'). Caller must free the argument vector
1861  * and its members.
1862  */
1863 int
1864 argv_split(const char *s, int *argcp, char ***argvp)
1865 {
1866 	int r = SSH_ERR_INTERNAL_ERROR;
1867 	int argc = 0, quote, i, j;
1868 	char *arg, **argv = xcalloc(1, sizeof(*argv));
1869 
1870 	*argvp = NULL;
1871 	*argcp = 0;
1872 
1873 	for (i = 0; s[i] != '\0'; i++) {
1874 		/* Skip leading whitespace */
1875 		if (s[i] == ' ' || s[i] == '\t')
1876 			continue;
1877 
1878 		/* Start of a token */
1879 		quote = 0;
1880 		if (s[i] == '\\' &&
1881 		    (s[i + 1] == '\'' || s[i + 1] == '\"' || s[i + 1] == '\\'))
1882 			i++;
1883 		else if (s[i] == '\'' || s[i] == '"')
1884 			quote = s[i++];
1885 
1886 		argv = xreallocarray(argv, (argc + 2), sizeof(*argv));
1887 		arg = argv[argc++] = xcalloc(1, strlen(s + i) + 1);
1888 		argv[argc] = NULL;
1889 
1890 		/* Copy the token in, removing escapes */
1891 		for (j = 0; s[i] != '\0'; i++) {
1892 			if (s[i] == '\\') {
1893 				if (s[i + 1] == '\'' ||
1894 				    s[i + 1] == '\"' ||
1895 				    s[i + 1] == '\\') {
1896 					i++; /* Skip '\' */
1897 					arg[j++] = s[i];
1898 				} else {
1899 					/* Unrecognised escape */
1900 					arg[j++] = s[i];
1901 				}
1902 			} else if (quote == 0 && (s[i] == ' ' || s[i] == '\t'))
1903 				break; /* done */
1904 			else if (quote != 0 && s[i] == quote)
1905 				break; /* done */
1906 			else
1907 				arg[j++] = s[i];
1908 		}
1909 		if (s[i] == '\0') {
1910 			if (quote != 0) {
1911 				/* Ran out of string looking for close quote */
1912 				r = SSH_ERR_INVALID_FORMAT;
1913 				goto out;
1914 			}
1915 			break;
1916 		}
1917 	}
1918 	/* Success */
1919 	*argcp = argc;
1920 	*argvp = argv;
1921 	argc = 0;
1922 	argv = NULL;
1923 	r = 0;
1924  out:
1925 	if (argc != 0 && argv != NULL) {
1926 		for (i = 0; i < argc; i++)
1927 			free(argv[i]);
1928 		free(argv);
1929 	}
1930 	return r;
1931 }
1932 
1933 /*
1934  * Reassemble an argument vector into a string, quoting and escaping as
1935  * necessary. Caller must free returned string.
1936  */
1937 char *
1938 argv_assemble(int argc, char **argv)
1939 {
1940 	int i, j, ws, r;
1941 	char c, *ret;
1942 	struct sshbuf *buf, *arg;
1943 
1944 	if ((buf = sshbuf_new()) == NULL || (arg = sshbuf_new()) == NULL)
1945 		fatal("%s: sshbuf_new failed", __func__);
1946 
1947 	for (i = 0; i < argc; i++) {
1948 		ws = 0;
1949 		sshbuf_reset(arg);
1950 		for (j = 0; argv[i][j] != '\0'; j++) {
1951 			r = 0;
1952 			c = argv[i][j];
1953 			switch (c) {
1954 			case ' ':
1955 			case '\t':
1956 				ws = 1;
1957 				r = sshbuf_put_u8(arg, c);
1958 				break;
1959 			case '\\':
1960 			case '\'':
1961 			case '"':
1962 				if ((r = sshbuf_put_u8(arg, '\\')) != 0)
1963 					break;
1964 				/* FALLTHROUGH */
1965 			default:
1966 				r = sshbuf_put_u8(arg, c);
1967 				break;
1968 			}
1969 			if (r != 0)
1970 				fatal("%s: sshbuf_put_u8: %s",
1971 				    __func__, ssh_err(r));
1972 		}
1973 		if ((i != 0 && (r = sshbuf_put_u8(buf, ' ')) != 0) ||
1974 		    (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0) ||
1975 		    (r = sshbuf_putb(buf, arg)) != 0 ||
1976 		    (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0))
1977 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
1978 	}
1979 	if ((ret = malloc(sshbuf_len(buf) + 1)) == NULL)
1980 		fatal("%s: malloc failed", __func__);
1981 	memcpy(ret, sshbuf_ptr(buf), sshbuf_len(buf));
1982 	ret[sshbuf_len(buf)] = '\0';
1983 	sshbuf_free(buf);
1984 	sshbuf_free(arg);
1985 	return ret;
1986 }
1987 
1988 /* Returns 0 if pid exited cleanly, non-zero otherwise */
1989 int
1990 exited_cleanly(pid_t pid, const char *tag, const char *cmd, int quiet)
1991 {
1992 	int status;
1993 
1994 	while (waitpid(pid, &status, 0) == -1) {
1995 		if (errno != EINTR) {
1996 			error("%s: waitpid: %s", tag, strerror(errno));
1997 			return -1;
1998 		}
1999 	}
2000 	if (WIFSIGNALED(status)) {
2001 		error("%s %s exited on signal %d", tag, cmd, WTERMSIG(status));
2002 		return -1;
2003 	} else if (WEXITSTATUS(status) != 0) {
2004 		do_log2(quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_INFO,
2005 		    "%s %s failed, status %d", tag, cmd, WEXITSTATUS(status));
2006 		return -1;
2007 	}
2008 	return 0;
2009 }
2010 
2011 /*
2012  * Check a given path for security. This is defined as all components
2013  * of the path to the file must be owned by either the owner of
2014  * of the file or root and no directories must be group or world writable.
2015  *
2016  * XXX Should any specific check be done for sym links ?
2017  *
2018  * Takes a file name, its stat information (preferably from fstat() to
2019  * avoid races), the uid of the expected owner, their home directory and an
2020  * error buffer plus max size as arguments.
2021  *
2022  * Returns 0 on success and -1 on failure
2023  */
2024 int
2025 safe_path(const char *name, struct stat *stp, const char *pw_dir,
2026     uid_t uid, char *err, size_t errlen)
2027 {
2028 	char buf[PATH_MAX], homedir[PATH_MAX];
2029 	char *cp;
2030 	int comparehome = 0;
2031 	struct stat st;
2032 
2033 	if (realpath(name, buf) == NULL) {
2034 		snprintf(err, errlen, "realpath %s failed: %s", name,
2035 		    strerror(errno));
2036 		return -1;
2037 	}
2038 	if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL)
2039 		comparehome = 1;
2040 
2041 	if (!S_ISREG(stp->st_mode)) {
2042 		snprintf(err, errlen, "%s is not a regular file", buf);
2043 		return -1;
2044 	}
2045 	if ((!platform_sys_dir_uid(stp->st_uid) && stp->st_uid != uid) ||
2046 	    (stp->st_mode & 022) != 0) {
2047 		snprintf(err, errlen, "bad ownership or modes for file %s",
2048 		    buf);
2049 		return -1;
2050 	}
2051 
2052 	/* for each component of the canonical path, walking upwards */
2053 	for (;;) {
2054 		if ((cp = dirname(buf)) == NULL) {
2055 			snprintf(err, errlen, "dirname() failed");
2056 			return -1;
2057 		}
2058 		strlcpy(buf, cp, sizeof(buf));
2059 
2060 		if (stat(buf, &st) == -1 ||
2061 		    (!platform_sys_dir_uid(st.st_uid) && st.st_uid != uid) ||
2062 		    (st.st_mode & 022) != 0) {
2063 			snprintf(err, errlen,
2064 			    "bad ownership or modes for directory %s", buf);
2065 			return -1;
2066 		}
2067 
2068 		/* If are past the homedir then we can stop */
2069 		if (comparehome && strcmp(homedir, buf) == 0)
2070 			break;
2071 
2072 		/*
2073 		 * dirname should always complete with a "/" path,
2074 		 * but we can be paranoid and check for "." too
2075 		 */
2076 		if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
2077 			break;
2078 	}
2079 	return 0;
2080 }
2081 
2082 /*
2083  * Version of safe_path() that accepts an open file descriptor to
2084  * avoid races.
2085  *
2086  * Returns 0 on success and -1 on failure
2087  */
2088 int
2089 safe_path_fd(int fd, const char *file, struct passwd *pw,
2090     char *err, size_t errlen)
2091 {
2092 	struct stat st;
2093 
2094 	/* check the open file to avoid races */
2095 	if (fstat(fd, &st) == -1) {
2096 		snprintf(err, errlen, "cannot stat file %s: %s",
2097 		    file, strerror(errno));
2098 		return -1;
2099 	}
2100 	return safe_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen);
2101 }
2102 
2103 /*
2104  * Sets the value of the given variable in the environment.  If the variable
2105  * already exists, its value is overridden.
2106  */
2107 void
2108 child_set_env(char ***envp, u_int *envsizep, const char *name,
2109 	const char *value)
2110 {
2111 	char **env;
2112 	u_int envsize;
2113 	u_int i, namelen;
2114 
2115 	if (strchr(name, '=') != NULL) {
2116 		error("Invalid environment variable \"%.100s\"", name);
2117 		return;
2118 	}
2119 
2120 	/*
2121 	 * If we're passed an uninitialized list, allocate a single null
2122 	 * entry before continuing.
2123 	 */
2124 	if (*envp == NULL && *envsizep == 0) {
2125 		*envp = xmalloc(sizeof(char *));
2126 		*envp[0] = NULL;
2127 		*envsizep = 1;
2128 	}
2129 
2130 	/*
2131 	 * Find the slot where the value should be stored.  If the variable
2132 	 * already exists, we reuse the slot; otherwise we append a new slot
2133 	 * at the end of the array, expanding if necessary.
2134 	 */
2135 	env = *envp;
2136 	namelen = strlen(name);
2137 	for (i = 0; env[i]; i++)
2138 		if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
2139 			break;
2140 	if (env[i]) {
2141 		/* Reuse the slot. */
2142 		free(env[i]);
2143 	} else {
2144 		/* New variable.  Expand if necessary. */
2145 		envsize = *envsizep;
2146 		if (i >= envsize - 1) {
2147 			if (envsize >= 1000)
2148 				fatal("child_set_env: too many env vars");
2149 			envsize += 50;
2150 			env = (*envp) = xreallocarray(env, envsize, sizeof(char *));
2151 			*envsizep = envsize;
2152 		}
2153 		/* Need to set the NULL pointer at end of array beyond the new slot. */
2154 		env[i + 1] = NULL;
2155 	}
2156 
2157 	/* Allocate space and format the variable in the appropriate slot. */
2158 	/* XXX xasprintf */
2159 	env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
2160 	snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
2161 }
2162 
2163 /*
2164  * Check and optionally lowercase a domain name, also removes trailing '.'
2165  * Returns 1 on success and 0 on failure, storing an error message in errstr.
2166  */
2167 int
2168 valid_domain(char *name, int makelower, const char **errstr)
2169 {
2170 	size_t i, l = strlen(name);
2171 	u_char c, last = '\0';
2172 	static char errbuf[256];
2173 
2174 	if (l == 0) {
2175 		strlcpy(errbuf, "empty domain name", sizeof(errbuf));
2176 		goto bad;
2177 	}
2178 	if (!isalpha((u_char)name[0]) && !isdigit((u_char)name[0])) {
2179 		snprintf(errbuf, sizeof(errbuf), "domain name \"%.100s\" "
2180 		    "starts with invalid character", name);
2181 		goto bad;
2182 	}
2183 	for (i = 0; i < l; i++) {
2184 		c = tolower((u_char)name[i]);
2185 		if (makelower)
2186 			name[i] = (char)c;
2187 		if (last == '.' && c == '.') {
2188 			snprintf(errbuf, sizeof(errbuf), "domain name "
2189 			    "\"%.100s\" contains consecutive separators", name);
2190 			goto bad;
2191 		}
2192 		if (c != '.' && c != '-' && !isalnum(c) &&
2193 		    c != '_') /* technically invalid, but common */ {
2194 			snprintf(errbuf, sizeof(errbuf), "domain name "
2195 			    "\"%.100s\" contains invalid characters", name);
2196 			goto bad;
2197 		}
2198 		last = c;
2199 	}
2200 	if (name[l - 1] == '.')
2201 		name[l - 1] = '\0';
2202 	if (errstr != NULL)
2203 		*errstr = NULL;
2204 	return 1;
2205 bad:
2206 	if (errstr != NULL)
2207 		*errstr = errbuf;
2208 	return 0;
2209 }
2210 
2211 /*
2212  * Verify that a environment variable name (not including initial '$') is
2213  * valid; consisting of one or more alphanumeric or underscore characters only.
2214  * Returns 1 on valid, 0 otherwise.
2215  */
2216 int
2217 valid_env_name(const char *name)
2218 {
2219 	const char *cp;
2220 
2221 	if (name[0] == '\0')
2222 		return 0;
2223 	for (cp = name; *cp != '\0'; cp++) {
2224 		if (!isalnum((u_char)*cp) && *cp != '_')
2225 			return 0;
2226 	}
2227 	return 1;
2228 }
2229 
2230 const char *
2231 atoi_err(const char *nptr, int *val)
2232 {
2233 	const char *errstr = NULL;
2234 	long long num;
2235 
2236 	if (nptr == NULL || *nptr == '\0')
2237 		return "missing";
2238 	num = strtonum(nptr, 0, INT_MAX, &errstr);
2239 	if (errstr == NULL)
2240 		*val = (int)num;
2241 	return errstr;
2242 }
2243 
2244 int
2245 parse_absolute_time(const char *s, uint64_t *tp)
2246 {
2247 	struct tm tm;
2248 	time_t tt;
2249 	char buf[32], *fmt;
2250 
2251 	*tp = 0;
2252 
2253 	/*
2254 	 * POSIX strptime says "The application shall ensure that there
2255 	 * is white-space or other non-alphanumeric characters between
2256 	 * any two conversion specifications" so arrange things this way.
2257 	 */
2258 	switch (strlen(s)) {
2259 	case 8: /* YYYYMMDD */
2260 		fmt = "%Y-%m-%d";
2261 		snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
2262 		break;
2263 	case 12: /* YYYYMMDDHHMM */
2264 		fmt = "%Y-%m-%dT%H:%M";
2265 		snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s",
2266 		    s, s + 4, s + 6, s + 8, s + 10);
2267 		break;
2268 	case 14: /* YYYYMMDDHHMMSS */
2269 		fmt = "%Y-%m-%dT%H:%M:%S";
2270 		snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
2271 		    s, s + 4, s + 6, s + 8, s + 10, s + 12);
2272 		break;
2273 	default:
2274 		return SSH_ERR_INVALID_FORMAT;
2275 	}
2276 
2277 	memset(&tm, 0, sizeof(tm));
2278 	if (strptime(buf, fmt, &tm) == NULL)
2279 		return SSH_ERR_INVALID_FORMAT;
2280 	if ((tt = mktime(&tm)) < 0)
2281 		return SSH_ERR_INVALID_FORMAT;
2282 	/* success */
2283 	*tp = (uint64_t)tt;
2284 	return 0;
2285 }
2286 
2287 void
2288 format_absolute_time(uint64_t t, char *buf, size_t len)
2289 {
2290 	time_t tt = t > INT_MAX ? INT_MAX : t; /* XXX revisit in 2038 :P */
2291 	struct tm tm;
2292 
2293 	localtime_r(&tt, &tm);
2294 	strftime(buf, len, "%Y-%m-%dT%H:%M:%S", &tm);
2295 }
2296 
2297 /* check if path is absolute */
2298 int
2299 path_absolute(const char *path)
2300 {
2301 	return (*path == '/') ? 1 : 0;
2302 }
2303 
2304 void
2305 skip_space(char **cpp)
2306 {
2307 	char *cp;
2308 
2309 	for (cp = *cpp; *cp == ' ' || *cp == '\t'; cp++)
2310 		;
2311 	*cpp = cp;
2312 }
2313 
2314 /* authorized_key-style options parsing helpers */
2315 
2316 /*
2317  * Match flag 'opt' in *optsp, and if allow_negate is set then also match
2318  * 'no-opt'. Returns -1 if option not matched, 1 if option matches or 0
2319  * if negated option matches.
2320  * If the option or negated option matches, then *optsp is updated to
2321  * point to the first character after the option.
2322  */
2323 int
2324 opt_flag(const char *opt, int allow_negate, const char **optsp)
2325 {
2326 	size_t opt_len = strlen(opt);
2327 	const char *opts = *optsp;
2328 	int negate = 0;
2329 
2330 	if (allow_negate && strncasecmp(opts, "no-", 3) == 0) {
2331 		opts += 3;
2332 		negate = 1;
2333 	}
2334 	if (strncasecmp(opts, opt, opt_len) == 0) {
2335 		*optsp = opts + opt_len;
2336 		return negate ? 0 : 1;
2337 	}
2338 	return -1;
2339 }
2340 
2341 char *
2342 opt_dequote(const char **sp, const char **errstrp)
2343 {
2344 	const char *s = *sp;
2345 	char *ret;
2346 	size_t i;
2347 
2348 	*errstrp = NULL;
2349 	if (*s != '"') {
2350 		*errstrp = "missing start quote";
2351 		return NULL;
2352 	}
2353 	s++;
2354 	if ((ret = malloc(strlen((s)) + 1)) == NULL) {
2355 		*errstrp = "memory allocation failed";
2356 		return NULL;
2357 	}
2358 	for (i = 0; *s != '\0' && *s != '"';) {
2359 		if (s[0] == '\\' && s[1] == '"')
2360 			s++;
2361 		ret[i++] = *s++;
2362 	}
2363 	if (*s == '\0') {
2364 		*errstrp = "missing end quote";
2365 		free(ret);
2366 		return NULL;
2367 	}
2368 	ret[i] = '\0';
2369 	s++;
2370 	*sp = s;
2371 	return ret;
2372 }
2373 
2374 int
2375 opt_match(const char **opts, const char *term)
2376 {
2377 	if (strncasecmp((*opts), term, strlen(term)) == 0 &&
2378 	    (*opts)[strlen(term)] == '=') {
2379 		*opts += strlen(term) + 1;
2380 		return 1;
2381 	}
2382 	return 0;
2383 }
2384 
2385 sshsig_t
2386 ssh_signal(int signum, sshsig_t handler)
2387 {
2388 	struct sigaction sa, osa;
2389 
2390 	/* mask all other signals while in handler */
2391 	memset(&sa, 0, sizeof(sa));
2392 	sa.sa_handler = handler;
2393 	sigfillset(&sa.sa_mask);
2394 #if defined(SA_RESTART) && !defined(NO_SA_RESTART)
2395 	if (signum != SIGALRM)
2396 		sa.sa_flags = SA_RESTART;
2397 #endif
2398 	if (sigaction(signum, &sa, &osa) == -1) {
2399 		debug3("sigaction(%s): %s", strsignal(signum), strerror(errno));
2400 		return SIG_ERR;
2401 	}
2402 	return osa.sa_handler;
2403 }
2404