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