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