xref: /openbsd-src/usr.bin/ssh/misc.c (revision f933361f20df4def12f9bc8391f68d6bfad3bb75)
1 /* $OpenBSD: misc.c,v 1.110 2017/05/31 09:15:42 deraadt Exp $ */
2 /*
3  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
4  * Copyright (c) 2005,2006 Damien Miller.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include <sys/types.h>
28 #include <sys/ioctl.h>
29 #include <sys/socket.h>
30 #include <sys/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, multiplier = 1;
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 			multiplier = MINUTES;
320 			break;
321 		case 'h':
322 		case 'H':
323 			multiplier = HOURS;
324 			break;
325 		case 'd':
326 		case 'D':
327 			multiplier = DAYS;
328 			break;
329 		case 'w':
330 		case 'W':
331 			multiplier = WEEKS;
332 			break;
333 		default:
334 			return -1;
335 		}
336 		if (secs >= LONG_MAX / multiplier)
337 			return -1;
338 		secs *= multiplier;
339 		if  (total >= LONG_MAX - secs)
340 			return -1;
341 		total += secs;
342 		if (total < 0)
343 			return -1;
344 		p = endp;
345 	}
346 
347 	return total;
348 }
349 
350 /*
351  * Returns a standardized host+port identifier string.
352  * Caller must free returned string.
353  */
354 char *
355 put_host_port(const char *host, u_short port)
356 {
357 	char *hoststr;
358 
359 	if (port == 0 || port == SSH_DEFAULT_PORT)
360 		return(xstrdup(host));
361 	if (asprintf(&hoststr, "[%s]:%d", host, (int)port) < 0)
362 		fatal("put_host_port: asprintf: %s", strerror(errno));
363 	debug3("put_host_port: %s", hoststr);
364 	return hoststr;
365 }
366 
367 /*
368  * Search for next delimiter between hostnames/addresses and ports.
369  * Argument may be modified (for termination).
370  * Returns *cp if parsing succeeds.
371  * *cp is set to the start of the next delimiter, if one was found.
372  * If this is the last field, *cp is set to NULL.
373  */
374 char *
375 hpdelim(char **cp)
376 {
377 	char *s, *old;
378 
379 	if (cp == NULL || *cp == NULL)
380 		return NULL;
381 
382 	old = s = *cp;
383 	if (*s == '[') {
384 		if ((s = strchr(s, ']')) == NULL)
385 			return NULL;
386 		else
387 			s++;
388 	} else if ((s = strpbrk(s, ":/")) == NULL)
389 		s = *cp + strlen(*cp); /* skip to end (see first case below) */
390 
391 	switch (*s) {
392 	case '\0':
393 		*cp = NULL;	/* no more fields*/
394 		break;
395 
396 	case ':':
397 	case '/':
398 		*s = '\0';	/* terminate */
399 		*cp = s + 1;
400 		break;
401 
402 	default:
403 		return NULL;
404 	}
405 
406 	return old;
407 }
408 
409 char *
410 cleanhostname(char *host)
411 {
412 	if (*host == '[' && host[strlen(host) - 1] == ']') {
413 		host[strlen(host) - 1] = '\0';
414 		return (host + 1);
415 	} else
416 		return host;
417 }
418 
419 char *
420 colon(char *cp)
421 {
422 	int flag = 0;
423 
424 	if (*cp == ':')		/* Leading colon is part of file name. */
425 		return NULL;
426 	if (*cp == '[')
427 		flag = 1;
428 
429 	for (; *cp; ++cp) {
430 		if (*cp == '@' && *(cp+1) == '[')
431 			flag = 1;
432 		if (*cp == ']' && *(cp+1) == ':' && flag)
433 			return (cp+1);
434 		if (*cp == ':' && !flag)
435 			return (cp);
436 		if (*cp == '/')
437 			return NULL;
438 	}
439 	return NULL;
440 }
441 
442 /*
443  * Parse a [user@]host[:port] string.
444  * Caller must free returned user and host.
445  * Any of the pointer return arguments may be NULL (useful for syntax checking).
446  * If user was not specified then *userp will be set to NULL.
447  * If port was not specified then *portp will be -1.
448  * Returns 0 on success, -1 on failure.
449  */
450 int
451 parse_user_host_port(const char *s, char **userp, char **hostp, int *portp)
452 {
453 	char *sdup, *cp, *tmp;
454 	char *user = NULL, *host = NULL;
455 	int port = -1, ret = -1;
456 
457 	if (userp != NULL)
458 		*userp = NULL;
459 	if (hostp != NULL)
460 		*hostp = NULL;
461 	if (portp != NULL)
462 		*portp = -1;
463 
464 	if ((sdup = tmp = strdup(s)) == NULL)
465 		return -1;
466 	/* Extract optional username */
467 	if ((cp = strchr(tmp, '@')) != NULL) {
468 		*cp = '\0';
469 		if (*tmp == '\0')
470 			goto out;
471 		if ((user = strdup(tmp)) == NULL)
472 			goto out;
473 		tmp = cp + 1;
474 	}
475 	/* Extract mandatory hostname */
476 	if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0')
477 		goto out;
478 	host = xstrdup(cleanhostname(cp));
479 	/* Convert and verify optional port */
480 	if (tmp != NULL && *tmp != '\0') {
481 		if ((port = a2port(tmp)) <= 0)
482 			goto out;
483 	}
484 	/* Success */
485 	if (userp != NULL) {
486 		*userp = user;
487 		user = NULL;
488 	}
489 	if (hostp != NULL) {
490 		*hostp = host;
491 		host = NULL;
492 	}
493 	if (portp != NULL)
494 		*portp = port;
495 	ret = 0;
496  out:
497 	free(sdup);
498 	free(user);
499 	free(host);
500 	return ret;
501 }
502 
503 /* function to assist building execv() arguments */
504 void
505 addargs(arglist *args, char *fmt, ...)
506 {
507 	va_list ap;
508 	char *cp;
509 	u_int nalloc;
510 	int r;
511 
512 	va_start(ap, fmt);
513 	r = vasprintf(&cp, fmt, ap);
514 	va_end(ap);
515 	if (r == -1)
516 		fatal("addargs: argument too long");
517 
518 	nalloc = args->nalloc;
519 	if (args->list == NULL) {
520 		nalloc = 32;
521 		args->num = 0;
522 	} else if (args->num+2 >= nalloc)
523 		nalloc *= 2;
524 
525 	args->list = xrecallocarray(args->list, args->nalloc, nalloc, sizeof(char *));
526 	args->nalloc = nalloc;
527 	args->list[args->num++] = cp;
528 	args->list[args->num] = NULL;
529 }
530 
531 void
532 replacearg(arglist *args, u_int which, char *fmt, ...)
533 {
534 	va_list ap;
535 	char *cp;
536 	int r;
537 
538 	va_start(ap, fmt);
539 	r = vasprintf(&cp, fmt, ap);
540 	va_end(ap);
541 	if (r == -1)
542 		fatal("replacearg: argument too long");
543 
544 	if (which >= args->num)
545 		fatal("replacearg: tried to replace invalid arg %d >= %d",
546 		    which, args->num);
547 	free(args->list[which]);
548 	args->list[which] = cp;
549 }
550 
551 void
552 freeargs(arglist *args)
553 {
554 	u_int i;
555 
556 	if (args->list != NULL) {
557 		for (i = 0; i < args->num; i++)
558 			free(args->list[i]);
559 		free(args->list);
560 		args->nalloc = args->num = 0;
561 		args->list = NULL;
562 	}
563 }
564 
565 /*
566  * Expands tildes in the file name.  Returns data allocated by xmalloc.
567  * Warning: this calls getpw*.
568  */
569 char *
570 tilde_expand_filename(const char *filename, uid_t uid)
571 {
572 	const char *path, *sep;
573 	char user[128], *ret;
574 	struct passwd *pw;
575 	u_int len, slash;
576 
577 	if (*filename != '~')
578 		return (xstrdup(filename));
579 	filename++;
580 
581 	path = strchr(filename, '/');
582 	if (path != NULL && path > filename) {		/* ~user/path */
583 		slash = path - filename;
584 		if (slash > sizeof(user) - 1)
585 			fatal("tilde_expand_filename: ~username too long");
586 		memcpy(user, filename, slash);
587 		user[slash] = '\0';
588 		if ((pw = getpwnam(user)) == NULL)
589 			fatal("tilde_expand_filename: No such user %s", user);
590 	} else if ((pw = getpwuid(uid)) == NULL)	/* ~/path */
591 		fatal("tilde_expand_filename: No such uid %ld", (long)uid);
592 
593 	/* Make sure directory has a trailing '/' */
594 	len = strlen(pw->pw_dir);
595 	if (len == 0 || pw->pw_dir[len - 1] != '/')
596 		sep = "/";
597 	else
598 		sep = "";
599 
600 	/* Skip leading '/' from specified path */
601 	if (path != NULL)
602 		filename = path + 1;
603 
604 	if (xasprintf(&ret, "%s%s%s", pw->pw_dir, sep, filename) >= PATH_MAX)
605 		fatal("tilde_expand_filename: Path too long");
606 
607 	return (ret);
608 }
609 
610 /*
611  * Expand a string with a set of %[char] escapes. A number of escapes may be
612  * specified as (char *escape_chars, char *replacement) pairs. The list must
613  * be terminated by a NULL escape_char. Returns replaced string in memory
614  * allocated by xmalloc.
615  */
616 char *
617 percent_expand(const char *string, ...)
618 {
619 #define EXPAND_MAX_KEYS	16
620 	u_int num_keys, i, j;
621 	struct {
622 		const char *key;
623 		const char *repl;
624 	} keys[EXPAND_MAX_KEYS];
625 	char buf[4096];
626 	va_list ap;
627 
628 	/* Gather keys */
629 	va_start(ap, string);
630 	for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
631 		keys[num_keys].key = va_arg(ap, char *);
632 		if (keys[num_keys].key == NULL)
633 			break;
634 		keys[num_keys].repl = va_arg(ap, char *);
635 		if (keys[num_keys].repl == NULL)
636 			fatal("%s: NULL replacement", __func__);
637 	}
638 	if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
639 		fatal("%s: too many keys", __func__);
640 	va_end(ap);
641 
642 	/* Expand string */
643 	*buf = '\0';
644 	for (i = 0; *string != '\0'; string++) {
645 		if (*string != '%') {
646  append:
647 			buf[i++] = *string;
648 			if (i >= sizeof(buf))
649 				fatal("%s: string too long", __func__);
650 			buf[i] = '\0';
651 			continue;
652 		}
653 		string++;
654 		/* %% case */
655 		if (*string == '%')
656 			goto append;
657 		if (*string == '\0')
658 			fatal("%s: invalid format", __func__);
659 		for (j = 0; j < num_keys; j++) {
660 			if (strchr(keys[j].key, *string) != NULL) {
661 				i = strlcat(buf, keys[j].repl, sizeof(buf));
662 				if (i >= sizeof(buf))
663 					fatal("%s: string too long", __func__);
664 				break;
665 			}
666 		}
667 		if (j >= num_keys)
668 			fatal("%s: unknown key %%%c", __func__, *string);
669 	}
670 	return (xstrdup(buf));
671 #undef EXPAND_MAX_KEYS
672 }
673 
674 /*
675  * Read an entire line from a public key file into a static buffer, discarding
676  * lines that exceed the buffer size.  Returns 0 on success, -1 on failure.
677  */
678 int
679 read_keyfile_line(FILE *f, const char *filename, char *buf, size_t bufsz,
680    u_long *lineno)
681 {
682 	while (fgets(buf, bufsz, f) != NULL) {
683 		if (buf[0] == '\0')
684 			continue;
685 		(*lineno)++;
686 		if (buf[strlen(buf) - 1] == '\n' || feof(f)) {
687 			return 0;
688 		} else {
689 			debug("%s: %s line %lu exceeds size limit", __func__,
690 			    filename, *lineno);
691 			/* discard remainder of line */
692 			while (fgetc(f) != '\n' && !feof(f))
693 				;	/* nothing */
694 		}
695 	}
696 	return -1;
697 }
698 
699 int
700 tun_open(int tun, int mode)
701 {
702 	struct ifreq ifr;
703 	char name[100];
704 	int fd = -1, sock;
705 	const char *tunbase = "tun";
706 
707 	if (mode == SSH_TUNMODE_ETHERNET)
708 		tunbase = "tap";
709 
710 	/* Open the tunnel device */
711 	if (tun <= SSH_TUNID_MAX) {
712 		snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
713 		fd = open(name, O_RDWR);
714 	} else if (tun == SSH_TUNID_ANY) {
715 		for (tun = 100; tun >= 0; tun--) {
716 			snprintf(name, sizeof(name), "/dev/%s%d",
717 			    tunbase, tun);
718 			if ((fd = open(name, O_RDWR)) >= 0)
719 				break;
720 		}
721 	} else {
722 		debug("%s: invalid tunnel %u", __func__, tun);
723 		return -1;
724 	}
725 
726 	if (fd < 0) {
727 		debug("%s: %s open: %s", __func__, name, strerror(errno));
728 		return -1;
729 	}
730 
731 	debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
732 
733 	/* Bring interface up if it is not already */
734 	snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
735 	if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
736 		goto failed;
737 
738 	if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
739 		debug("%s: get interface %s flags: %s", __func__,
740 		    ifr.ifr_name, strerror(errno));
741 		goto failed;
742 	}
743 
744 	if (!(ifr.ifr_flags & IFF_UP)) {
745 		ifr.ifr_flags |= IFF_UP;
746 		if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
747 			debug("%s: activate interface %s: %s", __func__,
748 			    ifr.ifr_name, strerror(errno));
749 			goto failed;
750 		}
751 	}
752 
753 	close(sock);
754 	return fd;
755 
756  failed:
757 	if (fd >= 0)
758 		close(fd);
759 	if (sock >= 0)
760 		close(sock);
761 	return -1;
762 }
763 
764 void
765 sanitise_stdfd(void)
766 {
767 	int nullfd, dupfd;
768 
769 	if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
770 		fprintf(stderr, "Couldn't open /dev/null: %s\n",
771 		    strerror(errno));
772 		exit(1);
773 	}
774 	while (++dupfd <= STDERR_FILENO) {
775 		/* Only populate closed fds. */
776 		if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
777 			if (dup2(nullfd, dupfd) == -1) {
778 				fprintf(stderr, "dup2: %s\n", strerror(errno));
779 				exit(1);
780 			}
781 		}
782 	}
783 	if (nullfd > STDERR_FILENO)
784 		close(nullfd);
785 }
786 
787 char *
788 tohex(const void *vp, size_t l)
789 {
790 	const u_char *p = (const u_char *)vp;
791 	char b[3], *r;
792 	size_t i, hl;
793 
794 	if (l > 65536)
795 		return xstrdup("tohex: length > 65536");
796 
797 	hl = l * 2 + 1;
798 	r = xcalloc(1, hl);
799 	for (i = 0; i < l; i++) {
800 		snprintf(b, sizeof(b), "%02x", p[i]);
801 		strlcat(r, b, hl);
802 	}
803 	return (r);
804 }
805 
806 u_int64_t
807 get_u64(const void *vp)
808 {
809 	const u_char *p = (const u_char *)vp;
810 	u_int64_t v;
811 
812 	v  = (u_int64_t)p[0] << 56;
813 	v |= (u_int64_t)p[1] << 48;
814 	v |= (u_int64_t)p[2] << 40;
815 	v |= (u_int64_t)p[3] << 32;
816 	v |= (u_int64_t)p[4] << 24;
817 	v |= (u_int64_t)p[5] << 16;
818 	v |= (u_int64_t)p[6] << 8;
819 	v |= (u_int64_t)p[7];
820 
821 	return (v);
822 }
823 
824 u_int32_t
825 get_u32(const void *vp)
826 {
827 	const u_char *p = (const u_char *)vp;
828 	u_int32_t v;
829 
830 	v  = (u_int32_t)p[0] << 24;
831 	v |= (u_int32_t)p[1] << 16;
832 	v |= (u_int32_t)p[2] << 8;
833 	v |= (u_int32_t)p[3];
834 
835 	return (v);
836 }
837 
838 u_int32_t
839 get_u32_le(const void *vp)
840 {
841 	const u_char *p = (const u_char *)vp;
842 	u_int32_t v;
843 
844 	v  = (u_int32_t)p[0];
845 	v |= (u_int32_t)p[1] << 8;
846 	v |= (u_int32_t)p[2] << 16;
847 	v |= (u_int32_t)p[3] << 24;
848 
849 	return (v);
850 }
851 
852 u_int16_t
853 get_u16(const void *vp)
854 {
855 	const u_char *p = (const u_char *)vp;
856 	u_int16_t v;
857 
858 	v  = (u_int16_t)p[0] << 8;
859 	v |= (u_int16_t)p[1];
860 
861 	return (v);
862 }
863 
864 void
865 put_u64(void *vp, u_int64_t v)
866 {
867 	u_char *p = (u_char *)vp;
868 
869 	p[0] = (u_char)(v >> 56) & 0xff;
870 	p[1] = (u_char)(v >> 48) & 0xff;
871 	p[2] = (u_char)(v >> 40) & 0xff;
872 	p[3] = (u_char)(v >> 32) & 0xff;
873 	p[4] = (u_char)(v >> 24) & 0xff;
874 	p[5] = (u_char)(v >> 16) & 0xff;
875 	p[6] = (u_char)(v >> 8) & 0xff;
876 	p[7] = (u_char)v & 0xff;
877 }
878 
879 void
880 put_u32(void *vp, u_int32_t v)
881 {
882 	u_char *p = (u_char *)vp;
883 
884 	p[0] = (u_char)(v >> 24) & 0xff;
885 	p[1] = (u_char)(v >> 16) & 0xff;
886 	p[2] = (u_char)(v >> 8) & 0xff;
887 	p[3] = (u_char)v & 0xff;
888 }
889 
890 void
891 put_u32_le(void *vp, u_int32_t v)
892 {
893 	u_char *p = (u_char *)vp;
894 
895 	p[0] = (u_char)v & 0xff;
896 	p[1] = (u_char)(v >> 8) & 0xff;
897 	p[2] = (u_char)(v >> 16) & 0xff;
898 	p[3] = (u_char)(v >> 24) & 0xff;
899 }
900 
901 void
902 put_u16(void *vp, u_int16_t v)
903 {
904 	u_char *p = (u_char *)vp;
905 
906 	p[0] = (u_char)(v >> 8) & 0xff;
907 	p[1] = (u_char)v & 0xff;
908 }
909 
910 void
911 ms_subtract_diff(struct timeval *start, int *ms)
912 {
913 	struct timeval diff, finish;
914 
915 	gettimeofday(&finish, NULL);
916 	timersub(&finish, start, &diff);
917 	*ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
918 }
919 
920 void
921 ms_to_timeval(struct timeval *tv, int ms)
922 {
923 	if (ms < 0)
924 		ms = 0;
925 	tv->tv_sec = ms / 1000;
926 	tv->tv_usec = (ms % 1000) * 1000;
927 }
928 
929 time_t
930 monotime(void)
931 {
932 	struct timespec ts;
933 
934 	if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
935 		fatal("clock_gettime: %s", strerror(errno));
936 
937 	return (ts.tv_sec);
938 }
939 
940 double
941 monotime_double(void)
942 {
943 	struct timespec ts;
944 
945 	if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
946 		fatal("clock_gettime: %s", strerror(errno));
947 
948 	return (ts.tv_sec + (double)ts.tv_nsec / 1000000000);
949 }
950 
951 void
952 bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
953 {
954 	bw->buflen = buflen;
955 	bw->rate = kbps;
956 	bw->thresh = bw->rate;
957 	bw->lamt = 0;
958 	timerclear(&bw->bwstart);
959 	timerclear(&bw->bwend);
960 }
961 
962 /* Callback from read/write loop to insert bandwidth-limiting delays */
963 void
964 bandwidth_limit(struct bwlimit *bw, size_t read_len)
965 {
966 	u_int64_t waitlen;
967 	struct timespec ts, rm;
968 
969 	if (!timerisset(&bw->bwstart)) {
970 		gettimeofday(&bw->bwstart, NULL);
971 		return;
972 	}
973 
974 	bw->lamt += read_len;
975 	if (bw->lamt < bw->thresh)
976 		return;
977 
978 	gettimeofday(&bw->bwend, NULL);
979 	timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
980 	if (!timerisset(&bw->bwend))
981 		return;
982 
983 	bw->lamt *= 8;
984 	waitlen = (double)1000000L * bw->lamt / bw->rate;
985 
986 	bw->bwstart.tv_sec = waitlen / 1000000L;
987 	bw->bwstart.tv_usec = waitlen % 1000000L;
988 
989 	if (timercmp(&bw->bwstart, &bw->bwend, >)) {
990 		timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
991 
992 		/* Adjust the wait time */
993 		if (bw->bwend.tv_sec) {
994 			bw->thresh /= 2;
995 			if (bw->thresh < bw->buflen / 4)
996 				bw->thresh = bw->buflen / 4;
997 		} else if (bw->bwend.tv_usec < 10000) {
998 			bw->thresh *= 2;
999 			if (bw->thresh > bw->buflen * 8)
1000 				bw->thresh = bw->buflen * 8;
1001 		}
1002 
1003 		TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
1004 		while (nanosleep(&ts, &rm) == -1) {
1005 			if (errno != EINTR)
1006 				break;
1007 			ts = rm;
1008 		}
1009 	}
1010 
1011 	bw->lamt = 0;
1012 	gettimeofday(&bw->bwstart, NULL);
1013 }
1014 
1015 /* Make a template filename for mk[sd]temp() */
1016 void
1017 mktemp_proto(char *s, size_t len)
1018 {
1019 	const char *tmpdir;
1020 	int r;
1021 
1022 	if ((tmpdir = getenv("TMPDIR")) != NULL) {
1023 		r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
1024 		if (r > 0 && (size_t)r < len)
1025 			return;
1026 	}
1027 	r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
1028 	if (r < 0 || (size_t)r >= len)
1029 		fatal("%s: template string too short", __func__);
1030 }
1031 
1032 static const struct {
1033 	const char *name;
1034 	int value;
1035 } ipqos[] = {
1036 	{ "af11", IPTOS_DSCP_AF11 },
1037 	{ "af12", IPTOS_DSCP_AF12 },
1038 	{ "af13", IPTOS_DSCP_AF13 },
1039 	{ "af21", IPTOS_DSCP_AF21 },
1040 	{ "af22", IPTOS_DSCP_AF22 },
1041 	{ "af23", IPTOS_DSCP_AF23 },
1042 	{ "af31", IPTOS_DSCP_AF31 },
1043 	{ "af32", IPTOS_DSCP_AF32 },
1044 	{ "af33", IPTOS_DSCP_AF33 },
1045 	{ "af41", IPTOS_DSCP_AF41 },
1046 	{ "af42", IPTOS_DSCP_AF42 },
1047 	{ "af43", IPTOS_DSCP_AF43 },
1048 	{ "cs0", IPTOS_DSCP_CS0 },
1049 	{ "cs1", IPTOS_DSCP_CS1 },
1050 	{ "cs2", IPTOS_DSCP_CS2 },
1051 	{ "cs3", IPTOS_DSCP_CS3 },
1052 	{ "cs4", IPTOS_DSCP_CS4 },
1053 	{ "cs5", IPTOS_DSCP_CS5 },
1054 	{ "cs6", IPTOS_DSCP_CS6 },
1055 	{ "cs7", IPTOS_DSCP_CS7 },
1056 	{ "ef", IPTOS_DSCP_EF },
1057 	{ "lowdelay", IPTOS_LOWDELAY },
1058 	{ "throughput", IPTOS_THROUGHPUT },
1059 	{ "reliability", IPTOS_RELIABILITY },
1060 	{ NULL, -1 }
1061 };
1062 
1063 int
1064 parse_ipqos(const char *cp)
1065 {
1066 	u_int i;
1067 	char *ep;
1068 	long val;
1069 
1070 	if (cp == NULL)
1071 		return -1;
1072 	for (i = 0; ipqos[i].name != NULL; i++) {
1073 		if (strcasecmp(cp, ipqos[i].name) == 0)
1074 			return ipqos[i].value;
1075 	}
1076 	/* Try parsing as an integer */
1077 	val = strtol(cp, &ep, 0);
1078 	if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1079 		return -1;
1080 	return val;
1081 }
1082 
1083 const char *
1084 iptos2str(int iptos)
1085 {
1086 	int i;
1087 	static char iptos_str[sizeof "0xff"];
1088 
1089 	for (i = 0; ipqos[i].name != NULL; i++) {
1090 		if (ipqos[i].value == iptos)
1091 			return ipqos[i].name;
1092 	}
1093 	snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1094 	return iptos_str;
1095 }
1096 
1097 void
1098 lowercase(char *s)
1099 {
1100 	for (; *s; s++)
1101 		*s = tolower((u_char)*s);
1102 }
1103 
1104 int
1105 unix_listener(const char *path, int backlog, int unlink_first)
1106 {
1107 	struct sockaddr_un sunaddr;
1108 	int saved_errno, sock;
1109 
1110 	memset(&sunaddr, 0, sizeof(sunaddr));
1111 	sunaddr.sun_family = AF_UNIX;
1112 	if (strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1113 		error("%s: \"%s\" too long for Unix domain socket", __func__,
1114 		    path);
1115 		errno = ENAMETOOLONG;
1116 		return -1;
1117 	}
1118 
1119 	sock = socket(PF_UNIX, SOCK_STREAM, 0);
1120 	if (sock < 0) {
1121 		saved_errno = errno;
1122 		error("socket: %.100s", strerror(errno));
1123 		errno = saved_errno;
1124 		return -1;
1125 	}
1126 	if (unlink_first == 1) {
1127 		if (unlink(path) != 0 && errno != ENOENT)
1128 			error("unlink(%s): %.100s", path, strerror(errno));
1129 	}
1130 	if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0) {
1131 		saved_errno = errno;
1132 		error("bind: %.100s", strerror(errno));
1133 		close(sock);
1134 		error("%s: cannot bind to path: %s", __func__, path);
1135 		errno = saved_errno;
1136 		return -1;
1137 	}
1138 	if (listen(sock, backlog) < 0) {
1139 		saved_errno = errno;
1140 		error("listen: %.100s", strerror(errno));
1141 		close(sock);
1142 		unlink(path);
1143 		error("%s: cannot listen on path: %s", __func__, path);
1144 		errno = saved_errno;
1145 		return -1;
1146 	}
1147 	return sock;
1148 }
1149 
1150 /*
1151  * Compares two strings that maybe be NULL. Returns non-zero if strings
1152  * are both NULL or are identical, returns zero otherwise.
1153  */
1154 static int
1155 strcmp_maybe_null(const char *a, const char *b)
1156 {
1157 	if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1158 		return 0;
1159 	if (a != NULL && strcmp(a, b) != 0)
1160 		return 0;
1161 	return 1;
1162 }
1163 
1164 /*
1165  * Compare two forwards, returning non-zero if they are identical or
1166  * zero otherwise.
1167  */
1168 int
1169 forward_equals(const struct Forward *a, const struct Forward *b)
1170 {
1171 	if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
1172 		return 0;
1173 	if (a->listen_port != b->listen_port)
1174 		return 0;
1175 	if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
1176 		return 0;
1177 	if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
1178 		return 0;
1179 	if (a->connect_port != b->connect_port)
1180 		return 0;
1181 	if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
1182 		return 0;
1183 	/* allocated_port and handle are not checked */
1184 	return 1;
1185 }
1186 
1187 /* returns 1 if bind to specified port by specified user is permitted */
1188 int
1189 bind_permitted(int port, uid_t uid)
1190 {
1191 	if (port < IPPORT_RESERVED && uid != 0)
1192 		return 0;
1193 	return 1;
1194 }
1195 
1196 /* returns 1 if process is already daemonized, 0 otherwise */
1197 int
1198 daemonized(void)
1199 {
1200 	int fd;
1201 
1202 	if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
1203 		close(fd);
1204 		return 0;	/* have controlling terminal */
1205 	}
1206 	if (getppid() != 1)
1207 		return 0;	/* parent is not init */
1208 	if (getsid(0) != getpid())
1209 		return 0;	/* not session leader */
1210 	debug3("already daemonized");
1211 	return 1;
1212 }
1213