xref: /openbsd-src/usr.bin/ssh/misc.c (revision 0b7734b3d77bb9b21afec6f4621cae6c805dbd45)
1 /* $OpenBSD: misc.c,v 1.105 2016/07/15 00:24:30 djm Exp $ */
2 /*
3  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
4  * Copyright (c) 2005,2006 Damien Miller.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include <sys/types.h>
28 #include <sys/ioctl.h>
29 #include <sys/socket.h>
30 #include <sys/time.h>
31 #include <sys/un.h>
32 
33 #include <net/if.h>
34 #include <netinet/in.h>
35 #include <netinet/ip.h>
36 #include <netinet/tcp.h>
37 
38 #include <ctype.h>
39 #include <errno.h>
40 #include <fcntl.h>
41 #include <netdb.h>
42 #include <paths.h>
43 #include <pwd.h>
44 #include <limits.h>
45 #include <stdarg.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <unistd.h>
50 
51 #include "xmalloc.h"
52 #include "misc.h"
53 #include "log.h"
54 #include "ssh.h"
55 
56 /* remove newline at end of string */
57 char *
58 chop(char *s)
59 {
60 	char *t = s;
61 	while (*t) {
62 		if (*t == '\n' || *t == '\r') {
63 			*t = '\0';
64 			return s;
65 		}
66 		t++;
67 	}
68 	return s;
69 
70 }
71 
72 /* set/unset filedescriptor to non-blocking */
73 int
74 set_nonblock(int fd)
75 {
76 	int val;
77 
78 	val = fcntl(fd, F_GETFL);
79 	if (val < 0) {
80 		error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
81 		return (-1);
82 	}
83 	if (val & O_NONBLOCK) {
84 		debug3("fd %d is O_NONBLOCK", fd);
85 		return (0);
86 	}
87 	debug2("fd %d setting O_NONBLOCK", fd);
88 	val |= O_NONBLOCK;
89 	if (fcntl(fd, F_SETFL, val) == -1) {
90 		debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
91 		    strerror(errno));
92 		return (-1);
93 	}
94 	return (0);
95 }
96 
97 int
98 unset_nonblock(int fd)
99 {
100 	int val;
101 
102 	val = fcntl(fd, F_GETFL);
103 	if (val < 0) {
104 		error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
105 		return (-1);
106 	}
107 	if (!(val & O_NONBLOCK)) {
108 		debug3("fd %d is not O_NONBLOCK", fd);
109 		return (0);
110 	}
111 	debug("fd %d clearing O_NONBLOCK", fd);
112 	val &= ~O_NONBLOCK;
113 	if (fcntl(fd, F_SETFL, val) == -1) {
114 		debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
115 		    fd, strerror(errno));
116 		return (-1);
117 	}
118 	return (0);
119 }
120 
121 const char *
122 ssh_gai_strerror(int gaierr)
123 {
124 	if (gaierr == EAI_SYSTEM && errno != 0)
125 		return strerror(errno);
126 	return gai_strerror(gaierr);
127 }
128 
129 /* disable nagle on socket */
130 void
131 set_nodelay(int fd)
132 {
133 	int opt;
134 	socklen_t optlen;
135 
136 	optlen = sizeof opt;
137 	if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
138 		debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
139 		return;
140 	}
141 	if (opt == 1) {
142 		debug2("fd %d is TCP_NODELAY", fd);
143 		return;
144 	}
145 	opt = 1;
146 	debug2("fd %d setting TCP_NODELAY", fd);
147 	if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
148 		error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
149 }
150 
151 /* Characters considered whitespace in strsep calls. */
152 #define WHITESPACE " \t\r\n"
153 #define QUOTE	"\""
154 
155 /* return next token in configuration line */
156 char *
157 strdelim(char **s)
158 {
159 	char *old;
160 	int wspace = 0;
161 
162 	if (*s == NULL)
163 		return NULL;
164 
165 	old = *s;
166 
167 	*s = strpbrk(*s, WHITESPACE QUOTE "=");
168 	if (*s == NULL)
169 		return (old);
170 
171 	if (*s[0] == '\"') {
172 		memmove(*s, *s + 1, strlen(*s)); /* move nul too */
173 		/* Find matching quote */
174 		if ((*s = strpbrk(*s, QUOTE)) == NULL) {
175 			return (NULL);		/* no matching quote */
176 		} else {
177 			*s[0] = '\0';
178 			*s += strspn(*s + 1, WHITESPACE) + 1;
179 			return (old);
180 		}
181 	}
182 
183 	/* Allow only one '=' to be skipped */
184 	if (*s[0] == '=')
185 		wspace = 1;
186 	*s[0] = '\0';
187 
188 	/* Skip any extra whitespace after first token */
189 	*s += strspn(*s + 1, WHITESPACE) + 1;
190 	if (*s[0] == '=' && !wspace)
191 		*s += strspn(*s + 1, WHITESPACE) + 1;
192 
193 	return (old);
194 }
195 
196 struct passwd *
197 pwcopy(struct passwd *pw)
198 {
199 	struct passwd *copy = xcalloc(1, sizeof(*copy));
200 
201 	copy->pw_name = xstrdup(pw->pw_name);
202 	copy->pw_passwd = xstrdup(pw->pw_passwd);
203 	copy->pw_gecos = xstrdup(pw->pw_gecos);
204 	copy->pw_uid = pw->pw_uid;
205 	copy->pw_gid = pw->pw_gid;
206 	copy->pw_expire = pw->pw_expire;
207 	copy->pw_change = pw->pw_change;
208 	copy->pw_class = xstrdup(pw->pw_class);
209 	copy->pw_dir = xstrdup(pw->pw_dir);
210 	copy->pw_shell = xstrdup(pw->pw_shell);
211 	return copy;
212 }
213 
214 /*
215  * Convert ASCII string to TCP/IP port number.
216  * Port must be >=0 and <=65535.
217  * Return -1 if invalid.
218  */
219 int
220 a2port(const char *s)
221 {
222 	long long port;
223 	const char *errstr;
224 
225 	port = strtonum(s, 0, 65535, &errstr);
226 	if (errstr != NULL)
227 		return -1;
228 	return (int)port;
229 }
230 
231 int
232 a2tun(const char *s, int *remote)
233 {
234 	const char *errstr = NULL;
235 	char *sp, *ep;
236 	int tun;
237 
238 	if (remote != NULL) {
239 		*remote = SSH_TUNID_ANY;
240 		sp = xstrdup(s);
241 		if ((ep = strchr(sp, ':')) == NULL) {
242 			free(sp);
243 			return (a2tun(s, NULL));
244 		}
245 		ep[0] = '\0'; ep++;
246 		*remote = a2tun(ep, NULL);
247 		tun = a2tun(sp, NULL);
248 		free(sp);
249 		return (*remote == SSH_TUNID_ERR ? *remote : tun);
250 	}
251 
252 	if (strcasecmp(s, "any") == 0)
253 		return (SSH_TUNID_ANY);
254 
255 	tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
256 	if (errstr != NULL)
257 		return (SSH_TUNID_ERR);
258 
259 	return (tun);
260 }
261 
262 #define SECONDS		1
263 #define MINUTES		(SECONDS * 60)
264 #define HOURS		(MINUTES * 60)
265 #define DAYS		(HOURS * 24)
266 #define WEEKS		(DAYS * 7)
267 
268 /*
269  * Convert a time string into seconds; format is
270  * a sequence of:
271  *      time[qualifier]
272  *
273  * Valid time qualifiers are:
274  *      <none>  seconds
275  *      s|S     seconds
276  *      m|M     minutes
277  *      h|H     hours
278  *      d|D     days
279  *      w|W     weeks
280  *
281  * Examples:
282  *      90m     90 minutes
283  *      1h30m   90 minutes
284  *      2d      2 days
285  *      1w      1 week
286  *
287  * Return -1 if time string is invalid.
288  */
289 long
290 convtime(const char *s)
291 {
292 	long total, secs;
293 	const char *p;
294 	char *endp;
295 
296 	errno = 0;
297 	total = 0;
298 	p = s;
299 
300 	if (p == NULL || *p == '\0')
301 		return -1;
302 
303 	while (*p) {
304 		secs = strtol(p, &endp, 10);
305 		if (p == endp ||
306 		    (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
307 		    secs < 0)
308 			return -1;
309 
310 		switch (*endp++) {
311 		case '\0':
312 			endp--;
313 			break;
314 		case 's':
315 		case 'S':
316 			break;
317 		case 'm':
318 		case 'M':
319 			secs *= MINUTES;
320 			break;
321 		case 'h':
322 		case 'H':
323 			secs *= HOURS;
324 			break;
325 		case 'd':
326 		case 'D':
327 			secs *= DAYS;
328 			break;
329 		case 'w':
330 		case 'W':
331 			secs *= WEEKS;
332 			break;
333 		default:
334 			return -1;
335 		}
336 		total += secs;
337 		if (total < 0)
338 			return -1;
339 		p = endp;
340 	}
341 
342 	return total;
343 }
344 
345 /*
346  * Returns a standardized host+port identifier string.
347  * Caller must free returned string.
348  */
349 char *
350 put_host_port(const char *host, u_short port)
351 {
352 	char *hoststr;
353 
354 	if (port == 0 || port == SSH_DEFAULT_PORT)
355 		return(xstrdup(host));
356 	if (asprintf(&hoststr, "[%s]:%d", host, (int)port) < 0)
357 		fatal("put_host_port: asprintf: %s", strerror(errno));
358 	debug3("put_host_port: %s", hoststr);
359 	return hoststr;
360 }
361 
362 /*
363  * Search for next delimiter between hostnames/addresses and ports.
364  * Argument may be modified (for termination).
365  * Returns *cp if parsing succeeds.
366  * *cp is set to the start of the next delimiter, if one was found.
367  * If this is the last field, *cp is set to NULL.
368  */
369 char *
370 hpdelim(char **cp)
371 {
372 	char *s, *old;
373 
374 	if (cp == NULL || *cp == NULL)
375 		return NULL;
376 
377 	old = s = *cp;
378 	if (*s == '[') {
379 		if ((s = strchr(s, ']')) == NULL)
380 			return NULL;
381 		else
382 			s++;
383 	} else if ((s = strpbrk(s, ":/")) == NULL)
384 		s = *cp + strlen(*cp); /* skip to end (see first case below) */
385 
386 	switch (*s) {
387 	case '\0':
388 		*cp = NULL;	/* no more fields*/
389 		break;
390 
391 	case ':':
392 	case '/':
393 		*s = '\0';	/* terminate */
394 		*cp = s + 1;
395 		break;
396 
397 	default:
398 		return NULL;
399 	}
400 
401 	return old;
402 }
403 
404 char *
405 cleanhostname(char *host)
406 {
407 	if (*host == '[' && host[strlen(host) - 1] == ']') {
408 		host[strlen(host) - 1] = '\0';
409 		return (host + 1);
410 	} else
411 		return host;
412 }
413 
414 char *
415 colon(char *cp)
416 {
417 	int flag = 0;
418 
419 	if (*cp == ':')		/* Leading colon is part of file name. */
420 		return NULL;
421 	if (*cp == '[')
422 		flag = 1;
423 
424 	for (; *cp; ++cp) {
425 		if (*cp == '@' && *(cp+1) == '[')
426 			flag = 1;
427 		if (*cp == ']' && *(cp+1) == ':' && flag)
428 			return (cp+1);
429 		if (*cp == ':' && !flag)
430 			return (cp);
431 		if (*cp == '/')
432 			return NULL;
433 	}
434 	return NULL;
435 }
436 
437 /*
438  * Parse a [user@]host[:port] string.
439  * Caller must free returned user and host.
440  * Any of the pointer return arguments may be NULL (useful for syntax checking).
441  * If user was not specified then *userp will be set to NULL.
442  * If port was not specified then *portp will be -1.
443  * Returns 0 on success, -1 on failure.
444  */
445 int
446 parse_user_host_port(const char *s, char **userp, char **hostp, int *portp)
447 {
448 	char *sdup, *cp, *tmp;
449 	char *user = NULL, *host = NULL;
450 	int port = -1, ret = -1;
451 
452 	if (userp != NULL)
453 		*userp = NULL;
454 	if (hostp != NULL)
455 		*hostp = NULL;
456 	if (portp != NULL)
457 		*portp = -1;
458 
459 	if ((sdup = tmp = strdup(s)) == NULL)
460 		return -1;
461 	/* Extract optional username */
462 	if ((cp = strchr(tmp, '@')) != NULL) {
463 		*cp = '\0';
464 		if (*tmp == '\0')
465 			goto out;
466 		if ((user = strdup(tmp)) == NULL)
467 			goto out;
468 		tmp = cp + 1;
469 	}
470 	/* Extract mandatory hostname */
471 	if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0')
472 		goto out;
473 	host = xstrdup(cleanhostname(cp));
474 	/* Convert and verify optional port */
475 	if (tmp != NULL && *tmp != '\0') {
476 		if ((port = a2port(tmp)) <= 0)
477 			goto out;
478 	}
479 	/* Success */
480 	if (userp != NULL) {
481 		*userp = user;
482 		user = NULL;
483 	}
484 	if (hostp != NULL) {
485 		*hostp = host;
486 		host = NULL;
487 	}
488 	if (portp != NULL)
489 		*portp = port;
490 	ret = 0;
491  out:
492 	free(sdup);
493 	free(user);
494 	free(host);
495 	return ret;
496 }
497 
498 /* function to assist building execv() arguments */
499 void
500 addargs(arglist *args, char *fmt, ...)
501 {
502 	va_list ap;
503 	char *cp;
504 	u_int nalloc;
505 	int r;
506 
507 	va_start(ap, fmt);
508 	r = vasprintf(&cp, fmt, ap);
509 	va_end(ap);
510 	if (r == -1)
511 		fatal("addargs: argument too long");
512 
513 	nalloc = args->nalloc;
514 	if (args->list == NULL) {
515 		nalloc = 32;
516 		args->num = 0;
517 	} else if (args->num+2 >= nalloc)
518 		nalloc *= 2;
519 
520 	args->list = xreallocarray(args->list, nalloc, sizeof(char *));
521 	args->nalloc = nalloc;
522 	args->list[args->num++] = cp;
523 	args->list[args->num] = NULL;
524 }
525 
526 void
527 replacearg(arglist *args, u_int which, char *fmt, ...)
528 {
529 	va_list ap;
530 	char *cp;
531 	int r;
532 
533 	va_start(ap, fmt);
534 	r = vasprintf(&cp, fmt, ap);
535 	va_end(ap);
536 	if (r == -1)
537 		fatal("replacearg: argument too long");
538 
539 	if (which >= args->num)
540 		fatal("replacearg: tried to replace invalid arg %d >= %d",
541 		    which, args->num);
542 	free(args->list[which]);
543 	args->list[which] = cp;
544 }
545 
546 void
547 freeargs(arglist *args)
548 {
549 	u_int i;
550 
551 	if (args->list != NULL) {
552 		for (i = 0; i < args->num; i++)
553 			free(args->list[i]);
554 		free(args->list);
555 		args->nalloc = args->num = 0;
556 		args->list = NULL;
557 	}
558 }
559 
560 /*
561  * Expands tildes in the file name.  Returns data allocated by xmalloc.
562  * Warning: this calls getpw*.
563  */
564 char *
565 tilde_expand_filename(const char *filename, uid_t uid)
566 {
567 	const char *path, *sep;
568 	char user[128], *ret;
569 	struct passwd *pw;
570 	u_int len, slash;
571 
572 	if (*filename != '~')
573 		return (xstrdup(filename));
574 	filename++;
575 
576 	path = strchr(filename, '/');
577 	if (path != NULL && path > filename) {		/* ~user/path */
578 		slash = path - filename;
579 		if (slash > sizeof(user) - 1)
580 			fatal("tilde_expand_filename: ~username too long");
581 		memcpy(user, filename, slash);
582 		user[slash] = '\0';
583 		if ((pw = getpwnam(user)) == NULL)
584 			fatal("tilde_expand_filename: No such user %s", user);
585 	} else if ((pw = getpwuid(uid)) == NULL)	/* ~/path */
586 		fatal("tilde_expand_filename: No such uid %ld", (long)uid);
587 
588 	/* Make sure directory has a trailing '/' */
589 	len = strlen(pw->pw_dir);
590 	if (len == 0 || pw->pw_dir[len - 1] != '/')
591 		sep = "/";
592 	else
593 		sep = "";
594 
595 	/* Skip leading '/' from specified path */
596 	if (path != NULL)
597 		filename = path + 1;
598 
599 	if (xasprintf(&ret, "%s%s%s", pw->pw_dir, sep, filename) >= PATH_MAX)
600 		fatal("tilde_expand_filename: Path too long");
601 
602 	return (ret);
603 }
604 
605 /*
606  * Expand a string with a set of %[char] escapes. A number of escapes may be
607  * specified as (char *escape_chars, char *replacement) pairs. The list must
608  * be terminated by a NULL escape_char. Returns replaced string in memory
609  * allocated by xmalloc.
610  */
611 char *
612 percent_expand(const char *string, ...)
613 {
614 #define EXPAND_MAX_KEYS	16
615 	u_int num_keys, i, j;
616 	struct {
617 		const char *key;
618 		const char *repl;
619 	} keys[EXPAND_MAX_KEYS];
620 	char buf[4096];
621 	va_list ap;
622 
623 	/* Gather keys */
624 	va_start(ap, string);
625 	for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
626 		keys[num_keys].key = va_arg(ap, char *);
627 		if (keys[num_keys].key == NULL)
628 			break;
629 		keys[num_keys].repl = va_arg(ap, char *);
630 		if (keys[num_keys].repl == NULL)
631 			fatal("%s: NULL replacement", __func__);
632 	}
633 	if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
634 		fatal("%s: too many keys", __func__);
635 	va_end(ap);
636 
637 	/* Expand string */
638 	*buf = '\0';
639 	for (i = 0; *string != '\0'; string++) {
640 		if (*string != '%') {
641  append:
642 			buf[i++] = *string;
643 			if (i >= sizeof(buf))
644 				fatal("%s: string too long", __func__);
645 			buf[i] = '\0';
646 			continue;
647 		}
648 		string++;
649 		/* %% case */
650 		if (*string == '%')
651 			goto append;
652 		if (*string == '\0')
653 			fatal("%s: invalid format", __func__);
654 		for (j = 0; j < num_keys; j++) {
655 			if (strchr(keys[j].key, *string) != NULL) {
656 				i = strlcat(buf, keys[j].repl, sizeof(buf));
657 				if (i >= sizeof(buf))
658 					fatal("%s: string too long", __func__);
659 				break;
660 			}
661 		}
662 		if (j >= num_keys)
663 			fatal("%s: unknown key %%%c", __func__, *string);
664 	}
665 	return (xstrdup(buf));
666 #undef EXPAND_MAX_KEYS
667 }
668 
669 /*
670  * Read an entire line from a public key file into a static buffer, discarding
671  * lines that exceed the buffer size.  Returns 0 on success, -1 on failure.
672  */
673 int
674 read_keyfile_line(FILE *f, const char *filename, char *buf, size_t bufsz,
675    u_long *lineno)
676 {
677 	while (fgets(buf, bufsz, f) != NULL) {
678 		if (buf[0] == '\0')
679 			continue;
680 		(*lineno)++;
681 		if (buf[strlen(buf) - 1] == '\n' || feof(f)) {
682 			return 0;
683 		} else {
684 			debug("%s: %s line %lu exceeds size limit", __func__,
685 			    filename, *lineno);
686 			/* discard remainder of line */
687 			while (fgetc(f) != '\n' && !feof(f))
688 				;	/* nothing */
689 		}
690 	}
691 	return -1;
692 }
693 
694 int
695 tun_open(int tun, int mode)
696 {
697 	struct ifreq ifr;
698 	char name[100];
699 	int fd = -1, sock;
700 	const char *tunbase = "tun";
701 
702 	if (mode == SSH_TUNMODE_ETHERNET)
703 		tunbase = "tap";
704 
705 	/* Open the tunnel device */
706 	if (tun <= SSH_TUNID_MAX) {
707 		snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
708 		fd = open(name, O_RDWR);
709 	} else if (tun == SSH_TUNID_ANY) {
710 		for (tun = 100; tun >= 0; tun--) {
711 			snprintf(name, sizeof(name), "/dev/%s%d",
712 			    tunbase, tun);
713 			if ((fd = open(name, O_RDWR)) >= 0)
714 				break;
715 		}
716 	} else {
717 		debug("%s: invalid tunnel %u", __func__, tun);
718 		return -1;
719 	}
720 
721 	if (fd < 0) {
722 		debug("%s: %s open: %s", __func__, name, strerror(errno));
723 		return -1;
724 	}
725 
726 	debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
727 
728 	/* Bring interface up if it is not already */
729 	snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
730 	if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
731 		goto failed;
732 
733 	if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
734 		debug("%s: get interface %s flags: %s", __func__,
735 		    ifr.ifr_name, strerror(errno));
736 		goto failed;
737 	}
738 
739 	if (!(ifr.ifr_flags & IFF_UP)) {
740 		ifr.ifr_flags |= IFF_UP;
741 		if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
742 			debug("%s: activate interface %s: %s", __func__,
743 			    ifr.ifr_name, strerror(errno));
744 			goto failed;
745 		}
746 	}
747 
748 	close(sock);
749 	return fd;
750 
751  failed:
752 	if (fd >= 0)
753 		close(fd);
754 	if (sock >= 0)
755 		close(sock);
756 	return -1;
757 }
758 
759 void
760 sanitise_stdfd(void)
761 {
762 	int nullfd, dupfd;
763 
764 	if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
765 		fprintf(stderr, "Couldn't open /dev/null: %s\n",
766 		    strerror(errno));
767 		exit(1);
768 	}
769 	while (++dupfd <= STDERR_FILENO) {
770 		/* Only populate closed fds. */
771 		if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
772 			if (dup2(nullfd, dupfd) == -1) {
773 				fprintf(stderr, "dup2: %s\n", strerror(errno));
774 				exit(1);
775 			}
776 		}
777 	}
778 	if (nullfd > STDERR_FILENO)
779 		close(nullfd);
780 }
781 
782 char *
783 tohex(const void *vp, size_t l)
784 {
785 	const u_char *p = (const u_char *)vp;
786 	char b[3], *r;
787 	size_t i, hl;
788 
789 	if (l > 65536)
790 		return xstrdup("tohex: length > 65536");
791 
792 	hl = l * 2 + 1;
793 	r = xcalloc(1, hl);
794 	for (i = 0; i < l; i++) {
795 		snprintf(b, sizeof(b), "%02x", p[i]);
796 		strlcat(r, b, hl);
797 	}
798 	return (r);
799 }
800 
801 u_int64_t
802 get_u64(const void *vp)
803 {
804 	const u_char *p = (const u_char *)vp;
805 	u_int64_t v;
806 
807 	v  = (u_int64_t)p[0] << 56;
808 	v |= (u_int64_t)p[1] << 48;
809 	v |= (u_int64_t)p[2] << 40;
810 	v |= (u_int64_t)p[3] << 32;
811 	v |= (u_int64_t)p[4] << 24;
812 	v |= (u_int64_t)p[5] << 16;
813 	v |= (u_int64_t)p[6] << 8;
814 	v |= (u_int64_t)p[7];
815 
816 	return (v);
817 }
818 
819 u_int32_t
820 get_u32(const void *vp)
821 {
822 	const u_char *p = (const u_char *)vp;
823 	u_int32_t v;
824 
825 	v  = (u_int32_t)p[0] << 24;
826 	v |= (u_int32_t)p[1] << 16;
827 	v |= (u_int32_t)p[2] << 8;
828 	v |= (u_int32_t)p[3];
829 
830 	return (v);
831 }
832 
833 u_int32_t
834 get_u32_le(const void *vp)
835 {
836 	const u_char *p = (const u_char *)vp;
837 	u_int32_t v;
838 
839 	v  = (u_int32_t)p[0];
840 	v |= (u_int32_t)p[1] << 8;
841 	v |= (u_int32_t)p[2] << 16;
842 	v |= (u_int32_t)p[3] << 24;
843 
844 	return (v);
845 }
846 
847 u_int16_t
848 get_u16(const void *vp)
849 {
850 	const u_char *p = (const u_char *)vp;
851 	u_int16_t v;
852 
853 	v  = (u_int16_t)p[0] << 8;
854 	v |= (u_int16_t)p[1];
855 
856 	return (v);
857 }
858 
859 void
860 put_u64(void *vp, u_int64_t v)
861 {
862 	u_char *p = (u_char *)vp;
863 
864 	p[0] = (u_char)(v >> 56) & 0xff;
865 	p[1] = (u_char)(v >> 48) & 0xff;
866 	p[2] = (u_char)(v >> 40) & 0xff;
867 	p[3] = (u_char)(v >> 32) & 0xff;
868 	p[4] = (u_char)(v >> 24) & 0xff;
869 	p[5] = (u_char)(v >> 16) & 0xff;
870 	p[6] = (u_char)(v >> 8) & 0xff;
871 	p[7] = (u_char)v & 0xff;
872 }
873 
874 void
875 put_u32(void *vp, u_int32_t v)
876 {
877 	u_char *p = (u_char *)vp;
878 
879 	p[0] = (u_char)(v >> 24) & 0xff;
880 	p[1] = (u_char)(v >> 16) & 0xff;
881 	p[2] = (u_char)(v >> 8) & 0xff;
882 	p[3] = (u_char)v & 0xff;
883 }
884 
885 void
886 put_u32_le(void *vp, u_int32_t v)
887 {
888 	u_char *p = (u_char *)vp;
889 
890 	p[0] = (u_char)v & 0xff;
891 	p[1] = (u_char)(v >> 8) & 0xff;
892 	p[2] = (u_char)(v >> 16) & 0xff;
893 	p[3] = (u_char)(v >> 24) & 0xff;
894 }
895 
896 void
897 put_u16(void *vp, u_int16_t v)
898 {
899 	u_char *p = (u_char *)vp;
900 
901 	p[0] = (u_char)(v >> 8) & 0xff;
902 	p[1] = (u_char)v & 0xff;
903 }
904 
905 void
906 ms_subtract_diff(struct timeval *start, int *ms)
907 {
908 	struct timeval diff, finish;
909 
910 	gettimeofday(&finish, NULL);
911 	timersub(&finish, start, &diff);
912 	*ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
913 }
914 
915 void
916 ms_to_timeval(struct timeval *tv, int ms)
917 {
918 	if (ms < 0)
919 		ms = 0;
920 	tv->tv_sec = ms / 1000;
921 	tv->tv_usec = (ms % 1000) * 1000;
922 }
923 
924 time_t
925 monotime(void)
926 {
927 	struct timespec ts;
928 
929 	if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
930 		fatal("clock_gettime: %s", strerror(errno));
931 
932 	return (ts.tv_sec);
933 }
934 
935 double
936 monotime_double(void)
937 {
938 	struct timespec ts;
939 
940 	if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
941 		fatal("clock_gettime: %s", strerror(errno));
942 
943 	return (ts.tv_sec + (double)ts.tv_nsec / 1000000000);
944 }
945 
946 void
947 bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
948 {
949 	bw->buflen = buflen;
950 	bw->rate = kbps;
951 	bw->thresh = bw->rate;
952 	bw->lamt = 0;
953 	timerclear(&bw->bwstart);
954 	timerclear(&bw->bwend);
955 }
956 
957 /* Callback from read/write loop to insert bandwidth-limiting delays */
958 void
959 bandwidth_limit(struct bwlimit *bw, size_t read_len)
960 {
961 	u_int64_t waitlen;
962 	struct timespec ts, rm;
963 
964 	if (!timerisset(&bw->bwstart)) {
965 		gettimeofday(&bw->bwstart, NULL);
966 		return;
967 	}
968 
969 	bw->lamt += read_len;
970 	if (bw->lamt < bw->thresh)
971 		return;
972 
973 	gettimeofday(&bw->bwend, NULL);
974 	timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
975 	if (!timerisset(&bw->bwend))
976 		return;
977 
978 	bw->lamt *= 8;
979 	waitlen = (double)1000000L * bw->lamt / bw->rate;
980 
981 	bw->bwstart.tv_sec = waitlen / 1000000L;
982 	bw->bwstart.tv_usec = waitlen % 1000000L;
983 
984 	if (timercmp(&bw->bwstart, &bw->bwend, >)) {
985 		timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
986 
987 		/* Adjust the wait time */
988 		if (bw->bwend.tv_sec) {
989 			bw->thresh /= 2;
990 			if (bw->thresh < bw->buflen / 4)
991 				bw->thresh = bw->buflen / 4;
992 		} else if (bw->bwend.tv_usec < 10000) {
993 			bw->thresh *= 2;
994 			if (bw->thresh > bw->buflen * 8)
995 				bw->thresh = bw->buflen * 8;
996 		}
997 
998 		TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
999 		while (nanosleep(&ts, &rm) == -1) {
1000 			if (errno != EINTR)
1001 				break;
1002 			ts = rm;
1003 		}
1004 	}
1005 
1006 	bw->lamt = 0;
1007 	gettimeofday(&bw->bwstart, NULL);
1008 }
1009 
1010 /* Make a template filename for mk[sd]temp() */
1011 void
1012 mktemp_proto(char *s, size_t len)
1013 {
1014 	const char *tmpdir;
1015 	int r;
1016 
1017 	if ((tmpdir = getenv("TMPDIR")) != NULL) {
1018 		r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
1019 		if (r > 0 && (size_t)r < len)
1020 			return;
1021 	}
1022 	r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
1023 	if (r < 0 || (size_t)r >= len)
1024 		fatal("%s: template string too short", __func__);
1025 }
1026 
1027 static const struct {
1028 	const char *name;
1029 	int value;
1030 } ipqos[] = {
1031 	{ "af11", IPTOS_DSCP_AF11 },
1032 	{ "af12", IPTOS_DSCP_AF12 },
1033 	{ "af13", IPTOS_DSCP_AF13 },
1034 	{ "af21", IPTOS_DSCP_AF21 },
1035 	{ "af22", IPTOS_DSCP_AF22 },
1036 	{ "af23", IPTOS_DSCP_AF23 },
1037 	{ "af31", IPTOS_DSCP_AF31 },
1038 	{ "af32", IPTOS_DSCP_AF32 },
1039 	{ "af33", IPTOS_DSCP_AF33 },
1040 	{ "af41", IPTOS_DSCP_AF41 },
1041 	{ "af42", IPTOS_DSCP_AF42 },
1042 	{ "af43", IPTOS_DSCP_AF43 },
1043 	{ "cs0", IPTOS_DSCP_CS0 },
1044 	{ "cs1", IPTOS_DSCP_CS1 },
1045 	{ "cs2", IPTOS_DSCP_CS2 },
1046 	{ "cs3", IPTOS_DSCP_CS3 },
1047 	{ "cs4", IPTOS_DSCP_CS4 },
1048 	{ "cs5", IPTOS_DSCP_CS5 },
1049 	{ "cs6", IPTOS_DSCP_CS6 },
1050 	{ "cs7", IPTOS_DSCP_CS7 },
1051 	{ "ef", IPTOS_DSCP_EF },
1052 	{ "lowdelay", IPTOS_LOWDELAY },
1053 	{ "throughput", IPTOS_THROUGHPUT },
1054 	{ "reliability", IPTOS_RELIABILITY },
1055 	{ NULL, -1 }
1056 };
1057 
1058 int
1059 parse_ipqos(const char *cp)
1060 {
1061 	u_int i;
1062 	char *ep;
1063 	long val;
1064 
1065 	if (cp == NULL)
1066 		return -1;
1067 	for (i = 0; ipqos[i].name != NULL; i++) {
1068 		if (strcasecmp(cp, ipqos[i].name) == 0)
1069 			return ipqos[i].value;
1070 	}
1071 	/* Try parsing as an integer */
1072 	val = strtol(cp, &ep, 0);
1073 	if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1074 		return -1;
1075 	return val;
1076 }
1077 
1078 const char *
1079 iptos2str(int iptos)
1080 {
1081 	int i;
1082 	static char iptos_str[sizeof "0xff"];
1083 
1084 	for (i = 0; ipqos[i].name != NULL; i++) {
1085 		if (ipqos[i].value == iptos)
1086 			return ipqos[i].name;
1087 	}
1088 	snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1089 	return iptos_str;
1090 }
1091 
1092 void
1093 lowercase(char *s)
1094 {
1095 	for (; *s; s++)
1096 		*s = tolower((u_char)*s);
1097 }
1098 
1099 int
1100 unix_listener(const char *path, int backlog, int unlink_first)
1101 {
1102 	struct sockaddr_un sunaddr;
1103 	int saved_errno, sock;
1104 
1105 	memset(&sunaddr, 0, sizeof(sunaddr));
1106 	sunaddr.sun_family = AF_UNIX;
1107 	if (strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1108 		error("%s: \"%s\" too long for Unix domain socket", __func__,
1109 		    path);
1110 		errno = ENAMETOOLONG;
1111 		return -1;
1112 	}
1113 
1114 	sock = socket(PF_UNIX, SOCK_STREAM, 0);
1115 	if (sock < 0) {
1116 		saved_errno = errno;
1117 		error("socket: %.100s", strerror(errno));
1118 		errno = saved_errno;
1119 		return -1;
1120 	}
1121 	if (unlink_first == 1) {
1122 		if (unlink(path) != 0 && errno != ENOENT)
1123 			error("unlink(%s): %.100s", path, strerror(errno));
1124 	}
1125 	if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0) {
1126 		saved_errno = errno;
1127 		error("bind: %.100s", strerror(errno));
1128 		close(sock);
1129 		error("%s: cannot bind to path: %s", __func__, path);
1130 		errno = saved_errno;
1131 		return -1;
1132 	}
1133 	if (listen(sock, backlog) < 0) {
1134 		saved_errno = errno;
1135 		error("listen: %.100s", strerror(errno));
1136 		close(sock);
1137 		unlink(path);
1138 		error("%s: cannot listen on path: %s", __func__, path);
1139 		errno = saved_errno;
1140 		return -1;
1141 	}
1142 	return sock;
1143 }
1144 
1145 /*
1146  * Compares two strings that maybe be NULL. Returns non-zero if strings
1147  * are both NULL or are identical, returns zero otherwise.
1148  */
1149 static int
1150 strcmp_maybe_null(const char *a, const char *b)
1151 {
1152 	if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1153 		return 0;
1154 	if (a != NULL && strcmp(a, b) != 0)
1155 		return 0;
1156 	return 1;
1157 }
1158 
1159 /*
1160  * Compare two forwards, returning non-zero if they are identical or
1161  * zero otherwise.
1162  */
1163 int
1164 forward_equals(const struct Forward *a, const struct Forward *b)
1165 {
1166 	if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
1167 		return 0;
1168 	if (a->listen_port != b->listen_port)
1169 		return 0;
1170 	if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
1171 		return 0;
1172 	if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
1173 		return 0;
1174 	if (a->connect_port != b->connect_port)
1175 		return 0;
1176 	if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
1177 		return 0;
1178 	/* allocated_port and handle are not checked */
1179 	return 1;
1180 }
1181 
1182