xref: /openssh-portable/misc.c (revision 5485f8d5)
1 /* $OpenBSD: misc.c,v 1.142 2019/09/03 08:32:11 djm 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;
1053 	struct {
1054 		const char *key;
1055 		const char *repl;
1056 	} keys[EXPAND_MAX_KEYS];
1057 	struct sshbuf *buf;
1058 	va_list ap;
1059 	int r;
1060 	char *ret;
1061 
1062 	if ((buf = sshbuf_new()) == NULL)
1063 		fatal("%s: sshbuf_new failed", __func__);
1064 
1065 	/* Gather keys */
1066 	va_start(ap, string);
1067 	for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
1068 		keys[num_keys].key = va_arg(ap, char *);
1069 		if (keys[num_keys].key == NULL)
1070 			break;
1071 		keys[num_keys].repl = va_arg(ap, char *);
1072 		if (keys[num_keys].repl == NULL)
1073 			fatal("%s: NULL replacement", __func__);
1074 	}
1075 	if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
1076 		fatal("%s: too many keys", __func__);
1077 	va_end(ap);
1078 
1079 	/* Expand string */
1080 	for (i = 0; *string != '\0'; string++) {
1081 		if (*string != '%') {
1082  append:
1083 			if ((r = sshbuf_put_u8(buf, *string)) != 0) {
1084 				fatal("%s: sshbuf_put_u8: %s",
1085 				    __func__, ssh_err(r));
1086 			}
1087 			continue;
1088 		}
1089 		string++;
1090 		/* %% case */
1091 		if (*string == '%')
1092 			goto append;
1093 		if (*string == '\0')
1094 			fatal("%s: invalid format", __func__);
1095 		for (i = 0; i < num_keys; i++) {
1096 			if (strchr(keys[i].key, *string) != NULL) {
1097 				if ((r = sshbuf_put(buf, keys[i].repl,
1098 				    strlen(keys[i].repl))) != 0) {
1099 					fatal("%s: sshbuf_put: %s",
1100 					    __func__, ssh_err(r));
1101 				}
1102 				break;
1103 			}
1104 		}
1105 		if (i >= num_keys)
1106 			fatal("%s: unknown key %%%c", __func__, *string);
1107 	}
1108 	if ((ret = sshbuf_dup_string(buf)) == NULL)
1109 		fatal("%s: sshbuf_dup_string failed", __func__);
1110 	sshbuf_free(buf);
1111 	return ret;
1112 #undef EXPAND_MAX_KEYS
1113 }
1114 
1115 int
tun_open(int tun,int mode,char ** ifname)1116 tun_open(int tun, int mode, char **ifname)
1117 {
1118 #if defined(CUSTOM_SYS_TUN_OPEN)
1119 	return (sys_tun_open(tun, mode, ifname));
1120 #elif defined(SSH_TUN_OPENBSD)
1121 	struct ifreq ifr;
1122 	char name[100];
1123 	int fd = -1, sock;
1124 	const char *tunbase = "tun";
1125 
1126 	if (ifname != NULL)
1127 		*ifname = NULL;
1128 
1129 	if (mode == SSH_TUNMODE_ETHERNET)
1130 		tunbase = "tap";
1131 
1132 	/* Open the tunnel device */
1133 	if (tun <= SSH_TUNID_MAX) {
1134 		snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
1135 		fd = open(name, O_RDWR);
1136 	} else if (tun == SSH_TUNID_ANY) {
1137 		for (tun = 100; tun >= 0; tun--) {
1138 			snprintf(name, sizeof(name), "/dev/%s%d",
1139 			    tunbase, tun);
1140 			if ((fd = open(name, O_RDWR)) >= 0)
1141 				break;
1142 		}
1143 	} else {
1144 		debug("%s: invalid tunnel %u", __func__, tun);
1145 		return -1;
1146 	}
1147 
1148 	if (fd == -1) {
1149 		debug("%s: %s open: %s", __func__, name, strerror(errno));
1150 		return -1;
1151 	}
1152 
1153 	debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
1154 
1155 	/* Bring interface up if it is not already */
1156 	snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
1157 	if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
1158 		goto failed;
1159 
1160 	if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
1161 		debug("%s: get interface %s flags: %s", __func__,
1162 		    ifr.ifr_name, strerror(errno));
1163 		goto failed;
1164 	}
1165 
1166 	if (!(ifr.ifr_flags & IFF_UP)) {
1167 		ifr.ifr_flags |= IFF_UP;
1168 		if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
1169 			debug("%s: activate interface %s: %s", __func__,
1170 			    ifr.ifr_name, strerror(errno));
1171 			goto failed;
1172 		}
1173 	}
1174 
1175 	if (ifname != NULL)
1176 		*ifname = xstrdup(ifr.ifr_name);
1177 
1178 	close(sock);
1179 	return fd;
1180 
1181  failed:
1182 	if (fd >= 0)
1183 		close(fd);
1184 	if (sock >= 0)
1185 		close(sock);
1186 	return -1;
1187 #else
1188 	error("Tunnel interfaces are not supported on this platform");
1189 	return (-1);
1190 #endif
1191 }
1192 
1193 void
sanitise_stdfd(void)1194 sanitise_stdfd(void)
1195 {
1196 	int nullfd, dupfd;
1197 
1198 	if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1199 		fprintf(stderr, "Couldn't open /dev/null: %s\n",
1200 		    strerror(errno));
1201 		exit(1);
1202 	}
1203 	while (++dupfd <= STDERR_FILENO) {
1204 		/* Only populate closed fds. */
1205 		if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
1206 			if (dup2(nullfd, dupfd) == -1) {
1207 				fprintf(stderr, "dup2: %s\n", strerror(errno));
1208 				exit(1);
1209 			}
1210 		}
1211 	}
1212 	if (nullfd > STDERR_FILENO)
1213 		close(nullfd);
1214 }
1215 
1216 char *
tohex(const void * vp,size_t l)1217 tohex(const void *vp, size_t l)
1218 {
1219 	const u_char *p = (const u_char *)vp;
1220 	char b[3], *r;
1221 	size_t i, hl;
1222 
1223 	if (l > 65536)
1224 		return xstrdup("tohex: length > 65536");
1225 
1226 	hl = l * 2 + 1;
1227 	r = xcalloc(1, hl);
1228 	for (i = 0; i < l; i++) {
1229 		snprintf(b, sizeof(b), "%02x", p[i]);
1230 		strlcat(r, b, hl);
1231 	}
1232 	return (r);
1233 }
1234 
1235 u_int64_t
get_u64(const void * vp)1236 get_u64(const void *vp)
1237 {
1238 	const u_char *p = (const u_char *)vp;
1239 	u_int64_t v;
1240 
1241 	v  = (u_int64_t)p[0] << 56;
1242 	v |= (u_int64_t)p[1] << 48;
1243 	v |= (u_int64_t)p[2] << 40;
1244 	v |= (u_int64_t)p[3] << 32;
1245 	v |= (u_int64_t)p[4] << 24;
1246 	v |= (u_int64_t)p[5] << 16;
1247 	v |= (u_int64_t)p[6] << 8;
1248 	v |= (u_int64_t)p[7];
1249 
1250 	return (v);
1251 }
1252 
1253 u_int32_t
get_u32(const void * vp)1254 get_u32(const void *vp)
1255 {
1256 	const u_char *p = (const u_char *)vp;
1257 	u_int32_t v;
1258 
1259 	v  = (u_int32_t)p[0] << 24;
1260 	v |= (u_int32_t)p[1] << 16;
1261 	v |= (u_int32_t)p[2] << 8;
1262 	v |= (u_int32_t)p[3];
1263 
1264 	return (v);
1265 }
1266 
1267 u_int32_t
get_u32_le(const void * vp)1268 get_u32_le(const void *vp)
1269 {
1270 	const u_char *p = (const u_char *)vp;
1271 	u_int32_t v;
1272 
1273 	v  = (u_int32_t)p[0];
1274 	v |= (u_int32_t)p[1] << 8;
1275 	v |= (u_int32_t)p[2] << 16;
1276 	v |= (u_int32_t)p[3] << 24;
1277 
1278 	return (v);
1279 }
1280 
1281 u_int16_t
get_u16(const void * vp)1282 get_u16(const void *vp)
1283 {
1284 	const u_char *p = (const u_char *)vp;
1285 	u_int16_t v;
1286 
1287 	v  = (u_int16_t)p[0] << 8;
1288 	v |= (u_int16_t)p[1];
1289 
1290 	return (v);
1291 }
1292 
1293 void
put_u64(void * vp,u_int64_t v)1294 put_u64(void *vp, u_int64_t v)
1295 {
1296 	u_char *p = (u_char *)vp;
1297 
1298 	p[0] = (u_char)(v >> 56) & 0xff;
1299 	p[1] = (u_char)(v >> 48) & 0xff;
1300 	p[2] = (u_char)(v >> 40) & 0xff;
1301 	p[3] = (u_char)(v >> 32) & 0xff;
1302 	p[4] = (u_char)(v >> 24) & 0xff;
1303 	p[5] = (u_char)(v >> 16) & 0xff;
1304 	p[6] = (u_char)(v >> 8) & 0xff;
1305 	p[7] = (u_char)v & 0xff;
1306 }
1307 
1308 void
put_u32(void * vp,u_int32_t v)1309 put_u32(void *vp, u_int32_t v)
1310 {
1311 	u_char *p = (u_char *)vp;
1312 
1313 	p[0] = (u_char)(v >> 24) & 0xff;
1314 	p[1] = (u_char)(v >> 16) & 0xff;
1315 	p[2] = (u_char)(v >> 8) & 0xff;
1316 	p[3] = (u_char)v & 0xff;
1317 }
1318 
1319 void
put_u32_le(void * vp,u_int32_t v)1320 put_u32_le(void *vp, u_int32_t v)
1321 {
1322 	u_char *p = (u_char *)vp;
1323 
1324 	p[0] = (u_char)v & 0xff;
1325 	p[1] = (u_char)(v >> 8) & 0xff;
1326 	p[2] = (u_char)(v >> 16) & 0xff;
1327 	p[3] = (u_char)(v >> 24) & 0xff;
1328 }
1329 
1330 void
put_u16(void * vp,u_int16_t v)1331 put_u16(void *vp, u_int16_t v)
1332 {
1333 	u_char *p = (u_char *)vp;
1334 
1335 	p[0] = (u_char)(v >> 8) & 0xff;
1336 	p[1] = (u_char)v & 0xff;
1337 }
1338 
1339 void
ms_subtract_diff(struct timeval * start,int * ms)1340 ms_subtract_diff(struct timeval *start, int *ms)
1341 {
1342 	struct timeval diff, finish;
1343 
1344 	monotime_tv(&finish);
1345 	timersub(&finish, start, &diff);
1346 	*ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
1347 }
1348 
1349 void
ms_to_timeval(struct timeval * tv,int ms)1350 ms_to_timeval(struct timeval *tv, int ms)
1351 {
1352 	if (ms < 0)
1353 		ms = 0;
1354 	tv->tv_sec = ms / 1000;
1355 	tv->tv_usec = (ms % 1000) * 1000;
1356 }
1357 
1358 void
monotime_ts(struct timespec * ts)1359 monotime_ts(struct timespec *ts)
1360 {
1361 	struct timeval tv;
1362 #if defined(HAVE_CLOCK_GETTIME) && (defined(CLOCK_BOOTTIME) || \
1363     defined(CLOCK_MONOTONIC) || defined(CLOCK_REALTIME))
1364 	static int gettime_failed = 0;
1365 
1366 	if (!gettime_failed) {
1367 # ifdef CLOCK_BOOTTIME
1368 		if (clock_gettime(CLOCK_BOOTTIME, ts) == 0)
1369 			return;
1370 # endif /* CLOCK_BOOTTIME */
1371 # ifdef CLOCK_MONOTONIC
1372 		if (clock_gettime(CLOCK_MONOTONIC, ts) == 0)
1373 			return;
1374 # endif /* CLOCK_MONOTONIC */
1375 # ifdef CLOCK_REALTIME
1376 		/* Not monotonic, but we're almost out of options here. */
1377 		if (clock_gettime(CLOCK_REALTIME, ts) == 0)
1378 			return;
1379 # endif /* CLOCK_REALTIME */
1380 		debug3("clock_gettime: %s", strerror(errno));
1381 		gettime_failed = 1;
1382 	}
1383 #endif /* HAVE_CLOCK_GETTIME && (BOOTTIME || MONOTONIC || REALTIME) */
1384 	gettimeofday(&tv, NULL);
1385 	ts->tv_sec = tv.tv_sec;
1386 	ts->tv_nsec = (long)tv.tv_usec * 1000;
1387 }
1388 
1389 void
monotime_tv(struct timeval * tv)1390 monotime_tv(struct timeval *tv)
1391 {
1392 	struct timespec ts;
1393 
1394 	monotime_ts(&ts);
1395 	tv->tv_sec = ts.tv_sec;
1396 	tv->tv_usec = ts.tv_nsec / 1000;
1397 }
1398 
1399 time_t
monotime(void)1400 monotime(void)
1401 {
1402 	struct timespec ts;
1403 
1404 	monotime_ts(&ts);
1405 	return ts.tv_sec;
1406 }
1407 
1408 double
monotime_double(void)1409 monotime_double(void)
1410 {
1411 	struct timespec ts;
1412 
1413 	monotime_ts(&ts);
1414 	return ts.tv_sec + ((double)ts.tv_nsec / 1000000000);
1415 }
1416 
1417 void
bandwidth_limit_init(struct bwlimit * bw,u_int64_t kbps,size_t buflen)1418 bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
1419 {
1420 	bw->buflen = buflen;
1421 	bw->rate = kbps;
1422 	bw->thresh = buflen;
1423 	bw->lamt = 0;
1424 	timerclear(&bw->bwstart);
1425 	timerclear(&bw->bwend);
1426 }
1427 
1428 /* Callback from read/write loop to insert bandwidth-limiting delays */
1429 void
bandwidth_limit(struct bwlimit * bw,size_t read_len)1430 bandwidth_limit(struct bwlimit *bw, size_t read_len)
1431 {
1432 	u_int64_t waitlen;
1433 	struct timespec ts, rm;
1434 
1435 	bw->lamt += read_len;
1436 	if (!timerisset(&bw->bwstart)) {
1437 		monotime_tv(&bw->bwstart);
1438 		return;
1439 	}
1440 	if (bw->lamt < bw->thresh)
1441 		return;
1442 
1443 	monotime_tv(&bw->bwend);
1444 	timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
1445 	if (!timerisset(&bw->bwend))
1446 		return;
1447 
1448 	bw->lamt *= 8;
1449 	waitlen = (double)1000000L * bw->lamt / bw->rate;
1450 
1451 	bw->bwstart.tv_sec = waitlen / 1000000L;
1452 	bw->bwstart.tv_usec = waitlen % 1000000L;
1453 
1454 	if (timercmp(&bw->bwstart, &bw->bwend, >)) {
1455 		timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
1456 
1457 		/* Adjust the wait time */
1458 		if (bw->bwend.tv_sec) {
1459 			bw->thresh /= 2;
1460 			if (bw->thresh < bw->buflen / 4)
1461 				bw->thresh = bw->buflen / 4;
1462 		} else if (bw->bwend.tv_usec < 10000) {
1463 			bw->thresh *= 2;
1464 			if (bw->thresh > bw->buflen * 8)
1465 				bw->thresh = bw->buflen * 8;
1466 		}
1467 
1468 		TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
1469 		while (nanosleep(&ts, &rm) == -1) {
1470 			if (errno != EINTR)
1471 				break;
1472 			ts = rm;
1473 		}
1474 	}
1475 
1476 	bw->lamt = 0;
1477 	monotime_tv(&bw->bwstart);
1478 }
1479 
1480 /* Make a template filename for mk[sd]temp() */
1481 void
mktemp_proto(char * s,size_t len)1482 mktemp_proto(char *s, size_t len)
1483 {
1484 	const char *tmpdir;
1485 	int r;
1486 
1487 	if ((tmpdir = getenv("TMPDIR")) != NULL) {
1488 		r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
1489 		if (r > 0 && (size_t)r < len)
1490 			return;
1491 	}
1492 	r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
1493 	if (r < 0 || (size_t)r >= len)
1494 		fatal("%s: template string too short", __func__);
1495 }
1496 
1497 static const struct {
1498 	const char *name;
1499 	int value;
1500 } ipqos[] = {
1501 	{ "none", INT_MAX },		/* can't use 0 here; that's CS0 */
1502 	{ "af11", IPTOS_DSCP_AF11 },
1503 	{ "af12", IPTOS_DSCP_AF12 },
1504 	{ "af13", IPTOS_DSCP_AF13 },
1505 	{ "af21", IPTOS_DSCP_AF21 },
1506 	{ "af22", IPTOS_DSCP_AF22 },
1507 	{ "af23", IPTOS_DSCP_AF23 },
1508 	{ "af31", IPTOS_DSCP_AF31 },
1509 	{ "af32", IPTOS_DSCP_AF32 },
1510 	{ "af33", IPTOS_DSCP_AF33 },
1511 	{ "af41", IPTOS_DSCP_AF41 },
1512 	{ "af42", IPTOS_DSCP_AF42 },
1513 	{ "af43", IPTOS_DSCP_AF43 },
1514 	{ "cs0", IPTOS_DSCP_CS0 },
1515 	{ "cs1", IPTOS_DSCP_CS1 },
1516 	{ "cs2", IPTOS_DSCP_CS2 },
1517 	{ "cs3", IPTOS_DSCP_CS3 },
1518 	{ "cs4", IPTOS_DSCP_CS4 },
1519 	{ "cs5", IPTOS_DSCP_CS5 },
1520 	{ "cs6", IPTOS_DSCP_CS6 },
1521 	{ "cs7", IPTOS_DSCP_CS7 },
1522 	{ "ef", IPTOS_DSCP_EF },
1523 	{ "lowdelay", IPTOS_LOWDELAY },
1524 	{ "throughput", IPTOS_THROUGHPUT },
1525 	{ "reliability", IPTOS_RELIABILITY },
1526 	{ NULL, -1 }
1527 };
1528 
1529 int
parse_ipqos(const char * cp)1530 parse_ipqos(const char *cp)
1531 {
1532 	u_int i;
1533 	char *ep;
1534 	long val;
1535 
1536 	if (cp == NULL)
1537 		return -1;
1538 	for (i = 0; ipqos[i].name != NULL; i++) {
1539 		if (strcasecmp(cp, ipqos[i].name) == 0)
1540 			return ipqos[i].value;
1541 	}
1542 	/* Try parsing as an integer */
1543 	val = strtol(cp, &ep, 0);
1544 	if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1545 		return -1;
1546 	return val;
1547 }
1548 
1549 const char *
iptos2str(int iptos)1550 iptos2str(int iptos)
1551 {
1552 	int i;
1553 	static char iptos_str[sizeof "0xff"];
1554 
1555 	for (i = 0; ipqos[i].name != NULL; i++) {
1556 		if (ipqos[i].value == iptos)
1557 			return ipqos[i].name;
1558 	}
1559 	snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1560 	return iptos_str;
1561 }
1562 
1563 void
lowercase(char * s)1564 lowercase(char *s)
1565 {
1566 	for (; *s; s++)
1567 		*s = tolower((u_char)*s);
1568 }
1569 
1570 int
unix_listener(const char * path,int backlog,int unlink_first)1571 unix_listener(const char *path, int backlog, int unlink_first)
1572 {
1573 	struct sockaddr_un sunaddr;
1574 	int saved_errno, sock;
1575 
1576 	memset(&sunaddr, 0, sizeof(sunaddr));
1577 	sunaddr.sun_family = AF_UNIX;
1578 	if (strlcpy(sunaddr.sun_path, path,
1579 	    sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1580 		error("%s: path \"%s\" too long for Unix domain socket",
1581 		    __func__, path);
1582 		errno = ENAMETOOLONG;
1583 		return -1;
1584 	}
1585 
1586 	sock = socket(PF_UNIX, SOCK_STREAM, 0);
1587 	if (sock == -1) {
1588 		saved_errno = errno;
1589 		error("%s: socket: %.100s", __func__, strerror(errno));
1590 		errno = saved_errno;
1591 		return -1;
1592 	}
1593 	if (unlink_first == 1) {
1594 		if (unlink(path) != 0 && errno != ENOENT)
1595 			error("unlink(%s): %.100s", path, strerror(errno));
1596 	}
1597 	if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1598 		saved_errno = errno;
1599 		error("%s: cannot bind to path %s: %s",
1600 		    __func__, path, strerror(errno));
1601 		close(sock);
1602 		errno = saved_errno;
1603 		return -1;
1604 	}
1605 	if (listen(sock, backlog) == -1) {
1606 		saved_errno = errno;
1607 		error("%s: cannot listen on path %s: %s",
1608 		    __func__, path, strerror(errno));
1609 		close(sock);
1610 		unlink(path);
1611 		errno = saved_errno;
1612 		return -1;
1613 	}
1614 	return sock;
1615 }
1616 
1617 void
sock_set_v6only(int s)1618 sock_set_v6only(int s)
1619 {
1620 #if defined(IPV6_V6ONLY) && !defined(__OpenBSD__)
1621 	int on = 1;
1622 
1623 	debug3("%s: set socket %d IPV6_V6ONLY", __func__, s);
1624 	if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1)
1625 		error("setsockopt IPV6_V6ONLY: %s", strerror(errno));
1626 #endif
1627 }
1628 
1629 /*
1630  * Compares two strings that maybe be NULL. Returns non-zero if strings
1631  * are both NULL or are identical, returns zero otherwise.
1632  */
1633 static int
strcmp_maybe_null(const char * a,const char * b)1634 strcmp_maybe_null(const char *a, const char *b)
1635 {
1636 	if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1637 		return 0;
1638 	if (a != NULL && strcmp(a, b) != 0)
1639 		return 0;
1640 	return 1;
1641 }
1642 
1643 /*
1644  * Compare two forwards, returning non-zero if they are identical or
1645  * zero otherwise.
1646  */
1647 int
forward_equals(const struct Forward * a,const struct Forward * b)1648 forward_equals(const struct Forward *a, const struct Forward *b)
1649 {
1650 	if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
1651 		return 0;
1652 	if (a->listen_port != b->listen_port)
1653 		return 0;
1654 	if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
1655 		return 0;
1656 	if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
1657 		return 0;
1658 	if (a->connect_port != b->connect_port)
1659 		return 0;
1660 	if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
1661 		return 0;
1662 	/* allocated_port and handle are not checked */
1663 	return 1;
1664 }
1665 
1666 /* returns 1 if process is already daemonized, 0 otherwise */
1667 int
daemonized(void)1668 daemonized(void)
1669 {
1670 	int fd;
1671 
1672 	if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
1673 		close(fd);
1674 		return 0;	/* have controlling terminal */
1675 	}
1676 	if (getppid() != 1)
1677 		return 0;	/* parent is not init */
1678 	if (getsid(0) != getpid())
1679 		return 0;	/* not session leader */
1680 	debug3("already daemonized");
1681 	return 1;
1682 }
1683 
1684 
1685 /*
1686  * Splits 's' into an argument vector. Handles quoted string and basic
1687  * escape characters (\\, \", \'). Caller must free the argument vector
1688  * and its members.
1689  */
1690 int
argv_split(const char * s,int * argcp,char *** argvp)1691 argv_split(const char *s, int *argcp, char ***argvp)
1692 {
1693 	int r = SSH_ERR_INTERNAL_ERROR;
1694 	int argc = 0, quote, i, j;
1695 	char *arg, **argv = xcalloc(1, sizeof(*argv));
1696 
1697 	*argvp = NULL;
1698 	*argcp = 0;
1699 
1700 	for (i = 0; s[i] != '\0'; i++) {
1701 		/* Skip leading whitespace */
1702 		if (s[i] == ' ' || s[i] == '\t')
1703 			continue;
1704 
1705 		/* Start of a token */
1706 		quote = 0;
1707 		if (s[i] == '\\' &&
1708 		    (s[i + 1] == '\'' || s[i + 1] == '\"' || s[i + 1] == '\\'))
1709 			i++;
1710 		else if (s[i] == '\'' || s[i] == '"')
1711 			quote = s[i++];
1712 
1713 		argv = xreallocarray(argv, (argc + 2), sizeof(*argv));
1714 		arg = argv[argc++] = xcalloc(1, strlen(s + i) + 1);
1715 		argv[argc] = NULL;
1716 
1717 		/* Copy the token in, removing escapes */
1718 		for (j = 0; s[i] != '\0'; i++) {
1719 			if (s[i] == '\\') {
1720 				if (s[i + 1] == '\'' ||
1721 				    s[i + 1] == '\"' ||
1722 				    s[i + 1] == '\\') {
1723 					i++; /* Skip '\' */
1724 					arg[j++] = s[i];
1725 				} else {
1726 					/* Unrecognised escape */
1727 					arg[j++] = s[i];
1728 				}
1729 			} else if (quote == 0 && (s[i] == ' ' || s[i] == '\t'))
1730 				break; /* done */
1731 			else if (quote != 0 && s[i] == quote)
1732 				break; /* done */
1733 			else
1734 				arg[j++] = s[i];
1735 		}
1736 		if (s[i] == '\0') {
1737 			if (quote != 0) {
1738 				/* Ran out of string looking for close quote */
1739 				r = SSH_ERR_INVALID_FORMAT;
1740 				goto out;
1741 			}
1742 			break;
1743 		}
1744 	}
1745 	/* Success */
1746 	*argcp = argc;
1747 	*argvp = argv;
1748 	argc = 0;
1749 	argv = NULL;
1750 	r = 0;
1751  out:
1752 	if (argc != 0 && argv != NULL) {
1753 		for (i = 0; i < argc; i++)
1754 			free(argv[i]);
1755 		free(argv);
1756 	}
1757 	return r;
1758 }
1759 
1760 /*
1761  * Reassemble an argument vector into a string, quoting and escaping as
1762  * necessary. Caller must free returned string.
1763  */
1764 char *
argv_assemble(int argc,char ** argv)1765 argv_assemble(int argc, char **argv)
1766 {
1767 	int i, j, ws, r;
1768 	char c, *ret;
1769 	struct sshbuf *buf, *arg;
1770 
1771 	if ((buf = sshbuf_new()) == NULL || (arg = sshbuf_new()) == NULL)
1772 		fatal("%s: sshbuf_new failed", __func__);
1773 
1774 	for (i = 0; i < argc; i++) {
1775 		ws = 0;
1776 		sshbuf_reset(arg);
1777 		for (j = 0; argv[i][j] != '\0'; j++) {
1778 			r = 0;
1779 			c = argv[i][j];
1780 			switch (c) {
1781 			case ' ':
1782 			case '\t':
1783 				ws = 1;
1784 				r = sshbuf_put_u8(arg, c);
1785 				break;
1786 			case '\\':
1787 			case '\'':
1788 			case '"':
1789 				if ((r = sshbuf_put_u8(arg, '\\')) != 0)
1790 					break;
1791 				/* FALLTHROUGH */
1792 			default:
1793 				r = sshbuf_put_u8(arg, c);
1794 				break;
1795 			}
1796 			if (r != 0)
1797 				fatal("%s: sshbuf_put_u8: %s",
1798 				    __func__, ssh_err(r));
1799 		}
1800 		if ((i != 0 && (r = sshbuf_put_u8(buf, ' ')) != 0) ||
1801 		    (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0) ||
1802 		    (r = sshbuf_putb(buf, arg)) != 0 ||
1803 		    (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0))
1804 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
1805 	}
1806 	if ((ret = malloc(sshbuf_len(buf) + 1)) == NULL)
1807 		fatal("%s: malloc failed", __func__);
1808 	memcpy(ret, sshbuf_ptr(buf), sshbuf_len(buf));
1809 	ret[sshbuf_len(buf)] = '\0';
1810 	sshbuf_free(buf);
1811 	sshbuf_free(arg);
1812 	return ret;
1813 }
1814 
1815 /* Returns 0 if pid exited cleanly, non-zero otherwise */
1816 int
exited_cleanly(pid_t pid,const char * tag,const char * cmd,int quiet)1817 exited_cleanly(pid_t pid, const char *tag, const char *cmd, int quiet)
1818 {
1819 	int status;
1820 
1821 	while (waitpid(pid, &status, 0) == -1) {
1822 		if (errno != EINTR) {
1823 			error("%s: waitpid: %s", tag, strerror(errno));
1824 			return -1;
1825 		}
1826 	}
1827 	if (WIFSIGNALED(status)) {
1828 		error("%s %s exited on signal %d", tag, cmd, WTERMSIG(status));
1829 		return -1;
1830 	} else if (WEXITSTATUS(status) != 0) {
1831 		do_log2(quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_INFO,
1832 		    "%s %s failed, status %d", tag, cmd, WEXITSTATUS(status));
1833 		return -1;
1834 	}
1835 	return 0;
1836 }
1837 
1838 /*
1839  * Check a given path for security. This is defined as all components
1840  * of the path to the file must be owned by either the owner of
1841  * of the file or root and no directories must be group or world writable.
1842  *
1843  * XXX Should any specific check be done for sym links ?
1844  *
1845  * Takes a file name, its stat information (preferably from fstat() to
1846  * avoid races), the uid of the expected owner, their home directory and an
1847  * error buffer plus max size as arguments.
1848  *
1849  * Returns 0 on success and -1 on failure
1850  */
1851 int
safe_path(const char * name,struct stat * stp,const char * pw_dir,uid_t uid,char * err,size_t errlen)1852 safe_path(const char *name, struct stat *stp, const char *pw_dir,
1853     uid_t uid, char *err, size_t errlen)
1854 {
1855 	char buf[PATH_MAX], homedir[PATH_MAX];
1856 	char *cp;
1857 	int comparehome = 0;
1858 	struct stat st;
1859 
1860 	if (realpath(name, buf) == NULL) {
1861 		snprintf(err, errlen, "realpath %s failed: %s", name,
1862 		    strerror(errno));
1863 		return -1;
1864 	}
1865 	if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL)
1866 		comparehome = 1;
1867 
1868 	if (!S_ISREG(stp->st_mode)) {
1869 		snprintf(err, errlen, "%s is not a regular file", buf);
1870 		return -1;
1871 	}
1872 	if ((!platform_sys_dir_uid(stp->st_uid) && stp->st_uid != uid) ||
1873 	    (stp->st_mode & 022) != 0) {
1874 		snprintf(err, errlen, "bad ownership or modes for file %s",
1875 		    buf);
1876 		return -1;
1877 	}
1878 
1879 	/* for each component of the canonical path, walking upwards */
1880 	for (;;) {
1881 		if ((cp = dirname(buf)) == NULL) {
1882 			snprintf(err, errlen, "dirname() failed");
1883 			return -1;
1884 		}
1885 		strlcpy(buf, cp, sizeof(buf));
1886 
1887 		if (stat(buf, &st) == -1 ||
1888 		    (!platform_sys_dir_uid(st.st_uid) && st.st_uid != uid) ||
1889 		    (st.st_mode & 022) != 0) {
1890 			snprintf(err, errlen,
1891 			    "bad ownership or modes for directory %s", buf);
1892 			return -1;
1893 		}
1894 
1895 		/* If are past the homedir then we can stop */
1896 		if (comparehome && strcmp(homedir, buf) == 0)
1897 			break;
1898 
1899 		/*
1900 		 * dirname should always complete with a "/" path,
1901 		 * but we can be paranoid and check for "." too
1902 		 */
1903 		if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
1904 			break;
1905 	}
1906 	return 0;
1907 }
1908 
1909 /*
1910  * Version of safe_path() that accepts an open file descriptor to
1911  * avoid races.
1912  *
1913  * Returns 0 on success and -1 on failure
1914  */
1915 int
safe_path_fd(int fd,const char * file,struct passwd * pw,char * err,size_t errlen)1916 safe_path_fd(int fd, const char *file, struct passwd *pw,
1917     char *err, size_t errlen)
1918 {
1919 	struct stat st;
1920 
1921 	/* check the open file to avoid races */
1922 	if (fstat(fd, &st) == -1) {
1923 		snprintf(err, errlen, "cannot stat file %s: %s",
1924 		    file, strerror(errno));
1925 		return -1;
1926 	}
1927 	return safe_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen);
1928 }
1929 
1930 /*
1931  * Sets the value of the given variable in the environment.  If the variable
1932  * already exists, its value is overridden.
1933  */
1934 void
child_set_env(char *** envp,u_int * envsizep,const char * name,const char * value)1935 child_set_env(char ***envp, u_int *envsizep, const char *name,
1936 	const char *value)
1937 {
1938 	char **env;
1939 	u_int envsize;
1940 	u_int i, namelen;
1941 
1942 	if (strchr(name, '=') != NULL) {
1943 		error("Invalid environment variable \"%.100s\"", name);
1944 		return;
1945 	}
1946 
1947 	/*
1948 	 * If we're passed an uninitialized list, allocate a single null
1949 	 * entry before continuing.
1950 	 */
1951 	if (*envp == NULL && *envsizep == 0) {
1952 		*envp = xmalloc(sizeof(char *));
1953 		*envp[0] = NULL;
1954 		*envsizep = 1;
1955 	}
1956 
1957 	/*
1958 	 * Find the slot where the value should be stored.  If the variable
1959 	 * already exists, we reuse the slot; otherwise we append a new slot
1960 	 * at the end of the array, expanding if necessary.
1961 	 */
1962 	env = *envp;
1963 	namelen = strlen(name);
1964 	for (i = 0; env[i]; i++)
1965 		if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
1966 			break;
1967 	if (env[i]) {
1968 		/* Reuse the slot. */
1969 		free(env[i]);
1970 	} else {
1971 		/* New variable.  Expand if necessary. */
1972 		envsize = *envsizep;
1973 		if (i >= envsize - 1) {
1974 			if (envsize >= 1000)
1975 				fatal("child_set_env: too many env vars");
1976 			envsize += 50;
1977 			env = (*envp) = xreallocarray(env, envsize, sizeof(char *));
1978 			*envsizep = envsize;
1979 		}
1980 		/* Need to set the NULL pointer at end of array beyond the new slot. */
1981 		env[i + 1] = NULL;
1982 	}
1983 
1984 	/* Allocate space and format the variable in the appropriate slot. */
1985 	/* XXX xasprintf */
1986 	env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
1987 	snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
1988 }
1989 
1990 /*
1991  * Check and optionally lowercase a domain name, also removes trailing '.'
1992  * Returns 1 on success and 0 on failure, storing an error message in errstr.
1993  */
1994 int
valid_domain(char * name,int makelower,const char ** errstr)1995 valid_domain(char *name, int makelower, const char **errstr)
1996 {
1997 	size_t i, l = strlen(name);
1998 	u_char c, last = '\0';
1999 	static char errbuf[256];
2000 
2001 	if (l == 0) {
2002 		strlcpy(errbuf, "empty domain name", sizeof(errbuf));
2003 		goto bad;
2004 	}
2005 	if (!isalpha((u_char)name[0]) && !isdigit((u_char)name[0])) {
2006 		snprintf(errbuf, sizeof(errbuf), "domain name \"%.100s\" "
2007 		    "starts with invalid character", name);
2008 		goto bad;
2009 	}
2010 	for (i = 0; i < l; i++) {
2011 		c = tolower((u_char)name[i]);
2012 		if (makelower)
2013 			name[i] = (char)c;
2014 		if (last == '.' && c == '.') {
2015 			snprintf(errbuf, sizeof(errbuf), "domain name "
2016 			    "\"%.100s\" contains consecutive separators", name);
2017 			goto bad;
2018 		}
2019 		if (c != '.' && c != '-' && !isalnum(c) &&
2020 		    c != '_') /* technically invalid, but common */ {
2021 			snprintf(errbuf, sizeof(errbuf), "domain name "
2022 			    "\"%.100s\" contains invalid characters", name);
2023 			goto bad;
2024 		}
2025 		last = c;
2026 	}
2027 	if (name[l - 1] == '.')
2028 		name[l - 1] = '\0';
2029 	if (errstr != NULL)
2030 		*errstr = NULL;
2031 	return 1;
2032 bad:
2033 	if (errstr != NULL)
2034 		*errstr = errbuf;
2035 	return 0;
2036 }
2037 
2038 /*
2039  * Verify that a environment variable name (not including initial '$') is
2040  * valid; consisting of one or more alphanumeric or underscore characters only.
2041  * Returns 1 on valid, 0 otherwise.
2042  */
2043 int
valid_env_name(const char * name)2044 valid_env_name(const char *name)
2045 {
2046 	const char *cp;
2047 
2048 	if (name[0] == '\0')
2049 		return 0;
2050 	for (cp = name; *cp != '\0'; cp++) {
2051 		if (!isalnum((u_char)*cp) && *cp != '_')
2052 			return 0;
2053 	}
2054 	return 1;
2055 }
2056 
2057 const char *
atoi_err(const char * nptr,int * val)2058 atoi_err(const char *nptr, int *val)
2059 {
2060 	const char *errstr = NULL;
2061 	long long num;
2062 
2063 	if (nptr == NULL || *nptr == '\0')
2064 		return "missing";
2065 	num = strtonum(nptr, 0, INT_MAX, &errstr);
2066 	if (errstr == NULL)
2067 		*val = (int)num;
2068 	return errstr;
2069 }
2070 
2071 int
parse_absolute_time(const char * s,uint64_t * tp)2072 parse_absolute_time(const char *s, uint64_t *tp)
2073 {
2074 	struct tm tm;
2075 	time_t tt;
2076 	char buf[32], *fmt;
2077 
2078 	*tp = 0;
2079 
2080 	/*
2081 	 * POSIX strptime says "The application shall ensure that there
2082 	 * is white-space or other non-alphanumeric characters between
2083 	 * any two conversion specifications" so arrange things this way.
2084 	 */
2085 	switch (strlen(s)) {
2086 	case 8: /* YYYYMMDD */
2087 		fmt = "%Y-%m-%d";
2088 		snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
2089 		break;
2090 	case 12: /* YYYYMMDDHHMM */
2091 		fmt = "%Y-%m-%dT%H:%M";
2092 		snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s",
2093 		    s, s + 4, s + 6, s + 8, s + 10);
2094 		break;
2095 	case 14: /* YYYYMMDDHHMMSS */
2096 		fmt = "%Y-%m-%dT%H:%M:%S";
2097 		snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
2098 		    s, s + 4, s + 6, s + 8, s + 10, s + 12);
2099 		break;
2100 	default:
2101 		return SSH_ERR_INVALID_FORMAT;
2102 	}
2103 
2104 	memset(&tm, 0, sizeof(tm));
2105 	if (strptime(buf, fmt, &tm) == NULL)
2106 		return SSH_ERR_INVALID_FORMAT;
2107 	if ((tt = mktime(&tm)) < 0)
2108 		return SSH_ERR_INVALID_FORMAT;
2109 	/* success */
2110 	*tp = (uint64_t)tt;
2111 	return 0;
2112 }
2113 
2114 void
format_absolute_time(uint64_t t,char * buf,size_t len)2115 format_absolute_time(uint64_t t, char *buf, size_t len)
2116 {
2117 	time_t tt = t > INT_MAX ? INT_MAX : t; /* XXX revisit in 2038 :P */
2118 	struct tm tm;
2119 
2120 	localtime_r(&tt, &tm);
2121 	strftime(buf, len, "%Y-%m-%dT%H:%M:%S", &tm);
2122 }
2123 
2124 /* check if path is absolute */
2125 int
path_absolute(const char * path)2126 path_absolute(const char *path)
2127 {
2128 	return (*path == '/') ? 1 : 0;
2129 }
2130 
2131 void
skip_space(char ** cpp)2132 skip_space(char **cpp)
2133 {
2134 	char *cp;
2135 
2136 	for (cp = *cpp; *cp == ' ' || *cp == '\t'; cp++)
2137 		;
2138 	*cpp = cp;
2139 }
2140 
2141 /* authorized_key-style options parsing helpers */
2142 
2143 /*
2144  * Match flag 'opt' in *optsp, and if allow_negate is set then also match
2145  * 'no-opt'. Returns -1 if option not matched, 1 if option matches or 0
2146  * if negated option matches.
2147  * If the option or negated option matches, then *optsp is updated to
2148  * point to the first character after the option.
2149  */
2150 int
opt_flag(const char * opt,int allow_negate,const char ** optsp)2151 opt_flag(const char *opt, int allow_negate, const char **optsp)
2152 {
2153 	size_t opt_len = strlen(opt);
2154 	const char *opts = *optsp;
2155 	int negate = 0;
2156 
2157 	if (allow_negate && strncasecmp(opts, "no-", 3) == 0) {
2158 		opts += 3;
2159 		negate = 1;
2160 	}
2161 	if (strncasecmp(opts, opt, opt_len) == 0) {
2162 		*optsp = opts + opt_len;
2163 		return negate ? 0 : 1;
2164 	}
2165 	return -1;
2166 }
2167 
2168 char *
opt_dequote(const char ** sp,const char ** errstrp)2169 opt_dequote(const char **sp, const char **errstrp)
2170 {
2171 	const char *s = *sp;
2172 	char *ret;
2173 	size_t i;
2174 
2175 	*errstrp = NULL;
2176 	if (*s != '"') {
2177 		*errstrp = "missing start quote";
2178 		return NULL;
2179 	}
2180 	s++;
2181 	if ((ret = malloc(strlen((s)) + 1)) == NULL) {
2182 		*errstrp = "memory allocation failed";
2183 		return NULL;
2184 	}
2185 	for (i = 0; *s != '\0' && *s != '"';) {
2186 		if (s[0] == '\\' && s[1] == '"')
2187 			s++;
2188 		ret[i++] = *s++;
2189 	}
2190 	if (*s == '\0') {
2191 		*errstrp = "missing end quote";
2192 		free(ret);
2193 		return NULL;
2194 	}
2195 	ret[i] = '\0';
2196 	s++;
2197 	*sp = s;
2198 	return ret;
2199 }
2200 
2201 int
opt_match(const char ** opts,const char * term)2202 opt_match(const char **opts, const char *term)
2203 {
2204 	if (strncasecmp((*opts), term, strlen(term)) == 0 &&
2205 	    (*opts)[strlen(term)] == '=') {
2206 		*opts += strlen(term) + 1;
2207 		return 1;
2208 	}
2209 	return 0;
2210 }
2211 
2212