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