]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - crypto/openssh/misc.c
MFV: zlib 1.3
[FreeBSD/FreeBSD.git] / crypto / openssh / misc.c
1 /* $OpenBSD: misc.c,v 1.185 2023/08/04 06:32:40 dtucker 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>
6  *
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.
10  *
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.
18  */
19
20
21 #include "includes.h"
22
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>
31
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>
52
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>
58
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
71
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"
79
80 /* remove newline at end of string */
81 char *
82 chop(char *s)
83 {
84         char *t = s;
85         while (*t) {
86                 if (*t == '\n' || *t == '\r') {
87                         *t = '\0';
88                         return s;
89                 }
90                 t++;
91         }
92         return s;
93
94 }
95
96 /* remove whitespace from end of string */
97 void
98 rtrim(char *s)
99 {
100         size_t i;
101
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';
107         }
108 }
109
110 /* set/unset filedescriptor to non-blocking */
111 int
112 set_nonblock(int fd)
113 {
114         int val;
115
116         val = fcntl(fd, F_GETFL);
117         if (val == -1) {
118                 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
119                 return (-1);
120         }
121         if (val & O_NONBLOCK) {
122                 debug3("fd %d is O_NONBLOCK", fd);
123                 return (0);
124         }
125         debug2("fd %d setting O_NONBLOCK", fd);
126         val |= O_NONBLOCK;
127         if (fcntl(fd, F_SETFL, val) == -1) {
128                 debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
129                     strerror(errno));
130                 return (-1);
131         }
132         return (0);
133 }
134
135 int
136 unset_nonblock(int fd)
137 {
138         int val;
139
140         val = fcntl(fd, F_GETFL);
141         if (val == -1) {
142                 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
143                 return (-1);
144         }
145         if (!(val & O_NONBLOCK)) {
146                 debug3("fd %d is not O_NONBLOCK", fd);
147                 return (0);
148         }
149         debug("fd %d clearing O_NONBLOCK", fd);
150         val &= ~O_NONBLOCK;
151         if (fcntl(fd, F_SETFL, val) == -1) {
152                 debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
153                     fd, strerror(errno));
154                 return (-1);
155         }
156         return (0);
157 }
158
159 const char *
160 ssh_gai_strerror(int gaierr)
161 {
162         if (gaierr == EAI_SYSTEM && errno != 0)
163                 return strerror(errno);
164         return gai_strerror(gaierr);
165 }
166
167 /* disable nagle on socket */
168 void
169 set_nodelay(int fd)
170 {
171         int opt;
172         socklen_t optlen;
173
174         optlen = sizeof opt;
175         if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
176                 debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
177                 return;
178         }
179         if (opt == 1) {
180                 debug2("fd %d is TCP_NODELAY", fd);
181                 return;
182         }
183         opt = 1;
184         debug2("fd %d setting TCP_NODELAY", fd);
185         if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
186                 error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
187 }
188
189 /* Allow local port reuse in TIME_WAIT */
190 int
191 set_reuseaddr(int fd)
192 {
193         int on = 1;
194
195         if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
196                 error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
197                 return -1;
198         }
199         return 0;
200 }
201
202 /* Get/set routing domain */
203 char *
204 get_rdomain(int fd)
205 {
206 #if defined(HAVE_SYS_GET_RDOMAIN)
207         return sys_get_rdomain(fd);
208 #elif defined(__OpenBSD__)
209         int rtable;
210         char *ret;
211         socklen_t len = sizeof(rtable);
212
213         if (getsockopt(fd, SOL_SOCKET, SO_RTABLE, &rtable, &len) == -1) {
214                 error("Failed to get routing domain for fd %d: %s",
215                     fd, strerror(errno));
216                 return NULL;
217         }
218         xasprintf(&ret, "%d", rtable);
219         return ret;
220 #else /* defined(__OpenBSD__) */
221         return NULL;
222 #endif
223 }
224
225 int
226 set_rdomain(int fd, const char *name)
227 {
228 #if defined(HAVE_SYS_SET_RDOMAIN)
229         return sys_set_rdomain(fd, name);
230 #elif defined(__OpenBSD__)
231         int rtable;
232         const char *errstr;
233
234         if (name == NULL)
235                 return 0; /* default table */
236
237         rtable = (int)strtonum(name, 0, 255, &errstr);
238         if (errstr != NULL) {
239                 /* Shouldn't happen */
240                 error("Invalid routing domain \"%s\": %s", name, errstr);
241                 return -1;
242         }
243         if (setsockopt(fd, SOL_SOCKET, SO_RTABLE,
244             &rtable, sizeof(rtable)) == -1) {
245                 error("Failed to set routing domain %d on fd %d: %s",
246                     rtable, fd, strerror(errno));
247                 return -1;
248         }
249         return 0;
250 #else /* defined(__OpenBSD__) */
251         error("Setting routing domain is not supported on this platform");
252         return -1;
253 #endif
254 }
255
256 int
257 get_sock_af(int fd)
258 {
259         struct sockaddr_storage to;
260         socklen_t tolen = sizeof(to);
261
262         memset(&to, 0, sizeof(to));
263         if (getsockname(fd, (struct sockaddr *)&to, &tolen) == -1)
264                 return -1;
265 #ifdef IPV4_IN_IPV6
266         if (to.ss_family == AF_INET6 &&
267             IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
268                 return AF_INET;
269 #endif
270         return to.ss_family;
271 }
272
273 void
274 set_sock_tos(int fd, int tos)
275 {
276 #ifndef IP_TOS_IS_BROKEN
277         int af;
278
279         switch ((af = get_sock_af(fd))) {
280         case -1:
281                 /* assume not a socket */
282                 break;
283         case AF_INET:
284 # ifdef IP_TOS
285                 debug3_f("set socket %d IP_TOS 0x%02x", fd, tos);
286                 if (setsockopt(fd, IPPROTO_IP, IP_TOS,
287                     &tos, sizeof(tos)) == -1) {
288                         error("setsockopt socket %d IP_TOS %d: %s",
289                             fd, tos, strerror(errno));
290                 }
291 # endif /* IP_TOS */
292                 break;
293         case AF_INET6:
294 # ifdef IPV6_TCLASS
295                 debug3_f("set socket %d IPV6_TCLASS 0x%02x", fd, tos);
296                 if (setsockopt(fd, IPPROTO_IPV6, IPV6_TCLASS,
297                     &tos, sizeof(tos)) == -1) {
298                         error("setsockopt socket %d IPV6_TCLASS %d: %s",
299                             fd, tos, strerror(errno));
300                 }
301 # endif /* IPV6_TCLASS */
302                 break;
303         default:
304                 debug2_f("unsupported socket family %d", af);
305                 break;
306         }
307 #endif /* IP_TOS_IS_BROKEN */
308 }
309
310 /*
311  * Wait up to *timeoutp milliseconds for events on fd. Updates
312  * *timeoutp with time remaining.
313  * Returns 0 if fd ready or -1 on timeout or error (see errno).
314  */
315 static int
316 waitfd(int fd, int *timeoutp, short events)
317 {
318         struct pollfd pfd;
319         struct timeval t_start;
320         int oerrno, r, have_timeout = (*timeoutp >= 0);
321
322         pfd.fd = fd;
323         pfd.events = events;
324         for (; !have_timeout || *timeoutp >= 0;) {
325                 monotime_tv(&t_start);
326                 r = poll(&pfd, 1, *timeoutp);
327                 oerrno = errno;
328                 if (have_timeout)
329                         ms_subtract_diff(&t_start, timeoutp);
330                 errno = oerrno;
331                 if (r > 0)
332                         return 0;
333                 else if (r == -1 && errno != EAGAIN && errno != EINTR)
334                         return -1;
335                 else if (r == 0)
336                         break;
337         }
338         /* timeout */
339         errno = ETIMEDOUT;
340         return -1;
341 }
342
343 /*
344  * Wait up to *timeoutp milliseconds for fd to be readable. Updates
345  * *timeoutp with time remaining.
346  * Returns 0 if fd ready or -1 on timeout or error (see errno).
347  */
348 int
349 waitrfd(int fd, int *timeoutp) {
350         return waitfd(fd, timeoutp, POLLIN);
351 }
352
353 /*
354  * Attempt a non-blocking connect(2) to the specified address, waiting up to
355  * *timeoutp milliseconds for the connection to complete. If the timeout is
356  * <=0, then wait indefinitely.
357  *
358  * Returns 0 on success or -1 on failure.
359  */
360 int
361 timeout_connect(int sockfd, const struct sockaddr *serv_addr,
362     socklen_t addrlen, int *timeoutp)
363 {
364         int optval = 0;
365         socklen_t optlen = sizeof(optval);
366
367         /* No timeout: just do a blocking connect() */
368         if (timeoutp == NULL || *timeoutp <= 0)
369                 return connect(sockfd, serv_addr, addrlen);
370
371         set_nonblock(sockfd);
372         for (;;) {
373                 if (connect(sockfd, serv_addr, addrlen) == 0) {
374                         /* Succeeded already? */
375                         unset_nonblock(sockfd);
376                         return 0;
377                 } else if (errno == EINTR)
378                         continue;
379                 else if (errno != EINPROGRESS)
380                         return -1;
381                 break;
382         }
383
384         if (waitfd(sockfd, timeoutp, POLLIN | POLLOUT) == -1)
385                 return -1;
386
387         /* Completed or failed */
388         if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval, &optlen) == -1) {
389                 debug("getsockopt: %s", strerror(errno));
390                 return -1;
391         }
392         if (optval != 0) {
393                 errno = optval;
394                 return -1;
395         }
396         unset_nonblock(sockfd);
397         return 0;
398 }
399
400 /* Characters considered whitespace in strsep calls. */
401 #define WHITESPACE " \t\r\n"
402 #define QUOTE   "\""
403
404 /* return next token in configuration line */
405 static char *
406 strdelim_internal(char **s, int split_equals)
407 {
408         char *old;
409         int wspace = 0;
410
411         if (*s == NULL)
412                 return NULL;
413
414         old = *s;
415
416         *s = strpbrk(*s,
417             split_equals ? WHITESPACE QUOTE "=" : WHITESPACE QUOTE);
418         if (*s == NULL)
419                 return (old);
420
421         if (*s[0] == '\"') {
422                 memmove(*s, *s + 1, strlen(*s)); /* move nul too */
423                 /* Find matching quote */
424                 if ((*s = strpbrk(*s, QUOTE)) == NULL) {
425                         return (NULL);          /* no matching quote */
426                 } else {
427                         *s[0] = '\0';
428                         *s += strspn(*s + 1, WHITESPACE) + 1;
429                         return (old);
430                 }
431         }
432
433         /* Allow only one '=' to be skipped */
434         if (split_equals && *s[0] == '=')
435                 wspace = 1;
436         *s[0] = '\0';
437
438         /* Skip any extra whitespace after first token */
439         *s += strspn(*s + 1, WHITESPACE) + 1;
440         if (split_equals && *s[0] == '=' && !wspace)
441                 *s += strspn(*s + 1, WHITESPACE) + 1;
442
443         return (old);
444 }
445
446 /*
447  * Return next token in configuration line; splts on whitespace or a
448  * single '=' character.
449  */
450 char *
451 strdelim(char **s)
452 {
453         return strdelim_internal(s, 1);
454 }
455
456 /*
457  * Return next token in configuration line; splts on whitespace only.
458  */
459 char *
460 strdelimw(char **s)
461 {
462         return strdelim_internal(s, 0);
463 }
464
465 struct passwd *
466 pwcopy(struct passwd *pw)
467 {
468         struct passwd *copy = xcalloc(1, sizeof(*copy));
469
470         copy->pw_name = xstrdup(pw->pw_name);
471         copy->pw_passwd = xstrdup(pw->pw_passwd == NULL ? "*" : pw->pw_passwd);
472 #ifdef HAVE_STRUCT_PASSWD_PW_GECOS
473         copy->pw_gecos = xstrdup(pw->pw_gecos);
474 #endif
475         copy->pw_uid = pw->pw_uid;
476         copy->pw_gid = pw->pw_gid;
477 #ifdef HAVE_STRUCT_PASSWD_PW_EXPIRE
478         copy->pw_expire = pw->pw_expire;
479 #endif
480 #ifdef HAVE_STRUCT_PASSWD_PW_CHANGE
481         copy->pw_change = pw->pw_change;
482 #endif
483 #ifdef HAVE_STRUCT_PASSWD_PW_CLASS
484         copy->pw_class = xstrdup(pw->pw_class);
485 #endif
486         copy->pw_dir = xstrdup(pw->pw_dir);
487         copy->pw_shell = xstrdup(pw->pw_shell);
488         return copy;
489 }
490
491 /*
492  * Convert ASCII string to TCP/IP port number.
493  * Port must be >=0 and <=65535.
494  * Return -1 if invalid.
495  */
496 int
497 a2port(const char *s)
498 {
499         struct servent *se;
500         long long port;
501         const char *errstr;
502
503         port = strtonum(s, 0, 65535, &errstr);
504         if (errstr == NULL)
505                 return (int)port;
506         if ((se = getservbyname(s, "tcp")) != NULL)
507                 return ntohs(se->s_port);
508         return -1;
509 }
510
511 int
512 a2tun(const char *s, int *remote)
513 {
514         const char *errstr = NULL;
515         char *sp, *ep;
516         int tun;
517
518         if (remote != NULL) {
519                 *remote = SSH_TUNID_ANY;
520                 sp = xstrdup(s);
521                 if ((ep = strchr(sp, ':')) == NULL) {
522                         free(sp);
523                         return (a2tun(s, NULL));
524                 }
525                 ep[0] = '\0'; ep++;
526                 *remote = a2tun(ep, NULL);
527                 tun = a2tun(sp, NULL);
528                 free(sp);
529                 return (*remote == SSH_TUNID_ERR ? *remote : tun);
530         }
531
532         if (strcasecmp(s, "any") == 0)
533                 return (SSH_TUNID_ANY);
534
535         tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
536         if (errstr != NULL)
537                 return (SSH_TUNID_ERR);
538
539         return (tun);
540 }
541
542 #define SECONDS         1
543 #define MINUTES         (SECONDS * 60)
544 #define HOURS           (MINUTES * 60)
545 #define DAYS            (HOURS * 24)
546 #define WEEKS           (DAYS * 7)
547
548 /*
549  * Convert a time string into seconds; format is
550  * a sequence of:
551  *      time[qualifier]
552  *
553  * Valid time qualifiers are:
554  *      <none>  seconds
555  *      s|S     seconds
556  *      m|M     minutes
557  *      h|H     hours
558  *      d|D     days
559  *      w|W     weeks
560  *
561  * Examples:
562  *      90m     90 minutes
563  *      1h30m   90 minutes
564  *      2d      2 days
565  *      1w      1 week
566  *
567  * Return -1 if time string is invalid.
568  */
569 int
570 convtime(const char *s)
571 {
572         long total, secs, multiplier;
573         const char *p;
574         char *endp;
575
576         errno = 0;
577         total = 0;
578         p = s;
579
580         if (p == NULL || *p == '\0')
581                 return -1;
582
583         while (*p) {
584                 secs = strtol(p, &endp, 10);
585                 if (p == endp ||
586                     (errno == ERANGE && (secs == INT_MIN || secs == INT_MAX)) ||
587                     secs < 0)
588                         return -1;
589
590                 multiplier = 1;
591                 switch (*endp++) {
592                 case '\0':
593                         endp--;
594                         break;
595                 case 's':
596                 case 'S':
597                         break;
598                 case 'm':
599                 case 'M':
600                         multiplier = MINUTES;
601                         break;
602                 case 'h':
603                 case 'H':
604                         multiplier = HOURS;
605                         break;
606                 case 'd':
607                 case 'D':
608                         multiplier = DAYS;
609                         break;
610                 case 'w':
611                 case 'W':
612                         multiplier = WEEKS;
613                         break;
614                 default:
615                         return -1;
616                 }
617                 if (secs > INT_MAX / multiplier)
618                         return -1;
619                 secs *= multiplier;
620                 if  (total > INT_MAX - secs)
621                         return -1;
622                 total += secs;
623                 if (total < 0)
624                         return -1;
625                 p = endp;
626         }
627
628         return total;
629 }
630
631 #define TF_BUFS 8
632 #define TF_LEN  9
633
634 const char *
635 fmt_timeframe(time_t t)
636 {
637         char            *buf;
638         static char      tfbuf[TF_BUFS][TF_LEN];        /* ring buffer */
639         static int       idx = 0;
640         unsigned int     sec, min, hrs, day;
641         unsigned long long      week;
642
643         buf = tfbuf[idx++];
644         if (idx == TF_BUFS)
645                 idx = 0;
646
647         week = t;
648
649         sec = week % 60;
650         week /= 60;
651         min = week % 60;
652         week /= 60;
653         hrs = week % 24;
654         week /= 24;
655         day = week % 7;
656         week /= 7;
657
658         if (week > 0)
659                 snprintf(buf, TF_LEN, "%02lluw%01ud%02uh", week, day, hrs);
660         else if (day > 0)
661                 snprintf(buf, TF_LEN, "%01ud%02uh%02um", day, hrs, min);
662         else
663                 snprintf(buf, TF_LEN, "%02u:%02u:%02u", hrs, min, sec);
664
665         return (buf);
666 }
667
668 /*
669  * Returns a standardized host+port identifier string.
670  * Caller must free returned string.
671  */
672 char *
673 put_host_port(const char *host, u_short port)
674 {
675         char *hoststr;
676
677         if (port == 0 || port == SSH_DEFAULT_PORT)
678                 return(xstrdup(host));
679         if (asprintf(&hoststr, "[%s]:%d", host, (int)port) == -1)
680                 fatal("put_host_port: asprintf: %s", strerror(errno));
681         debug3("put_host_port: %s", hoststr);
682         return hoststr;
683 }
684
685 /*
686  * Search for next delimiter between hostnames/addresses and ports.
687  * Argument may be modified (for termination).
688  * Returns *cp if parsing succeeds.
689  * *cp is set to the start of the next field, if one was found.
690  * The delimiter char, if present, is stored in delim.
691  * If this is the last field, *cp is set to NULL.
692  */
693 char *
694 hpdelim2(char **cp, char *delim)
695 {
696         char *s, *old;
697
698         if (cp == NULL || *cp == NULL)
699                 return NULL;
700
701         old = s = *cp;
702         if (*s == '[') {
703                 if ((s = strchr(s, ']')) == NULL)
704                         return NULL;
705                 else
706                         s++;
707         } else if ((s = strpbrk(s, ":/")) == NULL)
708                 s = *cp + strlen(*cp); /* skip to end (see first case below) */
709
710         switch (*s) {
711         case '\0':
712                 *cp = NULL;     /* no more fields*/
713                 break;
714
715         case ':':
716         case '/':
717                 if (delim != NULL)
718                         *delim = *s;
719                 *s = '\0';      /* terminate */
720                 *cp = s + 1;
721                 break;
722
723         default:
724                 return NULL;
725         }
726
727         return old;
728 }
729
730 /* The common case: only accept colon as delimiter. */
731 char *
732 hpdelim(char **cp)
733 {
734         char *r, delim = '\0';
735
736         r =  hpdelim2(cp, &delim);
737         if (delim == '/')
738                 return NULL;
739         return r;
740 }
741
742 char *
743 cleanhostname(char *host)
744 {
745         if (*host == '[' && host[strlen(host) - 1] == ']') {
746                 host[strlen(host) - 1] = '\0';
747                 return (host + 1);
748         } else
749                 return host;
750 }
751
752 char *
753 colon(char *cp)
754 {
755         int flag = 0;
756
757         if (*cp == ':')         /* Leading colon is part of file name. */
758                 return NULL;
759         if (*cp == '[')
760                 flag = 1;
761
762         for (; *cp; ++cp) {
763                 if (*cp == '@' && *(cp+1) == '[')
764                         flag = 1;
765                 if (*cp == ']' && *(cp+1) == ':' && flag)
766                         return (cp+1);
767                 if (*cp == ':' && !flag)
768                         return (cp);
769                 if (*cp == '/')
770                         return NULL;
771         }
772         return NULL;
773 }
774
775 /*
776  * Parse a [user@]host:[path] string.
777  * Caller must free returned user, host and path.
778  * Any of the pointer return arguments may be NULL (useful for syntax checking).
779  * If user was not specified then *userp will be set to NULL.
780  * If host was not specified then *hostp will be set to NULL.
781  * If path was not specified then *pathp will be set to ".".
782  * Returns 0 on success, -1 on failure.
783  */
784 int
785 parse_user_host_path(const char *s, char **userp, char **hostp, char **pathp)
786 {
787         char *user = NULL, *host = NULL, *path = NULL;
788         char *sdup, *tmp;
789         int ret = -1;
790
791         if (userp != NULL)
792                 *userp = NULL;
793         if (hostp != NULL)
794                 *hostp = NULL;
795         if (pathp != NULL)
796                 *pathp = NULL;
797
798         sdup = xstrdup(s);
799
800         /* Check for remote syntax: [user@]host:[path] */
801         if ((tmp = colon(sdup)) == NULL)
802                 goto out;
803
804         /* Extract optional path */
805         *tmp++ = '\0';
806         if (*tmp == '\0')
807                 tmp = ".";
808         path = xstrdup(tmp);
809
810         /* Extract optional user and mandatory host */
811         tmp = strrchr(sdup, '@');
812         if (tmp != NULL) {
813                 *tmp++ = '\0';
814                 host = xstrdup(cleanhostname(tmp));
815                 if (*sdup != '\0')
816                         user = xstrdup(sdup);
817         } else {
818                 host = xstrdup(cleanhostname(sdup));
819                 user = NULL;
820         }
821
822         /* Success */
823         if (userp != NULL) {
824                 *userp = user;
825                 user = NULL;
826         }
827         if (hostp != NULL) {
828                 *hostp = host;
829                 host = NULL;
830         }
831         if (pathp != NULL) {
832                 *pathp = path;
833                 path = NULL;
834         }
835         ret = 0;
836 out:
837         free(sdup);
838         free(user);
839         free(host);
840         free(path);
841         return ret;
842 }
843
844 /*
845  * Parse a [user@]host[:port] string.
846  * Caller must free returned user and host.
847  * Any of the pointer return arguments may be NULL (useful for syntax checking).
848  * If user was not specified then *userp will be set to NULL.
849  * If port was not specified then *portp will be -1.
850  * Returns 0 on success, -1 on failure.
851  */
852 int
853 parse_user_host_port(const char *s, char **userp, char **hostp, int *portp)
854 {
855         char *sdup, *cp, *tmp;
856         char *user = NULL, *host = NULL;
857         int port = -1, ret = -1;
858
859         if (userp != NULL)
860                 *userp = NULL;
861         if (hostp != NULL)
862                 *hostp = NULL;
863         if (portp != NULL)
864                 *portp = -1;
865
866         if ((sdup = tmp = strdup(s)) == NULL)
867                 return -1;
868         /* Extract optional username */
869         if ((cp = strrchr(tmp, '@')) != NULL) {
870                 *cp = '\0';
871                 if (*tmp == '\0')
872                         goto out;
873                 if ((user = strdup(tmp)) == NULL)
874                         goto out;
875                 tmp = cp + 1;
876         }
877         /* Extract mandatory hostname */
878         if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0')
879                 goto out;
880         host = xstrdup(cleanhostname(cp));
881         /* Convert and verify optional port */
882         if (tmp != NULL && *tmp != '\0') {
883                 if ((port = a2port(tmp)) <= 0)
884                         goto out;
885         }
886         /* Success */
887         if (userp != NULL) {
888                 *userp = user;
889                 user = NULL;
890         }
891         if (hostp != NULL) {
892                 *hostp = host;
893                 host = NULL;
894         }
895         if (portp != NULL)
896                 *portp = port;
897         ret = 0;
898  out:
899         free(sdup);
900         free(user);
901         free(host);
902         return ret;
903 }
904
905 /*
906  * Converts a two-byte hex string to decimal.
907  * Returns the decimal value or -1 for invalid input.
908  */
909 static int
910 hexchar(const char *s)
911 {
912         unsigned char result[2];
913         int i;
914
915         for (i = 0; i < 2; i++) {
916                 if (s[i] >= '0' && s[i] <= '9')
917                         result[i] = (unsigned char)(s[i] - '0');
918                 else if (s[i] >= 'a' && s[i] <= 'f')
919                         result[i] = (unsigned char)(s[i] - 'a') + 10;
920                 else if (s[i] >= 'A' && s[i] <= 'F')
921                         result[i] = (unsigned char)(s[i] - 'A') + 10;
922                 else
923                         return -1;
924         }
925         return (result[0] << 4) | result[1];
926 }
927
928 /*
929  * Decode an url-encoded string.
930  * Returns a newly allocated string on success or NULL on failure.
931  */
932 static char *
933 urldecode(const char *src)
934 {
935         char *ret, *dst;
936         int ch;
937         size_t srclen;
938
939         if ((srclen = strlen(src)) >= SIZE_MAX)
940                 fatal_f("input too large");
941         ret = xmalloc(srclen + 1);
942         for (dst = ret; *src != '\0'; src++) {
943                 switch (*src) {
944                 case '+':
945                         *dst++ = ' ';
946                         break;
947                 case '%':
948                         if (!isxdigit((unsigned char)src[1]) ||
949                             !isxdigit((unsigned char)src[2]) ||
950                             (ch = hexchar(src + 1)) == -1) {
951                                 free(ret);
952                                 return NULL;
953                         }
954                         *dst++ = ch;
955                         src += 2;
956                         break;
957                 default:
958                         *dst++ = *src;
959                         break;
960                 }
961         }
962         *dst = '\0';
963
964         return ret;
965 }
966
967 /*
968  * Parse an (scp|ssh|sftp)://[user@]host[:port][/path] URI.
969  * See https://tools.ietf.org/html/draft-ietf-secsh-scp-sftp-ssh-uri-04
970  * Either user or path may be url-encoded (but not host or port).
971  * Caller must free returned user, host and path.
972  * Any of the pointer return arguments may be NULL (useful for syntax checking)
973  * but the scheme must always be specified.
974  * If user was not specified then *userp will be set to NULL.
975  * If port was not specified then *portp will be -1.
976  * If path was not specified then *pathp will be set to NULL.
977  * Returns 0 on success, 1 if non-uri/wrong scheme, -1 on error/invalid uri.
978  */
979 int
980 parse_uri(const char *scheme, const char *uri, char **userp, char **hostp,
981     int *portp, char **pathp)
982 {
983         char *uridup, *cp, *tmp, ch;
984         char *user = NULL, *host = NULL, *path = NULL;
985         int port = -1, ret = -1;
986         size_t len;
987
988         len = strlen(scheme);
989         if (strncmp(uri, scheme, len) != 0 || strncmp(uri + len, "://", 3) != 0)
990                 return 1;
991         uri += len + 3;
992
993         if (userp != NULL)
994                 *userp = NULL;
995         if (hostp != NULL)
996                 *hostp = NULL;
997         if (portp != NULL)
998                 *portp = -1;
999         if (pathp != NULL)
1000                 *pathp = NULL;
1001
1002         uridup = tmp = xstrdup(uri);
1003
1004         /* Extract optional ssh-info (username + connection params) */
1005         if ((cp = strchr(tmp, '@')) != NULL) {
1006                 char *delim;
1007
1008                 *cp = '\0';
1009                 /* Extract username and connection params */
1010                 if ((delim = strchr(tmp, ';')) != NULL) {
1011                         /* Just ignore connection params for now */
1012                         *delim = '\0';
1013                 }
1014                 if (*tmp == '\0') {
1015                         /* Empty username */
1016                         goto out;
1017                 }
1018                 if ((user = urldecode(tmp)) == NULL)
1019                         goto out;
1020                 tmp = cp + 1;
1021         }
1022
1023         /* Extract mandatory hostname */
1024         if ((cp = hpdelim2(&tmp, &ch)) == NULL || *cp == '\0')
1025                 goto out;
1026         host = xstrdup(cleanhostname(cp));
1027         if (!valid_domain(host, 0, NULL))
1028                 goto out;
1029
1030         if (tmp != NULL && *tmp != '\0') {
1031                 if (ch == ':') {
1032                         /* Convert and verify port. */
1033                         if ((cp = strchr(tmp, '/')) != NULL)
1034                                 *cp = '\0';
1035                         if ((port = a2port(tmp)) <= 0)
1036                                 goto out;
1037                         tmp = cp ? cp + 1 : NULL;
1038                 }
1039                 if (tmp != NULL && *tmp != '\0') {
1040                         /* Extract optional path */
1041                         if ((path = urldecode(tmp)) == NULL)
1042                                 goto out;
1043                 }
1044         }
1045
1046         /* Success */
1047         if (userp != NULL) {
1048                 *userp = user;
1049                 user = NULL;
1050         }
1051         if (hostp != NULL) {
1052                 *hostp = host;
1053                 host = NULL;
1054         }
1055         if (portp != NULL)
1056                 *portp = port;
1057         if (pathp != NULL) {
1058                 *pathp = path;
1059                 path = NULL;
1060         }
1061         ret = 0;
1062  out:
1063         free(uridup);
1064         free(user);
1065         free(host);
1066         free(path);
1067         return ret;
1068 }
1069
1070 /* function to assist building execv() arguments */
1071 void
1072 addargs(arglist *args, char *fmt, ...)
1073 {
1074         va_list ap;
1075         char *cp;
1076         u_int nalloc;
1077         int r;
1078
1079         va_start(ap, fmt);
1080         r = vasprintf(&cp, fmt, ap);
1081         va_end(ap);
1082         if (r == -1)
1083                 fatal_f("argument too long");
1084
1085         nalloc = args->nalloc;
1086         if (args->list == NULL) {
1087                 nalloc = 32;
1088                 args->num = 0;
1089         } else if (args->num > (256 * 1024))
1090                 fatal_f("too many arguments");
1091         else if (args->num >= args->nalloc)
1092                 fatal_f("arglist corrupt");
1093         else if (args->num+2 >= nalloc)
1094                 nalloc *= 2;
1095
1096         args->list = xrecallocarray(args->list, args->nalloc,
1097             nalloc, sizeof(char *));
1098         args->nalloc = nalloc;
1099         args->list[args->num++] = cp;
1100         args->list[args->num] = NULL;
1101 }
1102
1103 void
1104 replacearg(arglist *args, u_int which, char *fmt, ...)
1105 {
1106         va_list ap;
1107         char *cp;
1108         int r;
1109
1110         va_start(ap, fmt);
1111         r = vasprintf(&cp, fmt, ap);
1112         va_end(ap);
1113         if (r == -1)
1114                 fatal_f("argument too long");
1115         if (args->list == NULL || args->num >= args->nalloc)
1116                 fatal_f("arglist corrupt");
1117
1118         if (which >= args->num)
1119                 fatal_f("tried to replace invalid arg %d >= %d",
1120                     which, args->num);
1121         free(args->list[which]);
1122         args->list[which] = cp;
1123 }
1124
1125 void
1126 freeargs(arglist *args)
1127 {
1128         u_int i;
1129
1130         if (args == NULL)
1131                 return;
1132         if (args->list != NULL && args->num < args->nalloc) {
1133                 for (i = 0; i < args->num; i++)
1134                         free(args->list[i]);
1135                 free(args->list);
1136         }
1137         args->nalloc = args->num = 0;
1138         args->list = NULL;
1139 }
1140
1141 /*
1142  * Expands tildes in the file name.  Returns data allocated by xmalloc.
1143  * Warning: this calls getpw*.
1144  */
1145 int
1146 tilde_expand(const char *filename, uid_t uid, char **retp)
1147 {
1148         char *ocopy = NULL, *copy, *s = NULL;
1149         const char *path = NULL, *user = NULL;
1150         struct passwd *pw;
1151         size_t len;
1152         int ret = -1, r, slash;
1153
1154         *retp = NULL;
1155         if (*filename != '~') {
1156                 *retp = xstrdup(filename);
1157                 return 0;
1158         }
1159         ocopy = copy = xstrdup(filename + 1);
1160
1161         if (*copy == '\0')                              /* ~ */
1162                 path = NULL;
1163         else if (*copy == '/') {
1164                 copy += strspn(copy, "/");
1165                 if (*copy == '\0')
1166                         path = NULL;                    /* ~/ */
1167                 else
1168                         path = copy;                    /* ~/path */
1169         } else {
1170                 user = copy;
1171                 if ((path = strchr(copy, '/')) != NULL) {
1172                         copy[path - copy] = '\0';
1173                         path++;
1174                         path += strspn(path, "/");
1175                         if (*path == '\0')              /* ~user/ */
1176                                 path = NULL;
1177                         /* else                          ~user/path */
1178                 }
1179                 /* else                                 ~user */
1180         }
1181         if (user != NULL) {
1182                 if ((pw = getpwnam(user)) == NULL) {
1183                         error_f("No such user %s", user);
1184                         goto out;
1185                 }
1186         } else if ((pw = getpwuid(uid)) == NULL) {
1187                 error_f("No such uid %ld", (long)uid);
1188                 goto out;
1189         }
1190
1191         /* Make sure directory has a trailing '/' */
1192         slash = (len = strlen(pw->pw_dir)) == 0 || pw->pw_dir[len - 1] != '/';
1193
1194         if ((r = xasprintf(&s, "%s%s%s", pw->pw_dir,
1195             slash ? "/" : "", path != NULL ? path : "")) <= 0) {
1196                 error_f("xasprintf failed");
1197                 goto out;
1198         }
1199         if (r >= PATH_MAX) {
1200                 error_f("Path too long");
1201                 goto out;
1202         }
1203         /* success */
1204         ret = 0;
1205         *retp = s;
1206         s = NULL;
1207  out:
1208         free(s);
1209         free(ocopy);
1210         return ret;
1211 }
1212
1213 char *
1214 tilde_expand_filename(const char *filename, uid_t uid)
1215 {
1216         char *ret;
1217
1218         if (tilde_expand(filename, uid, &ret) != 0)
1219                 cleanup_exit(255);
1220         return ret;
1221 }
1222
1223 /*
1224  * Expand a string with a set of %[char] escapes and/or ${ENVIRONMENT}
1225  * substitutions.  A number of escapes may be specified as
1226  * (char *escape_chars, char *replacement) pairs. The list must be terminated
1227  * by a NULL escape_char. Returns replaced string in memory allocated by
1228  * xmalloc which the caller must free.
1229  */
1230 static char *
1231 vdollar_percent_expand(int *parseerror, int dollar, int percent,
1232     const char *string, va_list ap)
1233 {
1234 #define EXPAND_MAX_KEYS 16
1235         u_int num_keys = 0, i;
1236         struct {
1237                 const char *key;
1238                 const char *repl;
1239         } keys[EXPAND_MAX_KEYS];
1240         struct sshbuf *buf;
1241         int r, missingvar = 0;
1242         char *ret = NULL, *var, *varend, *val;
1243         size_t len;
1244
1245         if ((buf = sshbuf_new()) == NULL)
1246                 fatal_f("sshbuf_new failed");
1247         if (parseerror == NULL)
1248                 fatal_f("null parseerror arg");
1249         *parseerror = 1;
1250
1251         /* Gather keys if we're doing percent expansion. */
1252         if (percent) {
1253                 for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
1254                         keys[num_keys].key = va_arg(ap, char *);
1255                         if (keys[num_keys].key == NULL)
1256                                 break;
1257                         keys[num_keys].repl = va_arg(ap, char *);
1258                         if (keys[num_keys].repl == NULL) {
1259                                 fatal_f("NULL replacement for token %s",
1260                                     keys[num_keys].key);
1261                         }
1262                 }
1263                 if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
1264                         fatal_f("too many keys");
1265                 if (num_keys == 0)
1266                         fatal_f("percent expansion without token list");
1267         }
1268
1269         /* Expand string */
1270         for (i = 0; *string != '\0'; string++) {
1271                 /* Optionally process ${ENVIRONMENT} expansions. */
1272                 if (dollar && string[0] == '$' && string[1] == '{') {
1273                         string += 2;  /* skip over '${' */
1274                         if ((varend = strchr(string, '}')) == NULL) {
1275                                 error_f("environment variable '%s' missing "
1276                                     "closing '}'", string);
1277                                 goto out;
1278                         }
1279                         len = varend - string;
1280                         if (len == 0) {
1281                                 error_f("zero-length environment variable");
1282                                 goto out;
1283                         }
1284                         var = xmalloc(len + 1);
1285                         (void)strlcpy(var, string, len + 1);
1286                         if ((val = getenv(var)) == NULL) {
1287                                 error_f("env var ${%s} has no value", var);
1288                                 missingvar = 1;
1289                         } else {
1290                                 debug3_f("expand ${%s} -> '%s'", var, val);
1291                                 if ((r = sshbuf_put(buf, val, strlen(val))) !=0)
1292                                         fatal_fr(r, "sshbuf_put ${}");
1293                         }
1294                         free(var);
1295                         string += len;
1296                         continue;
1297                 }
1298
1299                 /*
1300                  * Process percent expansions if we have a list of TOKENs.
1301                  * If we're not doing percent expansion everything just gets
1302                  * appended here.
1303                  */
1304                 if (*string != '%' || !percent) {
1305  append:
1306                         if ((r = sshbuf_put_u8(buf, *string)) != 0)
1307                                 fatal_fr(r, "sshbuf_put_u8 %%");
1308                         continue;
1309                 }
1310                 string++;
1311                 /* %% case */
1312                 if (*string == '%')
1313                         goto append;
1314                 if (*string == '\0') {
1315                         error_f("invalid format");
1316                         goto out;
1317                 }
1318                 for (i = 0; i < num_keys; i++) {
1319                         if (strchr(keys[i].key, *string) != NULL) {
1320                                 if ((r = sshbuf_put(buf, keys[i].repl,
1321                                     strlen(keys[i].repl))) != 0)
1322                                         fatal_fr(r, "sshbuf_put %%-repl");
1323                                 break;
1324                         }
1325                 }
1326                 if (i >= num_keys) {
1327                         error_f("unknown key %%%c", *string);
1328                         goto out;
1329                 }
1330         }
1331         if (!missingvar && (ret = sshbuf_dup_string(buf)) == NULL)
1332                 fatal_f("sshbuf_dup_string failed");
1333         *parseerror = 0;
1334  out:
1335         sshbuf_free(buf);
1336         return *parseerror ? NULL : ret;
1337 #undef EXPAND_MAX_KEYS
1338 }
1339
1340 /*
1341  * Expand only environment variables.
1342  * Note that although this function is variadic like the other similar
1343  * functions, any such arguments will be unused.
1344  */
1345
1346 char *
1347 dollar_expand(int *parseerr, const char *string, ...)
1348 {
1349         char *ret;
1350         int err;
1351         va_list ap;
1352
1353         va_start(ap, string);
1354         ret = vdollar_percent_expand(&err, 1, 0, string, ap);
1355         va_end(ap);
1356         if (parseerr != NULL)
1357                 *parseerr = err;
1358         return ret;
1359 }
1360
1361 /*
1362  * Returns expanded string or NULL if a specified environment variable is
1363  * not defined, or calls fatal if the string is invalid.
1364  */
1365 char *
1366 percent_expand(const char *string, ...)
1367 {
1368         char *ret;
1369         int err;
1370         va_list ap;
1371
1372         va_start(ap, string);
1373         ret = vdollar_percent_expand(&err, 0, 1, string, ap);
1374         va_end(ap);
1375         if (err)
1376                 fatal_f("failed");
1377         return ret;
1378 }
1379
1380 /*
1381  * Returns expanded string or NULL if a specified environment variable is
1382  * not defined, or calls fatal if the string is invalid.
1383  */
1384 char *
1385 percent_dollar_expand(const char *string, ...)
1386 {
1387         char *ret;
1388         int err;
1389         va_list ap;
1390
1391         va_start(ap, string);
1392         ret = vdollar_percent_expand(&err, 1, 1, string, ap);
1393         va_end(ap);
1394         if (err)
1395                 fatal_f("failed");
1396         return ret;
1397 }
1398
1399 int
1400 tun_open(int tun, int mode, char **ifname)
1401 {
1402 #if defined(CUSTOM_SYS_TUN_OPEN)
1403         return (sys_tun_open(tun, mode, ifname));
1404 #elif defined(SSH_TUN_OPENBSD)
1405         struct ifreq ifr;
1406         char name[100];
1407         int fd = -1, sock;
1408         const char *tunbase = "tun";
1409
1410         if (ifname != NULL)
1411                 *ifname = NULL;
1412
1413         if (mode == SSH_TUNMODE_ETHERNET)
1414                 tunbase = "tap";
1415
1416         /* Open the tunnel device */
1417         if (tun <= SSH_TUNID_MAX) {
1418                 snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
1419                 fd = open(name, O_RDWR);
1420         } else if (tun == SSH_TUNID_ANY) {
1421                 for (tun = 100; tun >= 0; tun--) {
1422                         snprintf(name, sizeof(name), "/dev/%s%d",
1423                             tunbase, tun);
1424                         if ((fd = open(name, O_RDWR)) >= 0)
1425                                 break;
1426                 }
1427         } else {
1428                 debug_f("invalid tunnel %u", tun);
1429                 return -1;
1430         }
1431
1432         if (fd == -1) {
1433                 debug_f("%s open: %s", name, strerror(errno));
1434                 return -1;
1435         }
1436
1437         debug_f("%s mode %d fd %d", name, mode, fd);
1438
1439         /* Bring interface up if it is not already */
1440         snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
1441         if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
1442                 goto failed;
1443
1444         if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
1445                 debug_f("get interface %s flags: %s", ifr.ifr_name,
1446                     strerror(errno));
1447                 goto failed;
1448         }
1449
1450         if (!(ifr.ifr_flags & IFF_UP)) {
1451                 ifr.ifr_flags |= IFF_UP;
1452                 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
1453                         debug_f("activate interface %s: %s", ifr.ifr_name,
1454                             strerror(errno));
1455                         goto failed;
1456                 }
1457         }
1458
1459         if (ifname != NULL)
1460                 *ifname = xstrdup(ifr.ifr_name);
1461
1462         close(sock);
1463         return fd;
1464
1465  failed:
1466         if (fd >= 0)
1467                 close(fd);
1468         if (sock >= 0)
1469                 close(sock);
1470         return -1;
1471 #else
1472         error("Tunnel interfaces are not supported on this platform");
1473         return (-1);
1474 #endif
1475 }
1476
1477 void
1478 sanitise_stdfd(void)
1479 {
1480         int nullfd, dupfd;
1481
1482         if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1483                 fprintf(stderr, "Couldn't open /dev/null: %s\n",
1484                     strerror(errno));
1485                 exit(1);
1486         }
1487         while (++dupfd <= STDERR_FILENO) {
1488                 /* Only populate closed fds. */
1489                 if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
1490                         if (dup2(nullfd, dupfd) == -1) {
1491                                 fprintf(stderr, "dup2: %s\n", strerror(errno));
1492                                 exit(1);
1493                         }
1494                 }
1495         }
1496         if (nullfd > STDERR_FILENO)
1497                 close(nullfd);
1498 }
1499
1500 char *
1501 tohex(const void *vp, size_t l)
1502 {
1503         const u_char *p = (const u_char *)vp;
1504         char b[3], *r;
1505         size_t i, hl;
1506
1507         if (l > 65536)
1508                 return xstrdup("tohex: length > 65536");
1509
1510         hl = l * 2 + 1;
1511         r = xcalloc(1, hl);
1512         for (i = 0; i < l; i++) {
1513                 snprintf(b, sizeof(b), "%02x", p[i]);
1514                 strlcat(r, b, hl);
1515         }
1516         return (r);
1517 }
1518
1519 /*
1520  * Extend string *sp by the specified format. If *sp is not NULL (or empty),
1521  * then the separator 'sep' will be prepended before the formatted arguments.
1522  * Extended strings are heap allocated.
1523  */
1524 void
1525 xextendf(char **sp, const char *sep, const char *fmt, ...)
1526 {
1527         va_list ap;
1528         char *tmp1, *tmp2;
1529
1530         va_start(ap, fmt);
1531         xvasprintf(&tmp1, fmt, ap);
1532         va_end(ap);
1533
1534         if (*sp == NULL || **sp == '\0') {
1535                 free(*sp);
1536                 *sp = tmp1;
1537                 return;
1538         }
1539         xasprintf(&tmp2, "%s%s%s", *sp, sep == NULL ? "" : sep, tmp1);
1540         free(tmp1);
1541         free(*sp);
1542         *sp = tmp2;
1543 }
1544
1545
1546 u_int64_t
1547 get_u64(const void *vp)
1548 {
1549         const u_char *p = (const u_char *)vp;
1550         u_int64_t v;
1551
1552         v  = (u_int64_t)p[0] << 56;
1553         v |= (u_int64_t)p[1] << 48;
1554         v |= (u_int64_t)p[2] << 40;
1555         v |= (u_int64_t)p[3] << 32;
1556         v |= (u_int64_t)p[4] << 24;
1557         v |= (u_int64_t)p[5] << 16;
1558         v |= (u_int64_t)p[6] << 8;
1559         v |= (u_int64_t)p[7];
1560
1561         return (v);
1562 }
1563
1564 u_int32_t
1565 get_u32(const void *vp)
1566 {
1567         const u_char *p = (const u_char *)vp;
1568         u_int32_t v;
1569
1570         v  = (u_int32_t)p[0] << 24;
1571         v |= (u_int32_t)p[1] << 16;
1572         v |= (u_int32_t)p[2] << 8;
1573         v |= (u_int32_t)p[3];
1574
1575         return (v);
1576 }
1577
1578 u_int32_t
1579 get_u32_le(const void *vp)
1580 {
1581         const u_char *p = (const u_char *)vp;
1582         u_int32_t v;
1583
1584         v  = (u_int32_t)p[0];
1585         v |= (u_int32_t)p[1] << 8;
1586         v |= (u_int32_t)p[2] << 16;
1587         v |= (u_int32_t)p[3] << 24;
1588
1589         return (v);
1590 }
1591
1592 u_int16_t
1593 get_u16(const void *vp)
1594 {
1595         const u_char *p = (const u_char *)vp;
1596         u_int16_t v;
1597
1598         v  = (u_int16_t)p[0] << 8;
1599         v |= (u_int16_t)p[1];
1600
1601         return (v);
1602 }
1603
1604 void
1605 put_u64(void *vp, u_int64_t v)
1606 {
1607         u_char *p = (u_char *)vp;
1608
1609         p[0] = (u_char)(v >> 56) & 0xff;
1610         p[1] = (u_char)(v >> 48) & 0xff;
1611         p[2] = (u_char)(v >> 40) & 0xff;
1612         p[3] = (u_char)(v >> 32) & 0xff;
1613         p[4] = (u_char)(v >> 24) & 0xff;
1614         p[5] = (u_char)(v >> 16) & 0xff;
1615         p[6] = (u_char)(v >> 8) & 0xff;
1616         p[7] = (u_char)v & 0xff;
1617 }
1618
1619 void
1620 put_u32(void *vp, u_int32_t v)
1621 {
1622         u_char *p = (u_char *)vp;
1623
1624         p[0] = (u_char)(v >> 24) & 0xff;
1625         p[1] = (u_char)(v >> 16) & 0xff;
1626         p[2] = (u_char)(v >> 8) & 0xff;
1627         p[3] = (u_char)v & 0xff;
1628 }
1629
1630 void
1631 put_u32_le(void *vp, u_int32_t v)
1632 {
1633         u_char *p = (u_char *)vp;
1634
1635         p[0] = (u_char)v & 0xff;
1636         p[1] = (u_char)(v >> 8) & 0xff;
1637         p[2] = (u_char)(v >> 16) & 0xff;
1638         p[3] = (u_char)(v >> 24) & 0xff;
1639 }
1640
1641 void
1642 put_u16(void *vp, u_int16_t v)
1643 {
1644         u_char *p = (u_char *)vp;
1645
1646         p[0] = (u_char)(v >> 8) & 0xff;
1647         p[1] = (u_char)v & 0xff;
1648 }
1649
1650 void
1651 ms_subtract_diff(struct timeval *start, int *ms)
1652 {
1653         struct timeval diff, finish;
1654
1655         monotime_tv(&finish);
1656         timersub(&finish, start, &diff);
1657         *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
1658 }
1659
1660 void
1661 ms_to_timespec(struct timespec *ts, int ms)
1662 {
1663         if (ms < 0)
1664                 ms = 0;
1665         ts->tv_sec = ms / 1000;
1666         ts->tv_nsec = (ms % 1000) * 1000 * 1000;
1667 }
1668
1669 void
1670 monotime_ts(struct timespec *ts)
1671 {
1672         struct timeval tv;
1673 #if defined(HAVE_CLOCK_GETTIME) && (defined(CLOCK_BOOTTIME) || \
1674     defined(CLOCK_MONOTONIC) || defined(CLOCK_REALTIME))
1675         static int gettime_failed = 0;
1676
1677         if (!gettime_failed) {
1678 # ifdef CLOCK_BOOTTIME
1679                 if (clock_gettime(CLOCK_BOOTTIME, ts) == 0)
1680                         return;
1681 # endif /* CLOCK_BOOTTIME */
1682 # ifdef CLOCK_MONOTONIC
1683                 if (clock_gettime(CLOCK_MONOTONIC, ts) == 0)
1684                         return;
1685 # endif /* CLOCK_MONOTONIC */
1686 # ifdef CLOCK_REALTIME
1687                 /* Not monotonic, but we're almost out of options here. */
1688                 if (clock_gettime(CLOCK_REALTIME, ts) == 0)
1689                         return;
1690 # endif /* CLOCK_REALTIME */
1691                 debug3("clock_gettime: %s", strerror(errno));
1692                 gettime_failed = 1;
1693         }
1694 #endif /* HAVE_CLOCK_GETTIME && (BOOTTIME || MONOTONIC || REALTIME) */
1695         gettimeofday(&tv, NULL);
1696         ts->tv_sec = tv.tv_sec;
1697         ts->tv_nsec = (long)tv.tv_usec * 1000;
1698 }
1699
1700 void
1701 monotime_tv(struct timeval *tv)
1702 {
1703         struct timespec ts;
1704
1705         monotime_ts(&ts);
1706         tv->tv_sec = ts.tv_sec;
1707         tv->tv_usec = ts.tv_nsec / 1000;
1708 }
1709
1710 time_t
1711 monotime(void)
1712 {
1713         struct timespec ts;
1714
1715         monotime_ts(&ts);
1716         return ts.tv_sec;
1717 }
1718
1719 double
1720 monotime_double(void)
1721 {
1722         struct timespec ts;
1723
1724         monotime_ts(&ts);
1725         return ts.tv_sec + ((double)ts.tv_nsec / 1000000000);
1726 }
1727
1728 void
1729 bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
1730 {
1731         bw->buflen = buflen;
1732         bw->rate = kbps;
1733         bw->thresh = buflen;
1734         bw->lamt = 0;
1735         timerclear(&bw->bwstart);
1736         timerclear(&bw->bwend);
1737 }
1738
1739 /* Callback from read/write loop to insert bandwidth-limiting delays */
1740 void
1741 bandwidth_limit(struct bwlimit *bw, size_t read_len)
1742 {
1743         u_int64_t waitlen;
1744         struct timespec ts, rm;
1745
1746         bw->lamt += read_len;
1747         if (!timerisset(&bw->bwstart)) {
1748                 monotime_tv(&bw->bwstart);
1749                 return;
1750         }
1751         if (bw->lamt < bw->thresh)
1752                 return;
1753
1754         monotime_tv(&bw->bwend);
1755         timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
1756         if (!timerisset(&bw->bwend))
1757                 return;
1758
1759         bw->lamt *= 8;
1760         waitlen = (double)1000000L * bw->lamt / bw->rate;
1761
1762         bw->bwstart.tv_sec = waitlen / 1000000L;
1763         bw->bwstart.tv_usec = waitlen % 1000000L;
1764
1765         if (timercmp(&bw->bwstart, &bw->bwend, >)) {
1766                 timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
1767
1768                 /* Adjust the wait time */
1769                 if (bw->bwend.tv_sec) {
1770                         bw->thresh /= 2;
1771                         if (bw->thresh < bw->buflen / 4)
1772                                 bw->thresh = bw->buflen / 4;
1773                 } else if (bw->bwend.tv_usec < 10000) {
1774                         bw->thresh *= 2;
1775                         if (bw->thresh > bw->buflen * 8)
1776                                 bw->thresh = bw->buflen * 8;
1777                 }
1778
1779                 TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
1780                 while (nanosleep(&ts, &rm) == -1) {
1781                         if (errno != EINTR)
1782                                 break;
1783                         ts = rm;
1784                 }
1785         }
1786
1787         bw->lamt = 0;
1788         monotime_tv(&bw->bwstart);
1789 }
1790
1791 /* Make a template filename for mk[sd]temp() */
1792 void
1793 mktemp_proto(char *s, size_t len)
1794 {
1795         const char *tmpdir;
1796         int r;
1797
1798         if ((tmpdir = getenv("TMPDIR")) != NULL) {
1799                 r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
1800                 if (r > 0 && (size_t)r < len)
1801                         return;
1802         }
1803         r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
1804         if (r < 0 || (size_t)r >= len)
1805                 fatal_f("template string too short");
1806 }
1807
1808 static const struct {
1809         const char *name;
1810         int value;
1811 } ipqos[] = {
1812         { "none", INT_MAX },            /* can't use 0 here; that's CS0 */
1813         { "af11", IPTOS_DSCP_AF11 },
1814         { "af12", IPTOS_DSCP_AF12 },
1815         { "af13", IPTOS_DSCP_AF13 },
1816         { "af21", IPTOS_DSCP_AF21 },
1817         { "af22", IPTOS_DSCP_AF22 },
1818         { "af23", IPTOS_DSCP_AF23 },
1819         { "af31", IPTOS_DSCP_AF31 },
1820         { "af32", IPTOS_DSCP_AF32 },
1821         { "af33", IPTOS_DSCP_AF33 },
1822         { "af41", IPTOS_DSCP_AF41 },
1823         { "af42", IPTOS_DSCP_AF42 },
1824         { "af43", IPTOS_DSCP_AF43 },
1825         { "cs0", IPTOS_DSCP_CS0 },
1826         { "cs1", IPTOS_DSCP_CS1 },
1827         { "cs2", IPTOS_DSCP_CS2 },
1828         { "cs3", IPTOS_DSCP_CS3 },
1829         { "cs4", IPTOS_DSCP_CS4 },
1830         { "cs5", IPTOS_DSCP_CS5 },
1831         { "cs6", IPTOS_DSCP_CS6 },
1832         { "cs7", IPTOS_DSCP_CS7 },
1833         { "ef", IPTOS_DSCP_EF },
1834         { "le", IPTOS_DSCP_LE },
1835         { "lowdelay", IPTOS_LOWDELAY },
1836         { "throughput", IPTOS_THROUGHPUT },
1837         { "reliability", IPTOS_RELIABILITY },
1838         { NULL, -1 }
1839 };
1840
1841 int
1842 parse_ipqos(const char *cp)
1843 {
1844         u_int i;
1845         char *ep;
1846         long val;
1847
1848         if (cp == NULL)
1849                 return -1;
1850         for (i = 0; ipqos[i].name != NULL; i++) {
1851                 if (strcasecmp(cp, ipqos[i].name) == 0)
1852                         return ipqos[i].value;
1853         }
1854         /* Try parsing as an integer */
1855         val = strtol(cp, &ep, 0);
1856         if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1857                 return -1;
1858         return val;
1859 }
1860
1861 const char *
1862 iptos2str(int iptos)
1863 {
1864         int i;
1865         static char iptos_str[sizeof "0xff"];
1866
1867         for (i = 0; ipqos[i].name != NULL; i++) {
1868                 if (ipqos[i].value == iptos)
1869                         return ipqos[i].name;
1870         }
1871         snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1872         return iptos_str;
1873 }
1874
1875 void
1876 lowercase(char *s)
1877 {
1878         for (; *s; s++)
1879                 *s = tolower((u_char)*s);
1880 }
1881
1882 int
1883 unix_listener(const char *path, int backlog, int unlink_first)
1884 {
1885         struct sockaddr_un sunaddr;
1886         int saved_errno, sock;
1887
1888         memset(&sunaddr, 0, sizeof(sunaddr));
1889         sunaddr.sun_family = AF_UNIX;
1890         if (strlcpy(sunaddr.sun_path, path,
1891             sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1892                 error_f("path \"%s\" too long for Unix domain socket", path);
1893                 errno = ENAMETOOLONG;
1894                 return -1;
1895         }
1896
1897         sock = socket(PF_UNIX, SOCK_STREAM, 0);
1898         if (sock == -1) {
1899                 saved_errno = errno;
1900                 error_f("socket: %.100s", strerror(errno));
1901                 errno = saved_errno;
1902                 return -1;
1903         }
1904         if (unlink_first == 1) {
1905                 if (unlink(path) != 0 && errno != ENOENT)
1906                         error("unlink(%s): %.100s", path, strerror(errno));
1907         }
1908         if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1909                 saved_errno = errno;
1910                 error_f("cannot bind to path %s: %s", path, strerror(errno));
1911                 close(sock);
1912                 errno = saved_errno;
1913                 return -1;
1914         }
1915         if (listen(sock, backlog) == -1) {
1916                 saved_errno = errno;
1917                 error_f("cannot listen on path %s: %s", path, strerror(errno));
1918                 close(sock);
1919                 unlink(path);
1920                 errno = saved_errno;
1921                 return -1;
1922         }
1923         return sock;
1924 }
1925
1926 void
1927 sock_set_v6only(int s)
1928 {
1929 #if defined(IPV6_V6ONLY) && !defined(__OpenBSD__)
1930         int on = 1;
1931
1932         debug3("%s: set socket %d IPV6_V6ONLY", __func__, s);
1933         if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1)
1934                 error("setsockopt IPV6_V6ONLY: %s", strerror(errno));
1935 #endif
1936 }
1937
1938 /*
1939  * Compares two strings that maybe be NULL. Returns non-zero if strings
1940  * are both NULL or are identical, returns zero otherwise.
1941  */
1942 static int
1943 strcmp_maybe_null(const char *a, const char *b)
1944 {
1945         if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1946                 return 0;
1947         if (a != NULL && strcmp(a, b) != 0)
1948                 return 0;
1949         return 1;
1950 }
1951
1952 /*
1953  * Compare two forwards, returning non-zero if they are identical or
1954  * zero otherwise.
1955  */
1956 int
1957 forward_equals(const struct Forward *a, const struct Forward *b)
1958 {
1959         if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
1960                 return 0;
1961         if (a->listen_port != b->listen_port)
1962                 return 0;
1963         if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
1964                 return 0;
1965         if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
1966                 return 0;
1967         if (a->connect_port != b->connect_port)
1968                 return 0;
1969         if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
1970                 return 0;
1971         /* allocated_port and handle are not checked */
1972         return 1;
1973 }
1974
1975 /* returns 1 if process is already daemonized, 0 otherwise */
1976 int
1977 daemonized(void)
1978 {
1979         int fd;
1980
1981         if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
1982                 close(fd);
1983                 return 0;       /* have controlling terminal */
1984         }
1985         if (getppid() != 1)
1986                 return 0;       /* parent is not init */
1987         if (getsid(0) != getpid())
1988                 return 0;       /* not session leader */
1989         debug3("already daemonized");
1990         return 1;
1991 }
1992
1993 /*
1994  * Splits 's' into an argument vector. Handles quoted string and basic
1995  * escape characters (\\, \", \'). Caller must free the argument vector
1996  * and its members.
1997  */
1998 int
1999 argv_split(const char *s, int *argcp, char ***argvp, int terminate_on_comment)
2000 {
2001         int r = SSH_ERR_INTERNAL_ERROR;
2002         int argc = 0, quote, i, j;
2003         char *arg, **argv = xcalloc(1, sizeof(*argv));
2004
2005         *argvp = NULL;
2006         *argcp = 0;
2007
2008         for (i = 0; s[i] != '\0'; i++) {
2009                 /* Skip leading whitespace */
2010                 if (s[i] == ' ' || s[i] == '\t')
2011                         continue;
2012                 if (terminate_on_comment && s[i] == '#')
2013                         break;
2014                 /* Start of a token */
2015                 quote = 0;
2016
2017                 argv = xreallocarray(argv, (argc + 2), sizeof(*argv));
2018                 arg = argv[argc++] = xcalloc(1, strlen(s + i) + 1);
2019                 argv[argc] = NULL;
2020
2021                 /* Copy the token in, removing escapes */
2022                 for (j = 0; s[i] != '\0'; i++) {
2023                         if (s[i] == '\\') {
2024                                 if (s[i + 1] == '\'' ||
2025                                     s[i + 1] == '\"' ||
2026                                     s[i + 1] == '\\' ||
2027                                     (quote == 0 && s[i + 1] == ' ')) {
2028                                         i++; /* Skip '\' */
2029                                         arg[j++] = s[i];
2030                                 } else {
2031                                         /* Unrecognised escape */
2032                                         arg[j++] = s[i];
2033                                 }
2034                         } else if (quote == 0 && (s[i] == ' ' || s[i] == '\t'))
2035                                 break; /* done */
2036                         else if (quote == 0 && (s[i] == '\"' || s[i] == '\''))
2037                                 quote = s[i]; /* quote start */
2038                         else if (quote != 0 && s[i] == quote)
2039                                 quote = 0; /* quote end */
2040                         else
2041                                 arg[j++] = s[i];
2042                 }
2043                 if (s[i] == '\0') {
2044                         if (quote != 0) {
2045                                 /* Ran out of string looking for close quote */
2046                                 r = SSH_ERR_INVALID_FORMAT;
2047                                 goto out;
2048                         }
2049                         break;
2050                 }
2051         }
2052         /* Success */
2053         *argcp = argc;
2054         *argvp = argv;
2055         argc = 0;
2056         argv = NULL;
2057         r = 0;
2058  out:
2059         if (argc != 0 && argv != NULL) {
2060                 for (i = 0; i < argc; i++)
2061                         free(argv[i]);
2062                 free(argv);
2063         }
2064         return r;
2065 }
2066
2067 /*
2068  * Reassemble an argument vector into a string, quoting and escaping as
2069  * necessary. Caller must free returned string.
2070  */
2071 char *
2072 argv_assemble(int argc, char **argv)
2073 {
2074         int i, j, ws, r;
2075         char c, *ret;
2076         struct sshbuf *buf, *arg;
2077
2078         if ((buf = sshbuf_new()) == NULL || (arg = sshbuf_new()) == NULL)
2079                 fatal_f("sshbuf_new failed");
2080
2081         for (i = 0; i < argc; i++) {
2082                 ws = 0;
2083                 sshbuf_reset(arg);
2084                 for (j = 0; argv[i][j] != '\0'; j++) {
2085                         r = 0;
2086                         c = argv[i][j];
2087                         switch (c) {
2088                         case ' ':
2089                         case '\t':
2090                                 ws = 1;
2091                                 r = sshbuf_put_u8(arg, c);
2092                                 break;
2093                         case '\\':
2094                         case '\'':
2095                         case '"':
2096                                 if ((r = sshbuf_put_u8(arg, '\\')) != 0)
2097                                         break;
2098                                 /* FALLTHROUGH */
2099                         default:
2100                                 r = sshbuf_put_u8(arg, c);
2101                                 break;
2102                         }
2103                         if (r != 0)
2104                                 fatal_fr(r, "sshbuf_put_u8");
2105                 }
2106                 if ((i != 0 && (r = sshbuf_put_u8(buf, ' ')) != 0) ||
2107                     (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0) ||
2108                     (r = sshbuf_putb(buf, arg)) != 0 ||
2109                     (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0))
2110                         fatal_fr(r, "assemble");
2111         }
2112         if ((ret = malloc(sshbuf_len(buf) + 1)) == NULL)
2113                 fatal_f("malloc failed");
2114         memcpy(ret, sshbuf_ptr(buf), sshbuf_len(buf));
2115         ret[sshbuf_len(buf)] = '\0';
2116         sshbuf_free(buf);
2117         sshbuf_free(arg);
2118         return ret;
2119 }
2120
2121 char *
2122 argv_next(int *argcp, char ***argvp)
2123 {
2124         char *ret = (*argvp)[0];
2125
2126         if (*argcp > 0 && ret != NULL) {
2127                 (*argcp)--;
2128                 (*argvp)++;
2129         }
2130         return ret;
2131 }
2132
2133 void
2134 argv_consume(int *argcp)
2135 {
2136         *argcp = 0;
2137 }
2138
2139 void
2140 argv_free(char **av, int ac)
2141 {
2142         int i;
2143
2144         if (av == NULL)
2145                 return;
2146         for (i = 0; i < ac; i++)
2147                 free(av[i]);
2148         free(av);
2149 }
2150
2151 /* Returns 0 if pid exited cleanly, non-zero otherwise */
2152 int
2153 exited_cleanly(pid_t pid, const char *tag, const char *cmd, int quiet)
2154 {
2155         int status;
2156
2157         while (waitpid(pid, &status, 0) == -1) {
2158                 if (errno != EINTR) {
2159                         error("%s waitpid: %s", tag, strerror(errno));
2160                         return -1;
2161                 }
2162         }
2163         if (WIFSIGNALED(status)) {
2164                 error("%s %s exited on signal %d", tag, cmd, WTERMSIG(status));
2165                 return -1;
2166         } else if (WEXITSTATUS(status) != 0) {
2167                 do_log2(quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_INFO,
2168                     "%s %s failed, status %d", tag, cmd, WEXITSTATUS(status));
2169                 return -1;
2170         }
2171         return 0;
2172 }
2173
2174 /*
2175  * Check a given path for security. This is defined as all components
2176  * of the path to the file must be owned by either the owner of
2177  * of the file or root and no directories must be group or world writable.
2178  *
2179  * XXX Should any specific check be done for sym links ?
2180  *
2181  * Takes a file name, its stat information (preferably from fstat() to
2182  * avoid races), the uid of the expected owner, their home directory and an
2183  * error buffer plus max size as arguments.
2184  *
2185  * Returns 0 on success and -1 on failure
2186  */
2187 int
2188 safe_path(const char *name, struct stat *stp, const char *pw_dir,
2189     uid_t uid, char *err, size_t errlen)
2190 {
2191         char buf[PATH_MAX], homedir[PATH_MAX];
2192         char *cp;
2193         int comparehome = 0;
2194         struct stat st;
2195
2196         if (realpath(name, buf) == NULL) {
2197                 snprintf(err, errlen, "realpath %s failed: %s", name,
2198                     strerror(errno));
2199                 return -1;
2200         }
2201         if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL)
2202                 comparehome = 1;
2203
2204         if (!S_ISREG(stp->st_mode)) {
2205                 snprintf(err, errlen, "%s is not a regular file", buf);
2206                 return -1;
2207         }
2208         if ((!platform_sys_dir_uid(stp->st_uid) && stp->st_uid != uid) ||
2209             (stp->st_mode & 022) != 0) {
2210                 snprintf(err, errlen, "bad ownership or modes for file %s",
2211                     buf);
2212                 return -1;
2213         }
2214
2215         /* for each component of the canonical path, walking upwards */
2216         for (;;) {
2217                 if ((cp = dirname(buf)) == NULL) {
2218                         snprintf(err, errlen, "dirname() failed");
2219                         return -1;
2220                 }
2221                 strlcpy(buf, cp, sizeof(buf));
2222
2223                 if (stat(buf, &st) == -1 ||
2224                     (!platform_sys_dir_uid(st.st_uid) && st.st_uid != uid) ||
2225                     (st.st_mode & 022) != 0) {
2226                         snprintf(err, errlen,
2227                             "bad ownership or modes for directory %s", buf);
2228                         return -1;
2229                 }
2230
2231                 /* If are past the homedir then we can stop */
2232                 if (comparehome && strcmp(homedir, buf) == 0)
2233                         break;
2234
2235                 /*
2236                  * dirname should always complete with a "/" path,
2237                  * but we can be paranoid and check for "." too
2238                  */
2239                 if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
2240                         break;
2241         }
2242         return 0;
2243 }
2244
2245 /*
2246  * Version of safe_path() that accepts an open file descriptor to
2247  * avoid races.
2248  *
2249  * Returns 0 on success and -1 on failure
2250  */
2251 int
2252 safe_path_fd(int fd, const char *file, struct passwd *pw,
2253     char *err, size_t errlen)
2254 {
2255         struct stat st;
2256
2257         /* check the open file to avoid races */
2258         if (fstat(fd, &st) == -1) {
2259                 snprintf(err, errlen, "cannot stat file %s: %s",
2260                     file, strerror(errno));
2261                 return -1;
2262         }
2263         return safe_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen);
2264 }
2265
2266 /*
2267  * Sets the value of the given variable in the environment.  If the variable
2268  * already exists, its value is overridden.
2269  */
2270 void
2271 child_set_env(char ***envp, u_int *envsizep, const char *name,
2272         const char *value)
2273 {
2274         char **env;
2275         u_int envsize;
2276         u_int i, namelen;
2277
2278         if (strchr(name, '=') != NULL) {
2279                 error("Invalid environment variable \"%.100s\"", name);
2280                 return;
2281         }
2282
2283         /*
2284          * If we're passed an uninitialized list, allocate a single null
2285          * entry before continuing.
2286          */
2287         if ((*envp == NULL) != (*envsizep == 0))
2288                 fatal_f("environment size mismatch");
2289         if (*envp == NULL && *envsizep == 0) {
2290                 *envp = xmalloc(sizeof(char *));
2291                 *envp[0] = NULL;
2292                 *envsizep = 1;
2293         }
2294
2295         /*
2296          * Find the slot where the value should be stored.  If the variable
2297          * already exists, we reuse the slot; otherwise we append a new slot
2298          * at the end of the array, expanding if necessary.
2299          */
2300         env = *envp;
2301         namelen = strlen(name);
2302         for (i = 0; env[i]; i++)
2303                 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
2304                         break;
2305         if (env[i]) {
2306                 /* Reuse the slot. */
2307                 free(env[i]);
2308         } else {
2309                 /* New variable.  Expand if necessary. */
2310                 envsize = *envsizep;
2311                 if (i >= envsize - 1) {
2312                         if (envsize >= 1000)
2313                                 fatal("child_set_env: too many env vars");
2314                         envsize += 50;
2315                         env = (*envp) = xreallocarray(env, envsize, sizeof(char *));
2316                         *envsizep = envsize;
2317                 }
2318                 /* Need to set the NULL pointer at end of array beyond the new slot. */
2319                 env[i + 1] = NULL;
2320         }
2321
2322         /* Allocate space and format the variable in the appropriate slot. */
2323         /* XXX xasprintf */
2324         env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
2325         snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
2326 }
2327
2328 /*
2329  * Check and optionally lowercase a domain name, also removes trailing '.'
2330  * Returns 1 on success and 0 on failure, storing an error message in errstr.
2331  */
2332 int
2333 valid_domain(char *name, int makelower, const char **errstr)
2334 {
2335         size_t i, l = strlen(name);
2336         u_char c, last = '\0';
2337         static char errbuf[256];
2338
2339         if (l == 0) {
2340                 strlcpy(errbuf, "empty domain name", sizeof(errbuf));
2341                 goto bad;
2342         }
2343         if (!isalpha((u_char)name[0]) && !isdigit((u_char)name[0])) {
2344                 snprintf(errbuf, sizeof(errbuf), "domain name \"%.100s\" "
2345                     "starts with invalid character", name);
2346                 goto bad;
2347         }
2348         for (i = 0; i < l; i++) {
2349                 c = tolower((u_char)name[i]);
2350                 if (makelower)
2351                         name[i] = (char)c;
2352                 if (last == '.' && c == '.') {
2353                         snprintf(errbuf, sizeof(errbuf), "domain name "
2354                             "\"%.100s\" contains consecutive separators", name);
2355                         goto bad;
2356                 }
2357                 if (c != '.' && c != '-' && !isalnum(c) &&
2358                     c != '_') /* technically invalid, but common */ {
2359                         snprintf(errbuf, sizeof(errbuf), "domain name "
2360                             "\"%.100s\" contains invalid characters", name);
2361                         goto bad;
2362                 }
2363                 last = c;
2364         }
2365         if (name[l - 1] == '.')
2366                 name[l - 1] = '\0';
2367         if (errstr != NULL)
2368                 *errstr = NULL;
2369         return 1;
2370 bad:
2371         if (errstr != NULL)
2372                 *errstr = errbuf;
2373         return 0;
2374 }
2375
2376 /*
2377  * Verify that a environment variable name (not including initial '$') is
2378  * valid; consisting of one or more alphanumeric or underscore characters only.
2379  * Returns 1 on valid, 0 otherwise.
2380  */
2381 int
2382 valid_env_name(const char *name)
2383 {
2384         const char *cp;
2385
2386         if (name[0] == '\0')
2387                 return 0;
2388         for (cp = name; *cp != '\0'; cp++) {
2389                 if (!isalnum((u_char)*cp) && *cp != '_')
2390                         return 0;
2391         }
2392         return 1;
2393 }
2394
2395 const char *
2396 atoi_err(const char *nptr, int *val)
2397 {
2398         const char *errstr = NULL;
2399         long long num;
2400
2401         if (nptr == NULL || *nptr == '\0')
2402                 return "missing";
2403         num = strtonum(nptr, 0, INT_MAX, &errstr);
2404         if (errstr == NULL)
2405                 *val = (int)num;
2406         return errstr;
2407 }
2408
2409 int
2410 parse_absolute_time(const char *s, uint64_t *tp)
2411 {
2412         struct tm tm;
2413         time_t tt;
2414         char buf[32], *fmt;
2415         const char *cp;
2416         size_t l;
2417         int is_utc = 0;
2418
2419         *tp = 0;
2420
2421         l = strlen(s);
2422         if (l > 1 && strcasecmp(s + l - 1, "Z") == 0) {
2423                 is_utc = 1;
2424                 l--;
2425         } else if (l > 3 && strcasecmp(s + l - 3, "UTC") == 0) {
2426                 is_utc = 1;
2427                 l -= 3;
2428         }
2429         /*
2430          * POSIX strptime says "The application shall ensure that there
2431          * is white-space or other non-alphanumeric characters between
2432          * any two conversion specifications" so arrange things this way.
2433          */
2434         switch (l) {
2435         case 8: /* YYYYMMDD */
2436                 fmt = "%Y-%m-%d";
2437                 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
2438                 break;
2439         case 12: /* YYYYMMDDHHMM */
2440                 fmt = "%Y-%m-%dT%H:%M";
2441                 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s",
2442                     s, s + 4, s + 6, s + 8, s + 10);
2443                 break;
2444         case 14: /* YYYYMMDDHHMMSS */
2445                 fmt = "%Y-%m-%dT%H:%M:%S";
2446                 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
2447                     s, s + 4, s + 6, s + 8, s + 10, s + 12);
2448                 break;
2449         default:
2450                 return SSH_ERR_INVALID_FORMAT;
2451         }
2452
2453         memset(&tm, 0, sizeof(tm));
2454         if ((cp = strptime(buf, fmt, &tm)) == NULL || *cp != '\0')
2455                 return SSH_ERR_INVALID_FORMAT;
2456         if (is_utc) {
2457                 if ((tt = timegm(&tm)) < 0)
2458                         return SSH_ERR_INVALID_FORMAT;
2459         } else {
2460                 if ((tt = mktime(&tm)) < 0)
2461                         return SSH_ERR_INVALID_FORMAT;
2462         }
2463         /* success */
2464         *tp = (uint64_t)tt;
2465         return 0;
2466 }
2467
2468 void
2469 format_absolute_time(uint64_t t, char *buf, size_t len)
2470 {
2471         time_t tt = t > SSH_TIME_T_MAX ? SSH_TIME_T_MAX : t;
2472         struct tm tm;
2473
2474         localtime_r(&tt, &tm);
2475         strftime(buf, len, "%Y-%m-%dT%H:%M:%S", &tm);
2476 }
2477
2478 /* check if path is absolute */
2479 int
2480 path_absolute(const char *path)
2481 {
2482         return (*path == '/') ? 1 : 0;
2483 }
2484
2485 void
2486 skip_space(char **cpp)
2487 {
2488         char *cp;
2489
2490         for (cp = *cpp; *cp == ' ' || *cp == '\t'; cp++)
2491                 ;
2492         *cpp = cp;
2493 }
2494
2495 /* authorized_key-style options parsing helpers */
2496
2497 /*
2498  * Match flag 'opt' in *optsp, and if allow_negate is set then also match
2499  * 'no-opt'. Returns -1 if option not matched, 1 if option matches or 0
2500  * if negated option matches.
2501  * If the option or negated option matches, then *optsp is updated to
2502  * point to the first character after the option.
2503  */
2504 int
2505 opt_flag(const char *opt, int allow_negate, const char **optsp)
2506 {
2507         size_t opt_len = strlen(opt);
2508         const char *opts = *optsp;
2509         int negate = 0;
2510
2511         if (allow_negate && strncasecmp(opts, "no-", 3) == 0) {
2512                 opts += 3;
2513                 negate = 1;
2514         }
2515         if (strncasecmp(opts, opt, opt_len) == 0) {
2516                 *optsp = opts + opt_len;
2517                 return negate ? 0 : 1;
2518         }
2519         return -1;
2520 }
2521
2522 char *
2523 opt_dequote(const char **sp, const char **errstrp)
2524 {
2525         const char *s = *sp;
2526         char *ret;
2527         size_t i;
2528
2529         *errstrp = NULL;
2530         if (*s != '"') {
2531                 *errstrp = "missing start quote";
2532                 return NULL;
2533         }
2534         s++;
2535         if ((ret = malloc(strlen((s)) + 1)) == NULL) {
2536                 *errstrp = "memory allocation failed";
2537                 return NULL;
2538         }
2539         for (i = 0; *s != '\0' && *s != '"';) {
2540                 if (s[0] == '\\' && s[1] == '"')
2541                         s++;
2542                 ret[i++] = *s++;
2543         }
2544         if (*s == '\0') {
2545                 *errstrp = "missing end quote";
2546                 free(ret);
2547                 return NULL;
2548         }
2549         ret[i] = '\0';
2550         s++;
2551         *sp = s;
2552         return ret;
2553 }
2554
2555 int
2556 opt_match(const char **opts, const char *term)
2557 {
2558         if (strncasecmp((*opts), term, strlen(term)) == 0 &&
2559             (*opts)[strlen(term)] == '=') {
2560                 *opts += strlen(term) + 1;
2561                 return 1;
2562         }
2563         return 0;
2564 }
2565
2566 void
2567 opt_array_append2(const char *file, const int line, const char *directive,
2568     char ***array, int **iarray, u_int *lp, const char *s, int i)
2569 {
2570
2571         if (*lp >= INT_MAX)
2572                 fatal("%s line %d: Too many %s entries", file, line, directive);
2573
2574         if (iarray != NULL) {
2575                 *iarray = xrecallocarray(*iarray, *lp, *lp + 1,
2576                     sizeof(**iarray));
2577                 (*iarray)[*lp] = i;
2578         }
2579
2580         *array = xrecallocarray(*array, *lp, *lp + 1, sizeof(**array));
2581         (*array)[*lp] = xstrdup(s);
2582         (*lp)++;
2583 }
2584
2585 void
2586 opt_array_append(const char *file, const int line, const char *directive,
2587     char ***array, u_int *lp, const char *s)
2588 {
2589         opt_array_append2(file, line, directive, array, NULL, lp, s, 0);
2590 }
2591
2592 sshsig_t
2593 ssh_signal(int signum, sshsig_t handler)
2594 {
2595         struct sigaction sa, osa;
2596
2597         /* mask all other signals while in handler */
2598         memset(&sa, 0, sizeof(sa));
2599         sa.sa_handler = handler;
2600         sigfillset(&sa.sa_mask);
2601 #if defined(SA_RESTART) && !defined(NO_SA_RESTART)
2602         if (signum != SIGALRM)
2603                 sa.sa_flags = SA_RESTART;
2604 #endif
2605         if (sigaction(signum, &sa, &osa) == -1) {
2606                 debug3("sigaction(%s): %s", strsignal(signum), strerror(errno));
2607                 return SIG_ERR;
2608         }
2609         return osa.sa_handler;
2610 }
2611
2612 int
2613 stdfd_devnull(int do_stdin, int do_stdout, int do_stderr)
2614 {
2615         int devnull, ret = 0;
2616
2617         if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
2618                 error_f("open %s: %s", _PATH_DEVNULL,
2619                     strerror(errno));
2620                 return -1;
2621         }
2622         if ((do_stdin && dup2(devnull, STDIN_FILENO) == -1) ||
2623             (do_stdout && dup2(devnull, STDOUT_FILENO) == -1) ||
2624             (do_stderr && dup2(devnull, STDERR_FILENO) == -1)) {
2625                 error_f("dup2: %s", strerror(errno));
2626                 ret = -1;
2627         }
2628         if (devnull > STDERR_FILENO)
2629                 close(devnull);
2630         return ret;
2631 }
2632
2633 /*
2634  * Runs command in a subprocess with a minimal environment.
2635  * Returns pid on success, 0 on failure.
2636  * The child stdout and stderr maybe captured, left attached or sent to
2637  * /dev/null depending on the contents of flags.
2638  * "tag" is prepended to log messages.
2639  * NB. "command" is only used for logging; the actual command executed is
2640  * av[0].
2641  */
2642 pid_t
2643 subprocess(const char *tag, const char *command,
2644     int ac, char **av, FILE **child, u_int flags,
2645     struct passwd *pw, privdrop_fn *drop_privs, privrestore_fn *restore_privs)
2646 {
2647         FILE *f = NULL;
2648         struct stat st;
2649         int fd, devnull, p[2], i;
2650         pid_t pid;
2651         char *cp, errmsg[512];
2652         u_int nenv = 0;
2653         char **env = NULL;
2654
2655         /* If dropping privs, then must specify user and restore function */
2656         if (drop_privs != NULL && (pw == NULL || restore_privs == NULL)) {
2657                 error("%s: inconsistent arguments", tag); /* XXX fatal? */
2658                 return 0;
2659         }
2660         if (pw == NULL && (pw = getpwuid(getuid())) == NULL) {
2661                 error("%s: no user for current uid", tag);
2662                 return 0;
2663         }
2664         if (child != NULL)
2665                 *child = NULL;
2666
2667         debug3_f("%s command \"%s\" running as %s (flags 0x%x)",
2668             tag, command, pw->pw_name, flags);
2669
2670         /* Check consistency */
2671         if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
2672             (flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0) {
2673                 error_f("inconsistent flags");
2674                 return 0;
2675         }
2676         if (((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0) != (child == NULL)) {
2677                 error_f("inconsistent flags/output");
2678                 return 0;
2679         }
2680
2681         /*
2682          * If executing an explicit binary, then verify the it exists
2683          * and appears safe-ish to execute
2684          */
2685         if (!path_absolute(av[0])) {
2686                 error("%s path is not absolute", tag);
2687                 return 0;
2688         }
2689         if (drop_privs != NULL)
2690                 drop_privs(pw);
2691         if (stat(av[0], &st) == -1) {
2692                 error("Could not stat %s \"%s\": %s", tag,
2693                     av[0], strerror(errno));
2694                 goto restore_return;
2695         }
2696         if ((flags & SSH_SUBPROCESS_UNSAFE_PATH) == 0 &&
2697             safe_path(av[0], &st, NULL, 0, errmsg, sizeof(errmsg)) != 0) {
2698                 error("Unsafe %s \"%s\": %s", tag, av[0], errmsg);
2699                 goto restore_return;
2700         }
2701         /* Prepare to keep the child's stdout if requested */
2702         if (pipe(p) == -1) {
2703                 error("%s: pipe: %s", tag, strerror(errno));
2704  restore_return:
2705                 if (restore_privs != NULL)
2706                         restore_privs();
2707                 return 0;
2708         }
2709         if (restore_privs != NULL)
2710                 restore_privs();
2711
2712         switch ((pid = fork())) {
2713         case -1: /* error */
2714                 error("%s: fork: %s", tag, strerror(errno));
2715                 close(p[0]);
2716                 close(p[1]);
2717                 return 0;
2718         case 0: /* child */
2719                 /* Prepare a minimal environment for the child. */
2720                 if ((flags & SSH_SUBPROCESS_PRESERVE_ENV) == 0) {
2721                         nenv = 5;
2722                         env = xcalloc(sizeof(*env), nenv);
2723                         child_set_env(&env, &nenv, "PATH", _PATH_STDPATH);
2724                         child_set_env(&env, &nenv, "USER", pw->pw_name);
2725                         child_set_env(&env, &nenv, "LOGNAME", pw->pw_name);
2726                         child_set_env(&env, &nenv, "HOME", pw->pw_dir);
2727                         if ((cp = getenv("LANG")) != NULL)
2728                                 child_set_env(&env, &nenv, "LANG", cp);
2729                 }
2730
2731                 for (i = 1; i < NSIG; i++)
2732                         ssh_signal(i, SIG_DFL);
2733
2734                 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
2735                         error("%s: open %s: %s", tag, _PATH_DEVNULL,
2736                             strerror(errno));
2737                         _exit(1);
2738                 }
2739                 if (dup2(devnull, STDIN_FILENO) == -1) {
2740                         error("%s: dup2: %s", tag, strerror(errno));
2741                         _exit(1);
2742                 }
2743
2744                 /* Set up stdout as requested; leave stderr in place for now. */
2745                 fd = -1;
2746                 if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0)
2747                         fd = p[1];
2748                 else if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0)
2749                         fd = devnull;
2750                 if (fd != -1 && dup2(fd, STDOUT_FILENO) == -1) {
2751                         error("%s: dup2: %s", tag, strerror(errno));
2752                         _exit(1);
2753                 }
2754                 closefrom(STDERR_FILENO + 1);
2755
2756                 if (geteuid() == 0 &&
2757                     initgroups(pw->pw_name, pw->pw_gid) == -1) {
2758                         error("%s: initgroups(%s, %u): %s", tag,
2759                             pw->pw_name, (u_int)pw->pw_gid, strerror(errno));
2760                         _exit(1);
2761                 }
2762                 if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1) {
2763                         error("%s: setresgid %u: %s", tag, (u_int)pw->pw_gid,
2764                             strerror(errno));
2765                         _exit(1);
2766                 }
2767                 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1) {
2768                         error("%s: setresuid %u: %s", tag, (u_int)pw->pw_uid,
2769                             strerror(errno));
2770                         _exit(1);
2771                 }
2772                 /* stdin is pointed to /dev/null at this point */
2773                 if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
2774                     dup2(STDIN_FILENO, STDERR_FILENO) == -1) {
2775                         error("%s: dup2: %s", tag, strerror(errno));
2776                         _exit(1);
2777                 }
2778                 if (env != NULL)
2779                         execve(av[0], av, env);
2780                 else
2781                         execv(av[0], av);
2782                 error("%s %s \"%s\": %s", tag, env == NULL ? "execv" : "execve",
2783                     command, strerror(errno));
2784                 _exit(127);
2785         default: /* parent */
2786                 break;
2787         }
2788
2789         close(p[1]);
2790         if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0)
2791                 close(p[0]);
2792         else if ((f = fdopen(p[0], "r")) == NULL) {
2793                 error("%s: fdopen: %s", tag, strerror(errno));
2794                 close(p[0]);
2795                 /* Don't leave zombie child */
2796                 kill(pid, SIGTERM);
2797                 while (waitpid(pid, NULL, 0) == -1 && errno == EINTR)
2798                         ;
2799                 return 0;
2800         }
2801         /* Success */
2802         debug3_f("%s pid %ld", tag, (long)pid);
2803         if (child != NULL)
2804                 *child = f;
2805         return pid;
2806 }
2807
2808 const char *
2809 lookup_env_in_list(const char *env, char * const *envs, size_t nenvs)
2810 {
2811         size_t i, envlen;
2812
2813         envlen = strlen(env);
2814         for (i = 0; i < nenvs; i++) {
2815                 if (strncmp(envs[i], env, envlen) == 0 &&
2816                     envs[i][envlen] == '=') {
2817                         return envs[i] + envlen + 1;
2818                 }
2819         }
2820         return NULL;
2821 }
2822
2823 const char *
2824 lookup_setenv_in_list(const char *env, char * const *envs, size_t nenvs)
2825 {
2826         char *name, *cp;
2827         const char *ret;
2828
2829         name = xstrdup(env);
2830         if ((cp = strchr(name, '=')) == NULL) {
2831                 free(name);
2832                 return NULL; /* not env=val */
2833         }
2834         *cp = '\0';
2835         ret = lookup_env_in_list(name, envs, nenvs);
2836         free(name);
2837         return ret;
2838 }
2839
2840 /*
2841  * Helpers for managing poll(2)/ppoll(2) timeouts
2842  * Will remember the earliest deadline and return it for use in poll/ppoll.
2843  */
2844
2845 /* Initialise a poll/ppoll timeout with an indefinite deadline */
2846 void
2847 ptimeout_init(struct timespec *pt)
2848 {
2849         /*
2850          * Deliberately invalid for ppoll(2).
2851          * Will be converted to NULL in ptimeout_get_tspec() later.
2852          */
2853         pt->tv_sec = -1;
2854         pt->tv_nsec = 0;
2855 }
2856
2857 /* Specify a poll/ppoll deadline of at most 'sec' seconds */
2858 void
2859 ptimeout_deadline_sec(struct timespec *pt, long sec)
2860 {
2861         if (pt->tv_sec == -1 || pt->tv_sec >= sec) {
2862                 pt->tv_sec = sec;
2863                 pt->tv_nsec = 0;
2864         }
2865 }
2866
2867 /* Specify a poll/ppoll deadline of at most 'p' (timespec) */
2868 static void
2869 ptimeout_deadline_tsp(struct timespec *pt, struct timespec *p)
2870 {
2871         if (pt->tv_sec == -1 || timespeccmp(pt, p, >=))
2872                 *pt = *p;
2873 }
2874
2875 /* Specify a poll/ppoll deadline of at most 'ms' milliseconds */
2876 void
2877 ptimeout_deadline_ms(struct timespec *pt, long ms)
2878 {
2879         struct timespec p;
2880
2881         p.tv_sec = ms / 1000;
2882         p.tv_nsec = (ms % 1000) * 1000000;
2883         ptimeout_deadline_tsp(pt, &p);
2884 }
2885
2886 /* Specify a poll/ppoll deadline at wall clock monotime 'when' */
2887 void
2888 ptimeout_deadline_monotime(struct timespec *pt, time_t when)
2889 {
2890         struct timespec now, t;
2891
2892         t.tv_sec = when;
2893         t.tv_nsec = 0;
2894         monotime_ts(&now);
2895
2896         if (timespeccmp(&now, &t, >=))
2897                 ptimeout_deadline_sec(pt, 0);
2898         else {
2899                 timespecsub(&t, &now, &t);
2900                 ptimeout_deadline_tsp(pt, &t);
2901         }
2902 }
2903
2904 /* Get a poll(2) timeout value in milliseconds */
2905 int
2906 ptimeout_get_ms(struct timespec *pt)
2907 {
2908         if (pt->tv_sec == -1)
2909                 return -1;
2910         if (pt->tv_sec >= (INT_MAX - (pt->tv_nsec / 1000000)) / 1000)
2911                 return INT_MAX;
2912         return (pt->tv_sec * 1000) + (pt->tv_nsec / 1000000);
2913 }
2914
2915 /* Get a ppoll(2) timeout value as a timespec pointer */
2916 struct timespec *
2917 ptimeout_get_tsp(struct timespec *pt)
2918 {
2919         return pt->tv_sec == -1 ? NULL : pt;
2920 }
2921
2922 /* Returns non-zero if a timeout has been set (i.e. is not indefinite) */
2923 int
2924 ptimeout_isset(struct timespec *pt)
2925 {
2926         return pt->tv_sec != -1;
2927 }
2928
2929 /*
2930  * Returns zero if the library at 'path' contains symbol 's', nonzero
2931  * otherwise.
2932  */
2933 int
2934 lib_contains_symbol(const char *path, const char *s)
2935 {
2936 #ifdef HAVE_NLIST_H
2937         struct nlist nl[2];
2938         int ret = -1, r;
2939
2940         memset(nl, 0, sizeof(nl));
2941         nl[0].n_name = xstrdup(s);
2942         nl[1].n_name = NULL;
2943         if ((r = nlist(path, nl)) == -1) {
2944                 error_f("nlist failed for %s", path);
2945                 goto out;
2946         }
2947         if (r != 0 || nl[0].n_value == 0 || nl[0].n_type == 0) {
2948                 error_f("library %s does not contain symbol %s", path, s);
2949                 goto out;
2950         }
2951         /* success */
2952         ret = 0;
2953  out:
2954         free(nl[0].n_name);
2955         return ret;
2956 #else /* HAVE_NLIST_H */
2957         int fd, ret = -1;
2958         struct stat st;
2959         void *m = NULL;
2960         size_t sz = 0;
2961
2962         memset(&st, 0, sizeof(st));
2963         if ((fd = open(path, O_RDONLY)) < 0) {
2964                 error_f("open %s: %s", path, strerror(errno));
2965                 return -1;
2966         }
2967         if (fstat(fd, &st) != 0) {
2968                 error_f("fstat %s: %s", path, strerror(errno));
2969                 goto out;
2970         }
2971         if (!S_ISREG(st.st_mode)) {
2972                 error_f("%s is not a regular file", path);
2973                 goto out;
2974         }
2975         if (st.st_size < 0 ||
2976             (size_t)st.st_size < strlen(s) ||
2977             st.st_size >= INT_MAX/2) {
2978                 error_f("%s bad size %lld", path, (long long)st.st_size);
2979                 goto out;
2980         }
2981         sz = (size_t)st.st_size;
2982         if ((m = mmap(NULL, sz, PROT_READ, MAP_PRIVATE, fd, 0)) == MAP_FAILED ||
2983             m == NULL) {
2984                 error_f("mmap %s: %s", path, strerror(errno));
2985                 goto out;
2986         }
2987         if (memmem(m, sz, s, strlen(s)) == NULL) {
2988                 error_f("%s does not contain expected string %s", path, s);
2989                 goto out;
2990         }
2991         /* success */
2992         ret = 0;
2993  out:
2994         if (m != NULL && m != MAP_FAILED)
2995                 munmap(m, sz);
2996         close(fd);
2997         return ret;
2998 #endif /* HAVE_NLIST_H */
2999 }