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