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