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