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