xref: /openbsd-src/usr.bin/ssh/misc.c (revision 2777ee89d0e541ec819d05abee114837837abbec)
1 /* $OpenBSD: misc.c,v 1.104 2016/04/06 06:42:17 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 /* function to assist building execv() arguments */
438 void
439 addargs(arglist *args, char *fmt, ...)
440 {
441 	va_list ap;
442 	char *cp;
443 	u_int nalloc;
444 	int r;
445 
446 	va_start(ap, fmt);
447 	r = vasprintf(&cp, fmt, ap);
448 	va_end(ap);
449 	if (r == -1)
450 		fatal("addargs: argument too long");
451 
452 	nalloc = args->nalloc;
453 	if (args->list == NULL) {
454 		nalloc = 32;
455 		args->num = 0;
456 	} else if (args->num+2 >= nalloc)
457 		nalloc *= 2;
458 
459 	args->list = xreallocarray(args->list, nalloc, sizeof(char *));
460 	args->nalloc = nalloc;
461 	args->list[args->num++] = cp;
462 	args->list[args->num] = NULL;
463 }
464 
465 void
466 replacearg(arglist *args, u_int which, char *fmt, ...)
467 {
468 	va_list ap;
469 	char *cp;
470 	int r;
471 
472 	va_start(ap, fmt);
473 	r = vasprintf(&cp, fmt, ap);
474 	va_end(ap);
475 	if (r == -1)
476 		fatal("replacearg: argument too long");
477 
478 	if (which >= args->num)
479 		fatal("replacearg: tried to replace invalid arg %d >= %d",
480 		    which, args->num);
481 	free(args->list[which]);
482 	args->list[which] = cp;
483 }
484 
485 void
486 freeargs(arglist *args)
487 {
488 	u_int i;
489 
490 	if (args->list != NULL) {
491 		for (i = 0; i < args->num; i++)
492 			free(args->list[i]);
493 		free(args->list);
494 		args->nalloc = args->num = 0;
495 		args->list = NULL;
496 	}
497 }
498 
499 /*
500  * Expands tildes in the file name.  Returns data allocated by xmalloc.
501  * Warning: this calls getpw*.
502  */
503 char *
504 tilde_expand_filename(const char *filename, uid_t uid)
505 {
506 	const char *path, *sep;
507 	char user[128], *ret;
508 	struct passwd *pw;
509 	u_int len, slash;
510 
511 	if (*filename != '~')
512 		return (xstrdup(filename));
513 	filename++;
514 
515 	path = strchr(filename, '/');
516 	if (path != NULL && path > filename) {		/* ~user/path */
517 		slash = path - filename;
518 		if (slash > sizeof(user) - 1)
519 			fatal("tilde_expand_filename: ~username too long");
520 		memcpy(user, filename, slash);
521 		user[slash] = '\0';
522 		if ((pw = getpwnam(user)) == NULL)
523 			fatal("tilde_expand_filename: No such user %s", user);
524 	} else if ((pw = getpwuid(uid)) == NULL)	/* ~/path */
525 		fatal("tilde_expand_filename: No such uid %ld", (long)uid);
526 
527 	/* Make sure directory has a trailing '/' */
528 	len = strlen(pw->pw_dir);
529 	if (len == 0 || pw->pw_dir[len - 1] != '/')
530 		sep = "/";
531 	else
532 		sep = "";
533 
534 	/* Skip leading '/' from specified path */
535 	if (path != NULL)
536 		filename = path + 1;
537 
538 	if (xasprintf(&ret, "%s%s%s", pw->pw_dir, sep, filename) >= PATH_MAX)
539 		fatal("tilde_expand_filename: Path too long");
540 
541 	return (ret);
542 }
543 
544 /*
545  * Expand a string with a set of %[char] escapes. A number of escapes may be
546  * specified as (char *escape_chars, char *replacement) pairs. The list must
547  * be terminated by a NULL escape_char. Returns replaced string in memory
548  * allocated by xmalloc.
549  */
550 char *
551 percent_expand(const char *string, ...)
552 {
553 #define EXPAND_MAX_KEYS	16
554 	u_int num_keys, i, j;
555 	struct {
556 		const char *key;
557 		const char *repl;
558 	} keys[EXPAND_MAX_KEYS];
559 	char buf[4096];
560 	va_list ap;
561 
562 	/* Gather keys */
563 	va_start(ap, string);
564 	for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
565 		keys[num_keys].key = va_arg(ap, char *);
566 		if (keys[num_keys].key == NULL)
567 			break;
568 		keys[num_keys].repl = va_arg(ap, char *);
569 		if (keys[num_keys].repl == NULL)
570 			fatal("%s: NULL replacement", __func__);
571 	}
572 	if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
573 		fatal("%s: too many keys", __func__);
574 	va_end(ap);
575 
576 	/* Expand string */
577 	*buf = '\0';
578 	for (i = 0; *string != '\0'; string++) {
579 		if (*string != '%') {
580  append:
581 			buf[i++] = *string;
582 			if (i >= sizeof(buf))
583 				fatal("%s: string too long", __func__);
584 			buf[i] = '\0';
585 			continue;
586 		}
587 		string++;
588 		/* %% case */
589 		if (*string == '%')
590 			goto append;
591 		if (*string == '\0')
592 			fatal("%s: invalid format", __func__);
593 		for (j = 0; j < num_keys; j++) {
594 			if (strchr(keys[j].key, *string) != NULL) {
595 				i = strlcat(buf, keys[j].repl, sizeof(buf));
596 				if (i >= sizeof(buf))
597 					fatal("%s: string too long", __func__);
598 				break;
599 			}
600 		}
601 		if (j >= num_keys)
602 			fatal("%s: unknown key %%%c", __func__, *string);
603 	}
604 	return (xstrdup(buf));
605 #undef EXPAND_MAX_KEYS
606 }
607 
608 /*
609  * Read an entire line from a public key file into a static buffer, discarding
610  * lines that exceed the buffer size.  Returns 0 on success, -1 on failure.
611  */
612 int
613 read_keyfile_line(FILE *f, const char *filename, char *buf, size_t bufsz,
614    u_long *lineno)
615 {
616 	while (fgets(buf, bufsz, f) != NULL) {
617 		if (buf[0] == '\0')
618 			continue;
619 		(*lineno)++;
620 		if (buf[strlen(buf) - 1] == '\n' || feof(f)) {
621 			return 0;
622 		} else {
623 			debug("%s: %s line %lu exceeds size limit", __func__,
624 			    filename, *lineno);
625 			/* discard remainder of line */
626 			while (fgetc(f) != '\n' && !feof(f))
627 				;	/* nothing */
628 		}
629 	}
630 	return -1;
631 }
632 
633 int
634 tun_open(int tun, int mode)
635 {
636 	struct ifreq ifr;
637 	char name[100];
638 	int fd = -1, sock;
639 	const char *tunbase = "tun";
640 
641 	if (mode == SSH_TUNMODE_ETHERNET)
642 		tunbase = "tap";
643 
644 	/* Open the tunnel device */
645 	if (tun <= SSH_TUNID_MAX) {
646 		snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
647 		fd = open(name, O_RDWR);
648 	} else if (tun == SSH_TUNID_ANY) {
649 		for (tun = 100; tun >= 0; tun--) {
650 			snprintf(name, sizeof(name), "/dev/%s%d",
651 			    tunbase, tun);
652 			if ((fd = open(name, O_RDWR)) >= 0)
653 				break;
654 		}
655 	} else {
656 		debug("%s: invalid tunnel %u", __func__, tun);
657 		return -1;
658 	}
659 
660 	if (fd < 0) {
661 		debug("%s: %s open: %s", __func__, name, strerror(errno));
662 		return -1;
663 	}
664 
665 	debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
666 
667 	/* Bring interface up if it is not already */
668 	snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
669 	if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
670 		goto failed;
671 
672 	if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
673 		debug("%s: get interface %s flags: %s", __func__,
674 		    ifr.ifr_name, strerror(errno));
675 		goto failed;
676 	}
677 
678 	if (!(ifr.ifr_flags & IFF_UP)) {
679 		ifr.ifr_flags |= IFF_UP;
680 		if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
681 			debug("%s: activate interface %s: %s", __func__,
682 			    ifr.ifr_name, strerror(errno));
683 			goto failed;
684 		}
685 	}
686 
687 	close(sock);
688 	return fd;
689 
690  failed:
691 	if (fd >= 0)
692 		close(fd);
693 	if (sock >= 0)
694 		close(sock);
695 	return -1;
696 }
697 
698 void
699 sanitise_stdfd(void)
700 {
701 	int nullfd, dupfd;
702 
703 	if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
704 		fprintf(stderr, "Couldn't open /dev/null: %s\n",
705 		    strerror(errno));
706 		exit(1);
707 	}
708 	while (++dupfd <= STDERR_FILENO) {
709 		/* Only populate closed fds. */
710 		if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
711 			if (dup2(nullfd, dupfd) == -1) {
712 				fprintf(stderr, "dup2: %s\n", strerror(errno));
713 				exit(1);
714 			}
715 		}
716 	}
717 	if (nullfd > STDERR_FILENO)
718 		close(nullfd);
719 }
720 
721 char *
722 tohex(const void *vp, size_t l)
723 {
724 	const u_char *p = (const u_char *)vp;
725 	char b[3], *r;
726 	size_t i, hl;
727 
728 	if (l > 65536)
729 		return xstrdup("tohex: length > 65536");
730 
731 	hl = l * 2 + 1;
732 	r = xcalloc(1, hl);
733 	for (i = 0; i < l; i++) {
734 		snprintf(b, sizeof(b), "%02x", p[i]);
735 		strlcat(r, b, hl);
736 	}
737 	return (r);
738 }
739 
740 u_int64_t
741 get_u64(const void *vp)
742 {
743 	const u_char *p = (const u_char *)vp;
744 	u_int64_t v;
745 
746 	v  = (u_int64_t)p[0] << 56;
747 	v |= (u_int64_t)p[1] << 48;
748 	v |= (u_int64_t)p[2] << 40;
749 	v |= (u_int64_t)p[3] << 32;
750 	v |= (u_int64_t)p[4] << 24;
751 	v |= (u_int64_t)p[5] << 16;
752 	v |= (u_int64_t)p[6] << 8;
753 	v |= (u_int64_t)p[7];
754 
755 	return (v);
756 }
757 
758 u_int32_t
759 get_u32(const void *vp)
760 {
761 	const u_char *p = (const u_char *)vp;
762 	u_int32_t v;
763 
764 	v  = (u_int32_t)p[0] << 24;
765 	v |= (u_int32_t)p[1] << 16;
766 	v |= (u_int32_t)p[2] << 8;
767 	v |= (u_int32_t)p[3];
768 
769 	return (v);
770 }
771 
772 u_int32_t
773 get_u32_le(const void *vp)
774 {
775 	const u_char *p = (const u_char *)vp;
776 	u_int32_t v;
777 
778 	v  = (u_int32_t)p[0];
779 	v |= (u_int32_t)p[1] << 8;
780 	v |= (u_int32_t)p[2] << 16;
781 	v |= (u_int32_t)p[3] << 24;
782 
783 	return (v);
784 }
785 
786 u_int16_t
787 get_u16(const void *vp)
788 {
789 	const u_char *p = (const u_char *)vp;
790 	u_int16_t v;
791 
792 	v  = (u_int16_t)p[0] << 8;
793 	v |= (u_int16_t)p[1];
794 
795 	return (v);
796 }
797 
798 void
799 put_u64(void *vp, u_int64_t v)
800 {
801 	u_char *p = (u_char *)vp;
802 
803 	p[0] = (u_char)(v >> 56) & 0xff;
804 	p[1] = (u_char)(v >> 48) & 0xff;
805 	p[2] = (u_char)(v >> 40) & 0xff;
806 	p[3] = (u_char)(v >> 32) & 0xff;
807 	p[4] = (u_char)(v >> 24) & 0xff;
808 	p[5] = (u_char)(v >> 16) & 0xff;
809 	p[6] = (u_char)(v >> 8) & 0xff;
810 	p[7] = (u_char)v & 0xff;
811 }
812 
813 void
814 put_u32(void *vp, u_int32_t v)
815 {
816 	u_char *p = (u_char *)vp;
817 
818 	p[0] = (u_char)(v >> 24) & 0xff;
819 	p[1] = (u_char)(v >> 16) & 0xff;
820 	p[2] = (u_char)(v >> 8) & 0xff;
821 	p[3] = (u_char)v & 0xff;
822 }
823 
824 void
825 put_u32_le(void *vp, u_int32_t v)
826 {
827 	u_char *p = (u_char *)vp;
828 
829 	p[0] = (u_char)v & 0xff;
830 	p[1] = (u_char)(v >> 8) & 0xff;
831 	p[2] = (u_char)(v >> 16) & 0xff;
832 	p[3] = (u_char)(v >> 24) & 0xff;
833 }
834 
835 void
836 put_u16(void *vp, u_int16_t v)
837 {
838 	u_char *p = (u_char *)vp;
839 
840 	p[0] = (u_char)(v >> 8) & 0xff;
841 	p[1] = (u_char)v & 0xff;
842 }
843 
844 void
845 ms_subtract_diff(struct timeval *start, int *ms)
846 {
847 	struct timeval diff, finish;
848 
849 	gettimeofday(&finish, NULL);
850 	timersub(&finish, start, &diff);
851 	*ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
852 }
853 
854 void
855 ms_to_timeval(struct timeval *tv, int ms)
856 {
857 	if (ms < 0)
858 		ms = 0;
859 	tv->tv_sec = ms / 1000;
860 	tv->tv_usec = (ms % 1000) * 1000;
861 }
862 
863 time_t
864 monotime(void)
865 {
866 	struct timespec ts;
867 
868 	if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
869 		fatal("clock_gettime: %s", strerror(errno));
870 
871 	return (ts.tv_sec);
872 }
873 
874 double
875 monotime_double(void)
876 {
877 	struct timespec ts;
878 
879 	if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
880 		fatal("clock_gettime: %s", strerror(errno));
881 
882 	return (ts.tv_sec + (double)ts.tv_nsec / 1000000000);
883 }
884 
885 void
886 bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
887 {
888 	bw->buflen = buflen;
889 	bw->rate = kbps;
890 	bw->thresh = bw->rate;
891 	bw->lamt = 0;
892 	timerclear(&bw->bwstart);
893 	timerclear(&bw->bwend);
894 }
895 
896 /* Callback from read/write loop to insert bandwidth-limiting delays */
897 void
898 bandwidth_limit(struct bwlimit *bw, size_t read_len)
899 {
900 	u_int64_t waitlen;
901 	struct timespec ts, rm;
902 
903 	if (!timerisset(&bw->bwstart)) {
904 		gettimeofday(&bw->bwstart, NULL);
905 		return;
906 	}
907 
908 	bw->lamt += read_len;
909 	if (bw->lamt < bw->thresh)
910 		return;
911 
912 	gettimeofday(&bw->bwend, NULL);
913 	timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
914 	if (!timerisset(&bw->bwend))
915 		return;
916 
917 	bw->lamt *= 8;
918 	waitlen = (double)1000000L * bw->lamt / bw->rate;
919 
920 	bw->bwstart.tv_sec = waitlen / 1000000L;
921 	bw->bwstart.tv_usec = waitlen % 1000000L;
922 
923 	if (timercmp(&bw->bwstart, &bw->bwend, >)) {
924 		timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
925 
926 		/* Adjust the wait time */
927 		if (bw->bwend.tv_sec) {
928 			bw->thresh /= 2;
929 			if (bw->thresh < bw->buflen / 4)
930 				bw->thresh = bw->buflen / 4;
931 		} else if (bw->bwend.tv_usec < 10000) {
932 			bw->thresh *= 2;
933 			if (bw->thresh > bw->buflen * 8)
934 				bw->thresh = bw->buflen * 8;
935 		}
936 
937 		TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
938 		while (nanosleep(&ts, &rm) == -1) {
939 			if (errno != EINTR)
940 				break;
941 			ts = rm;
942 		}
943 	}
944 
945 	bw->lamt = 0;
946 	gettimeofday(&bw->bwstart, NULL);
947 }
948 
949 /* Make a template filename for mk[sd]temp() */
950 void
951 mktemp_proto(char *s, size_t len)
952 {
953 	const char *tmpdir;
954 	int r;
955 
956 	if ((tmpdir = getenv("TMPDIR")) != NULL) {
957 		r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
958 		if (r > 0 && (size_t)r < len)
959 			return;
960 	}
961 	r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
962 	if (r < 0 || (size_t)r >= len)
963 		fatal("%s: template string too short", __func__);
964 }
965 
966 static const struct {
967 	const char *name;
968 	int value;
969 } ipqos[] = {
970 	{ "af11", IPTOS_DSCP_AF11 },
971 	{ "af12", IPTOS_DSCP_AF12 },
972 	{ "af13", IPTOS_DSCP_AF13 },
973 	{ "af21", IPTOS_DSCP_AF21 },
974 	{ "af22", IPTOS_DSCP_AF22 },
975 	{ "af23", IPTOS_DSCP_AF23 },
976 	{ "af31", IPTOS_DSCP_AF31 },
977 	{ "af32", IPTOS_DSCP_AF32 },
978 	{ "af33", IPTOS_DSCP_AF33 },
979 	{ "af41", IPTOS_DSCP_AF41 },
980 	{ "af42", IPTOS_DSCP_AF42 },
981 	{ "af43", IPTOS_DSCP_AF43 },
982 	{ "cs0", IPTOS_DSCP_CS0 },
983 	{ "cs1", IPTOS_DSCP_CS1 },
984 	{ "cs2", IPTOS_DSCP_CS2 },
985 	{ "cs3", IPTOS_DSCP_CS3 },
986 	{ "cs4", IPTOS_DSCP_CS4 },
987 	{ "cs5", IPTOS_DSCP_CS5 },
988 	{ "cs6", IPTOS_DSCP_CS6 },
989 	{ "cs7", IPTOS_DSCP_CS7 },
990 	{ "ef", IPTOS_DSCP_EF },
991 	{ "lowdelay", IPTOS_LOWDELAY },
992 	{ "throughput", IPTOS_THROUGHPUT },
993 	{ "reliability", IPTOS_RELIABILITY },
994 	{ NULL, -1 }
995 };
996 
997 int
998 parse_ipqos(const char *cp)
999 {
1000 	u_int i;
1001 	char *ep;
1002 	long val;
1003 
1004 	if (cp == NULL)
1005 		return -1;
1006 	for (i = 0; ipqos[i].name != NULL; i++) {
1007 		if (strcasecmp(cp, ipqos[i].name) == 0)
1008 			return ipqos[i].value;
1009 	}
1010 	/* Try parsing as an integer */
1011 	val = strtol(cp, &ep, 0);
1012 	if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1013 		return -1;
1014 	return val;
1015 }
1016 
1017 const char *
1018 iptos2str(int iptos)
1019 {
1020 	int i;
1021 	static char iptos_str[sizeof "0xff"];
1022 
1023 	for (i = 0; ipqos[i].name != NULL; i++) {
1024 		if (ipqos[i].value == iptos)
1025 			return ipqos[i].name;
1026 	}
1027 	snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1028 	return iptos_str;
1029 }
1030 
1031 void
1032 lowercase(char *s)
1033 {
1034 	for (; *s; s++)
1035 		*s = tolower((u_char)*s);
1036 }
1037 
1038 int
1039 unix_listener(const char *path, int backlog, int unlink_first)
1040 {
1041 	struct sockaddr_un sunaddr;
1042 	int saved_errno, sock;
1043 
1044 	memset(&sunaddr, 0, sizeof(sunaddr));
1045 	sunaddr.sun_family = AF_UNIX;
1046 	if (strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1047 		error("%s: \"%s\" too long for Unix domain socket", __func__,
1048 		    path);
1049 		errno = ENAMETOOLONG;
1050 		return -1;
1051 	}
1052 
1053 	sock = socket(PF_UNIX, SOCK_STREAM, 0);
1054 	if (sock < 0) {
1055 		saved_errno = errno;
1056 		error("socket: %.100s", strerror(errno));
1057 		errno = saved_errno;
1058 		return -1;
1059 	}
1060 	if (unlink_first == 1) {
1061 		if (unlink(path) != 0 && errno != ENOENT)
1062 			error("unlink(%s): %.100s", path, strerror(errno));
1063 	}
1064 	if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0) {
1065 		saved_errno = errno;
1066 		error("bind: %.100s", strerror(errno));
1067 		close(sock);
1068 		error("%s: cannot bind to path: %s", __func__, path);
1069 		errno = saved_errno;
1070 		return -1;
1071 	}
1072 	if (listen(sock, backlog) < 0) {
1073 		saved_errno = errno;
1074 		error("listen: %.100s", strerror(errno));
1075 		close(sock);
1076 		unlink(path);
1077 		error("%s: cannot listen on path: %s", __func__, path);
1078 		errno = saved_errno;
1079 		return -1;
1080 	}
1081 	return sock;
1082 }
1083 
1084 /*
1085  * Compares two strings that maybe be NULL. Returns non-zero if strings
1086  * are both NULL or are identical, returns zero otherwise.
1087  */
1088 static int
1089 strcmp_maybe_null(const char *a, const char *b)
1090 {
1091 	if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1092 		return 0;
1093 	if (a != NULL && strcmp(a, b) != 0)
1094 		return 0;
1095 	return 1;
1096 }
1097 
1098 /*
1099  * Compare two forwards, returning non-zero if they are identical or
1100  * zero otherwise.
1101  */
1102 int
1103 forward_equals(const struct Forward *a, const struct Forward *b)
1104 {
1105 	if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
1106 		return 0;
1107 	if (a->listen_port != b->listen_port)
1108 		return 0;
1109 	if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
1110 		return 0;
1111 	if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
1112 		return 0;
1113 	if (a->connect_port != b->connect_port)
1114 		return 0;
1115 	if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
1116 		return 0;
1117 	/* allocated_port and handle are not checked */
1118 	return 1;
1119 }
1120 
1121