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