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