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