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