xref: /netbsd-src/crypto/external/bsd/openssh/dist/misc.c (revision daf6c4152fcddc27c445489775ed1f66ab4ea9a9)
1 /*	$NetBSD: misc.c,v 1.4 2010/11/21 18:29:48 adam Exp $	*/
2 /* $OpenBSD: misc.c,v 1.80 2010/07/21 02:10:58 djm 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.4 2010/11/21 18:29:48 adam Exp $");
30 #include <sys/types.h>
31 #include <sys/ioctl.h>
32 #include <sys/socket.h>
33 #include <sys/param.h>
34 
35 #include <net/if.h>
36 #include <net/if_tun.h>
37 #include <netinet/in.h>
38 #include <netinet/tcp.h>
39 
40 #include <errno.h>
41 #include <fcntl.h>
42 #include <netdb.h>
43 #include <paths.h>
44 #include <pwd.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, 0);
79 	if (val < 0) {
80 		error("fcntl(%d, F_GETFL, 0): %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, 0);
103 	if (val < 0) {
104 		error("fcntl(%d, F_GETFL, 0): %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)
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 			xfree(sp);
243 			return (a2tun(s, NULL));
244 		}
245 		ep[0] = '\0'; ep++;
246 		*remote = a2tun(ep, NULL);
247 		tun = a2tun(sp, NULL);
248 		xfree(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 = xrealloc(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 	xfree(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 			xfree(args->list[i]);
493 		xfree(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, *homedir;
507 	char user[128], ret[MAXPATHLEN];
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 		homedir = pw->pw_dir;
525 	} else {
526 		if ((pw = getpwuid(uid)) == NULL)	/* ~/path */
527 			fatal("tilde_expand_filename: No such uid %ld",
528 			    (long)uid);
529 		homedir = pw->pw_dir;
530 	}
531 
532 	if (strlcpy(ret, homedir, sizeof(ret)) >= sizeof(ret))
533 		fatal("tilde_expand_filename: Path too long");
534 
535 	/* Make sure directory has a trailing '/' */
536 	len = strlen(homedir);
537 	if ((len == 0 || homedir[len - 1] != '/') &&
538 	    strlcat(ret, "/", sizeof(ret)) >= sizeof(ret))
539 		fatal("tilde_expand_filename: Path too long");
540 
541 	/* Skip leading '/' from specified path */
542 	if (path != NULL)
543 		filename = path + 1;
544 	if (strlcat(ret, filename, sizeof(ret)) >= sizeof(ret))
545 		fatal("tilde_expand_filename: Path too long");
546 
547 	return (xstrdup(ret));
548 }
549 
550 /*
551  * Expand a string with a set of %[char] escapes. A number of escapes may be
552  * specified as (char *escape_chars, char *replacement) pairs. The list must
553  * be terminated by a NULL escape_char. Returns replaced string in memory
554  * allocated by xmalloc.
555  */
556 char *
557 percent_expand(const char *string, ...)
558 {
559 #define EXPAND_MAX_KEYS	16
560 	u_int num_keys, i, j;
561 	struct {
562 		const char *key;
563 		const char *repl;
564 	} keys[EXPAND_MAX_KEYS];
565 	char buf[4096];
566 	va_list ap;
567 
568 	/* Gather keys */
569 	va_start(ap, string);
570 	for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
571 		keys[num_keys].key = va_arg(ap, char *);
572 		if (keys[num_keys].key == NULL)
573 			break;
574 		keys[num_keys].repl = va_arg(ap, char *);
575 		if (keys[num_keys].repl == NULL)
576 			fatal("%s: NULL replacement", __func__);
577 	}
578 	if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
579 		fatal("%s: too many keys", __func__);
580 	va_end(ap);
581 
582 	/* Expand string */
583 	*buf = '\0';
584 	for (i = 0; *string != '\0'; string++) {
585 		if (*string != '%') {
586  append:
587 			buf[i++] = *string;
588 			if (i >= sizeof(buf))
589 				fatal("%s: string too long", __func__);
590 			buf[i] = '\0';
591 			continue;
592 		}
593 		string++;
594 		/* %% case */
595 		if (*string == '%')
596 			goto append;
597 		for (j = 0; j < num_keys; j++) {
598 			if (strchr(keys[j].key, *string) != NULL) {
599 				i = strlcat(buf, keys[j].repl, sizeof(buf));
600 				if (i >= sizeof(buf))
601 					fatal("%s: string too long", __func__);
602 				break;
603 			}
604 		}
605 		if (j >= num_keys)
606 			fatal("%s: unknown key %%%c", __func__, *string);
607 	}
608 	return (xstrdup(buf));
609 #undef EXPAND_MAX_KEYS
610 }
611 
612 /*
613  * Read an entire line from a public key file into a static buffer, discarding
614  * lines that exceed the buffer size.  Returns 0 on success, -1 on failure.
615  */
616 int
617 read_keyfile_line(FILE *f, const char *filename, char *buf, size_t bufsz,
618    u_long *lineno)
619 {
620 	while (fgets(buf, bufsz, f) != NULL) {
621 		if (buf[0] == '\0')
622 			continue;
623 		(*lineno)++;
624 		if (buf[strlen(buf) - 1] == '\n' || feof(f)) {
625 			return 0;
626 		} else {
627 			debug("%s: %s line %lu exceeds size limit", __func__,
628 			    filename, *lineno);
629 			/* discard remainder of line */
630 			while (fgetc(f) != '\n' && !feof(f))
631 				;	/* nothing */
632 		}
633 	}
634 	return -1;
635 }
636 
637 int
638 tun_open(int tun, int mode)
639 {
640 	struct ifreq ifr;
641 	int fd = -1, sock, flag;
642 	const char *tunbase = mode == SSH_TUNMODE_ETHERNET ? "tap" : "tun";
643 
644 	/* Open the tunnel device */
645 	if (tun <= SSH_TUNID_MAX) {
646 		snprintf(ifr.ifr_name, sizeof(ifr.ifr_name),
647 		    "/dev/%s%d", tunbase, tun);
648 		fd = open(ifr.ifr_name, O_RDWR);
649 	} else if (tun == SSH_TUNID_ANY) {
650 		for (tun = 100; tun >= 0; tun--) {
651 			snprintf(ifr.ifr_name, sizeof(ifr.ifr_name),
652 			    "/dev/%s%d", tunbase, tun);
653 			if ((fd = open(ifr.ifr_name, O_RDWR)) >= 0)
654 				break;
655 		}
656 	} else {
657 		debug("%s: invalid tunnel %u", __func__, tun);
658 		return (-1);
659 	}
660 
661 	if (fd < 0) {
662 		debug("%s: %s open failed: %s", __func__, ifr.ifr_name,
663 		    strerror(errno));
664 		return (-1);
665 	}
666 
667 
668 	/* Turn on tunnel headers */
669 	flag = 1;
670 	if (mode != SSH_TUNMODE_ETHERNET &&
671 	    ioctl(fd, TUNSIFHEAD, &flag) == -1) {
672 		debug("%s: ioctl(%d, TUNSIFHEAD, 1): %s", __func__, fd,
673 		    strerror(errno));
674 		close(fd);
675 		return -1;
676 	}
677 
678 	debug("%s: %s mode %d fd %d", __func__, ifr.ifr_name, mode, fd);
679 	/* Set the tunnel device operation mode */
680 	snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
681 	if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
682 		goto failed;
683 
684 	if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1)
685 		goto failed;
686 
687 #if 0
688 	/* Set interface mode */
689 	ifr.ifr_flags &= ~IFF_UP;
690 	if (mode == SSH_TUNMODE_ETHERNET)
691 		ifr.ifr_flags |= IFF_LINK0;
692 	else
693 		ifr.ifr_flags &= ~IFF_LINK0;
694 	if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1)
695 		goto failed;
696 #endif
697 
698 	/* Bring interface up */
699 	ifr.ifr_flags |= IFF_UP;
700 	if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1)
701 		goto failed;
702 
703 	close(sock);
704 	return (fd);
705 
706  failed:
707 	if (fd >= 0)
708 		close(fd);
709 	if (sock >= 0)
710 		close(sock);
711 	debug("%s: failed to set %s mode %d: %s", __func__, ifr.ifr_name,
712 	    mode, strerror(errno));
713 	return (-1);
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 int
858 timingsafe_bcmp(const void *b1, const void *b2, size_t n)
859 {
860 	const unsigned char *p1 = b1, *p2 = b2;
861 	int ret = 0;
862 
863 	for (; n > 0; n--)
864 		ret |= *p1++ ^ *p2++;
865 	return (ret != 0);
866 }
867