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