xref: /openssh-portable/misc.c (revision 4d28fa78)
1 /* $OpenBSD: misc.c,v 1.139 2019/06/28 13:35:04 deraadt Exp $ */
2 /*
3  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
4  * Copyright (c) 2005,2006 Damien Miller.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include "includes.h"
28 
29 #include <sys/types.h>
30 #include <sys/ioctl.h>
31 #include <sys/socket.h>
32 #include <sys/stat.h>
33 #include <sys/time.h>
34 #include <sys/wait.h>
35 #include <sys/un.h>
36 
37 #include <limits.h>
38 #ifdef HAVE_LIBGEN_H
39 # include <libgen.h>
40 #endif
41 #include <poll.h>
42 #include <signal.h>
43 #include <stdarg.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <time.h>
48 #include <unistd.h>
49 
50 #include <netinet/in.h>
51 #include <netinet/in_systm.h>
52 #include <netinet/ip.h>
53 #include <netinet/tcp.h>
54 #include <arpa/inet.h>
55 
56 #include <ctype.h>
57 #include <errno.h>
58 #include <fcntl.h>
59 #include <netdb.h>
60 #ifdef HAVE_PATHS_H
61 # include <paths.h>
62 #include <pwd.h>
63 #endif
64 #ifdef SSH_TUN_OPENBSD
65 #include <net/if.h>
66 #endif
67 
68 #include "xmalloc.h"
69 #include "misc.h"
70 #include "log.h"
71 #include "ssh.h"
72 #include "sshbuf.h"
73 #include "ssherr.h"
74 #include "platform.h"
75 
76 /* remove newline at end of string */
77 char *
chop(char * s)78 chop(char *s)
79 {
80 	char *t = s;
81 	while (*t) {
82 		if (*t == '\n' || *t == '\r') {
83 			*t = '\0';
84 			return s;
85 		}
86 		t++;
87 	}
88 	return s;
89 
90 }
91 
92 /* set/unset filedescriptor to non-blocking */
93 int
set_nonblock(int fd)94 set_nonblock(int fd)
95 {
96 	int val;
97 
98 	val = fcntl(fd, F_GETFL);
99 	if (val == -1) {
100 		error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
101 		return (-1);
102 	}
103 	if (val & O_NONBLOCK) {
104 		debug3("fd %d is O_NONBLOCK", fd);
105 		return (0);
106 	}
107 	debug2("fd %d setting O_NONBLOCK", fd);
108 	val |= O_NONBLOCK;
109 	if (fcntl(fd, F_SETFL, val) == -1) {
110 		debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
111 		    strerror(errno));
112 		return (-1);
113 	}
114 	return (0);
115 }
116 
117 int
unset_nonblock(int fd)118 unset_nonblock(int fd)
119 {
120 	int val;
121 
122 	val = fcntl(fd, F_GETFL);
123 	if (val == -1) {
124 		error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
125 		return (-1);
126 	}
127 	if (!(val & O_NONBLOCK)) {
128 		debug3("fd %d is not O_NONBLOCK", fd);
129 		return (0);
130 	}
131 	debug("fd %d clearing O_NONBLOCK", fd);
132 	val &= ~O_NONBLOCK;
133 	if (fcntl(fd, F_SETFL, val) == -1) {
134 		debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
135 		    fd, strerror(errno));
136 		return (-1);
137 	}
138 	return (0);
139 }
140 
141 const char *
ssh_gai_strerror(int gaierr)142 ssh_gai_strerror(int gaierr)
143 {
144 	if (gaierr == EAI_SYSTEM && errno != 0)
145 		return strerror(errno);
146 	return gai_strerror(gaierr);
147 }
148 
149 /* disable nagle on socket */
150 void
set_nodelay(int fd)151 set_nodelay(int fd)
152 {
153 	int opt;
154 	socklen_t optlen;
155 
156 	optlen = sizeof opt;
157 	if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
158 		debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
159 		return;
160 	}
161 	if (opt == 1) {
162 		debug2("fd %d is TCP_NODELAY", fd);
163 		return;
164 	}
165 	opt = 1;
166 	debug2("fd %d setting TCP_NODELAY", fd);
167 	if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
168 		error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
169 }
170 
171 /* Allow local port reuse in TIME_WAIT */
172 int
set_reuseaddr(int fd)173 set_reuseaddr(int fd)
174 {
175 	int on = 1;
176 
177 	if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
178 		error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
179 		return -1;
180 	}
181 	return 0;
182 }
183 
184 /* Get/set routing domain */
185 char *
get_rdomain(int fd)186 get_rdomain(int fd)
187 {
188 #if defined(HAVE_SYS_GET_RDOMAIN)
189 	return sys_get_rdomain(fd);
190 #elif defined(__OpenBSD__)
191 	int rtable;
192 	char *ret;
193 	socklen_t len = sizeof(rtable);
194 
195 	if (getsockopt(fd, SOL_SOCKET, SO_RTABLE, &rtable, &len) == -1) {
196 		error("Failed to get routing domain for fd %d: %s",
197 		    fd, strerror(errno));
198 		return NULL;
199 	}
200 	xasprintf(&ret, "%d", rtable);
201 	return ret;
202 #else /* defined(__OpenBSD__) */
203 	return NULL;
204 #endif
205 }
206 
207 int
set_rdomain(int fd,const char * name)208 set_rdomain(int fd, const char *name)
209 {
210 #if defined(HAVE_SYS_SET_RDOMAIN)
211 	return sys_set_rdomain(fd, name);
212 #elif defined(__OpenBSD__)
213 	int rtable;
214 	const char *errstr;
215 
216 	if (name == NULL)
217 		return 0; /* default table */
218 
219 	rtable = (int)strtonum(name, 0, 255, &errstr);
220 	if (errstr != NULL) {
221 		/* Shouldn't happen */
222 		error("Invalid routing domain \"%s\": %s", name, errstr);
223 		return -1;
224 	}
225 	if (setsockopt(fd, SOL_SOCKET, SO_RTABLE,
226 	    &rtable, sizeof(rtable)) == -1) {
227 		error("Failed to set routing domain %d on fd %d: %s",
228 		    rtable, fd, strerror(errno));
229 		return -1;
230 	}
231 	return 0;
232 #else /* defined(__OpenBSD__) */
233 	error("Setting routing domain is not supported on this platform");
234 	return -1;
235 #endif
236 }
237 
238 /*
239  * Wait up to *timeoutp milliseconds for fd to be readable. Updates
240  * *timeoutp with time remaining.
241  * Returns 0 if fd ready or -1 on timeout or error (see errno).
242  */
243 int
waitrfd(int fd,int * timeoutp)244 waitrfd(int fd, int *timeoutp)
245 {
246 	struct pollfd pfd;
247 	struct timeval t_start;
248 	int oerrno, r;
249 
250 	monotime_tv(&t_start);
251 	pfd.fd = fd;
252 	pfd.events = POLLIN;
253 	for (; *timeoutp >= 0;) {
254 		r = poll(&pfd, 1, *timeoutp);
255 		oerrno = errno;
256 		ms_subtract_diff(&t_start, timeoutp);
257 		errno = oerrno;
258 		if (r > 0)
259 			return 0;
260 		else if (r == -1 && errno != EAGAIN)
261 			return -1;
262 		else if (r == 0)
263 			break;
264 	}
265 	/* timeout */
266 	errno = ETIMEDOUT;
267 	return -1;
268 }
269 
270 /*
271  * Attempt a non-blocking connect(2) to the specified address, waiting up to
272  * *timeoutp milliseconds for the connection to complete. If the timeout is
273  * <=0, then wait indefinitely.
274  *
275  * Returns 0 on success or -1 on failure.
276  */
277 int
timeout_connect(int sockfd,const struct sockaddr * serv_addr,socklen_t addrlen,int * timeoutp)278 timeout_connect(int sockfd, const struct sockaddr *serv_addr,
279     socklen_t addrlen, int *timeoutp)
280 {
281 	int optval = 0;
282 	socklen_t optlen = sizeof(optval);
283 
284 	/* No timeout: just do a blocking connect() */
285 	if (timeoutp == NULL || *timeoutp <= 0)
286 		return connect(sockfd, serv_addr, addrlen);
287 
288 	set_nonblock(sockfd);
289 	if (connect(sockfd, serv_addr, addrlen) == 0) {
290 		/* Succeeded already? */
291 		unset_nonblock(sockfd);
292 		return 0;
293 	} else if (errno != EINPROGRESS)
294 		return -1;
295 
296 	if (waitrfd(sockfd, timeoutp) == -1)
297 		return -1;
298 
299 	/* Completed or failed */
300 	if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval, &optlen) == -1) {
301 		debug("getsockopt: %s", strerror(errno));
302 		return -1;
303 	}
304 	if (optval != 0) {
305 		errno = optval;
306 		return -1;
307 	}
308 	unset_nonblock(sockfd);
309 	return 0;
310 }
311 
312 /* Characters considered whitespace in strsep calls. */
313 #define WHITESPACE " \t\r\n"
314 #define QUOTE	"\""
315 
316 /* return next token in configuration line */
317 static char *
strdelim_internal(char ** s,int split_equals)318 strdelim_internal(char **s, int split_equals)
319 {
320 	char *old;
321 	int wspace = 0;
322 
323 	if (*s == NULL)
324 		return NULL;
325 
326 	old = *s;
327 
328 	*s = strpbrk(*s,
329 	    split_equals ? WHITESPACE QUOTE "=" : WHITESPACE QUOTE);
330 	if (*s == NULL)
331 		return (old);
332 
333 	if (*s[0] == '\"') {
334 		memmove(*s, *s + 1, strlen(*s)); /* move nul too */
335 		/* Find matching quote */
336 		if ((*s = strpbrk(*s, QUOTE)) == NULL) {
337 			return (NULL);		/* no matching quote */
338 		} else {
339 			*s[0] = '\0';
340 			*s += strspn(*s + 1, WHITESPACE) + 1;
341 			return (old);
342 		}
343 	}
344 
345 	/* Allow only one '=' to be skipped */
346 	if (split_equals && *s[0] == '=')
347 		wspace = 1;
348 	*s[0] = '\0';
349 
350 	/* Skip any extra whitespace after first token */
351 	*s += strspn(*s + 1, WHITESPACE) + 1;
352 	if (split_equals && *s[0] == '=' && !wspace)
353 		*s += strspn(*s + 1, WHITESPACE) + 1;
354 
355 	return (old);
356 }
357 
358 /*
359  * Return next token in configuration line; splts on whitespace or a
360  * single '=' character.
361  */
362 char *
strdelim(char ** s)363 strdelim(char **s)
364 {
365 	return strdelim_internal(s, 1);
366 }
367 
368 /*
369  * Return next token in configuration line; splts on whitespace only.
370  */
371 char *
strdelimw(char ** s)372 strdelimw(char **s)
373 {
374 	return strdelim_internal(s, 0);
375 }
376 
377 struct passwd *
pwcopy(struct passwd * pw)378 pwcopy(struct passwd *pw)
379 {
380 	struct passwd *copy = xcalloc(1, sizeof(*copy));
381 
382 	copy->pw_name = xstrdup(pw->pw_name);
383 	copy->pw_passwd = xstrdup(pw->pw_passwd);
384 #ifdef HAVE_STRUCT_PASSWD_PW_GECOS
385 	copy->pw_gecos = xstrdup(pw->pw_gecos);
386 #endif
387 	copy->pw_uid = pw->pw_uid;
388 	copy->pw_gid = pw->pw_gid;
389 #ifdef HAVE_STRUCT_PASSWD_PW_EXPIRE
390 	copy->pw_expire = pw->pw_expire;
391 #endif
392 #ifdef HAVE_STRUCT_PASSWD_PW_CHANGE
393 	copy->pw_change = pw->pw_change;
394 #endif
395 #ifdef HAVE_STRUCT_PASSWD_PW_CLASS
396 	copy->pw_class = xstrdup(pw->pw_class);
397 #endif
398 	copy->pw_dir = xstrdup(pw->pw_dir);
399 	copy->pw_shell = xstrdup(pw->pw_shell);
400 	return copy;
401 }
402 
403 /*
404  * Convert ASCII string to TCP/IP port number.
405  * Port must be >=0 and <=65535.
406  * Return -1 if invalid.
407  */
408 int
a2port(const char * s)409 a2port(const char *s)
410 {
411 	struct servent *se;
412 	long long port;
413 	const char *errstr;
414 
415 	port = strtonum(s, 0, 65535, &errstr);
416 	if (errstr == NULL)
417 		return (int)port;
418 	if ((se = getservbyname(s, "tcp")) != NULL)
419 		return ntohs(se->s_port);
420 	return -1;
421 }
422 
423 int
a2tun(const char * s,int * remote)424 a2tun(const char *s, int *remote)
425 {
426 	const char *errstr = NULL;
427 	char *sp, *ep;
428 	int tun;
429 
430 	if (remote != NULL) {
431 		*remote = SSH_TUNID_ANY;
432 		sp = xstrdup(s);
433 		if ((ep = strchr(sp, ':')) == NULL) {
434 			free(sp);
435 			return (a2tun(s, NULL));
436 		}
437 		ep[0] = '\0'; ep++;
438 		*remote = a2tun(ep, NULL);
439 		tun = a2tun(sp, NULL);
440 		free(sp);
441 		return (*remote == SSH_TUNID_ERR ? *remote : tun);
442 	}
443 
444 	if (strcasecmp(s, "any") == 0)
445 		return (SSH_TUNID_ANY);
446 
447 	tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
448 	if (errstr != NULL)
449 		return (SSH_TUNID_ERR);
450 
451 	return (tun);
452 }
453 
454 #define SECONDS		1
455 #define MINUTES		(SECONDS * 60)
456 #define HOURS		(MINUTES * 60)
457 #define DAYS		(HOURS * 24)
458 #define WEEKS		(DAYS * 7)
459 
460 /*
461  * Convert a time string into seconds; format is
462  * a sequence of:
463  *      time[qualifier]
464  *
465  * Valid time qualifiers are:
466  *      <none>  seconds
467  *      s|S     seconds
468  *      m|M     minutes
469  *      h|H     hours
470  *      d|D     days
471  *      w|W     weeks
472  *
473  * Examples:
474  *      90m     90 minutes
475  *      1h30m   90 minutes
476  *      2d      2 days
477  *      1w      1 week
478  *
479  * Return -1 if time string is invalid.
480  */
481 long
convtime(const char * s)482 convtime(const char *s)
483 {
484 	long total, secs, multiplier = 1;
485 	const char *p;
486 	char *endp;
487 
488 	errno = 0;
489 	total = 0;
490 	p = s;
491 
492 	if (p == NULL || *p == '\0')
493 		return -1;
494 
495 	while (*p) {
496 		secs = strtol(p, &endp, 10);
497 		if (p == endp ||
498 		    (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
499 		    secs < 0)
500 			return -1;
501 
502 		switch (*endp++) {
503 		case '\0':
504 			endp--;
505 			break;
506 		case 's':
507 		case 'S':
508 			break;
509 		case 'm':
510 		case 'M':
511 			multiplier = MINUTES;
512 			break;
513 		case 'h':
514 		case 'H':
515 			multiplier = HOURS;
516 			break;
517 		case 'd':
518 		case 'D':
519 			multiplier = DAYS;
520 			break;
521 		case 'w':
522 		case 'W':
523 			multiplier = WEEKS;
524 			break;
525 		default:
526 			return -1;
527 		}
528 		if (secs >= LONG_MAX / multiplier)
529 			return -1;
530 		secs *= multiplier;
531 		if  (total >= LONG_MAX - secs)
532 			return -1;
533 		total += secs;
534 		if (total < 0)
535 			return -1;
536 		p = endp;
537 	}
538 
539 	return total;
540 }
541 
542 /*
543  * Returns a standardized host+port identifier string.
544  * Caller must free returned string.
545  */
546 char *
put_host_port(const char * host,u_short port)547 put_host_port(const char *host, u_short port)
548 {
549 	char *hoststr;
550 
551 	if (port == 0 || port == SSH_DEFAULT_PORT)
552 		return(xstrdup(host));
553 	if (asprintf(&hoststr, "[%s]:%d", host, (int)port) == -1)
554 		fatal("put_host_port: asprintf: %s", strerror(errno));
555 	debug3("put_host_port: %s", hoststr);
556 	return hoststr;
557 }
558 
559 /*
560  * Search for next delimiter between hostnames/addresses and ports.
561  * Argument may be modified (for termination).
562  * Returns *cp if parsing succeeds.
563  * *cp is set to the start of the next field, if one was found.
564  * The delimiter char, if present, is stored in delim.
565  * If this is the last field, *cp is set to NULL.
566  */
567 char *
hpdelim2(char ** cp,char * delim)568 hpdelim2(char **cp, char *delim)
569 {
570 	char *s, *old;
571 
572 	if (cp == NULL || *cp == NULL)
573 		return NULL;
574 
575 	old = s = *cp;
576 	if (*s == '[') {
577 		if ((s = strchr(s, ']')) == NULL)
578 			return NULL;
579 		else
580 			s++;
581 	} else if ((s = strpbrk(s, ":/")) == NULL)
582 		s = *cp + strlen(*cp); /* skip to end (see first case below) */
583 
584 	switch (*s) {
585 	case '\0':
586 		*cp = NULL;	/* no more fields*/
587 		break;
588 
589 	case ':':
590 	case '/':
591 		if (delim != NULL)
592 			*delim = *s;
593 		*s = '\0';	/* terminate */
594 		*cp = s + 1;
595 		break;
596 
597 	default:
598 		return NULL;
599 	}
600 
601 	return old;
602 }
603 
604 char *
hpdelim(char ** cp)605 hpdelim(char **cp)
606 {
607 	return hpdelim2(cp, NULL);
608 }
609 
610 char *
cleanhostname(char * host)611 cleanhostname(char *host)
612 {
613 	if (*host == '[' && host[strlen(host) - 1] == ']') {
614 		host[strlen(host) - 1] = '\0';
615 		return (host + 1);
616 	} else
617 		return host;
618 }
619 
620 char *
colon(char * cp)621 colon(char *cp)
622 {
623 	int flag = 0;
624 
625 	if (*cp == ':')		/* Leading colon is part of file name. */
626 		return NULL;
627 	if (*cp == '[')
628 		flag = 1;
629 
630 	for (; *cp; ++cp) {
631 		if (*cp == '@' && *(cp+1) == '[')
632 			flag = 1;
633 		if (*cp == ']' && *(cp+1) == ':' && flag)
634 			return (cp+1);
635 		if (*cp == ':' && !flag)
636 			return (cp);
637 		if (*cp == '/')
638 			return NULL;
639 	}
640 	return NULL;
641 }
642 
643 /*
644  * Parse a [user@]host:[path] string.
645  * Caller must free returned user, host and path.
646  * Any of the pointer return arguments may be NULL (useful for syntax checking).
647  * If user was not specified then *userp will be set to NULL.
648  * If host was not specified then *hostp will be set to NULL.
649  * If path was not specified then *pathp will be set to ".".
650  * Returns 0 on success, -1 on failure.
651  */
652 int
parse_user_host_path(const char * s,char ** userp,char ** hostp,char ** pathp)653 parse_user_host_path(const char *s, char **userp, char **hostp, char **pathp)
654 {
655 	char *user = NULL, *host = NULL, *path = NULL;
656 	char *sdup, *tmp;
657 	int ret = -1;
658 
659 	if (userp != NULL)
660 		*userp = NULL;
661 	if (hostp != NULL)
662 		*hostp = NULL;
663 	if (pathp != NULL)
664 		*pathp = NULL;
665 
666 	sdup = xstrdup(s);
667 
668 	/* Check for remote syntax: [user@]host:[path] */
669 	if ((tmp = colon(sdup)) == NULL)
670 		goto out;
671 
672 	/* Extract optional path */
673 	*tmp++ = '\0';
674 	if (*tmp == '\0')
675 		tmp = ".";
676 	path = xstrdup(tmp);
677 
678 	/* Extract optional user and mandatory host */
679 	tmp = strrchr(sdup, '@');
680 	if (tmp != NULL) {
681 		*tmp++ = '\0';
682 		host = xstrdup(cleanhostname(tmp));
683 		if (*sdup != '\0')
684 			user = xstrdup(sdup);
685 	} else {
686 		host = xstrdup(cleanhostname(sdup));
687 		user = NULL;
688 	}
689 
690 	/* Success */
691 	if (userp != NULL) {
692 		*userp = user;
693 		user = NULL;
694 	}
695 	if (hostp != NULL) {
696 		*hostp = host;
697 		host = NULL;
698 	}
699 	if (pathp != NULL) {
700 		*pathp = path;
701 		path = NULL;
702 	}
703 	ret = 0;
704 out:
705 	free(sdup);
706 	free(user);
707 	free(host);
708 	free(path);
709 	return ret;
710 }
711 
712 /*
713  * Parse a [user@]host[:port] string.
714  * Caller must free returned user and host.
715  * Any of the pointer return arguments may be NULL (useful for syntax checking).
716  * If user was not specified then *userp will be set to NULL.
717  * If port was not specified then *portp will be -1.
718  * Returns 0 on success, -1 on failure.
719  */
720 int
parse_user_host_port(const char * s,char ** userp,char ** hostp,int * portp)721 parse_user_host_port(const char *s, char **userp, char **hostp, int *portp)
722 {
723 	char *sdup, *cp, *tmp;
724 	char *user = NULL, *host = NULL;
725 	int port = -1, ret = -1;
726 
727 	if (userp != NULL)
728 		*userp = NULL;
729 	if (hostp != NULL)
730 		*hostp = NULL;
731 	if (portp != NULL)
732 		*portp = -1;
733 
734 	if ((sdup = tmp = strdup(s)) == NULL)
735 		return -1;
736 	/* Extract optional username */
737 	if ((cp = strrchr(tmp, '@')) != NULL) {
738 		*cp = '\0';
739 		if (*tmp == '\0')
740 			goto out;
741 		if ((user = strdup(tmp)) == NULL)
742 			goto out;
743 		tmp = cp + 1;
744 	}
745 	/* Extract mandatory hostname */
746 	if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0')
747 		goto out;
748 	host = xstrdup(cleanhostname(cp));
749 	/* Convert and verify optional port */
750 	if (tmp != NULL && *tmp != '\0') {
751 		if ((port = a2port(tmp)) <= 0)
752 			goto out;
753 	}
754 	/* Success */
755 	if (userp != NULL) {
756 		*userp = user;
757 		user = NULL;
758 	}
759 	if (hostp != NULL) {
760 		*hostp = host;
761 		host = NULL;
762 	}
763 	if (portp != NULL)
764 		*portp = port;
765 	ret = 0;
766  out:
767 	free(sdup);
768 	free(user);
769 	free(host);
770 	return ret;
771 }
772 
773 /*
774  * Converts a two-byte hex string to decimal.
775  * Returns the decimal value or -1 for invalid input.
776  */
777 static int
hexchar(const char * s)778 hexchar(const char *s)
779 {
780 	unsigned char result[2];
781 	int i;
782 
783 	for (i = 0; i < 2; i++) {
784 		if (s[i] >= '0' && s[i] <= '9')
785 			result[i] = (unsigned char)(s[i] - '0');
786 		else if (s[i] >= 'a' && s[i] <= 'f')
787 			result[i] = (unsigned char)(s[i] - 'a') + 10;
788 		else if (s[i] >= 'A' && s[i] <= 'F')
789 			result[i] = (unsigned char)(s[i] - 'A') + 10;
790 		else
791 			return -1;
792 	}
793 	return (result[0] << 4) | result[1];
794 }
795 
796 /*
797  * Decode an url-encoded string.
798  * Returns a newly allocated string on success or NULL on failure.
799  */
800 static char *
urldecode(const char * src)801 urldecode(const char *src)
802 {
803 	char *ret, *dst;
804 	int ch;
805 
806 	ret = xmalloc(strlen(src) + 1);
807 	for (dst = ret; *src != '\0'; src++) {
808 		switch (*src) {
809 		case '+':
810 			*dst++ = ' ';
811 			break;
812 		case '%':
813 			if (!isxdigit((unsigned char)src[1]) ||
814 			    !isxdigit((unsigned char)src[2]) ||
815 			    (ch = hexchar(src + 1)) == -1) {
816 				free(ret);
817 				return NULL;
818 			}
819 			*dst++ = ch;
820 			src += 2;
821 			break;
822 		default:
823 			*dst++ = *src;
824 			break;
825 		}
826 	}
827 	*dst = '\0';
828 
829 	return ret;
830 }
831 
832 /*
833  * Parse an (scp|ssh|sftp)://[user@]host[:port][/path] URI.
834  * See https://tools.ietf.org/html/draft-ietf-secsh-scp-sftp-ssh-uri-04
835  * Either user or path may be url-encoded (but not host or port).
836  * Caller must free returned user, host and path.
837  * Any of the pointer return arguments may be NULL (useful for syntax checking)
838  * but the scheme must always be specified.
839  * If user was not specified then *userp will be set to NULL.
840  * If port was not specified then *portp will be -1.
841  * If path was not specified then *pathp will be set to NULL.
842  * Returns 0 on success, 1 if non-uri/wrong scheme, -1 on error/invalid uri.
843  */
844 int
parse_uri(const char * scheme,const char * uri,char ** userp,char ** hostp,int * portp,char ** pathp)845 parse_uri(const char *scheme, const char *uri, char **userp, char **hostp,
846     int *portp, char **pathp)
847 {
848 	char *uridup, *cp, *tmp, ch;
849 	char *user = NULL, *host = NULL, *path = NULL;
850 	int port = -1, ret = -1;
851 	size_t len;
852 
853 	len = strlen(scheme);
854 	if (strncmp(uri, scheme, len) != 0 || strncmp(uri + len, "://", 3) != 0)
855 		return 1;
856 	uri += len + 3;
857 
858 	if (userp != NULL)
859 		*userp = NULL;
860 	if (hostp != NULL)
861 		*hostp = NULL;
862 	if (portp != NULL)
863 		*portp = -1;
864 	if (pathp != NULL)
865 		*pathp = NULL;
866 
867 	uridup = tmp = xstrdup(uri);
868 
869 	/* Extract optional ssh-info (username + connection params) */
870 	if ((cp = strchr(tmp, '@')) != NULL) {
871 		char *delim;
872 
873 		*cp = '\0';
874 		/* Extract username and connection params */
875 		if ((delim = strchr(tmp, ';')) != NULL) {
876 			/* Just ignore connection params for now */
877 			*delim = '\0';
878 		}
879 		if (*tmp == '\0') {
880 			/* Empty username */
881 			goto out;
882 		}
883 		if ((user = urldecode(tmp)) == NULL)
884 			goto out;
885 		tmp = cp + 1;
886 	}
887 
888 	/* Extract mandatory hostname */
889 	if ((cp = hpdelim2(&tmp, &ch)) == NULL || *cp == '\0')
890 		goto out;
891 	host = xstrdup(cleanhostname(cp));
892 	if (!valid_domain(host, 0, NULL))
893 		goto out;
894 
895 	if (tmp != NULL && *tmp != '\0') {
896 		if (ch == ':') {
897 			/* Convert and verify port. */
898 			if ((cp = strchr(tmp, '/')) != NULL)
899 				*cp = '\0';
900 			if ((port = a2port(tmp)) <= 0)
901 				goto out;
902 			tmp = cp ? cp + 1 : NULL;
903 		}
904 		if (tmp != NULL && *tmp != '\0') {
905 			/* Extract optional path */
906 			if ((path = urldecode(tmp)) == NULL)
907 				goto out;
908 		}
909 	}
910 
911 	/* Success */
912 	if (userp != NULL) {
913 		*userp = user;
914 		user = NULL;
915 	}
916 	if (hostp != NULL) {
917 		*hostp = host;
918 		host = NULL;
919 	}
920 	if (portp != NULL)
921 		*portp = port;
922 	if (pathp != NULL) {
923 		*pathp = path;
924 		path = NULL;
925 	}
926 	ret = 0;
927  out:
928 	free(uridup);
929 	free(user);
930 	free(host);
931 	free(path);
932 	return ret;
933 }
934 
935 /* function to assist building execv() arguments */
936 void
addargs(arglist * args,char * fmt,...)937 addargs(arglist *args, char *fmt, ...)
938 {
939 	va_list ap;
940 	char *cp;
941 	u_int nalloc;
942 	int r;
943 
944 	va_start(ap, fmt);
945 	r = vasprintf(&cp, fmt, ap);
946 	va_end(ap);
947 	if (r == -1)
948 		fatal("addargs: argument too long");
949 
950 	nalloc = args->nalloc;
951 	if (args->list == NULL) {
952 		nalloc = 32;
953 		args->num = 0;
954 	} else if (args->num+2 >= nalloc)
955 		nalloc *= 2;
956 
957 	args->list = xrecallocarray(args->list, args->nalloc, nalloc, sizeof(char *));
958 	args->nalloc = nalloc;
959 	args->list[args->num++] = cp;
960 	args->list[args->num] = NULL;
961 }
962 
963 void
replacearg(arglist * args,u_int which,char * fmt,...)964 replacearg(arglist *args, u_int which, char *fmt, ...)
965 {
966 	va_list ap;
967 	char *cp;
968 	int r;
969 
970 	va_start(ap, fmt);
971 	r = vasprintf(&cp, fmt, ap);
972 	va_end(ap);
973 	if (r == -1)
974 		fatal("replacearg: argument too long");
975 
976 	if (which >= args->num)
977 		fatal("replacearg: tried to replace invalid arg %d >= %d",
978 		    which, args->num);
979 	free(args->list[which]);
980 	args->list[which] = cp;
981 }
982 
983 void
freeargs(arglist * args)984 freeargs(arglist *args)
985 {
986 	u_int i;
987 
988 	if (args->list != NULL) {
989 		for (i = 0; i < args->num; i++)
990 			free(args->list[i]);
991 		free(args->list);
992 		args->nalloc = args->num = 0;
993 		args->list = NULL;
994 	}
995 }
996 
997 /*
998  * Expands tildes in the file name.  Returns data allocated by xmalloc.
999  * Warning: this calls getpw*.
1000  */
1001 char *
tilde_expand_filename(const char * filename,uid_t uid)1002 tilde_expand_filename(const char *filename, uid_t uid)
1003 {
1004 	const char *path, *sep;
1005 	char user[128], *ret;
1006 	struct passwd *pw;
1007 	u_int len, slash;
1008 
1009 	if (*filename != '~')
1010 		return (xstrdup(filename));
1011 	filename++;
1012 
1013 	path = strchr(filename, '/');
1014 	if (path != NULL && path > filename) {		/* ~user/path */
1015 		slash = path - filename;
1016 		if (slash > sizeof(user) - 1)
1017 			fatal("tilde_expand_filename: ~username too long");
1018 		memcpy(user, filename, slash);
1019 		user[slash] = '\0';
1020 		if ((pw = getpwnam(user)) == NULL)
1021 			fatal("tilde_expand_filename: No such user %s", user);
1022 	} else if ((pw = getpwuid(uid)) == NULL)	/* ~/path */
1023 		fatal("tilde_expand_filename: No such uid %ld", (long)uid);
1024 
1025 	/* Make sure directory has a trailing '/' */
1026 	len = strlen(pw->pw_dir);
1027 	if (len == 0 || pw->pw_dir[len - 1] != '/')
1028 		sep = "/";
1029 	else
1030 		sep = "";
1031 
1032 	/* Skip leading '/' from specified path */
1033 	if (path != NULL)
1034 		filename = path + 1;
1035 
1036 	if (xasprintf(&ret, "%s%s%s", pw->pw_dir, sep, filename) >= PATH_MAX)
1037 		fatal("tilde_expand_filename: Path too long");
1038 
1039 	return (ret);
1040 }
1041 
1042 /*
1043  * Expand a string with a set of %[char] escapes. A number of escapes may be
1044  * specified as (char *escape_chars, char *replacement) pairs. The list must
1045  * be terminated by a NULL escape_char. Returns replaced string in memory
1046  * allocated by xmalloc.
1047  */
1048 char *
percent_expand(const char * string,...)1049 percent_expand(const char *string, ...)
1050 {
1051 #define EXPAND_MAX_KEYS	16
1052 	u_int num_keys, i, j;
1053 	struct {
1054 		const char *key;
1055 		const char *repl;
1056 	} keys[EXPAND_MAX_KEYS];
1057 	char buf[4096];
1058 	va_list ap;
1059 
1060 	/* Gather keys */
1061 	va_start(ap, string);
1062 	for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
1063 		keys[num_keys].key = va_arg(ap, char *);
1064 		if (keys[num_keys].key == NULL)
1065 			break;
1066 		keys[num_keys].repl = va_arg(ap, char *);
1067 		if (keys[num_keys].repl == NULL)
1068 			fatal("%s: NULL replacement", __func__);
1069 	}
1070 	if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
1071 		fatal("%s: too many keys", __func__);
1072 	va_end(ap);
1073 
1074 	/* Expand string */
1075 	*buf = '\0';
1076 	for (i = 0; *string != '\0'; string++) {
1077 		if (*string != '%') {
1078  append:
1079 			buf[i++] = *string;
1080 			if (i >= sizeof(buf))
1081 				fatal("%s: string too long", __func__);
1082 			buf[i] = '\0';
1083 			continue;
1084 		}
1085 		string++;
1086 		/* %% case */
1087 		if (*string == '%')
1088 			goto append;
1089 		if (*string == '\0')
1090 			fatal("%s: invalid format", __func__);
1091 		for (j = 0; j < num_keys; j++) {
1092 			if (strchr(keys[j].key, *string) != NULL) {
1093 				i = strlcat(buf, keys[j].repl, sizeof(buf));
1094 				if (i >= sizeof(buf))
1095 					fatal("%s: string too long", __func__);
1096 				break;
1097 			}
1098 		}
1099 		if (j >= num_keys)
1100 			fatal("%s: unknown key %%%c", __func__, *string);
1101 	}
1102 	return (xstrdup(buf));
1103 #undef EXPAND_MAX_KEYS
1104 }
1105 
1106 int
tun_open(int tun,int mode,char ** ifname)1107 tun_open(int tun, int mode, char **ifname)
1108 {
1109 #if defined(CUSTOM_SYS_TUN_OPEN)
1110 	return (sys_tun_open(tun, mode, ifname));
1111 #elif defined(SSH_TUN_OPENBSD)
1112 	struct ifreq ifr;
1113 	char name[100];
1114 	int fd = -1, sock;
1115 	const char *tunbase = "tun";
1116 
1117 	if (ifname != NULL)
1118 		*ifname = NULL;
1119 
1120 	if (mode == SSH_TUNMODE_ETHERNET)
1121 		tunbase = "tap";
1122 
1123 	/* Open the tunnel device */
1124 	if (tun <= SSH_TUNID_MAX) {
1125 		snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
1126 		fd = open(name, O_RDWR);
1127 	} else if (tun == SSH_TUNID_ANY) {
1128 		for (tun = 100; tun >= 0; tun--) {
1129 			snprintf(name, sizeof(name), "/dev/%s%d",
1130 			    tunbase, tun);
1131 			if ((fd = open(name, O_RDWR)) >= 0)
1132 				break;
1133 		}
1134 	} else {
1135 		debug("%s: invalid tunnel %u", __func__, tun);
1136 		return -1;
1137 	}
1138 
1139 	if (fd == -1) {
1140 		debug("%s: %s open: %s", __func__, name, strerror(errno));
1141 		return -1;
1142 	}
1143 
1144 	debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
1145 
1146 	/* Bring interface up if it is not already */
1147 	snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
1148 	if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
1149 		goto failed;
1150 
1151 	if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
1152 		debug("%s: get interface %s flags: %s", __func__,
1153 		    ifr.ifr_name, strerror(errno));
1154 		goto failed;
1155 	}
1156 
1157 	if (!(ifr.ifr_flags & IFF_UP)) {
1158 		ifr.ifr_flags |= IFF_UP;
1159 		if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
1160 			debug("%s: activate interface %s: %s", __func__,
1161 			    ifr.ifr_name, strerror(errno));
1162 			goto failed;
1163 		}
1164 	}
1165 
1166 	if (ifname != NULL)
1167 		*ifname = xstrdup(ifr.ifr_name);
1168 
1169 	close(sock);
1170 	return fd;
1171 
1172  failed:
1173 	if (fd >= 0)
1174 		close(fd);
1175 	if (sock >= 0)
1176 		close(sock);
1177 	return -1;
1178 #else
1179 	error("Tunnel interfaces are not supported on this platform");
1180 	return (-1);
1181 #endif
1182 }
1183 
1184 void
sanitise_stdfd(void)1185 sanitise_stdfd(void)
1186 {
1187 	int nullfd, dupfd;
1188 
1189 	if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1190 		fprintf(stderr, "Couldn't open /dev/null: %s\n",
1191 		    strerror(errno));
1192 		exit(1);
1193 	}
1194 	while (++dupfd <= STDERR_FILENO) {
1195 		/* Only populate closed fds. */
1196 		if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
1197 			if (dup2(nullfd, dupfd) == -1) {
1198 				fprintf(stderr, "dup2: %s\n", strerror(errno));
1199 				exit(1);
1200 			}
1201 		}
1202 	}
1203 	if (nullfd > STDERR_FILENO)
1204 		close(nullfd);
1205 }
1206 
1207 char *
tohex(const void * vp,size_t l)1208 tohex(const void *vp, size_t l)
1209 {
1210 	const u_char *p = (const u_char *)vp;
1211 	char b[3], *r;
1212 	size_t i, hl;
1213 
1214 	if (l > 65536)
1215 		return xstrdup("tohex: length > 65536");
1216 
1217 	hl = l * 2 + 1;
1218 	r = xcalloc(1, hl);
1219 	for (i = 0; i < l; i++) {
1220 		snprintf(b, sizeof(b), "%02x", p[i]);
1221 		strlcat(r, b, hl);
1222 	}
1223 	return (r);
1224 }
1225 
1226 u_int64_t
get_u64(const void * vp)1227 get_u64(const void *vp)
1228 {
1229 	const u_char *p = (const u_char *)vp;
1230 	u_int64_t v;
1231 
1232 	v  = (u_int64_t)p[0] << 56;
1233 	v |= (u_int64_t)p[1] << 48;
1234 	v |= (u_int64_t)p[2] << 40;
1235 	v |= (u_int64_t)p[3] << 32;
1236 	v |= (u_int64_t)p[4] << 24;
1237 	v |= (u_int64_t)p[5] << 16;
1238 	v |= (u_int64_t)p[6] << 8;
1239 	v |= (u_int64_t)p[7];
1240 
1241 	return (v);
1242 }
1243 
1244 u_int32_t
get_u32(const void * vp)1245 get_u32(const void *vp)
1246 {
1247 	const u_char *p = (const u_char *)vp;
1248 	u_int32_t v;
1249 
1250 	v  = (u_int32_t)p[0] << 24;
1251 	v |= (u_int32_t)p[1] << 16;
1252 	v |= (u_int32_t)p[2] << 8;
1253 	v |= (u_int32_t)p[3];
1254 
1255 	return (v);
1256 }
1257 
1258 u_int32_t
get_u32_le(const void * vp)1259 get_u32_le(const void *vp)
1260 {
1261 	const u_char *p = (const u_char *)vp;
1262 	u_int32_t v;
1263 
1264 	v  = (u_int32_t)p[0];
1265 	v |= (u_int32_t)p[1] << 8;
1266 	v |= (u_int32_t)p[2] << 16;
1267 	v |= (u_int32_t)p[3] << 24;
1268 
1269 	return (v);
1270 }
1271 
1272 u_int16_t
get_u16(const void * vp)1273 get_u16(const void *vp)
1274 {
1275 	const u_char *p = (const u_char *)vp;
1276 	u_int16_t v;
1277 
1278 	v  = (u_int16_t)p[0] << 8;
1279 	v |= (u_int16_t)p[1];
1280 
1281 	return (v);
1282 }
1283 
1284 void
put_u64(void * vp,u_int64_t v)1285 put_u64(void *vp, u_int64_t v)
1286 {
1287 	u_char *p = (u_char *)vp;
1288 
1289 	p[0] = (u_char)(v >> 56) & 0xff;
1290 	p[1] = (u_char)(v >> 48) & 0xff;
1291 	p[2] = (u_char)(v >> 40) & 0xff;
1292 	p[3] = (u_char)(v >> 32) & 0xff;
1293 	p[4] = (u_char)(v >> 24) & 0xff;
1294 	p[5] = (u_char)(v >> 16) & 0xff;
1295 	p[6] = (u_char)(v >> 8) & 0xff;
1296 	p[7] = (u_char)v & 0xff;
1297 }
1298 
1299 void
put_u32(void * vp,u_int32_t v)1300 put_u32(void *vp, u_int32_t v)
1301 {
1302 	u_char *p = (u_char *)vp;
1303 
1304 	p[0] = (u_char)(v >> 24) & 0xff;
1305 	p[1] = (u_char)(v >> 16) & 0xff;
1306 	p[2] = (u_char)(v >> 8) & 0xff;
1307 	p[3] = (u_char)v & 0xff;
1308 }
1309 
1310 void
put_u32_le(void * vp,u_int32_t v)1311 put_u32_le(void *vp, u_int32_t v)
1312 {
1313 	u_char *p = (u_char *)vp;
1314 
1315 	p[0] = (u_char)v & 0xff;
1316 	p[1] = (u_char)(v >> 8) & 0xff;
1317 	p[2] = (u_char)(v >> 16) & 0xff;
1318 	p[3] = (u_char)(v >> 24) & 0xff;
1319 }
1320 
1321 void
put_u16(void * vp,u_int16_t v)1322 put_u16(void *vp, u_int16_t v)
1323 {
1324 	u_char *p = (u_char *)vp;
1325 
1326 	p[0] = (u_char)(v >> 8) & 0xff;
1327 	p[1] = (u_char)v & 0xff;
1328 }
1329 
1330 void
ms_subtract_diff(struct timeval * start,int * ms)1331 ms_subtract_diff(struct timeval *start, int *ms)
1332 {
1333 	struct timeval diff, finish;
1334 
1335 	monotime_tv(&finish);
1336 	timersub(&finish, start, &diff);
1337 	*ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
1338 }
1339 
1340 void
ms_to_timeval(struct timeval * tv,int ms)1341 ms_to_timeval(struct timeval *tv, int ms)
1342 {
1343 	if (ms < 0)
1344 		ms = 0;
1345 	tv->tv_sec = ms / 1000;
1346 	tv->tv_usec = (ms % 1000) * 1000;
1347 }
1348 
1349 void
monotime_ts(struct timespec * ts)1350 monotime_ts(struct timespec *ts)
1351 {
1352 	struct timeval tv;
1353 #if defined(HAVE_CLOCK_GETTIME) && (defined(CLOCK_BOOTTIME) || \
1354     defined(CLOCK_MONOTONIC) || defined(CLOCK_REALTIME))
1355 	static int gettime_failed = 0;
1356 
1357 	if (!gettime_failed) {
1358 # ifdef CLOCK_BOOTTIME
1359 		if (clock_gettime(CLOCK_BOOTTIME, ts) == 0)
1360 			return;
1361 # endif /* CLOCK_BOOTTIME */
1362 # ifdef CLOCK_MONOTONIC
1363 		if (clock_gettime(CLOCK_MONOTONIC, ts) == 0)
1364 			return;
1365 # endif /* CLOCK_MONOTONIC */
1366 # ifdef CLOCK_REALTIME
1367 		/* Not monotonic, but we're almost out of options here. */
1368 		if (clock_gettime(CLOCK_REALTIME, ts) == 0)
1369 			return;
1370 # endif /* CLOCK_REALTIME */
1371 		debug3("clock_gettime: %s", strerror(errno));
1372 		gettime_failed = 1;
1373 	}
1374 #endif /* HAVE_CLOCK_GETTIME && (BOOTTIME || MONOTONIC || REALTIME) */
1375 	gettimeofday(&tv, NULL);
1376 	ts->tv_sec = tv.tv_sec;
1377 	ts->tv_nsec = (long)tv.tv_usec * 1000;
1378 }
1379 
1380 void
monotime_tv(struct timeval * tv)1381 monotime_tv(struct timeval *tv)
1382 {
1383 	struct timespec ts;
1384 
1385 	monotime_ts(&ts);
1386 	tv->tv_sec = ts.tv_sec;
1387 	tv->tv_usec = ts.tv_nsec / 1000;
1388 }
1389 
1390 time_t
monotime(void)1391 monotime(void)
1392 {
1393 	struct timespec ts;
1394 
1395 	monotime_ts(&ts);
1396 	return ts.tv_sec;
1397 }
1398 
1399 double
monotime_double(void)1400 monotime_double(void)
1401 {
1402 	struct timespec ts;
1403 
1404 	monotime_ts(&ts);
1405 	return ts.tv_sec + ((double)ts.tv_nsec / 1000000000);
1406 }
1407 
1408 void
bandwidth_limit_init(struct bwlimit * bw,u_int64_t kbps,size_t buflen)1409 bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
1410 {
1411 	bw->buflen = buflen;
1412 	bw->rate = kbps;
1413 	bw->thresh = buflen;
1414 	bw->lamt = 0;
1415 	timerclear(&bw->bwstart);
1416 	timerclear(&bw->bwend);
1417 }
1418 
1419 /* Callback from read/write loop to insert bandwidth-limiting delays */
1420 void
bandwidth_limit(struct bwlimit * bw,size_t read_len)1421 bandwidth_limit(struct bwlimit *bw, size_t read_len)
1422 {
1423 	u_int64_t waitlen;
1424 	struct timespec ts, rm;
1425 
1426 	bw->lamt += read_len;
1427 	if (!timerisset(&bw->bwstart)) {
1428 		monotime_tv(&bw->bwstart);
1429 		return;
1430 	}
1431 	if (bw->lamt < bw->thresh)
1432 		return;
1433 
1434 	monotime_tv(&bw->bwend);
1435 	timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
1436 	if (!timerisset(&bw->bwend))
1437 		return;
1438 
1439 	bw->lamt *= 8;
1440 	waitlen = (double)1000000L * bw->lamt / bw->rate;
1441 
1442 	bw->bwstart.tv_sec = waitlen / 1000000L;
1443 	bw->bwstart.tv_usec = waitlen % 1000000L;
1444 
1445 	if (timercmp(&bw->bwstart, &bw->bwend, >)) {
1446 		timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
1447 
1448 		/* Adjust the wait time */
1449 		if (bw->bwend.tv_sec) {
1450 			bw->thresh /= 2;
1451 			if (bw->thresh < bw->buflen / 4)
1452 				bw->thresh = bw->buflen / 4;
1453 		} else if (bw->bwend.tv_usec < 10000) {
1454 			bw->thresh *= 2;
1455 			if (bw->thresh > bw->buflen * 8)
1456 				bw->thresh = bw->buflen * 8;
1457 		}
1458 
1459 		TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
1460 		while (nanosleep(&ts, &rm) == -1) {
1461 			if (errno != EINTR)
1462 				break;
1463 			ts = rm;
1464 		}
1465 	}
1466 
1467 	bw->lamt = 0;
1468 	monotime_tv(&bw->bwstart);
1469 }
1470 
1471 /* Make a template filename for mk[sd]temp() */
1472 void
mktemp_proto(char * s,size_t len)1473 mktemp_proto(char *s, size_t len)
1474 {
1475 	const char *tmpdir;
1476 	int r;
1477 
1478 	if ((tmpdir = getenv("TMPDIR")) != NULL) {
1479 		r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
1480 		if (r > 0 && (size_t)r < len)
1481 			return;
1482 	}
1483 	r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
1484 	if (r < 0 || (size_t)r >= len)
1485 		fatal("%s: template string too short", __func__);
1486 }
1487 
1488 static const struct {
1489 	const char *name;
1490 	int value;
1491 } ipqos[] = {
1492 	{ "none", INT_MAX },		/* can't use 0 here; that's CS0 */
1493 	{ "af11", IPTOS_DSCP_AF11 },
1494 	{ "af12", IPTOS_DSCP_AF12 },
1495 	{ "af13", IPTOS_DSCP_AF13 },
1496 	{ "af21", IPTOS_DSCP_AF21 },
1497 	{ "af22", IPTOS_DSCP_AF22 },
1498 	{ "af23", IPTOS_DSCP_AF23 },
1499 	{ "af31", IPTOS_DSCP_AF31 },
1500 	{ "af32", IPTOS_DSCP_AF32 },
1501 	{ "af33", IPTOS_DSCP_AF33 },
1502 	{ "af41", IPTOS_DSCP_AF41 },
1503 	{ "af42", IPTOS_DSCP_AF42 },
1504 	{ "af43", IPTOS_DSCP_AF43 },
1505 	{ "cs0", IPTOS_DSCP_CS0 },
1506 	{ "cs1", IPTOS_DSCP_CS1 },
1507 	{ "cs2", IPTOS_DSCP_CS2 },
1508 	{ "cs3", IPTOS_DSCP_CS3 },
1509 	{ "cs4", IPTOS_DSCP_CS4 },
1510 	{ "cs5", IPTOS_DSCP_CS5 },
1511 	{ "cs6", IPTOS_DSCP_CS6 },
1512 	{ "cs7", IPTOS_DSCP_CS7 },
1513 	{ "ef", IPTOS_DSCP_EF },
1514 	{ "lowdelay", IPTOS_LOWDELAY },
1515 	{ "throughput", IPTOS_THROUGHPUT },
1516 	{ "reliability", IPTOS_RELIABILITY },
1517 	{ NULL, -1 }
1518 };
1519 
1520 int
parse_ipqos(const char * cp)1521 parse_ipqos(const char *cp)
1522 {
1523 	u_int i;
1524 	char *ep;
1525 	long val;
1526 
1527 	if (cp == NULL)
1528 		return -1;
1529 	for (i = 0; ipqos[i].name != NULL; i++) {
1530 		if (strcasecmp(cp, ipqos[i].name) == 0)
1531 			return ipqos[i].value;
1532 	}
1533 	/* Try parsing as an integer */
1534 	val = strtol(cp, &ep, 0);
1535 	if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1536 		return -1;
1537 	return val;
1538 }
1539 
1540 const char *
iptos2str(int iptos)1541 iptos2str(int iptos)
1542 {
1543 	int i;
1544 	static char iptos_str[sizeof "0xff"];
1545 
1546 	for (i = 0; ipqos[i].name != NULL; i++) {
1547 		if (ipqos[i].value == iptos)
1548 			return ipqos[i].name;
1549 	}
1550 	snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1551 	return iptos_str;
1552 }
1553 
1554 void
lowercase(char * s)1555 lowercase(char *s)
1556 {
1557 	for (; *s; s++)
1558 		*s = tolower((u_char)*s);
1559 }
1560 
1561 int
unix_listener(const char * path,int backlog,int unlink_first)1562 unix_listener(const char *path, int backlog, int unlink_first)
1563 {
1564 	struct sockaddr_un sunaddr;
1565 	int saved_errno, sock;
1566 
1567 	memset(&sunaddr, 0, sizeof(sunaddr));
1568 	sunaddr.sun_family = AF_UNIX;
1569 	if (strlcpy(sunaddr.sun_path, path,
1570 	    sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1571 		error("%s: path \"%s\" too long for Unix domain socket",
1572 		    __func__, path);
1573 		errno = ENAMETOOLONG;
1574 		return -1;
1575 	}
1576 
1577 	sock = socket(PF_UNIX, SOCK_STREAM, 0);
1578 	if (sock == -1) {
1579 		saved_errno = errno;
1580 		error("%s: socket: %.100s", __func__, strerror(errno));
1581 		errno = saved_errno;
1582 		return -1;
1583 	}
1584 	if (unlink_first == 1) {
1585 		if (unlink(path) != 0 && errno != ENOENT)
1586 			error("unlink(%s): %.100s", path, strerror(errno));
1587 	}
1588 	if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1589 		saved_errno = errno;
1590 		error("%s: cannot bind to path %s: %s",
1591 		    __func__, path, strerror(errno));
1592 		close(sock);
1593 		errno = saved_errno;
1594 		return -1;
1595 	}
1596 	if (listen(sock, backlog) == -1) {
1597 		saved_errno = errno;
1598 		error("%s: cannot listen on path %s: %s",
1599 		    __func__, path, strerror(errno));
1600 		close(sock);
1601 		unlink(path);
1602 		errno = saved_errno;
1603 		return -1;
1604 	}
1605 	return sock;
1606 }
1607 
1608 void
sock_set_v6only(int s)1609 sock_set_v6only(int s)
1610 {
1611 #if defined(IPV6_V6ONLY) && !defined(__OpenBSD__)
1612 	int on = 1;
1613 
1614 	debug3("%s: set socket %d IPV6_V6ONLY", __func__, s);
1615 	if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1)
1616 		error("setsockopt IPV6_V6ONLY: %s", strerror(errno));
1617 #endif
1618 }
1619 
1620 /*
1621  * Compares two strings that maybe be NULL. Returns non-zero if strings
1622  * are both NULL or are identical, returns zero otherwise.
1623  */
1624 static int
strcmp_maybe_null(const char * a,const char * b)1625 strcmp_maybe_null(const char *a, const char *b)
1626 {
1627 	if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1628 		return 0;
1629 	if (a != NULL && strcmp(a, b) != 0)
1630 		return 0;
1631 	return 1;
1632 }
1633 
1634 /*
1635  * Compare two forwards, returning non-zero if they are identical or
1636  * zero otherwise.
1637  */
1638 int
forward_equals(const struct Forward * a,const struct Forward * b)1639 forward_equals(const struct Forward *a, const struct Forward *b)
1640 {
1641 	if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
1642 		return 0;
1643 	if (a->listen_port != b->listen_port)
1644 		return 0;
1645 	if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
1646 		return 0;
1647 	if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
1648 		return 0;
1649 	if (a->connect_port != b->connect_port)
1650 		return 0;
1651 	if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
1652 		return 0;
1653 	/* allocated_port and handle are not checked */
1654 	return 1;
1655 }
1656 
1657 /* returns 1 if process is already daemonized, 0 otherwise */
1658 int
daemonized(void)1659 daemonized(void)
1660 {
1661 	int fd;
1662 
1663 	if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
1664 		close(fd);
1665 		return 0;	/* have controlling terminal */
1666 	}
1667 	if (getppid() != 1)
1668 		return 0;	/* parent is not init */
1669 	if (getsid(0) != getpid())
1670 		return 0;	/* not session leader */
1671 	debug3("already daemonized");
1672 	return 1;
1673 }
1674 
1675 
1676 /*
1677  * Splits 's' into an argument vector. Handles quoted string and basic
1678  * escape characters (\\, \", \'). Caller must free the argument vector
1679  * and its members.
1680  */
1681 int
argv_split(const char * s,int * argcp,char *** argvp)1682 argv_split(const char *s, int *argcp, char ***argvp)
1683 {
1684 	int r = SSH_ERR_INTERNAL_ERROR;
1685 	int argc = 0, quote, i, j;
1686 	char *arg, **argv = xcalloc(1, sizeof(*argv));
1687 
1688 	*argvp = NULL;
1689 	*argcp = 0;
1690 
1691 	for (i = 0; s[i] != '\0'; i++) {
1692 		/* Skip leading whitespace */
1693 		if (s[i] == ' ' || s[i] == '\t')
1694 			continue;
1695 
1696 		/* Start of a token */
1697 		quote = 0;
1698 		if (s[i] == '\\' &&
1699 		    (s[i + 1] == '\'' || s[i + 1] == '\"' || s[i + 1] == '\\'))
1700 			i++;
1701 		else if (s[i] == '\'' || s[i] == '"')
1702 			quote = s[i++];
1703 
1704 		argv = xreallocarray(argv, (argc + 2), sizeof(*argv));
1705 		arg = argv[argc++] = xcalloc(1, strlen(s + i) + 1);
1706 		argv[argc] = NULL;
1707 
1708 		/* Copy the token in, removing escapes */
1709 		for (j = 0; s[i] != '\0'; i++) {
1710 			if (s[i] == '\\') {
1711 				if (s[i + 1] == '\'' ||
1712 				    s[i + 1] == '\"' ||
1713 				    s[i + 1] == '\\') {
1714 					i++; /* Skip '\' */
1715 					arg[j++] = s[i];
1716 				} else {
1717 					/* Unrecognised escape */
1718 					arg[j++] = s[i];
1719 				}
1720 			} else if (quote == 0 && (s[i] == ' ' || s[i] == '\t'))
1721 				break; /* done */
1722 			else if (quote != 0 && s[i] == quote)
1723 				break; /* done */
1724 			else
1725 				arg[j++] = s[i];
1726 		}
1727 		if (s[i] == '\0') {
1728 			if (quote != 0) {
1729 				/* Ran out of string looking for close quote */
1730 				r = SSH_ERR_INVALID_FORMAT;
1731 				goto out;
1732 			}
1733 			break;
1734 		}
1735 	}
1736 	/* Success */
1737 	*argcp = argc;
1738 	*argvp = argv;
1739 	argc = 0;
1740 	argv = NULL;
1741 	r = 0;
1742  out:
1743 	if (argc != 0 && argv != NULL) {
1744 		for (i = 0; i < argc; i++)
1745 			free(argv[i]);
1746 		free(argv);
1747 	}
1748 	return r;
1749 }
1750 
1751 /*
1752  * Reassemble an argument vector into a string, quoting and escaping as
1753  * necessary. Caller must free returned string.
1754  */
1755 char *
argv_assemble(int argc,char ** argv)1756 argv_assemble(int argc, char **argv)
1757 {
1758 	int i, j, ws, r;
1759 	char c, *ret;
1760 	struct sshbuf *buf, *arg;
1761 
1762 	if ((buf = sshbuf_new()) == NULL || (arg = sshbuf_new()) == NULL)
1763 		fatal("%s: sshbuf_new failed", __func__);
1764 
1765 	for (i = 0; i < argc; i++) {
1766 		ws = 0;
1767 		sshbuf_reset(arg);
1768 		for (j = 0; argv[i][j] != '\0'; j++) {
1769 			r = 0;
1770 			c = argv[i][j];
1771 			switch (c) {
1772 			case ' ':
1773 			case '\t':
1774 				ws = 1;
1775 				r = sshbuf_put_u8(arg, c);
1776 				break;
1777 			case '\\':
1778 			case '\'':
1779 			case '"':
1780 				if ((r = sshbuf_put_u8(arg, '\\')) != 0)
1781 					break;
1782 				/* FALLTHROUGH */
1783 			default:
1784 				r = sshbuf_put_u8(arg, c);
1785 				break;
1786 			}
1787 			if (r != 0)
1788 				fatal("%s: sshbuf_put_u8: %s",
1789 				    __func__, ssh_err(r));
1790 		}
1791 		if ((i != 0 && (r = sshbuf_put_u8(buf, ' ')) != 0) ||
1792 		    (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0) ||
1793 		    (r = sshbuf_putb(buf, arg)) != 0 ||
1794 		    (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0))
1795 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
1796 	}
1797 	if ((ret = malloc(sshbuf_len(buf) + 1)) == NULL)
1798 		fatal("%s: malloc failed", __func__);
1799 	memcpy(ret, sshbuf_ptr(buf), sshbuf_len(buf));
1800 	ret[sshbuf_len(buf)] = '\0';
1801 	sshbuf_free(buf);
1802 	sshbuf_free(arg);
1803 	return ret;
1804 }
1805 
1806 /* Returns 0 if pid exited cleanly, non-zero otherwise */
1807 int
exited_cleanly(pid_t pid,const char * tag,const char * cmd,int quiet)1808 exited_cleanly(pid_t pid, const char *tag, const char *cmd, int quiet)
1809 {
1810 	int status;
1811 
1812 	while (waitpid(pid, &status, 0) == -1) {
1813 		if (errno != EINTR) {
1814 			error("%s: waitpid: %s", tag, strerror(errno));
1815 			return -1;
1816 		}
1817 	}
1818 	if (WIFSIGNALED(status)) {
1819 		error("%s %s exited on signal %d", tag, cmd, WTERMSIG(status));
1820 		return -1;
1821 	} else if (WEXITSTATUS(status) != 0) {
1822 		do_log2(quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_INFO,
1823 		    "%s %s failed, status %d", tag, cmd, WEXITSTATUS(status));
1824 		return -1;
1825 	}
1826 	return 0;
1827 }
1828 
1829 /*
1830  * Check a given path for security. This is defined as all components
1831  * of the path to the file must be owned by either the owner of
1832  * of the file or root and no directories must be group or world writable.
1833  *
1834  * XXX Should any specific check be done for sym links ?
1835  *
1836  * Takes a file name, its stat information (preferably from fstat() to
1837  * avoid races), the uid of the expected owner, their home directory and an
1838  * error buffer plus max size as arguments.
1839  *
1840  * Returns 0 on success and -1 on failure
1841  */
1842 int
safe_path(const char * name,struct stat * stp,const char * pw_dir,uid_t uid,char * err,size_t errlen)1843 safe_path(const char *name, struct stat *stp, const char *pw_dir,
1844     uid_t uid, char *err, size_t errlen)
1845 {
1846 	char buf[PATH_MAX], homedir[PATH_MAX];
1847 	char *cp;
1848 	int comparehome = 0;
1849 	struct stat st;
1850 
1851 	if (realpath(name, buf) == NULL) {
1852 		snprintf(err, errlen, "realpath %s failed: %s", name,
1853 		    strerror(errno));
1854 		return -1;
1855 	}
1856 	if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL)
1857 		comparehome = 1;
1858 
1859 	if (!S_ISREG(stp->st_mode)) {
1860 		snprintf(err, errlen, "%s is not a regular file", buf);
1861 		return -1;
1862 	}
1863 	if ((!platform_sys_dir_uid(stp->st_uid) && stp->st_uid != uid) ||
1864 	    (stp->st_mode & 022) != 0) {
1865 		snprintf(err, errlen, "bad ownership or modes for file %s",
1866 		    buf);
1867 		return -1;
1868 	}
1869 
1870 	/* for each component of the canonical path, walking upwards */
1871 	for (;;) {
1872 		if ((cp = dirname(buf)) == NULL) {
1873 			snprintf(err, errlen, "dirname() failed");
1874 			return -1;
1875 		}
1876 		strlcpy(buf, cp, sizeof(buf));
1877 
1878 		if (stat(buf, &st) == -1 ||
1879 		    (!platform_sys_dir_uid(st.st_uid) && st.st_uid != uid) ||
1880 		    (st.st_mode & 022) != 0) {
1881 			snprintf(err, errlen,
1882 			    "bad ownership or modes for directory %s", buf);
1883 			return -1;
1884 		}
1885 
1886 		/* If are past the homedir then we can stop */
1887 		if (comparehome && strcmp(homedir, buf) == 0)
1888 			break;
1889 
1890 		/*
1891 		 * dirname should always complete with a "/" path,
1892 		 * but we can be paranoid and check for "." too
1893 		 */
1894 		if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
1895 			break;
1896 	}
1897 	return 0;
1898 }
1899 
1900 /*
1901  * Version of safe_path() that accepts an open file descriptor to
1902  * avoid races.
1903  *
1904  * Returns 0 on success and -1 on failure
1905  */
1906 int
safe_path_fd(int fd,const char * file,struct passwd * pw,char * err,size_t errlen)1907 safe_path_fd(int fd, const char *file, struct passwd *pw,
1908     char *err, size_t errlen)
1909 {
1910 	struct stat st;
1911 
1912 	/* check the open file to avoid races */
1913 	if (fstat(fd, &st) == -1) {
1914 		snprintf(err, errlen, "cannot stat file %s: %s",
1915 		    file, strerror(errno));
1916 		return -1;
1917 	}
1918 	return safe_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen);
1919 }
1920 
1921 /*
1922  * Sets the value of the given variable in the environment.  If the variable
1923  * already exists, its value is overridden.
1924  */
1925 void
child_set_env(char *** envp,u_int * envsizep,const char * name,const char * value)1926 child_set_env(char ***envp, u_int *envsizep, const char *name,
1927 	const char *value)
1928 {
1929 	char **env;
1930 	u_int envsize;
1931 	u_int i, namelen;
1932 
1933 	if (strchr(name, '=') != NULL) {
1934 		error("Invalid environment variable \"%.100s\"", name);
1935 		return;
1936 	}
1937 
1938 	/*
1939 	 * If we're passed an uninitialized list, allocate a single null
1940 	 * entry before continuing.
1941 	 */
1942 	if (*envp == NULL && *envsizep == 0) {
1943 		*envp = xmalloc(sizeof(char *));
1944 		*envp[0] = NULL;
1945 		*envsizep = 1;
1946 	}
1947 
1948 	/*
1949 	 * Find the slot where the value should be stored.  If the variable
1950 	 * already exists, we reuse the slot; otherwise we append a new slot
1951 	 * at the end of the array, expanding if necessary.
1952 	 */
1953 	env = *envp;
1954 	namelen = strlen(name);
1955 	for (i = 0; env[i]; i++)
1956 		if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
1957 			break;
1958 	if (env[i]) {
1959 		/* Reuse the slot. */
1960 		free(env[i]);
1961 	} else {
1962 		/* New variable.  Expand if necessary. */
1963 		envsize = *envsizep;
1964 		if (i >= envsize - 1) {
1965 			if (envsize >= 1000)
1966 				fatal("child_set_env: too many env vars");
1967 			envsize += 50;
1968 			env = (*envp) = xreallocarray(env, envsize, sizeof(char *));
1969 			*envsizep = envsize;
1970 		}
1971 		/* Need to set the NULL pointer at end of array beyond the new slot. */
1972 		env[i + 1] = NULL;
1973 	}
1974 
1975 	/* Allocate space and format the variable in the appropriate slot. */
1976 	/* XXX xasprintf */
1977 	env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
1978 	snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
1979 }
1980 
1981 /*
1982  * Check and optionally lowercase a domain name, also removes trailing '.'
1983  * Returns 1 on success and 0 on failure, storing an error message in errstr.
1984  */
1985 int
valid_domain(char * name,int makelower,const char ** errstr)1986 valid_domain(char *name, int makelower, const char **errstr)
1987 {
1988 	size_t i, l = strlen(name);
1989 	u_char c, last = '\0';
1990 	static char errbuf[256];
1991 
1992 	if (l == 0) {
1993 		strlcpy(errbuf, "empty domain name", sizeof(errbuf));
1994 		goto bad;
1995 	}
1996 	if (!isalpha((u_char)name[0]) && !isdigit((u_char)name[0])) {
1997 		snprintf(errbuf, sizeof(errbuf), "domain name \"%.100s\" "
1998 		    "starts with invalid character", name);
1999 		goto bad;
2000 	}
2001 	for (i = 0; i < l; i++) {
2002 		c = tolower((u_char)name[i]);
2003 		if (makelower)
2004 			name[i] = (char)c;
2005 		if (last == '.' && c == '.') {
2006 			snprintf(errbuf, sizeof(errbuf), "domain name "
2007 			    "\"%.100s\" contains consecutive separators", name);
2008 			goto bad;
2009 		}
2010 		if (c != '.' && c != '-' && !isalnum(c) &&
2011 		    c != '_') /* technically invalid, but common */ {
2012 			snprintf(errbuf, sizeof(errbuf), "domain name "
2013 			    "\"%.100s\" contains invalid characters", name);
2014 			goto bad;
2015 		}
2016 		last = c;
2017 	}
2018 	if (name[l - 1] == '.')
2019 		name[l - 1] = '\0';
2020 	if (errstr != NULL)
2021 		*errstr = NULL;
2022 	return 1;
2023 bad:
2024 	if (errstr != NULL)
2025 		*errstr = errbuf;
2026 	return 0;
2027 }
2028 
2029 /*
2030  * Verify that a environment variable name (not including initial '$') is
2031  * valid; consisting of one or more alphanumeric or underscore characters only.
2032  * Returns 1 on valid, 0 otherwise.
2033  */
2034 int
valid_env_name(const char * name)2035 valid_env_name(const char *name)
2036 {
2037 	const char *cp;
2038 
2039 	if (name[0] == '\0')
2040 		return 0;
2041 	for (cp = name; *cp != '\0'; cp++) {
2042 		if (!isalnum((u_char)*cp) && *cp != '_')
2043 			return 0;
2044 	}
2045 	return 1;
2046 }
2047 
2048 const char *
atoi_err(const char * nptr,int * val)2049 atoi_err(const char *nptr, int *val)
2050 {
2051 	const char *errstr = NULL;
2052 	long long num;
2053 
2054 	if (nptr == NULL || *nptr == '\0')
2055 		return "missing";
2056 	num = strtonum(nptr, 0, INT_MAX, &errstr);
2057 	if (errstr == NULL)
2058 		*val = (int)num;
2059 	return errstr;
2060 }
2061 
2062 int
parse_absolute_time(const char * s,uint64_t * tp)2063 parse_absolute_time(const char *s, uint64_t *tp)
2064 {
2065 	struct tm tm;
2066 	time_t tt;
2067 	char buf[32], *fmt;
2068 
2069 	*tp = 0;
2070 
2071 	/*
2072 	 * POSIX strptime says "The application shall ensure that there
2073 	 * is white-space or other non-alphanumeric characters between
2074 	 * any two conversion specifications" so arrange things this way.
2075 	 */
2076 	switch (strlen(s)) {
2077 	case 8: /* YYYYMMDD */
2078 		fmt = "%Y-%m-%d";
2079 		snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
2080 		break;
2081 	case 12: /* YYYYMMDDHHMM */
2082 		fmt = "%Y-%m-%dT%H:%M";
2083 		snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s",
2084 		    s, s + 4, s + 6, s + 8, s + 10);
2085 		break;
2086 	case 14: /* YYYYMMDDHHMMSS */
2087 		fmt = "%Y-%m-%dT%H:%M:%S";
2088 		snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
2089 		    s, s + 4, s + 6, s + 8, s + 10, s + 12);
2090 		break;
2091 	default:
2092 		return SSH_ERR_INVALID_FORMAT;
2093 	}
2094 
2095 	memset(&tm, 0, sizeof(tm));
2096 	if (strptime(buf, fmt, &tm) == NULL)
2097 		return SSH_ERR_INVALID_FORMAT;
2098 	if ((tt = mktime(&tm)) < 0)
2099 		return SSH_ERR_INVALID_FORMAT;
2100 	/* success */
2101 	*tp = (uint64_t)tt;
2102 	return 0;
2103 }
2104 
2105 void
format_absolute_time(uint64_t t,char * buf,size_t len)2106 format_absolute_time(uint64_t t, char *buf, size_t len)
2107 {
2108 	time_t tt = t > INT_MAX ? INT_MAX : t; /* XXX revisit in 2038 :P */
2109 	struct tm tm;
2110 
2111 	localtime_r(&tt, &tm);
2112 	strftime(buf, len, "%Y-%m-%dT%H:%M:%S", &tm);
2113 }
2114 
2115 /* check if path is absolute */
2116 int
path_absolute(const char * path)2117 path_absolute(const char *path)
2118 {
2119 	return (*path == '/') ? 1 : 0;
2120 }
2121