fix old typo (s/SYSVINITSTOPT/SYSVINITSTOP/)
[openssh.git] / misc.c
blobdd0bd032ae3c0984e00c45edd2e513d49a56709b
1 /* $OpenBSD: misc.c,v 1.198 2024/10/24 03:14:37 djm Exp $ */
2 /*
3 * Copyright (c) 2000 Markus Friedl. All rights reserved.
4 * Copyright (c) 2005-2020 Damien Miller. All rights reserved.
5 * Copyright (c) 2004 Henning Brauer <henning@openbsd.org>
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21 #include "includes.h"
23 #include <sys/types.h>
24 #include <sys/ioctl.h>
25 #include <sys/mman.h>
26 #include <sys/socket.h>
27 #include <sys/stat.h>
28 #include <sys/time.h>
29 #include <sys/wait.h>
30 #include <sys/un.h>
32 #include <limits.h>
33 #ifdef HAVE_LIBGEN_H
34 # include <libgen.h>
35 #endif
36 #ifdef HAVE_POLL_H
37 #include <poll.h>
38 #endif
39 #ifdef HAVE_NLIST_H
40 #include <nlist.h>
41 #endif
42 #include <signal.h>
43 #include <stdarg.h>
44 #include <stdio.h>
45 #ifdef HAVE_STDINT_H
46 # include <stdint.h>
47 #endif
48 #include <stdlib.h>
49 #include <string.h>
50 #include <time.h>
51 #include <unistd.h>
53 #include <netinet/in.h>
54 #include <netinet/in_systm.h>
55 #include <netinet/ip.h>
56 #include <netinet/tcp.h>
57 #include <arpa/inet.h>
59 #include <ctype.h>
60 #include <errno.h>
61 #include <fcntl.h>
62 #include <netdb.h>
63 #ifdef HAVE_PATHS_H
64 # include <paths.h>
65 #include <pwd.h>
66 #include <grp.h>
67 #endif
68 #ifdef SSH_TUN_OPENBSD
69 #include <net/if.h>
70 #endif
72 #include "xmalloc.h"
73 #include "misc.h"
74 #include "log.h"
75 #include "ssh.h"
76 #include "sshbuf.h"
77 #include "ssherr.h"
78 #include "platform.h"
80 /* remove newline at end of string */
81 char *
82 chop(char *s)
84 char *t = s;
85 while (*t) {
86 if (*t == '\n' || *t == '\r') {
87 *t = '\0';
88 return s;
90 t++;
92 return s;
96 /* remove whitespace from end of string */
97 void
98 rtrim(char *s)
100 size_t i;
102 if ((i = strlen(s)) == 0)
103 return;
104 for (i--; i > 0; i--) {
105 if (isspace((unsigned char)s[i]))
106 s[i] = '\0';
111 * returns pointer to character after 'prefix' in 's' or otherwise NULL
112 * if the prefix is not present.
114 const char *
115 strprefix(const char *s, const char *prefix, int ignorecase)
117 size_t prefixlen;
119 if ((prefixlen = strlen(prefix)) == 0)
120 return s;
121 if (ignorecase) {
122 if (strncasecmp(s, prefix, prefixlen) != 0)
123 return NULL;
124 } else {
125 if (strncmp(s, prefix, prefixlen) != 0)
126 return NULL;
128 return s + prefixlen;
131 /* set/unset filedescriptor to non-blocking */
133 set_nonblock(int fd)
135 int val;
137 val = fcntl(fd, F_GETFL);
138 if (val == -1) {
139 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
140 return (-1);
142 if (val & O_NONBLOCK) {
143 debug3("fd %d is O_NONBLOCK", fd);
144 return (0);
146 debug2("fd %d setting O_NONBLOCK", fd);
147 val |= O_NONBLOCK;
148 if (fcntl(fd, F_SETFL, val) == -1) {
149 debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
150 strerror(errno));
151 return (-1);
153 return (0);
157 unset_nonblock(int fd)
159 int val;
161 val = fcntl(fd, F_GETFL);
162 if (val == -1) {
163 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
164 return (-1);
166 if (!(val & O_NONBLOCK)) {
167 debug3("fd %d is not O_NONBLOCK", fd);
168 return (0);
170 debug("fd %d clearing O_NONBLOCK", fd);
171 val &= ~O_NONBLOCK;
172 if (fcntl(fd, F_SETFL, val) == -1) {
173 debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
174 fd, strerror(errno));
175 return (-1);
177 return (0);
180 const char *
181 ssh_gai_strerror(int gaierr)
183 if (gaierr == EAI_SYSTEM && errno != 0)
184 return strerror(errno);
185 return gai_strerror(gaierr);
188 /* disable nagle on socket */
189 void
190 set_nodelay(int fd)
192 int opt;
193 socklen_t optlen;
195 optlen = sizeof opt;
196 if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
197 debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
198 return;
200 if (opt == 1) {
201 debug2("fd %d is TCP_NODELAY", fd);
202 return;
204 opt = 1;
205 debug2("fd %d setting TCP_NODELAY", fd);
206 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
207 error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
210 /* Allow local port reuse in TIME_WAIT */
212 set_reuseaddr(int fd)
214 int on = 1;
216 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
217 error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
218 return -1;
220 return 0;
223 /* Get/set routing domain */
224 char *
225 get_rdomain(int fd)
227 #if defined(HAVE_SYS_GET_RDOMAIN)
228 return sys_get_rdomain(fd);
229 #elif defined(__OpenBSD__)
230 int rtable;
231 char *ret;
232 socklen_t len = sizeof(rtable);
234 if (getsockopt(fd, SOL_SOCKET, SO_RTABLE, &rtable, &len) == -1) {
235 error("Failed to get routing domain for fd %d: %s",
236 fd, strerror(errno));
237 return NULL;
239 xasprintf(&ret, "%d", rtable);
240 return ret;
241 #else /* defined(__OpenBSD__) */
242 return NULL;
243 #endif
247 set_rdomain(int fd, const char *name)
249 #if defined(HAVE_SYS_SET_RDOMAIN)
250 return sys_set_rdomain(fd, name);
251 #elif defined(__OpenBSD__)
252 int rtable;
253 const char *errstr;
255 if (name == NULL)
256 return 0; /* default table */
258 rtable = (int)strtonum(name, 0, 255, &errstr);
259 if (errstr != NULL) {
260 /* Shouldn't happen */
261 error("Invalid routing domain \"%s\": %s", name, errstr);
262 return -1;
264 if (setsockopt(fd, SOL_SOCKET, SO_RTABLE,
265 &rtable, sizeof(rtable)) == -1) {
266 error("Failed to set routing domain %d on fd %d: %s",
267 rtable, fd, strerror(errno));
268 return -1;
270 return 0;
271 #else /* defined(__OpenBSD__) */
272 error("Setting routing domain is not supported on this platform");
273 return -1;
274 #endif
278 get_sock_af(int fd)
280 struct sockaddr_storage to;
281 socklen_t tolen = sizeof(to);
283 memset(&to, 0, sizeof(to));
284 if (getsockname(fd, (struct sockaddr *)&to, &tolen) == -1)
285 return -1;
286 #ifdef IPV4_IN_IPV6
287 if (to.ss_family == AF_INET6 &&
288 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
289 return AF_INET;
290 #endif
291 return to.ss_family;
294 void
295 set_sock_tos(int fd, int tos)
297 #ifndef IP_TOS_IS_BROKEN
298 int af;
300 switch ((af = get_sock_af(fd))) {
301 case -1:
302 /* assume not a socket */
303 break;
304 case AF_INET:
305 # ifdef IP_TOS
306 debug3_f("set socket %d IP_TOS 0x%02x", fd, tos);
307 if (setsockopt(fd, IPPROTO_IP, IP_TOS,
308 &tos, sizeof(tos)) == -1) {
309 error("setsockopt socket %d IP_TOS %d: %s",
310 fd, tos, strerror(errno));
312 # endif /* IP_TOS */
313 break;
314 case AF_INET6:
315 # ifdef IPV6_TCLASS
316 debug3_f("set socket %d IPV6_TCLASS 0x%02x", fd, tos);
317 if (setsockopt(fd, IPPROTO_IPV6, IPV6_TCLASS,
318 &tos, sizeof(tos)) == -1) {
319 error("setsockopt socket %d IPV6_TCLASS %d: %s",
320 fd, tos, strerror(errno));
322 # endif /* IPV6_TCLASS */
323 break;
324 default:
325 debug2_f("unsupported socket family %d", af);
326 break;
328 #endif /* IP_TOS_IS_BROKEN */
332 * Wait up to *timeoutp milliseconds for events on fd. Updates
333 * *timeoutp with time remaining.
334 * Returns 0 if fd ready or -1 on timeout or error (see errno).
336 static int
337 waitfd(int fd, int *timeoutp, short events, volatile sig_atomic_t *stop)
339 struct pollfd pfd;
340 struct timespec timeout;
341 int oerrno, r;
342 sigset_t nsigset, osigset;
344 if (timeoutp && *timeoutp == -1)
345 timeoutp = NULL;
346 pfd.fd = fd;
347 pfd.events = events;
348 ptimeout_init(&timeout);
349 if (timeoutp != NULL)
350 ptimeout_deadline_ms(&timeout, *timeoutp);
351 if (stop != NULL)
352 sigfillset(&nsigset);
353 for (; timeoutp == NULL || *timeoutp >= 0;) {
354 if (stop != NULL) {
355 sigprocmask(SIG_BLOCK, &nsigset, &osigset);
356 if (*stop) {
357 sigprocmask(SIG_SETMASK, &osigset, NULL);
358 errno = EINTR;
359 return -1;
362 r = ppoll(&pfd, 1, ptimeout_get_tsp(&timeout),
363 stop != NULL ? &osigset : NULL);
364 oerrno = errno;
365 if (stop != NULL)
366 sigprocmask(SIG_SETMASK, &osigset, NULL);
367 if (timeoutp)
368 *timeoutp = ptimeout_get_ms(&timeout);
369 errno = oerrno;
370 if (r > 0)
371 return 0;
372 else if (r == -1 && errno != EAGAIN && errno != EINTR)
373 return -1;
374 else if (r == 0)
375 break;
377 /* timeout */
378 errno = ETIMEDOUT;
379 return -1;
383 * Wait up to *timeoutp milliseconds for fd to be readable. Updates
384 * *timeoutp with time remaining.
385 * Returns 0 if fd ready or -1 on timeout or error (see errno).
388 waitrfd(int fd, int *timeoutp, volatile sig_atomic_t *stop) {
389 return waitfd(fd, timeoutp, POLLIN, stop);
393 * Attempt a non-blocking connect(2) to the specified address, waiting up to
394 * *timeoutp milliseconds for the connection to complete. If the timeout is
395 * <=0, then wait indefinitely.
397 * Returns 0 on success or -1 on failure.
400 timeout_connect(int sockfd, const struct sockaddr *serv_addr,
401 socklen_t addrlen, int *timeoutp)
403 int optval = 0;
404 socklen_t optlen = sizeof(optval);
406 /* No timeout: just do a blocking connect() */
407 if (timeoutp == NULL || *timeoutp <= 0)
408 return connect(sockfd, serv_addr, addrlen);
410 set_nonblock(sockfd);
411 for (;;) {
412 if (connect(sockfd, serv_addr, addrlen) == 0) {
413 /* Succeeded already? */
414 unset_nonblock(sockfd);
415 return 0;
416 } else if (errno == EINTR)
417 continue;
418 else if (errno != EINPROGRESS)
419 return -1;
420 break;
423 if (waitfd(sockfd, timeoutp, POLLIN | POLLOUT, NULL) == -1)
424 return -1;
426 /* Completed or failed */
427 if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval, &optlen) == -1) {
428 debug("getsockopt: %s", strerror(errno));
429 return -1;
431 if (optval != 0) {
432 errno = optval;
433 return -1;
435 unset_nonblock(sockfd);
436 return 0;
439 /* Characters considered whitespace in strsep calls. */
440 #define WHITESPACE " \t\r\n"
441 #define QUOTE "\""
443 /* return next token in configuration line */
444 static char *
445 strdelim_internal(char **s, int split_equals)
447 char *old;
448 int wspace = 0;
450 if (*s == NULL)
451 return NULL;
453 old = *s;
455 *s = strpbrk(*s,
456 split_equals ? WHITESPACE QUOTE "=" : WHITESPACE QUOTE);
457 if (*s == NULL)
458 return (old);
460 if (*s[0] == '\"') {
461 memmove(*s, *s + 1, strlen(*s)); /* move nul too */
462 /* Find matching quote */
463 if ((*s = strpbrk(*s, QUOTE)) == NULL) {
464 return (NULL); /* no matching quote */
465 } else {
466 *s[0] = '\0';
467 *s += strspn(*s + 1, WHITESPACE) + 1;
468 return (old);
472 /* Allow only one '=' to be skipped */
473 if (split_equals && *s[0] == '=')
474 wspace = 1;
475 *s[0] = '\0';
477 /* Skip any extra whitespace after first token */
478 *s += strspn(*s + 1, WHITESPACE) + 1;
479 if (split_equals && *s[0] == '=' && !wspace)
480 *s += strspn(*s + 1, WHITESPACE) + 1;
482 return (old);
486 * Return next token in configuration line; splts on whitespace or a
487 * single '=' character.
489 char *
490 strdelim(char **s)
492 return strdelim_internal(s, 1);
496 * Return next token in configuration line; splts on whitespace only.
498 char *
499 strdelimw(char **s)
501 return strdelim_internal(s, 0);
504 struct passwd *
505 pwcopy(struct passwd *pw)
507 struct passwd *copy = xcalloc(1, sizeof(*copy));
509 copy->pw_name = xstrdup(pw->pw_name);
510 copy->pw_passwd = xstrdup(pw->pw_passwd == NULL ? "*" : pw->pw_passwd);
511 #ifdef HAVE_STRUCT_PASSWD_PW_GECOS
512 copy->pw_gecos = xstrdup(pw->pw_gecos);
513 #endif
514 copy->pw_uid = pw->pw_uid;
515 copy->pw_gid = pw->pw_gid;
516 #ifdef HAVE_STRUCT_PASSWD_PW_EXPIRE
517 copy->pw_expire = pw->pw_expire;
518 #endif
519 #ifdef HAVE_STRUCT_PASSWD_PW_CHANGE
520 copy->pw_change = pw->pw_change;
521 #endif
522 #ifdef HAVE_STRUCT_PASSWD_PW_CLASS
523 copy->pw_class = xstrdup(pw->pw_class);
524 #endif
525 copy->pw_dir = xstrdup(pw->pw_dir);
526 copy->pw_shell = xstrdup(pw->pw_shell);
527 return copy;
531 * Convert ASCII string to TCP/IP port number.
532 * Port must be >=0 and <=65535.
533 * Return -1 if invalid.
536 a2port(const char *s)
538 struct servent *se;
539 long long port;
540 const char *errstr;
542 port = strtonum(s, 0, 65535, &errstr);
543 if (errstr == NULL)
544 return (int)port;
545 if ((se = getservbyname(s, "tcp")) != NULL)
546 return ntohs(se->s_port);
547 return -1;
551 a2tun(const char *s, int *remote)
553 const char *errstr = NULL;
554 char *sp, *ep;
555 int tun;
557 if (remote != NULL) {
558 *remote = SSH_TUNID_ANY;
559 sp = xstrdup(s);
560 if ((ep = strchr(sp, ':')) == NULL) {
561 free(sp);
562 return (a2tun(s, NULL));
564 ep[0] = '\0'; ep++;
565 *remote = a2tun(ep, NULL);
566 tun = a2tun(sp, NULL);
567 free(sp);
568 return (*remote == SSH_TUNID_ERR ? *remote : tun);
571 if (strcasecmp(s, "any") == 0)
572 return (SSH_TUNID_ANY);
574 tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
575 if (errstr != NULL)
576 return (SSH_TUNID_ERR);
578 return (tun);
581 #define SECONDS 1
582 #define MINUTES (SECONDS * 60)
583 #define HOURS (MINUTES * 60)
584 #define DAYS (HOURS * 24)
585 #define WEEKS (DAYS * 7)
587 static char *
588 scandigits(char *s)
590 while (isdigit((unsigned char)*s))
591 s++;
592 return s;
596 * Convert a time string into seconds; format is
597 * a sequence of:
598 * time[qualifier]
600 * Valid time qualifiers are:
601 * <none> seconds
602 * s|S seconds
603 * m|M minutes
604 * h|H hours
605 * d|D days
606 * w|W weeks
608 * Examples:
609 * 90m 90 minutes
610 * 1h30m 90 minutes
611 * 2d 2 days
612 * 1w 1 week
614 * Return -1 if time string is invalid.
617 convtime(const char *s)
619 int secs, total = 0, multiplier;
620 char *p, *os, *np, c = 0;
621 const char *errstr;
623 if (s == NULL || *s == '\0')
624 return -1;
625 p = os = strdup(s); /* deal with const */
626 if (os == NULL)
627 return -1;
629 while (*p) {
630 np = scandigits(p);
631 if (np) {
632 c = *np;
633 *np = '\0';
635 secs = (int)strtonum(p, 0, INT_MAX, &errstr);
636 if (errstr)
637 goto fail;
638 *np = c;
640 multiplier = 1;
641 switch (c) {
642 case '\0':
643 np--; /* back up */
644 break;
645 case 's':
646 case 'S':
647 break;
648 case 'm':
649 case 'M':
650 multiplier = MINUTES;
651 break;
652 case 'h':
653 case 'H':
654 multiplier = HOURS;
655 break;
656 case 'd':
657 case 'D':
658 multiplier = DAYS;
659 break;
660 case 'w':
661 case 'W':
662 multiplier = WEEKS;
663 break;
664 default:
665 goto fail;
667 if (secs > INT_MAX / multiplier)
668 goto fail;
669 secs *= multiplier;
670 if (total > INT_MAX - secs)
671 goto fail;
672 total += secs;
673 if (total < 0)
674 goto fail;
675 p = ++np;
677 free(os);
678 return total;
679 fail:
680 free(os);
681 return -1;
684 #define TF_BUFS 8
685 #define TF_LEN 9
687 const char *
688 fmt_timeframe(time_t t)
690 char *buf;
691 static char tfbuf[TF_BUFS][TF_LEN]; /* ring buffer */
692 static int idx = 0;
693 unsigned int sec, min, hrs, day;
694 unsigned long long week;
696 buf = tfbuf[idx++];
697 if (idx == TF_BUFS)
698 idx = 0;
700 week = t;
702 sec = week % 60;
703 week /= 60;
704 min = week % 60;
705 week /= 60;
706 hrs = week % 24;
707 week /= 24;
708 day = week % 7;
709 week /= 7;
711 if (week > 0)
712 snprintf(buf, TF_LEN, "%02lluw%01ud%02uh", week, day, hrs);
713 else if (day > 0)
714 snprintf(buf, TF_LEN, "%01ud%02uh%02um", day, hrs, min);
715 else
716 snprintf(buf, TF_LEN, "%02u:%02u:%02u", hrs, min, sec);
718 return (buf);
722 * Returns a standardized host+port identifier string.
723 * Caller must free returned string.
725 char *
726 put_host_port(const char *host, u_short port)
728 char *hoststr;
730 if (port == 0 || port == SSH_DEFAULT_PORT)
731 return(xstrdup(host));
732 if (asprintf(&hoststr, "[%s]:%d", host, (int)port) == -1)
733 fatal("put_host_port: asprintf: %s", strerror(errno));
734 debug3("put_host_port: %s", hoststr);
735 return hoststr;
739 * Search for next delimiter between hostnames/addresses and ports.
740 * Argument may be modified (for termination).
741 * Returns *cp if parsing succeeds.
742 * *cp is set to the start of the next field, if one was found.
743 * The delimiter char, if present, is stored in delim.
744 * If this is the last field, *cp is set to NULL.
746 char *
747 hpdelim2(char **cp, char *delim)
749 char *s, *old;
751 if (cp == NULL || *cp == NULL)
752 return NULL;
754 old = s = *cp;
755 if (*s == '[') {
756 if ((s = strchr(s, ']')) == NULL)
757 return NULL;
758 else
759 s++;
760 } else if ((s = strpbrk(s, ":/")) == NULL)
761 s = *cp + strlen(*cp); /* skip to end (see first case below) */
763 switch (*s) {
764 case '\0':
765 *cp = NULL; /* no more fields*/
766 break;
768 case ':':
769 case '/':
770 if (delim != NULL)
771 *delim = *s;
772 *s = '\0'; /* terminate */
773 *cp = s + 1;
774 break;
776 default:
777 return NULL;
780 return old;
783 /* The common case: only accept colon as delimiter. */
784 char *
785 hpdelim(char **cp)
787 char *r, delim = '\0';
789 r = hpdelim2(cp, &delim);
790 if (delim == '/')
791 return NULL;
792 return r;
795 char *
796 cleanhostname(char *host)
798 if (*host == '[' && host[strlen(host) - 1] == ']') {
799 host[strlen(host) - 1] = '\0';
800 return (host + 1);
801 } else
802 return host;
805 char *
806 colon(char *cp)
808 int flag = 0;
810 if (*cp == ':') /* Leading colon is part of file name. */
811 return NULL;
812 if (*cp == '[')
813 flag = 1;
815 for (; *cp; ++cp) {
816 if (*cp == '@' && *(cp+1) == '[')
817 flag = 1;
818 if (*cp == ']' && *(cp+1) == ':' && flag)
819 return (cp+1);
820 if (*cp == ':' && !flag)
821 return (cp);
822 if (*cp == '/')
823 return NULL;
825 return NULL;
829 * Parse a [user@]host:[path] string.
830 * Caller must free returned user, host and path.
831 * Any of the pointer return arguments may be NULL (useful for syntax checking).
832 * If user was not specified then *userp will be set to NULL.
833 * If host was not specified then *hostp will be set to NULL.
834 * If path was not specified then *pathp will be set to ".".
835 * Returns 0 on success, -1 on failure.
838 parse_user_host_path(const char *s, char **userp, char **hostp, char **pathp)
840 char *user = NULL, *host = NULL, *path = NULL;
841 char *sdup, *tmp;
842 int ret = -1;
844 if (userp != NULL)
845 *userp = NULL;
846 if (hostp != NULL)
847 *hostp = NULL;
848 if (pathp != NULL)
849 *pathp = NULL;
851 sdup = xstrdup(s);
853 /* Check for remote syntax: [user@]host:[path] */
854 if ((tmp = colon(sdup)) == NULL)
855 goto out;
857 /* Extract optional path */
858 *tmp++ = '\0';
859 if (*tmp == '\0')
860 tmp = ".";
861 path = xstrdup(tmp);
863 /* Extract optional user and mandatory host */
864 tmp = strrchr(sdup, '@');
865 if (tmp != NULL) {
866 *tmp++ = '\0';
867 host = xstrdup(cleanhostname(tmp));
868 if (*sdup != '\0')
869 user = xstrdup(sdup);
870 } else {
871 host = xstrdup(cleanhostname(sdup));
872 user = NULL;
875 /* Success */
876 if (userp != NULL) {
877 *userp = user;
878 user = NULL;
880 if (hostp != NULL) {
881 *hostp = host;
882 host = NULL;
884 if (pathp != NULL) {
885 *pathp = path;
886 path = NULL;
888 ret = 0;
889 out:
890 free(sdup);
891 free(user);
892 free(host);
893 free(path);
894 return ret;
898 * Parse a [user@]host[:port] string.
899 * Caller must free returned user and host.
900 * Any of the pointer return arguments may be NULL (useful for syntax checking).
901 * If user was not specified then *userp will be set to NULL.
902 * If port was not specified then *portp will be -1.
903 * Returns 0 on success, -1 on failure.
906 parse_user_host_port(const char *s, char **userp, char **hostp, int *portp)
908 char *sdup, *cp, *tmp;
909 char *user = NULL, *host = NULL;
910 int port = -1, ret = -1;
912 if (userp != NULL)
913 *userp = NULL;
914 if (hostp != NULL)
915 *hostp = NULL;
916 if (portp != NULL)
917 *portp = -1;
919 if ((sdup = tmp = strdup(s)) == NULL)
920 return -1;
921 /* Extract optional username */
922 if ((cp = strrchr(tmp, '@')) != NULL) {
923 *cp = '\0';
924 if (*tmp == '\0')
925 goto out;
926 if ((user = strdup(tmp)) == NULL)
927 goto out;
928 tmp = cp + 1;
930 /* Extract mandatory hostname */
931 if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0')
932 goto out;
933 host = xstrdup(cleanhostname(cp));
934 /* Convert and verify optional port */
935 if (tmp != NULL && *tmp != '\0') {
936 if ((port = a2port(tmp)) <= 0)
937 goto out;
939 /* Success */
940 if (userp != NULL) {
941 *userp = user;
942 user = NULL;
944 if (hostp != NULL) {
945 *hostp = host;
946 host = NULL;
948 if (portp != NULL)
949 *portp = port;
950 ret = 0;
951 out:
952 free(sdup);
953 free(user);
954 free(host);
955 return ret;
959 * Converts a two-byte hex string to decimal.
960 * Returns the decimal value or -1 for invalid input.
962 static int
963 hexchar(const char *s)
965 unsigned char result[2];
966 int i;
968 for (i = 0; i < 2; i++) {
969 if (s[i] >= '0' && s[i] <= '9')
970 result[i] = (unsigned char)(s[i] - '0');
971 else if (s[i] >= 'a' && s[i] <= 'f')
972 result[i] = (unsigned char)(s[i] - 'a') + 10;
973 else if (s[i] >= 'A' && s[i] <= 'F')
974 result[i] = (unsigned char)(s[i] - 'A') + 10;
975 else
976 return -1;
978 return (result[0] << 4) | result[1];
982 * Decode an url-encoded string.
983 * Returns a newly allocated string on success or NULL on failure.
985 static char *
986 urldecode(const char *src)
988 char *ret, *dst;
989 int ch;
990 size_t srclen;
992 if ((srclen = strlen(src)) >= SIZE_MAX)
993 fatal_f("input too large");
994 ret = xmalloc(srclen + 1);
995 for (dst = ret; *src != '\0'; src++) {
996 switch (*src) {
997 case '+':
998 *dst++ = ' ';
999 break;
1000 case '%':
1001 if (!isxdigit((unsigned char)src[1]) ||
1002 !isxdigit((unsigned char)src[2]) ||
1003 (ch = hexchar(src + 1)) == -1) {
1004 free(ret);
1005 return NULL;
1007 *dst++ = ch;
1008 src += 2;
1009 break;
1010 default:
1011 *dst++ = *src;
1012 break;
1015 *dst = '\0';
1017 return ret;
1021 * Parse an (scp|ssh|sftp)://[user@]host[:port][/path] URI.
1022 * See https://tools.ietf.org/html/draft-ietf-secsh-scp-sftp-ssh-uri-04
1023 * Either user or path may be url-encoded (but not host or port).
1024 * Caller must free returned user, host and path.
1025 * Any of the pointer return arguments may be NULL (useful for syntax checking)
1026 * but the scheme must always be specified.
1027 * If user was not specified then *userp will be set to NULL.
1028 * If port was not specified then *portp will be -1.
1029 * If path was not specified then *pathp will be set to NULL.
1030 * Returns 0 on success, 1 if non-uri/wrong scheme, -1 on error/invalid uri.
1033 parse_uri(const char *scheme, const char *uri, char **userp, char **hostp,
1034 int *portp, char **pathp)
1036 char *uridup, *cp, *tmp, ch;
1037 char *user = NULL, *host = NULL, *path = NULL;
1038 int port = -1, ret = -1;
1039 size_t len;
1041 len = strlen(scheme);
1042 if (strncmp(uri, scheme, len) != 0 || strncmp(uri + len, "://", 3) != 0)
1043 return 1;
1044 uri += len + 3;
1046 if (userp != NULL)
1047 *userp = NULL;
1048 if (hostp != NULL)
1049 *hostp = NULL;
1050 if (portp != NULL)
1051 *portp = -1;
1052 if (pathp != NULL)
1053 *pathp = NULL;
1055 uridup = tmp = xstrdup(uri);
1057 /* Extract optional ssh-info (username + connection params) */
1058 if ((cp = strchr(tmp, '@')) != NULL) {
1059 char *delim;
1061 *cp = '\0';
1062 /* Extract username and connection params */
1063 if ((delim = strchr(tmp, ';')) != NULL) {
1064 /* Just ignore connection params for now */
1065 *delim = '\0';
1067 if (*tmp == '\0') {
1068 /* Empty username */
1069 goto out;
1071 if ((user = urldecode(tmp)) == NULL)
1072 goto out;
1073 tmp = cp + 1;
1076 /* Extract mandatory hostname */
1077 if ((cp = hpdelim2(&tmp, &ch)) == NULL || *cp == '\0')
1078 goto out;
1079 host = xstrdup(cleanhostname(cp));
1080 if (!valid_domain(host, 0, NULL))
1081 goto out;
1083 if (tmp != NULL && *tmp != '\0') {
1084 if (ch == ':') {
1085 /* Convert and verify port. */
1086 if ((cp = strchr(tmp, '/')) != NULL)
1087 *cp = '\0';
1088 if ((port = a2port(tmp)) <= 0)
1089 goto out;
1090 tmp = cp ? cp + 1 : NULL;
1092 if (tmp != NULL && *tmp != '\0') {
1093 /* Extract optional path */
1094 if ((path = urldecode(tmp)) == NULL)
1095 goto out;
1099 /* Success */
1100 if (userp != NULL) {
1101 *userp = user;
1102 user = NULL;
1104 if (hostp != NULL) {
1105 *hostp = host;
1106 host = NULL;
1108 if (portp != NULL)
1109 *portp = port;
1110 if (pathp != NULL) {
1111 *pathp = path;
1112 path = NULL;
1114 ret = 0;
1115 out:
1116 free(uridup);
1117 free(user);
1118 free(host);
1119 free(path);
1120 return ret;
1123 /* function to assist building execv() arguments */
1124 void
1125 addargs(arglist *args, char *fmt, ...)
1127 va_list ap;
1128 char *cp;
1129 u_int nalloc;
1130 int r;
1132 va_start(ap, fmt);
1133 r = vasprintf(&cp, fmt, ap);
1134 va_end(ap);
1135 if (r == -1)
1136 fatal_f("argument too long");
1138 nalloc = args->nalloc;
1139 if (args->list == NULL) {
1140 nalloc = 32;
1141 args->num = 0;
1142 } else if (args->num > (256 * 1024))
1143 fatal_f("too many arguments");
1144 else if (args->num >= args->nalloc)
1145 fatal_f("arglist corrupt");
1146 else if (args->num+2 >= nalloc)
1147 nalloc *= 2;
1149 args->list = xrecallocarray(args->list, args->nalloc,
1150 nalloc, sizeof(char *));
1151 args->nalloc = nalloc;
1152 args->list[args->num++] = cp;
1153 args->list[args->num] = NULL;
1156 void
1157 replacearg(arglist *args, u_int which, char *fmt, ...)
1159 va_list ap;
1160 char *cp;
1161 int r;
1163 va_start(ap, fmt);
1164 r = vasprintf(&cp, fmt, ap);
1165 va_end(ap);
1166 if (r == -1)
1167 fatal_f("argument too long");
1168 if (args->list == NULL || args->num >= args->nalloc)
1169 fatal_f("arglist corrupt");
1171 if (which >= args->num)
1172 fatal_f("tried to replace invalid arg %d >= %d",
1173 which, args->num);
1174 free(args->list[which]);
1175 args->list[which] = cp;
1178 void
1179 freeargs(arglist *args)
1181 u_int i;
1183 if (args == NULL)
1184 return;
1185 if (args->list != NULL && args->num < args->nalloc) {
1186 for (i = 0; i < args->num; i++)
1187 free(args->list[i]);
1188 free(args->list);
1190 args->nalloc = args->num = 0;
1191 args->list = NULL;
1195 * Expands tildes in the file name. Returns data allocated by xmalloc.
1196 * Warning: this calls getpw*.
1199 tilde_expand(const char *filename, uid_t uid, char **retp)
1201 char *ocopy = NULL, *copy, *s = NULL;
1202 const char *path = NULL, *user = NULL;
1203 struct passwd *pw;
1204 size_t len;
1205 int ret = -1, r, slash;
1207 *retp = NULL;
1208 if (*filename != '~') {
1209 *retp = xstrdup(filename);
1210 return 0;
1212 ocopy = copy = xstrdup(filename + 1);
1214 if (*copy == '\0') /* ~ */
1215 path = NULL;
1216 else if (*copy == '/') {
1217 copy += strspn(copy, "/");
1218 if (*copy == '\0')
1219 path = NULL; /* ~/ */
1220 else
1221 path = copy; /* ~/path */
1222 } else {
1223 user = copy;
1224 if ((path = strchr(copy, '/')) != NULL) {
1225 copy[path - copy] = '\0';
1226 path++;
1227 path += strspn(path, "/");
1228 if (*path == '\0') /* ~user/ */
1229 path = NULL;
1230 /* else ~user/path */
1232 /* else ~user */
1234 if (user != NULL) {
1235 if ((pw = getpwnam(user)) == NULL) {
1236 error_f("No such user %s", user);
1237 goto out;
1239 } else if ((pw = getpwuid(uid)) == NULL) {
1240 error_f("No such uid %ld", (long)uid);
1241 goto out;
1244 /* Make sure directory has a trailing '/' */
1245 slash = (len = strlen(pw->pw_dir)) == 0 || pw->pw_dir[len - 1] != '/';
1247 if ((r = xasprintf(&s, "%s%s%s", pw->pw_dir,
1248 slash ? "/" : "", path != NULL ? path : "")) <= 0) {
1249 error_f("xasprintf failed");
1250 goto out;
1252 if (r >= PATH_MAX) {
1253 error_f("Path too long");
1254 goto out;
1256 /* success */
1257 ret = 0;
1258 *retp = s;
1259 s = NULL;
1260 out:
1261 free(s);
1262 free(ocopy);
1263 return ret;
1266 char *
1267 tilde_expand_filename(const char *filename, uid_t uid)
1269 char *ret;
1271 if (tilde_expand(filename, uid, &ret) != 0)
1272 cleanup_exit(255);
1273 return ret;
1277 * Expand a string with a set of %[char] escapes and/or ${ENVIRONMENT}
1278 * substitutions. A number of escapes may be specified as
1279 * (char *escape_chars, char *replacement) pairs. The list must be terminated
1280 * by a NULL escape_char. Returns replaced string in memory allocated by
1281 * xmalloc which the caller must free.
1283 static char *
1284 vdollar_percent_expand(int *parseerror, int dollar, int percent,
1285 const char *string, va_list ap)
1287 #define EXPAND_MAX_KEYS 64
1288 u_int num_keys = 0, i;
1289 struct {
1290 const char *key;
1291 const char *repl;
1292 } keys[EXPAND_MAX_KEYS];
1293 struct sshbuf *buf;
1294 int r, missingvar = 0;
1295 char *ret = NULL, *var, *varend, *val;
1296 size_t len;
1298 if ((buf = sshbuf_new()) == NULL)
1299 fatal_f("sshbuf_new failed");
1300 if (parseerror == NULL)
1301 fatal_f("null parseerror arg");
1302 *parseerror = 1;
1304 /* Gather keys if we're doing percent expansion. */
1305 if (percent) {
1306 for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
1307 keys[num_keys].key = va_arg(ap, char *);
1308 if (keys[num_keys].key == NULL)
1309 break;
1310 keys[num_keys].repl = va_arg(ap, char *);
1311 if (keys[num_keys].repl == NULL) {
1312 fatal_f("NULL replacement for token %s",
1313 keys[num_keys].key);
1316 if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
1317 fatal_f("too many keys");
1318 if (num_keys == 0)
1319 fatal_f("percent expansion without token list");
1322 /* Expand string */
1323 for (i = 0; *string != '\0'; string++) {
1324 /* Optionally process ${ENVIRONMENT} expansions. */
1325 if (dollar && string[0] == '$' && string[1] == '{') {
1326 string += 2; /* skip over '${' */
1327 if ((varend = strchr(string, '}')) == NULL) {
1328 error_f("environment variable '%s' missing "
1329 "closing '}'", string);
1330 goto out;
1332 len = varend - string;
1333 if (len == 0) {
1334 error_f("zero-length environment variable");
1335 goto out;
1337 var = xmalloc(len + 1);
1338 (void)strlcpy(var, string, len + 1);
1339 if ((val = getenv(var)) == NULL) {
1340 error_f("env var ${%s} has no value", var);
1341 missingvar = 1;
1342 } else {
1343 debug3_f("expand ${%s} -> '%s'", var, val);
1344 if ((r = sshbuf_put(buf, val, strlen(val))) !=0)
1345 fatal_fr(r, "sshbuf_put ${}");
1347 free(var);
1348 string += len;
1349 continue;
1353 * Process percent expansions if we have a list of TOKENs.
1354 * If we're not doing percent expansion everything just gets
1355 * appended here.
1357 if (*string != '%' || !percent) {
1358 append:
1359 if ((r = sshbuf_put_u8(buf, *string)) != 0)
1360 fatal_fr(r, "sshbuf_put_u8 %%");
1361 continue;
1363 string++;
1364 /* %% case */
1365 if (*string == '%')
1366 goto append;
1367 if (*string == '\0') {
1368 error_f("invalid format");
1369 goto out;
1371 for (i = 0; i < num_keys; i++) {
1372 if (strchr(keys[i].key, *string) != NULL) {
1373 if ((r = sshbuf_put(buf, keys[i].repl,
1374 strlen(keys[i].repl))) != 0)
1375 fatal_fr(r, "sshbuf_put %%-repl");
1376 break;
1379 if (i >= num_keys) {
1380 error_f("unknown key %%%c", *string);
1381 goto out;
1384 if (!missingvar && (ret = sshbuf_dup_string(buf)) == NULL)
1385 fatal_f("sshbuf_dup_string failed");
1386 *parseerror = 0;
1387 out:
1388 sshbuf_free(buf);
1389 return *parseerror ? NULL : ret;
1390 #undef EXPAND_MAX_KEYS
1394 * Expand only environment variables.
1395 * Note that although this function is variadic like the other similar
1396 * functions, any such arguments will be unused.
1399 char *
1400 dollar_expand(int *parseerr, const char *string, ...)
1402 char *ret;
1403 int err;
1404 va_list ap;
1406 va_start(ap, string);
1407 ret = vdollar_percent_expand(&err, 1, 0, string, ap);
1408 va_end(ap);
1409 if (parseerr != NULL)
1410 *parseerr = err;
1411 return ret;
1415 * Returns expanded string or NULL if a specified environment variable is
1416 * not defined, or calls fatal if the string is invalid.
1418 char *
1419 percent_expand(const char *string, ...)
1421 char *ret;
1422 int err;
1423 va_list ap;
1425 va_start(ap, string);
1426 ret = vdollar_percent_expand(&err, 0, 1, string, ap);
1427 va_end(ap);
1428 if (err)
1429 fatal_f("failed");
1430 return ret;
1434 * Returns expanded string or NULL if a specified environment variable is
1435 * not defined, or calls fatal if the string is invalid.
1437 char *
1438 percent_dollar_expand(const char *string, ...)
1440 char *ret;
1441 int err;
1442 va_list ap;
1444 va_start(ap, string);
1445 ret = vdollar_percent_expand(&err, 1, 1, string, ap);
1446 va_end(ap);
1447 if (err)
1448 fatal_f("failed");
1449 return ret;
1453 tun_open(int tun, int mode, char **ifname)
1455 #if defined(CUSTOM_SYS_TUN_OPEN)
1456 return (sys_tun_open(tun, mode, ifname));
1457 #elif defined(SSH_TUN_OPENBSD)
1458 struct ifreq ifr;
1459 char name[100];
1460 int fd = -1, sock;
1461 const char *tunbase = "tun";
1463 if (ifname != NULL)
1464 *ifname = NULL;
1466 if (mode == SSH_TUNMODE_ETHERNET)
1467 tunbase = "tap";
1469 /* Open the tunnel device */
1470 if (tun <= SSH_TUNID_MAX) {
1471 snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
1472 fd = open(name, O_RDWR);
1473 } else if (tun == SSH_TUNID_ANY) {
1474 for (tun = 100; tun >= 0; tun--) {
1475 snprintf(name, sizeof(name), "/dev/%s%d",
1476 tunbase, tun);
1477 if ((fd = open(name, O_RDWR)) >= 0)
1478 break;
1480 } else {
1481 debug_f("invalid tunnel %u", tun);
1482 return -1;
1485 if (fd == -1) {
1486 debug_f("%s open: %s", name, strerror(errno));
1487 return -1;
1490 debug_f("%s mode %d fd %d", name, mode, fd);
1492 /* Bring interface up if it is not already */
1493 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
1494 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
1495 goto failed;
1497 if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
1498 debug_f("get interface %s flags: %s", ifr.ifr_name,
1499 strerror(errno));
1500 goto failed;
1503 if (!(ifr.ifr_flags & IFF_UP)) {
1504 ifr.ifr_flags |= IFF_UP;
1505 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
1506 debug_f("activate interface %s: %s", ifr.ifr_name,
1507 strerror(errno));
1508 goto failed;
1512 if (ifname != NULL)
1513 *ifname = xstrdup(ifr.ifr_name);
1515 close(sock);
1516 return fd;
1518 failed:
1519 if (fd >= 0)
1520 close(fd);
1521 if (sock >= 0)
1522 close(sock);
1523 return -1;
1524 #else
1525 error("Tunnel interfaces are not supported on this platform");
1526 return (-1);
1527 #endif
1530 void
1531 sanitise_stdfd(void)
1533 int nullfd, dupfd;
1535 if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1536 fprintf(stderr, "Couldn't open /dev/null: %s\n",
1537 strerror(errno));
1538 exit(1);
1540 while (++dupfd <= STDERR_FILENO) {
1541 /* Only populate closed fds. */
1542 if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
1543 if (dup2(nullfd, dupfd) == -1) {
1544 fprintf(stderr, "dup2: %s\n", strerror(errno));
1545 exit(1);
1549 if (nullfd > STDERR_FILENO)
1550 close(nullfd);
1553 char *
1554 tohex(const void *vp, size_t l)
1556 const u_char *p = (const u_char *)vp;
1557 char b[3], *r;
1558 size_t i, hl;
1560 if (l > 65536)
1561 return xstrdup("tohex: length > 65536");
1563 hl = l * 2 + 1;
1564 r = xcalloc(1, hl);
1565 for (i = 0; i < l; i++) {
1566 snprintf(b, sizeof(b), "%02x", p[i]);
1567 strlcat(r, b, hl);
1569 return (r);
1573 * Extend string *sp by the specified format. If *sp is not NULL (or empty),
1574 * then the separator 'sep' will be prepended before the formatted arguments.
1575 * Extended strings are heap allocated.
1577 void
1578 xextendf(char **sp, const char *sep, const char *fmt, ...)
1580 va_list ap;
1581 char *tmp1, *tmp2;
1583 va_start(ap, fmt);
1584 xvasprintf(&tmp1, fmt, ap);
1585 va_end(ap);
1587 if (*sp == NULL || **sp == '\0') {
1588 free(*sp);
1589 *sp = tmp1;
1590 return;
1592 xasprintf(&tmp2, "%s%s%s", *sp, sep == NULL ? "" : sep, tmp1);
1593 free(tmp1);
1594 free(*sp);
1595 *sp = tmp2;
1599 u_int64_t
1600 get_u64(const void *vp)
1602 const u_char *p = (const u_char *)vp;
1603 u_int64_t v;
1605 v = (u_int64_t)p[0] << 56;
1606 v |= (u_int64_t)p[1] << 48;
1607 v |= (u_int64_t)p[2] << 40;
1608 v |= (u_int64_t)p[3] << 32;
1609 v |= (u_int64_t)p[4] << 24;
1610 v |= (u_int64_t)p[5] << 16;
1611 v |= (u_int64_t)p[6] << 8;
1612 v |= (u_int64_t)p[7];
1614 return (v);
1617 u_int32_t
1618 get_u32(const void *vp)
1620 const u_char *p = (const u_char *)vp;
1621 u_int32_t v;
1623 v = (u_int32_t)p[0] << 24;
1624 v |= (u_int32_t)p[1] << 16;
1625 v |= (u_int32_t)p[2] << 8;
1626 v |= (u_int32_t)p[3];
1628 return (v);
1631 u_int32_t
1632 get_u32_le(const void *vp)
1634 const u_char *p = (const u_char *)vp;
1635 u_int32_t v;
1637 v = (u_int32_t)p[0];
1638 v |= (u_int32_t)p[1] << 8;
1639 v |= (u_int32_t)p[2] << 16;
1640 v |= (u_int32_t)p[3] << 24;
1642 return (v);
1645 u_int16_t
1646 get_u16(const void *vp)
1648 const u_char *p = (const u_char *)vp;
1649 u_int16_t v;
1651 v = (u_int16_t)p[0] << 8;
1652 v |= (u_int16_t)p[1];
1654 return (v);
1657 void
1658 put_u64(void *vp, u_int64_t v)
1660 u_char *p = (u_char *)vp;
1662 p[0] = (u_char)(v >> 56) & 0xff;
1663 p[1] = (u_char)(v >> 48) & 0xff;
1664 p[2] = (u_char)(v >> 40) & 0xff;
1665 p[3] = (u_char)(v >> 32) & 0xff;
1666 p[4] = (u_char)(v >> 24) & 0xff;
1667 p[5] = (u_char)(v >> 16) & 0xff;
1668 p[6] = (u_char)(v >> 8) & 0xff;
1669 p[7] = (u_char)v & 0xff;
1672 void
1673 put_u32(void *vp, u_int32_t v)
1675 u_char *p = (u_char *)vp;
1677 p[0] = (u_char)(v >> 24) & 0xff;
1678 p[1] = (u_char)(v >> 16) & 0xff;
1679 p[2] = (u_char)(v >> 8) & 0xff;
1680 p[3] = (u_char)v & 0xff;
1683 void
1684 put_u32_le(void *vp, u_int32_t v)
1686 u_char *p = (u_char *)vp;
1688 p[0] = (u_char)v & 0xff;
1689 p[1] = (u_char)(v >> 8) & 0xff;
1690 p[2] = (u_char)(v >> 16) & 0xff;
1691 p[3] = (u_char)(v >> 24) & 0xff;
1694 void
1695 put_u16(void *vp, u_int16_t v)
1697 u_char *p = (u_char *)vp;
1699 p[0] = (u_char)(v >> 8) & 0xff;
1700 p[1] = (u_char)v & 0xff;
1703 void
1704 ms_subtract_diff(struct timeval *start, int *ms)
1706 struct timeval diff, finish;
1708 monotime_tv(&finish);
1709 timersub(&finish, start, &diff);
1710 *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
1713 void
1714 ms_to_timespec(struct timespec *ts, int ms)
1716 if (ms < 0)
1717 ms = 0;
1718 ts->tv_sec = ms / 1000;
1719 ts->tv_nsec = (ms % 1000) * 1000 * 1000;
1722 void
1723 monotime_ts(struct timespec *ts)
1725 struct timeval tv;
1726 #if defined(HAVE_CLOCK_GETTIME) && (defined(CLOCK_BOOTTIME) || \
1727 defined(CLOCK_MONOTONIC) || defined(CLOCK_REALTIME))
1728 static int gettime_failed = 0;
1730 if (!gettime_failed) {
1731 # ifdef CLOCK_BOOTTIME
1732 if (clock_gettime(CLOCK_BOOTTIME, ts) == 0)
1733 return;
1734 # endif /* CLOCK_BOOTTIME */
1735 # ifdef CLOCK_MONOTONIC
1736 if (clock_gettime(CLOCK_MONOTONIC, ts) == 0)
1737 return;
1738 # endif /* CLOCK_MONOTONIC */
1739 # ifdef CLOCK_REALTIME
1740 /* Not monotonic, but we're almost out of options here. */
1741 if (clock_gettime(CLOCK_REALTIME, ts) == 0)
1742 return;
1743 # endif /* CLOCK_REALTIME */
1744 debug3("clock_gettime: %s", strerror(errno));
1745 gettime_failed = 1;
1747 #endif /* HAVE_CLOCK_GETTIME && (BOOTTIME || MONOTONIC || REALTIME) */
1748 gettimeofday(&tv, NULL);
1749 ts->tv_sec = tv.tv_sec;
1750 ts->tv_nsec = (long)tv.tv_usec * 1000;
1753 void
1754 monotime_tv(struct timeval *tv)
1756 struct timespec ts;
1758 monotime_ts(&ts);
1759 tv->tv_sec = ts.tv_sec;
1760 tv->tv_usec = ts.tv_nsec / 1000;
1763 time_t
1764 monotime(void)
1766 struct timespec ts;
1768 monotime_ts(&ts);
1769 return ts.tv_sec;
1772 double
1773 monotime_double(void)
1775 struct timespec ts;
1777 monotime_ts(&ts);
1778 return ts.tv_sec + ((double)ts.tv_nsec / 1000000000);
1781 void
1782 bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
1784 bw->buflen = buflen;
1785 bw->rate = kbps;
1786 bw->thresh = buflen;
1787 bw->lamt = 0;
1788 timerclear(&bw->bwstart);
1789 timerclear(&bw->bwend);
1792 /* Callback from read/write loop to insert bandwidth-limiting delays */
1793 void
1794 bandwidth_limit(struct bwlimit *bw, size_t read_len)
1796 u_int64_t waitlen;
1797 struct timespec ts, rm;
1799 bw->lamt += read_len;
1800 if (!timerisset(&bw->bwstart)) {
1801 monotime_tv(&bw->bwstart);
1802 return;
1804 if (bw->lamt < bw->thresh)
1805 return;
1807 monotime_tv(&bw->bwend);
1808 timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
1809 if (!timerisset(&bw->bwend))
1810 return;
1812 bw->lamt *= 8;
1813 waitlen = (double)1000000L * bw->lamt / bw->rate;
1815 bw->bwstart.tv_sec = waitlen / 1000000L;
1816 bw->bwstart.tv_usec = waitlen % 1000000L;
1818 if (timercmp(&bw->bwstart, &bw->bwend, >)) {
1819 timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
1821 /* Adjust the wait time */
1822 if (bw->bwend.tv_sec) {
1823 bw->thresh /= 2;
1824 if (bw->thresh < bw->buflen / 4)
1825 bw->thresh = bw->buflen / 4;
1826 } else if (bw->bwend.tv_usec < 10000) {
1827 bw->thresh *= 2;
1828 if (bw->thresh > bw->buflen * 8)
1829 bw->thresh = bw->buflen * 8;
1832 TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
1833 while (nanosleep(&ts, &rm) == -1) {
1834 if (errno != EINTR)
1835 break;
1836 ts = rm;
1840 bw->lamt = 0;
1841 monotime_tv(&bw->bwstart);
1844 /* Make a template filename for mk[sd]temp() */
1845 void
1846 mktemp_proto(char *s, size_t len)
1848 const char *tmpdir;
1849 int r;
1851 if ((tmpdir = getenv("TMPDIR")) != NULL) {
1852 r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
1853 if (r > 0 && (size_t)r < len)
1854 return;
1856 r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
1857 if (r < 0 || (size_t)r >= len)
1858 fatal_f("template string too short");
1861 static const struct {
1862 const char *name;
1863 int value;
1864 } ipqos[] = {
1865 { "none", INT_MAX }, /* can't use 0 here; that's CS0 */
1866 { "af11", IPTOS_DSCP_AF11 },
1867 { "af12", IPTOS_DSCP_AF12 },
1868 { "af13", IPTOS_DSCP_AF13 },
1869 { "af21", IPTOS_DSCP_AF21 },
1870 { "af22", IPTOS_DSCP_AF22 },
1871 { "af23", IPTOS_DSCP_AF23 },
1872 { "af31", IPTOS_DSCP_AF31 },
1873 { "af32", IPTOS_DSCP_AF32 },
1874 { "af33", IPTOS_DSCP_AF33 },
1875 { "af41", IPTOS_DSCP_AF41 },
1876 { "af42", IPTOS_DSCP_AF42 },
1877 { "af43", IPTOS_DSCP_AF43 },
1878 { "cs0", IPTOS_DSCP_CS0 },
1879 { "cs1", IPTOS_DSCP_CS1 },
1880 { "cs2", IPTOS_DSCP_CS2 },
1881 { "cs3", IPTOS_DSCP_CS3 },
1882 { "cs4", IPTOS_DSCP_CS4 },
1883 { "cs5", IPTOS_DSCP_CS5 },
1884 { "cs6", IPTOS_DSCP_CS6 },
1885 { "cs7", IPTOS_DSCP_CS7 },
1886 { "ef", IPTOS_DSCP_EF },
1887 { "le", IPTOS_DSCP_LE },
1888 { "lowdelay", IPTOS_LOWDELAY },
1889 { "throughput", IPTOS_THROUGHPUT },
1890 { "reliability", IPTOS_RELIABILITY },
1891 { NULL, -1 }
1895 parse_ipqos(const char *cp)
1897 const char *errstr;
1898 u_int i;
1899 int val;
1901 if (cp == NULL)
1902 return -1;
1903 for (i = 0; ipqos[i].name != NULL; i++) {
1904 if (strcasecmp(cp, ipqos[i].name) == 0)
1905 return ipqos[i].value;
1907 /* Try parsing as an integer */
1908 val = (int)strtonum(cp, 0, 255, &errstr);
1909 if (errstr)
1910 return -1;
1911 return val;
1914 const char *
1915 iptos2str(int iptos)
1917 int i;
1918 static char iptos_str[sizeof "0xff"];
1920 for (i = 0; ipqos[i].name != NULL; i++) {
1921 if (ipqos[i].value == iptos)
1922 return ipqos[i].name;
1924 snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1925 return iptos_str;
1928 void
1929 lowercase(char *s)
1931 for (; *s; s++)
1932 *s = tolower((u_char)*s);
1936 unix_listener(const char *path, int backlog, int unlink_first)
1938 struct sockaddr_un sunaddr;
1939 int saved_errno, sock;
1941 memset(&sunaddr, 0, sizeof(sunaddr));
1942 sunaddr.sun_family = AF_UNIX;
1943 if (strlcpy(sunaddr.sun_path, path,
1944 sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1945 error_f("path \"%s\" too long for Unix domain socket", path);
1946 errno = ENAMETOOLONG;
1947 return -1;
1950 sock = socket(PF_UNIX, SOCK_STREAM, 0);
1951 if (sock == -1) {
1952 saved_errno = errno;
1953 error_f("socket: %.100s", strerror(errno));
1954 errno = saved_errno;
1955 return -1;
1957 if (unlink_first == 1) {
1958 if (unlink(path) != 0 && errno != ENOENT)
1959 error("unlink(%s): %.100s", path, strerror(errno));
1961 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1962 saved_errno = errno;
1963 error_f("cannot bind to path %s: %s", path, strerror(errno));
1964 close(sock);
1965 errno = saved_errno;
1966 return -1;
1968 if (listen(sock, backlog) == -1) {
1969 saved_errno = errno;
1970 error_f("cannot listen on path %s: %s", path, strerror(errno));
1971 close(sock);
1972 unlink(path);
1973 errno = saved_errno;
1974 return -1;
1976 return sock;
1979 void
1980 sock_set_v6only(int s)
1982 #if defined(IPV6_V6ONLY) && !defined(__OpenBSD__)
1983 int on = 1;
1985 debug3("%s: set socket %d IPV6_V6ONLY", __func__, s);
1986 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1)
1987 error("setsockopt IPV6_V6ONLY: %s", strerror(errno));
1988 #endif
1992 * Compares two strings that maybe be NULL. Returns non-zero if strings
1993 * are both NULL or are identical, returns zero otherwise.
1995 static int
1996 strcmp_maybe_null(const char *a, const char *b)
1998 if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1999 return 0;
2000 if (a != NULL && strcmp(a, b) != 0)
2001 return 0;
2002 return 1;
2006 * Compare two forwards, returning non-zero if they are identical or
2007 * zero otherwise.
2010 forward_equals(const struct Forward *a, const struct Forward *b)
2012 if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
2013 return 0;
2014 if (a->listen_port != b->listen_port)
2015 return 0;
2016 if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
2017 return 0;
2018 if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
2019 return 0;
2020 if (a->connect_port != b->connect_port)
2021 return 0;
2022 if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
2023 return 0;
2024 /* allocated_port and handle are not checked */
2025 return 1;
2028 /* returns port number, FWD_PERMIT_ANY_PORT or -1 on error */
2030 permitopen_port(const char *p)
2032 int port;
2034 if (strcmp(p, "*") == 0)
2035 return FWD_PERMIT_ANY_PORT;
2036 if ((port = a2port(p)) > 0)
2037 return port;
2038 return -1;
2041 /* returns 1 if process is already daemonized, 0 otherwise */
2043 daemonized(void)
2045 int fd;
2047 if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
2048 close(fd);
2049 return 0; /* have controlling terminal */
2051 if (getppid() != 1)
2052 return 0; /* parent is not init */
2053 if (getsid(0) != getpid())
2054 return 0; /* not session leader */
2055 debug3("already daemonized");
2056 return 1;
2060 * Splits 's' into an argument vector. Handles quoted string and basic
2061 * escape characters (\\, \", \'). Caller must free the argument vector
2062 * and its members.
2065 argv_split(const char *s, int *argcp, char ***argvp, int terminate_on_comment)
2067 int r = SSH_ERR_INTERNAL_ERROR;
2068 int argc = 0, quote, i, j;
2069 char *arg, **argv = xcalloc(1, sizeof(*argv));
2071 *argvp = NULL;
2072 *argcp = 0;
2074 for (i = 0; s[i] != '\0'; i++) {
2075 /* Skip leading whitespace */
2076 if (s[i] == ' ' || s[i] == '\t')
2077 continue;
2078 if (terminate_on_comment && s[i] == '#')
2079 break;
2080 /* Start of a token */
2081 quote = 0;
2083 argv = xreallocarray(argv, (argc + 2), sizeof(*argv));
2084 arg = argv[argc++] = xcalloc(1, strlen(s + i) + 1);
2085 argv[argc] = NULL;
2087 /* Copy the token in, removing escapes */
2088 for (j = 0; s[i] != '\0'; i++) {
2089 if (s[i] == '\\') {
2090 if (s[i + 1] == '\'' ||
2091 s[i + 1] == '\"' ||
2092 s[i + 1] == '\\' ||
2093 (quote == 0 && s[i + 1] == ' ')) {
2094 i++; /* Skip '\' */
2095 arg[j++] = s[i];
2096 } else {
2097 /* Unrecognised escape */
2098 arg[j++] = s[i];
2100 } else if (quote == 0 && (s[i] == ' ' || s[i] == '\t'))
2101 break; /* done */
2102 else if (quote == 0 && (s[i] == '\"' || s[i] == '\''))
2103 quote = s[i]; /* quote start */
2104 else if (quote != 0 && s[i] == quote)
2105 quote = 0; /* quote end */
2106 else
2107 arg[j++] = s[i];
2109 if (s[i] == '\0') {
2110 if (quote != 0) {
2111 /* Ran out of string looking for close quote */
2112 r = SSH_ERR_INVALID_FORMAT;
2113 goto out;
2115 break;
2118 /* Success */
2119 *argcp = argc;
2120 *argvp = argv;
2121 argc = 0;
2122 argv = NULL;
2123 r = 0;
2124 out:
2125 if (argc != 0 && argv != NULL) {
2126 for (i = 0; i < argc; i++)
2127 free(argv[i]);
2128 free(argv);
2130 return r;
2134 * Reassemble an argument vector into a string, quoting and escaping as
2135 * necessary. Caller must free returned string.
2137 char *
2138 argv_assemble(int argc, char **argv)
2140 int i, j, ws, r;
2141 char c, *ret;
2142 struct sshbuf *buf, *arg;
2144 if ((buf = sshbuf_new()) == NULL || (arg = sshbuf_new()) == NULL)
2145 fatal_f("sshbuf_new failed");
2147 for (i = 0; i < argc; i++) {
2148 ws = 0;
2149 sshbuf_reset(arg);
2150 for (j = 0; argv[i][j] != '\0'; j++) {
2151 r = 0;
2152 c = argv[i][j];
2153 switch (c) {
2154 case ' ':
2155 case '\t':
2156 ws = 1;
2157 r = sshbuf_put_u8(arg, c);
2158 break;
2159 case '\\':
2160 case '\'':
2161 case '"':
2162 if ((r = sshbuf_put_u8(arg, '\\')) != 0)
2163 break;
2164 /* FALLTHROUGH */
2165 default:
2166 r = sshbuf_put_u8(arg, c);
2167 break;
2169 if (r != 0)
2170 fatal_fr(r, "sshbuf_put_u8");
2172 if ((i != 0 && (r = sshbuf_put_u8(buf, ' ')) != 0) ||
2173 (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0) ||
2174 (r = sshbuf_putb(buf, arg)) != 0 ||
2175 (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0))
2176 fatal_fr(r, "assemble");
2178 if ((ret = malloc(sshbuf_len(buf) + 1)) == NULL)
2179 fatal_f("malloc failed");
2180 memcpy(ret, sshbuf_ptr(buf), sshbuf_len(buf));
2181 ret[sshbuf_len(buf)] = '\0';
2182 sshbuf_free(buf);
2183 sshbuf_free(arg);
2184 return ret;
2187 char *
2188 argv_next(int *argcp, char ***argvp)
2190 char *ret = (*argvp)[0];
2192 if (*argcp > 0 && ret != NULL) {
2193 (*argcp)--;
2194 (*argvp)++;
2196 return ret;
2199 void
2200 argv_consume(int *argcp)
2202 *argcp = 0;
2205 void
2206 argv_free(char **av, int ac)
2208 int i;
2210 if (av == NULL)
2211 return;
2212 for (i = 0; i < ac; i++)
2213 free(av[i]);
2214 free(av);
2217 /* Returns 0 if pid exited cleanly, non-zero otherwise */
2219 exited_cleanly(pid_t pid, const char *tag, const char *cmd, int quiet)
2221 int status;
2223 while (waitpid(pid, &status, 0) == -1) {
2224 if (errno != EINTR) {
2225 error("%s waitpid: %s", tag, strerror(errno));
2226 return -1;
2229 if (WIFSIGNALED(status)) {
2230 error("%s %s exited on signal %d", tag, cmd, WTERMSIG(status));
2231 return -1;
2232 } else if (WEXITSTATUS(status) != 0) {
2233 do_log2(quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_INFO,
2234 "%s %s failed, status %d", tag, cmd, WEXITSTATUS(status));
2235 return -1;
2237 return 0;
2241 * Check a given path for security. This is defined as all components
2242 * of the path to the file must be owned by either the owner of
2243 * of the file or root and no directories must be group or world writable.
2245 * XXX Should any specific check be done for sym links ?
2247 * Takes a file name, its stat information (preferably from fstat() to
2248 * avoid races), the uid of the expected owner, their home directory and an
2249 * error buffer plus max size as arguments.
2251 * Returns 0 on success and -1 on failure
2254 safe_path(const char *name, struct stat *stp, const char *pw_dir,
2255 uid_t uid, char *err, size_t errlen)
2257 char buf[PATH_MAX], homedir[PATH_MAX];
2258 char *cp;
2259 int comparehome = 0;
2260 struct stat st;
2262 if (realpath(name, buf) == NULL) {
2263 snprintf(err, errlen, "realpath %s failed: %s", name,
2264 strerror(errno));
2265 return -1;
2267 if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL)
2268 comparehome = 1;
2270 if (!S_ISREG(stp->st_mode)) {
2271 snprintf(err, errlen, "%s is not a regular file", buf);
2272 return -1;
2274 if ((!platform_sys_dir_uid(stp->st_uid) && stp->st_uid != uid) ||
2275 (stp->st_mode & 022) != 0) {
2276 snprintf(err, errlen, "bad ownership or modes for file %s",
2277 buf);
2278 return -1;
2281 /* for each component of the canonical path, walking upwards */
2282 for (;;) {
2283 if ((cp = dirname(buf)) == NULL) {
2284 snprintf(err, errlen, "dirname() failed");
2285 return -1;
2287 strlcpy(buf, cp, sizeof(buf));
2289 if (stat(buf, &st) == -1 ||
2290 (!platform_sys_dir_uid(st.st_uid) && st.st_uid != uid) ||
2291 (st.st_mode & 022) != 0) {
2292 snprintf(err, errlen,
2293 "bad ownership or modes for directory %s", buf);
2294 return -1;
2297 /* If are past the homedir then we can stop */
2298 if (comparehome && strcmp(homedir, buf) == 0)
2299 break;
2302 * dirname should always complete with a "/" path,
2303 * but we can be paranoid and check for "." too
2305 if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
2306 break;
2308 return 0;
2312 * Version of safe_path() that accepts an open file descriptor to
2313 * avoid races.
2315 * Returns 0 on success and -1 on failure
2318 safe_path_fd(int fd, const char *file, struct passwd *pw,
2319 char *err, size_t errlen)
2321 struct stat st;
2323 /* check the open file to avoid races */
2324 if (fstat(fd, &st) == -1) {
2325 snprintf(err, errlen, "cannot stat file %s: %s",
2326 file, strerror(errno));
2327 return -1;
2329 return safe_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen);
2333 * Sets the value of the given variable in the environment. If the variable
2334 * already exists, its value is overridden.
2336 void
2337 child_set_env(char ***envp, u_int *envsizep, const char *name,
2338 const char *value)
2340 char **env;
2341 u_int envsize;
2342 u_int i, namelen;
2344 if (strchr(name, '=') != NULL) {
2345 error("Invalid environment variable \"%.100s\"", name);
2346 return;
2350 * If we're passed an uninitialized list, allocate a single null
2351 * entry before continuing.
2353 if ((*envp == NULL) != (*envsizep == 0))
2354 fatal_f("environment size mismatch");
2355 if (*envp == NULL && *envsizep == 0) {
2356 *envp = xmalloc(sizeof(char *));
2357 *envp[0] = NULL;
2358 *envsizep = 1;
2362 * Find the slot where the value should be stored. If the variable
2363 * already exists, we reuse the slot; otherwise we append a new slot
2364 * at the end of the array, expanding if necessary.
2366 env = *envp;
2367 namelen = strlen(name);
2368 for (i = 0; env[i]; i++)
2369 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
2370 break;
2371 if (env[i]) {
2372 /* Reuse the slot. */
2373 free(env[i]);
2374 } else {
2375 /* New variable. Expand if necessary. */
2376 envsize = *envsizep;
2377 if (i >= envsize - 1) {
2378 if (envsize >= 1000)
2379 fatal("child_set_env: too many env vars");
2380 envsize += 50;
2381 env = (*envp) = xreallocarray(env, envsize, sizeof(char *));
2382 *envsizep = envsize;
2384 /* Need to set the NULL pointer at end of array beyond the new slot. */
2385 env[i + 1] = NULL;
2388 /* Allocate space and format the variable in the appropriate slot. */
2389 /* XXX xasprintf */
2390 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
2391 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
2395 * Check and optionally lowercase a domain name, also removes trailing '.'
2396 * Returns 1 on success and 0 on failure, storing an error message in errstr.
2399 valid_domain(char *name, int makelower, const char **errstr)
2401 size_t i, l = strlen(name);
2402 u_char c, last = '\0';
2403 static char errbuf[256];
2405 if (l == 0) {
2406 strlcpy(errbuf, "empty domain name", sizeof(errbuf));
2407 goto bad;
2409 if (!isalpha((u_char)name[0]) && !isdigit((u_char)name[0]) &&
2410 name[0] != '_' /* technically invalid, but common */) {
2411 snprintf(errbuf, sizeof(errbuf), "domain name \"%.100s\" "
2412 "starts with invalid character", name);
2413 goto bad;
2415 for (i = 0; i < l; i++) {
2416 c = tolower((u_char)name[i]);
2417 if (makelower)
2418 name[i] = (char)c;
2419 if (last == '.' && c == '.') {
2420 snprintf(errbuf, sizeof(errbuf), "domain name "
2421 "\"%.100s\" contains consecutive separators", name);
2422 goto bad;
2424 if (c != '.' && c != '-' && !isalnum(c) &&
2425 c != '_') /* technically invalid, but common */ {
2426 snprintf(errbuf, sizeof(errbuf), "domain name "
2427 "\"%.100s\" contains invalid characters", name);
2428 goto bad;
2430 last = c;
2432 if (name[l - 1] == '.')
2433 name[l - 1] = '\0';
2434 if (errstr != NULL)
2435 *errstr = NULL;
2436 return 1;
2437 bad:
2438 if (errstr != NULL)
2439 *errstr = errbuf;
2440 return 0;
2444 * Verify that a environment variable name (not including initial '$') is
2445 * valid; consisting of one or more alphanumeric or underscore characters only.
2446 * Returns 1 on valid, 0 otherwise.
2449 valid_env_name(const char *name)
2451 const char *cp;
2453 if (name[0] == '\0')
2454 return 0;
2455 for (cp = name; *cp != '\0'; cp++) {
2456 if (!isalnum((u_char)*cp) && *cp != '_')
2457 return 0;
2459 return 1;
2462 const char *
2463 atoi_err(const char *nptr, int *val)
2465 const char *errstr = NULL;
2467 if (nptr == NULL || *nptr == '\0')
2468 return "missing";
2469 *val = strtonum(nptr, 0, INT_MAX, &errstr);
2470 return errstr;
2474 parse_absolute_time(const char *s, uint64_t *tp)
2476 struct tm tm;
2477 time_t tt;
2478 char buf[32], *fmt;
2479 const char *cp;
2480 size_t l;
2481 int is_utc = 0;
2483 *tp = 0;
2485 l = strlen(s);
2486 if (l > 1 && strcasecmp(s + l - 1, "Z") == 0) {
2487 is_utc = 1;
2488 l--;
2489 } else if (l > 3 && strcasecmp(s + l - 3, "UTC") == 0) {
2490 is_utc = 1;
2491 l -= 3;
2494 * POSIX strptime says "The application shall ensure that there
2495 * is white-space or other non-alphanumeric characters between
2496 * any two conversion specifications" so arrange things this way.
2498 switch (l) {
2499 case 8: /* YYYYMMDD */
2500 fmt = "%Y-%m-%d";
2501 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
2502 break;
2503 case 12: /* YYYYMMDDHHMM */
2504 fmt = "%Y-%m-%dT%H:%M";
2505 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s",
2506 s, s + 4, s + 6, s + 8, s + 10);
2507 break;
2508 case 14: /* YYYYMMDDHHMMSS */
2509 fmt = "%Y-%m-%dT%H:%M:%S";
2510 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
2511 s, s + 4, s + 6, s + 8, s + 10, s + 12);
2512 break;
2513 default:
2514 return SSH_ERR_INVALID_FORMAT;
2517 memset(&tm, 0, sizeof(tm));
2518 if ((cp = strptime(buf, fmt, &tm)) == NULL || *cp != '\0')
2519 return SSH_ERR_INVALID_FORMAT;
2520 if (is_utc) {
2521 if ((tt = timegm(&tm)) < 0)
2522 return SSH_ERR_INVALID_FORMAT;
2523 } else {
2524 if ((tt = mktime(&tm)) < 0)
2525 return SSH_ERR_INVALID_FORMAT;
2527 /* success */
2528 *tp = (uint64_t)tt;
2529 return 0;
2532 void
2533 format_absolute_time(uint64_t t, char *buf, size_t len)
2535 time_t tt = t > SSH_TIME_T_MAX ? SSH_TIME_T_MAX : t;
2536 struct tm tm;
2538 localtime_r(&tt, &tm);
2539 strftime(buf, len, "%Y-%m-%dT%H:%M:%S", &tm);
2543 * Parse a "pattern=interval" clause (e.g. a ChannelTimeout).
2544 * Returns 0 on success or non-zero on failure.
2545 * Caller must free *typep.
2548 parse_pattern_interval(const char *s, char **typep, int *secsp)
2550 char *cp, *sdup;
2551 int secs;
2553 if (typep != NULL)
2554 *typep = NULL;
2555 if (secsp != NULL)
2556 *secsp = 0;
2557 if (s == NULL)
2558 return -1;
2559 sdup = xstrdup(s);
2561 if ((cp = strchr(sdup, '=')) == NULL || cp == sdup) {
2562 free(sdup);
2563 return -1;
2565 *cp++ = '\0';
2566 if ((secs = convtime(cp)) < 0) {
2567 free(sdup);
2568 return -1;
2570 /* success */
2571 if (typep != NULL)
2572 *typep = xstrdup(sdup);
2573 if (secsp != NULL)
2574 *secsp = secs;
2575 free(sdup);
2576 return 0;
2579 /* check if path is absolute */
2581 path_absolute(const char *path)
2583 return (*path == '/') ? 1 : 0;
2586 void
2587 skip_space(char **cpp)
2589 char *cp;
2591 for (cp = *cpp; *cp == ' ' || *cp == '\t'; cp++)
2593 *cpp = cp;
2596 /* authorized_key-style options parsing helpers */
2599 * Match flag 'opt' in *optsp, and if allow_negate is set then also match
2600 * 'no-opt'. Returns -1 if option not matched, 1 if option matches or 0
2601 * if negated option matches.
2602 * If the option or negated option matches, then *optsp is updated to
2603 * point to the first character after the option.
2606 opt_flag(const char *opt, int allow_negate, const char **optsp)
2608 size_t opt_len = strlen(opt);
2609 const char *opts = *optsp;
2610 int negate = 0;
2612 if (allow_negate && strncasecmp(opts, "no-", 3) == 0) {
2613 opts += 3;
2614 negate = 1;
2616 if (strncasecmp(opts, opt, opt_len) == 0) {
2617 *optsp = opts + opt_len;
2618 return negate ? 0 : 1;
2620 return -1;
2623 char *
2624 opt_dequote(const char **sp, const char **errstrp)
2626 const char *s = *sp;
2627 char *ret;
2628 size_t i;
2630 *errstrp = NULL;
2631 if (*s != '"') {
2632 *errstrp = "missing start quote";
2633 return NULL;
2635 s++;
2636 if ((ret = malloc(strlen((s)) + 1)) == NULL) {
2637 *errstrp = "memory allocation failed";
2638 return NULL;
2640 for (i = 0; *s != '\0' && *s != '"';) {
2641 if (s[0] == '\\' && s[1] == '"')
2642 s++;
2643 ret[i++] = *s++;
2645 if (*s == '\0') {
2646 *errstrp = "missing end quote";
2647 free(ret);
2648 return NULL;
2650 ret[i] = '\0';
2651 s++;
2652 *sp = s;
2653 return ret;
2657 opt_match(const char **opts, const char *term)
2659 if (strncasecmp((*opts), term, strlen(term)) == 0 &&
2660 (*opts)[strlen(term)] == '=') {
2661 *opts += strlen(term) + 1;
2662 return 1;
2664 return 0;
2667 void
2668 opt_array_append2(const char *file, const int line, const char *directive,
2669 char ***array, int **iarray, u_int *lp, const char *s, int i)
2672 if (*lp >= INT_MAX)
2673 fatal("%s line %d: Too many %s entries", file, line, directive);
2675 if (iarray != NULL) {
2676 *iarray = xrecallocarray(*iarray, *lp, *lp + 1,
2677 sizeof(**iarray));
2678 (*iarray)[*lp] = i;
2681 *array = xrecallocarray(*array, *lp, *lp + 1, sizeof(**array));
2682 (*array)[*lp] = xstrdup(s);
2683 (*lp)++;
2686 void
2687 opt_array_append(const char *file, const int line, const char *directive,
2688 char ***array, u_int *lp, const char *s)
2690 opt_array_append2(file, line, directive, array, NULL, lp, s, 0);
2693 void
2694 opt_array_free2(char **array, int **iarray, u_int l)
2696 u_int i;
2698 if (array == NULL || l == 0)
2699 return;
2700 for (i = 0; i < l; i++)
2701 free(array[i]);
2702 free(array);
2703 free(iarray);
2706 sshsig_t
2707 ssh_signal(int signum, sshsig_t handler)
2709 struct sigaction sa, osa;
2711 /* mask all other signals while in handler */
2712 memset(&sa, 0, sizeof(sa));
2713 sa.sa_handler = handler;
2714 sigfillset(&sa.sa_mask);
2715 #if defined(SA_RESTART) && !defined(NO_SA_RESTART)
2716 if (signum != SIGALRM)
2717 sa.sa_flags = SA_RESTART;
2718 #endif
2719 if (sigaction(signum, &sa, &osa) == -1) {
2720 debug3("sigaction(%s): %s", strsignal(signum), strerror(errno));
2721 return SIG_ERR;
2723 return osa.sa_handler;
2727 stdfd_devnull(int do_stdin, int do_stdout, int do_stderr)
2729 int devnull, ret = 0;
2731 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
2732 error_f("open %s: %s", _PATH_DEVNULL,
2733 strerror(errno));
2734 return -1;
2736 if ((do_stdin && dup2(devnull, STDIN_FILENO) == -1) ||
2737 (do_stdout && dup2(devnull, STDOUT_FILENO) == -1) ||
2738 (do_stderr && dup2(devnull, STDERR_FILENO) == -1)) {
2739 error_f("dup2: %s", strerror(errno));
2740 ret = -1;
2742 if (devnull > STDERR_FILENO)
2743 close(devnull);
2744 return ret;
2748 * Runs command in a subprocess with a minimal environment.
2749 * Returns pid on success, 0 on failure.
2750 * The child stdout and stderr maybe captured, left attached or sent to
2751 * /dev/null depending on the contents of flags.
2752 * "tag" is prepended to log messages.
2753 * NB. "command" is only used for logging; the actual command executed is
2754 * av[0].
2756 pid_t
2757 subprocess(const char *tag, const char *command,
2758 int ac, char **av, FILE **child, u_int flags,
2759 struct passwd *pw, privdrop_fn *drop_privs, privrestore_fn *restore_privs)
2761 FILE *f = NULL;
2762 struct stat st;
2763 int fd, devnull, p[2], i;
2764 pid_t pid;
2765 char *cp, errmsg[512];
2766 u_int nenv = 0;
2767 char **env = NULL;
2769 /* If dropping privs, then must specify user and restore function */
2770 if (drop_privs != NULL && (pw == NULL || restore_privs == NULL)) {
2771 error("%s: inconsistent arguments", tag); /* XXX fatal? */
2772 return 0;
2774 if (pw == NULL && (pw = getpwuid(getuid())) == NULL) {
2775 error("%s: no user for current uid", tag);
2776 return 0;
2778 if (child != NULL)
2779 *child = NULL;
2781 debug3_f("%s command \"%s\" running as %s (flags 0x%x)",
2782 tag, command, pw->pw_name, flags);
2784 /* Check consistency */
2785 if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
2786 (flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0) {
2787 error_f("inconsistent flags");
2788 return 0;
2790 if (((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0) != (child == NULL)) {
2791 error_f("inconsistent flags/output");
2792 return 0;
2796 * If executing an explicit binary, then verify the it exists
2797 * and appears safe-ish to execute
2799 if (!path_absolute(av[0])) {
2800 error("%s path is not absolute", tag);
2801 return 0;
2803 if (drop_privs != NULL)
2804 drop_privs(pw);
2805 if (stat(av[0], &st) == -1) {
2806 error("Could not stat %s \"%s\": %s", tag,
2807 av[0], strerror(errno));
2808 goto restore_return;
2810 if ((flags & SSH_SUBPROCESS_UNSAFE_PATH) == 0 &&
2811 safe_path(av[0], &st, NULL, 0, errmsg, sizeof(errmsg)) != 0) {
2812 error("Unsafe %s \"%s\": %s", tag, av[0], errmsg);
2813 goto restore_return;
2815 /* Prepare to keep the child's stdout if requested */
2816 if (pipe(p) == -1) {
2817 error("%s: pipe: %s", tag, strerror(errno));
2818 restore_return:
2819 if (restore_privs != NULL)
2820 restore_privs();
2821 return 0;
2823 if (restore_privs != NULL)
2824 restore_privs();
2826 switch ((pid = fork())) {
2827 case -1: /* error */
2828 error("%s: fork: %s", tag, strerror(errno));
2829 close(p[0]);
2830 close(p[1]);
2831 return 0;
2832 case 0: /* child */
2833 /* Prepare a minimal environment for the child. */
2834 if ((flags & SSH_SUBPROCESS_PRESERVE_ENV) == 0) {
2835 nenv = 5;
2836 env = xcalloc(sizeof(*env), nenv);
2837 child_set_env(&env, &nenv, "PATH", _PATH_STDPATH);
2838 child_set_env(&env, &nenv, "USER", pw->pw_name);
2839 child_set_env(&env, &nenv, "LOGNAME", pw->pw_name);
2840 child_set_env(&env, &nenv, "HOME", pw->pw_dir);
2841 if ((cp = getenv("LANG")) != NULL)
2842 child_set_env(&env, &nenv, "LANG", cp);
2845 for (i = 1; i < NSIG; i++)
2846 ssh_signal(i, SIG_DFL);
2848 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
2849 error("%s: open %s: %s", tag, _PATH_DEVNULL,
2850 strerror(errno));
2851 _exit(1);
2853 if (dup2(devnull, STDIN_FILENO) == -1) {
2854 error("%s: dup2: %s", tag, strerror(errno));
2855 _exit(1);
2858 /* Set up stdout as requested; leave stderr in place for now. */
2859 fd = -1;
2860 if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0)
2861 fd = p[1];
2862 else if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0)
2863 fd = devnull;
2864 if (fd != -1 && dup2(fd, STDOUT_FILENO) == -1) {
2865 error("%s: dup2: %s", tag, strerror(errno));
2866 _exit(1);
2868 closefrom(STDERR_FILENO + 1);
2870 if (geteuid() == 0 &&
2871 initgroups(pw->pw_name, pw->pw_gid) == -1) {
2872 error("%s: initgroups(%s, %u): %s", tag,
2873 pw->pw_name, (u_int)pw->pw_gid, strerror(errno));
2874 _exit(1);
2876 if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1) {
2877 error("%s: setresgid %u: %s", tag, (u_int)pw->pw_gid,
2878 strerror(errno));
2879 _exit(1);
2881 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1) {
2882 error("%s: setresuid %u: %s", tag, (u_int)pw->pw_uid,
2883 strerror(errno));
2884 _exit(1);
2886 /* stdin is pointed to /dev/null at this point */
2887 if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
2888 dup2(STDIN_FILENO, STDERR_FILENO) == -1) {
2889 error("%s: dup2: %s", tag, strerror(errno));
2890 _exit(1);
2892 if (env != NULL)
2893 execve(av[0], av, env);
2894 else
2895 execv(av[0], av);
2896 error("%s %s \"%s\": %s", tag, env == NULL ? "execv" : "execve",
2897 command, strerror(errno));
2898 _exit(127);
2899 default: /* parent */
2900 break;
2903 close(p[1]);
2904 if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0)
2905 close(p[0]);
2906 else if ((f = fdopen(p[0], "r")) == NULL) {
2907 error("%s: fdopen: %s", tag, strerror(errno));
2908 close(p[0]);
2909 /* Don't leave zombie child */
2910 kill(pid, SIGTERM);
2911 while (waitpid(pid, NULL, 0) == -1 && errno == EINTR)
2913 return 0;
2915 /* Success */
2916 debug3_f("%s pid %ld", tag, (long)pid);
2917 if (child != NULL)
2918 *child = f;
2919 return pid;
2922 const char *
2923 lookup_env_in_list(const char *env, char * const *envs, size_t nenvs)
2925 size_t i, envlen;
2927 envlen = strlen(env);
2928 for (i = 0; i < nenvs; i++) {
2929 if (strncmp(envs[i], env, envlen) == 0 &&
2930 envs[i][envlen] == '=') {
2931 return envs[i] + envlen + 1;
2934 return NULL;
2937 const char *
2938 lookup_setenv_in_list(const char *env, char * const *envs, size_t nenvs)
2940 char *name, *cp;
2941 const char *ret;
2943 name = xstrdup(env);
2944 if ((cp = strchr(name, '=')) == NULL) {
2945 free(name);
2946 return NULL; /* not env=val */
2948 *cp = '\0';
2949 ret = lookup_env_in_list(name, envs, nenvs);
2950 free(name);
2951 return ret;
2955 * Helpers for managing poll(2)/ppoll(2) timeouts
2956 * Will remember the earliest deadline and return it for use in poll/ppoll.
2959 /* Initialise a poll/ppoll timeout with an indefinite deadline */
2960 void
2961 ptimeout_init(struct timespec *pt)
2964 * Deliberately invalid for ppoll(2).
2965 * Will be converted to NULL in ptimeout_get_tspec() later.
2967 pt->tv_sec = -1;
2968 pt->tv_nsec = 0;
2971 /* Specify a poll/ppoll deadline of at most 'sec' seconds */
2972 void
2973 ptimeout_deadline_sec(struct timespec *pt, long sec)
2975 if (pt->tv_sec == -1 || pt->tv_sec >= sec) {
2976 pt->tv_sec = sec;
2977 pt->tv_nsec = 0;
2981 /* Specify a poll/ppoll deadline of at most 'p' (timespec) */
2982 static void
2983 ptimeout_deadline_tsp(struct timespec *pt, struct timespec *p)
2985 if (pt->tv_sec == -1 || timespeccmp(pt, p, >=))
2986 *pt = *p;
2989 /* Specify a poll/ppoll deadline of at most 'ms' milliseconds */
2990 void
2991 ptimeout_deadline_ms(struct timespec *pt, long ms)
2993 struct timespec p;
2995 p.tv_sec = ms / 1000;
2996 p.tv_nsec = (ms % 1000) * 1000000;
2997 ptimeout_deadline_tsp(pt, &p);
3000 /* Specify a poll/ppoll deadline at wall clock monotime 'when' (timespec) */
3001 void
3002 ptimeout_deadline_monotime_tsp(struct timespec *pt, struct timespec *when)
3004 struct timespec now, t;
3006 monotime_ts(&now);
3008 if (timespeccmp(&now, when, >=)) {
3009 /* 'when' is now or in the past. Timeout ASAP */
3010 pt->tv_sec = 0;
3011 pt->tv_nsec = 0;
3012 } else {
3013 timespecsub(when, &now, &t);
3014 ptimeout_deadline_tsp(pt, &t);
3018 /* Specify a poll/ppoll deadline at wall clock monotime 'when' */
3019 void
3020 ptimeout_deadline_monotime(struct timespec *pt, time_t when)
3022 struct timespec t;
3024 t.tv_sec = when;
3025 t.tv_nsec = 0;
3026 ptimeout_deadline_monotime_tsp(pt, &t);
3029 /* Get a poll(2) timeout value in milliseconds */
3031 ptimeout_get_ms(struct timespec *pt)
3033 if (pt->tv_sec == -1)
3034 return -1;
3035 if (pt->tv_sec >= (INT_MAX - (pt->tv_nsec / 1000000)) / 1000)
3036 return INT_MAX;
3037 return (pt->tv_sec * 1000) + (pt->tv_nsec / 1000000);
3040 /* Get a ppoll(2) timeout value as a timespec pointer */
3041 struct timespec *
3042 ptimeout_get_tsp(struct timespec *pt)
3044 return pt->tv_sec == -1 ? NULL : pt;
3047 /* Returns non-zero if a timeout has been set (i.e. is not indefinite) */
3049 ptimeout_isset(struct timespec *pt)
3051 return pt->tv_sec != -1;
3055 * Returns zero if the library at 'path' contains symbol 's', nonzero
3056 * otherwise.
3059 lib_contains_symbol(const char *path, const char *s)
3061 #ifdef HAVE_NLIST_H
3062 struct nlist nl[2];
3063 int ret = -1, r;
3065 memset(nl, 0, sizeof(nl));
3066 nl[0].n_name = xstrdup(s);
3067 nl[1].n_name = NULL;
3068 if ((r = nlist(path, nl)) == -1) {
3069 error_f("nlist failed for %s", path);
3070 goto out;
3072 if (r != 0 || nl[0].n_value == 0 || nl[0].n_type == 0) {
3073 error_f("library %s does not contain symbol %s", path, s);
3074 goto out;
3076 /* success */
3077 ret = 0;
3078 out:
3079 free(nl[0].n_name);
3080 return ret;
3081 #else /* HAVE_NLIST_H */
3082 int fd, ret = -1;
3083 struct stat st;
3084 void *m = NULL;
3085 size_t sz = 0;
3087 memset(&st, 0, sizeof(st));
3088 if ((fd = open(path, O_RDONLY)) < 0) {
3089 error_f("open %s: %s", path, strerror(errno));
3090 return -1;
3092 if (fstat(fd, &st) != 0) {
3093 error_f("fstat %s: %s", path, strerror(errno));
3094 goto out;
3096 if (!S_ISREG(st.st_mode)) {
3097 error_f("%s is not a regular file", path);
3098 goto out;
3100 if (st.st_size < 0 ||
3101 (size_t)st.st_size < strlen(s) ||
3102 st.st_size >= INT_MAX/2) {
3103 error_f("%s bad size %lld", path, (long long)st.st_size);
3104 goto out;
3106 sz = (size_t)st.st_size;
3107 if ((m = mmap(NULL, sz, PROT_READ, MAP_PRIVATE, fd, 0)) == MAP_FAILED ||
3108 m == NULL) {
3109 error_f("mmap %s: %s", path, strerror(errno));
3110 goto out;
3112 if (memmem(m, sz, s, strlen(s)) == NULL) {
3113 error_f("%s does not contain expected string %s", path, s);
3114 goto out;
3116 /* success */
3117 ret = 0;
3118 out:
3119 if (m != NULL && m != MAP_FAILED)
3120 munmap(m, sz);
3121 close(fd);
3122 return ret;
3123 #endif /* HAVE_NLIST_H */
3127 signal_is_crash(int sig)
3129 switch (sig) {
3130 case SIGSEGV:
3131 case SIGBUS:
3132 case SIGTRAP:
3133 case SIGSYS:
3134 case SIGFPE:
3135 case SIGILL:
3136 case SIGABRT:
3137 return 1;
3139 return 0;