Annotation of src/usr.bin/ssh/misc.c, Revision 1.145
1.145 ! djm 1: /* $OpenBSD: misc.c,v 1.144 2020/01/23 07:10:22 dtucker 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: }
1.145 ! djm 1204:
! 1205: /*
! 1206: * Extend string *sp by the specified format. If *sp is not NULL (or empty),
! 1207: * then the separator 'sep' will be prepended before the formatted arguments.
! 1208: * Extended strings are heap allocated.
! 1209: */
! 1210: void
! 1211: xextendf(char **sp, const char *sep, const char *fmt, ...)
! 1212: {
! 1213: va_list ap;
! 1214: char *tmp1, *tmp2;
! 1215:
! 1216: va_start(ap, fmt);
! 1217: xvasprintf(&tmp1, fmt, ap);
! 1218: va_end(ap);
! 1219:
! 1220: if (*sp == NULL || **sp == '\0') {
! 1221: free(*sp);
! 1222: *sp = tmp1;
! 1223: return;
! 1224: }
! 1225: xasprintf(&tmp2, "%s%s%s", *sp, sep == NULL ? "" : sep, tmp1);
! 1226: free(tmp1);
! 1227: free(*sp);
! 1228: *sp = tmp2;
! 1229: }
! 1230:
1.33 djm 1231:
1.52 djm 1232: u_int64_t
1233: get_u64(const void *vp)
1234: {
1235: const u_char *p = (const u_char *)vp;
1236: u_int64_t v;
1237:
1238: v = (u_int64_t)p[0] << 56;
1239: v |= (u_int64_t)p[1] << 48;
1240: v |= (u_int64_t)p[2] << 40;
1241: v |= (u_int64_t)p[3] << 32;
1242: v |= (u_int64_t)p[4] << 24;
1243: v |= (u_int64_t)p[5] << 16;
1244: v |= (u_int64_t)p[6] << 8;
1245: v |= (u_int64_t)p[7];
1246:
1247: return (v);
1248: }
1249:
1250: u_int32_t
1251: get_u32(const void *vp)
1252: {
1253: const u_char *p = (const u_char *)vp;
1254: u_int32_t v;
1255:
1256: v = (u_int32_t)p[0] << 24;
1257: v |= (u_int32_t)p[1] << 16;
1258: v |= (u_int32_t)p[2] << 8;
1259: v |= (u_int32_t)p[3];
1260:
1261: return (v);
1262: }
1263:
1.93 djm 1264: u_int32_t
1265: get_u32_le(const void *vp)
1266: {
1267: const u_char *p = (const u_char *)vp;
1268: u_int32_t v;
1269:
1270: v = (u_int32_t)p[0];
1271: v |= (u_int32_t)p[1] << 8;
1272: v |= (u_int32_t)p[2] << 16;
1273: v |= (u_int32_t)p[3] << 24;
1274:
1275: return (v);
1276: }
1277:
1.52 djm 1278: u_int16_t
1279: get_u16(const void *vp)
1280: {
1281: const u_char *p = (const u_char *)vp;
1282: u_int16_t v;
1283:
1284: v = (u_int16_t)p[0] << 8;
1285: v |= (u_int16_t)p[1];
1286:
1287: return (v);
1288: }
1289:
1290: void
1291: put_u64(void *vp, u_int64_t v)
1292: {
1293: u_char *p = (u_char *)vp;
1294:
1295: p[0] = (u_char)(v >> 56) & 0xff;
1296: p[1] = (u_char)(v >> 48) & 0xff;
1297: p[2] = (u_char)(v >> 40) & 0xff;
1298: p[3] = (u_char)(v >> 32) & 0xff;
1299: p[4] = (u_char)(v >> 24) & 0xff;
1300: p[5] = (u_char)(v >> 16) & 0xff;
1301: p[6] = (u_char)(v >> 8) & 0xff;
1302: p[7] = (u_char)v & 0xff;
1303: }
1304:
1305: void
1306: put_u32(void *vp, u_int32_t v)
1307: {
1308: u_char *p = (u_char *)vp;
1309:
1310: p[0] = (u_char)(v >> 24) & 0xff;
1311: p[1] = (u_char)(v >> 16) & 0xff;
1312: p[2] = (u_char)(v >> 8) & 0xff;
1313: p[3] = (u_char)v & 0xff;
1314: }
1315:
1.93 djm 1316: void
1317: put_u32_le(void *vp, u_int32_t v)
1318: {
1319: u_char *p = (u_char *)vp;
1320:
1321: p[0] = (u_char)v & 0xff;
1322: p[1] = (u_char)(v >> 8) & 0xff;
1323: p[2] = (u_char)(v >> 16) & 0xff;
1324: p[3] = (u_char)(v >> 24) & 0xff;
1325: }
1.52 djm 1326:
1327: void
1328: put_u16(void *vp, u_int16_t v)
1329: {
1330: u_char *p = (u_char *)vp;
1331:
1332: p[0] = (u_char)(v >> 8) & 0xff;
1333: p[1] = (u_char)v & 0xff;
1334: }
1.68 dtucker 1335:
1336: void
1337: ms_subtract_diff(struct timeval *start, int *ms)
1338: {
1339: struct timeval diff, finish;
1340:
1.119 dtucker 1341: monotime_tv(&finish);
1342: timersub(&finish, start, &diff);
1.68 dtucker 1343: *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
1344: }
1345:
1346: void
1347: ms_to_timeval(struct timeval *tv, int ms)
1348: {
1349: if (ms < 0)
1350: ms = 0;
1351: tv->tv_sec = ms / 1000;
1352: tv->tv_usec = (ms % 1000) * 1000;
1.90 dtucker 1353: }
1354:
1.119 dtucker 1355: void
1356: monotime_ts(struct timespec *ts)
1357: {
1358: if (clock_gettime(CLOCK_MONOTONIC, ts) != 0)
1359: fatal("clock_gettime: %s", strerror(errno));
1360: }
1361:
1362: void
1363: monotime_tv(struct timeval *tv)
1364: {
1365: struct timespec ts;
1366:
1367: monotime_ts(&ts);
1368: tv->tv_sec = ts.tv_sec;
1369: tv->tv_usec = ts.tv_nsec / 1000;
1370: }
1371:
1.90 dtucker 1372: time_t
1373: monotime(void)
1374: {
1375: struct timespec ts;
1376:
1.119 dtucker 1377: monotime_ts(&ts);
1.90 dtucker 1378: return (ts.tv_sec);
1.102 dtucker 1379: }
1380:
1381: double
1382: monotime_double(void)
1383: {
1384: struct timespec ts;
1385:
1.119 dtucker 1386: monotime_ts(&ts);
1387: return (double)ts.tv_sec + (double)ts.tv_nsec / 1000000000.0;
1.81 djm 1388: }
1389:
1390: void
1391: bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
1392: {
1393: bw->buflen = buflen;
1394: bw->rate = kbps;
1.135 dtucker 1395: bw->thresh = buflen;
1.81 djm 1396: bw->lamt = 0;
1397: timerclear(&bw->bwstart);
1398: timerclear(&bw->bwend);
1.135 dtucker 1399: }
1.81 djm 1400:
1401: /* Callback from read/write loop to insert bandwidth-limiting delays */
1402: void
1403: bandwidth_limit(struct bwlimit *bw, size_t read_len)
1404: {
1405: u_int64_t waitlen;
1406: struct timespec ts, rm;
1407:
1.135 dtucker 1408: bw->lamt += read_len;
1.81 djm 1409: if (!timerisset(&bw->bwstart)) {
1.119 dtucker 1410: monotime_tv(&bw->bwstart);
1.81 djm 1411: return;
1412: }
1413: if (bw->lamt < bw->thresh)
1414: return;
1415:
1.119 dtucker 1416: monotime_tv(&bw->bwend);
1.81 djm 1417: timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
1418: if (!timerisset(&bw->bwend))
1419: return;
1420:
1421: bw->lamt *= 8;
1422: waitlen = (double)1000000L * bw->lamt / bw->rate;
1423:
1424: bw->bwstart.tv_sec = waitlen / 1000000L;
1425: bw->bwstart.tv_usec = waitlen % 1000000L;
1426:
1427: if (timercmp(&bw->bwstart, &bw->bwend, >)) {
1428: timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
1429:
1430: /* Adjust the wait time */
1431: if (bw->bwend.tv_sec) {
1432: bw->thresh /= 2;
1433: if (bw->thresh < bw->buflen / 4)
1434: bw->thresh = bw->buflen / 4;
1435: } else if (bw->bwend.tv_usec < 10000) {
1436: bw->thresh *= 2;
1437: if (bw->thresh > bw->buflen * 8)
1438: bw->thresh = bw->buflen * 8;
1439: }
1440:
1441: TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
1442: while (nanosleep(&ts, &rm) == -1) {
1443: if (errno != EINTR)
1444: break;
1445: ts = rm;
1446: }
1447: }
1448:
1449: bw->lamt = 0;
1.119 dtucker 1450: monotime_tv(&bw->bwstart);
1.84 djm 1451: }
1452:
1453: /* Make a template filename for mk[sd]temp() */
1454: void
1455: mktemp_proto(char *s, size_t len)
1456: {
1457: const char *tmpdir;
1458: int r;
1459:
1460: if ((tmpdir = getenv("TMPDIR")) != NULL) {
1461: r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
1462: if (r > 0 && (size_t)r < len)
1463: return;
1464: }
1465: r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
1466: if (r < 0 || (size_t)r >= len)
1467: fatal("%s: template string too short", __func__);
1.68 dtucker 1468: }
1.83 djm 1469:
1470: static const struct {
1471: const char *name;
1472: int value;
1473: } ipqos[] = {
1.111 djm 1474: { "none", INT_MAX }, /* can't use 0 here; that's CS0 */
1.83 djm 1475: { "af11", IPTOS_DSCP_AF11 },
1476: { "af12", IPTOS_DSCP_AF12 },
1477: { "af13", IPTOS_DSCP_AF13 },
1.86 djm 1478: { "af21", IPTOS_DSCP_AF21 },
1.83 djm 1479: { "af22", IPTOS_DSCP_AF22 },
1480: { "af23", IPTOS_DSCP_AF23 },
1481: { "af31", IPTOS_DSCP_AF31 },
1482: { "af32", IPTOS_DSCP_AF32 },
1483: { "af33", IPTOS_DSCP_AF33 },
1484: { "af41", IPTOS_DSCP_AF41 },
1485: { "af42", IPTOS_DSCP_AF42 },
1486: { "af43", IPTOS_DSCP_AF43 },
1487: { "cs0", IPTOS_DSCP_CS0 },
1488: { "cs1", IPTOS_DSCP_CS1 },
1489: { "cs2", IPTOS_DSCP_CS2 },
1490: { "cs3", IPTOS_DSCP_CS3 },
1491: { "cs4", IPTOS_DSCP_CS4 },
1492: { "cs5", IPTOS_DSCP_CS5 },
1493: { "cs6", IPTOS_DSCP_CS6 },
1494: { "cs7", IPTOS_DSCP_CS7 },
1495: { "ef", IPTOS_DSCP_EF },
1496: { "lowdelay", IPTOS_LOWDELAY },
1497: { "throughput", IPTOS_THROUGHPUT },
1498: { "reliability", IPTOS_RELIABILITY },
1499: { NULL, -1 }
1500: };
1501:
1502: int
1503: parse_ipqos(const char *cp)
1504: {
1505: u_int i;
1506: char *ep;
1507: long val;
1508:
1509: if (cp == NULL)
1510: return -1;
1511: for (i = 0; ipqos[i].name != NULL; i++) {
1512: if (strcasecmp(cp, ipqos[i].name) == 0)
1513: return ipqos[i].value;
1514: }
1515: /* Try parsing as an integer */
1516: val = strtol(cp, &ep, 0);
1517: if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1518: return -1;
1519: return val;
1520: }
1521:
1.85 stevesk 1522: const char *
1523: iptos2str(int iptos)
1524: {
1525: int i;
1526: static char iptos_str[sizeof "0xff"];
1527:
1528: for (i = 0; ipqos[i].name != NULL; i++) {
1529: if (ipqos[i].value == iptos)
1530: return ipqos[i].name;
1531: }
1532: snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1533: return iptos_str;
1.92 djm 1534: }
1535:
1536: void
1537: lowercase(char *s)
1538: {
1539: for (; *s; s++)
1540: *s = tolower((u_char)*s);
1.94 millert 1541: }
1542:
1543: int
1544: unix_listener(const char *path, int backlog, int unlink_first)
1545: {
1546: struct sockaddr_un sunaddr;
1547: int saved_errno, sock;
1548:
1549: memset(&sunaddr, 0, sizeof(sunaddr));
1550: sunaddr.sun_family = AF_UNIX;
1.121 djm 1551: if (strlcpy(sunaddr.sun_path, path,
1552: sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1553: error("%s: path \"%s\" too long for Unix domain socket",
1554: __func__, path);
1.94 millert 1555: errno = ENAMETOOLONG;
1556: return -1;
1557: }
1558:
1559: sock = socket(PF_UNIX, SOCK_STREAM, 0);
1.139 deraadt 1560: if (sock == -1) {
1.94 millert 1561: saved_errno = errno;
1.121 djm 1562: error("%s: socket: %.100s", __func__, strerror(errno));
1.94 millert 1563: errno = saved_errno;
1564: return -1;
1565: }
1566: if (unlink_first == 1) {
1567: if (unlink(path) != 0 && errno != ENOENT)
1568: error("unlink(%s): %.100s", path, strerror(errno));
1569: }
1.139 deraadt 1570: if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1.94 millert 1571: saved_errno = errno;
1.121 djm 1572: error("%s: cannot bind to path %s: %s",
1573: __func__, path, strerror(errno));
1.122 djm 1574: close(sock);
1.94 millert 1575: errno = saved_errno;
1576: return -1;
1577: }
1.139 deraadt 1578: if (listen(sock, backlog) == -1) {
1.94 millert 1579: saved_errno = errno;
1.122 djm 1580: error("%s: cannot listen on path %s: %s",
1581: __func__, path, strerror(errno));
1.94 millert 1582: close(sock);
1583: unlink(path);
1584: errno = saved_errno;
1585: return -1;
1586: }
1587: return sock;
1.85 stevesk 1588: }
1.104 djm 1589:
1590: /*
1591: * Compares two strings that maybe be NULL. Returns non-zero if strings
1592: * are both NULL or are identical, returns zero otherwise.
1593: */
1594: static int
1595: strcmp_maybe_null(const char *a, const char *b)
1596: {
1597: if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1598: return 0;
1599: if (a != NULL && strcmp(a, b) != 0)
1600: return 0;
1601: return 1;
1602: }
1603:
1604: /*
1605: * Compare two forwards, returning non-zero if they are identical or
1606: * zero otherwise.
1607: */
1608: int
1609: forward_equals(const struct Forward *a, const struct Forward *b)
1610: {
1611: if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
1612: return 0;
1613: if (a->listen_port != b->listen_port)
1614: return 0;
1615: if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
1616: return 0;
1617: if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
1618: return 0;
1619: if (a->connect_port != b->connect_port)
1620: return 0;
1621: if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
1622: return 0;
1623: /* allocated_port and handle are not checked */
1.107 dtucker 1624: return 1;
1625: }
1626:
1627: /* returns 1 if process is already daemonized, 0 otherwise */
1628: int
1629: daemonized(void)
1630: {
1631: int fd;
1632:
1633: if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
1634: close(fd);
1635: return 0; /* have controlling terminal */
1636: }
1637: if (getppid() != 1)
1638: return 0; /* parent is not init */
1639: if (getsid(0) != getpid())
1640: return 0; /* not session leader */
1641: debug3("already daemonized");
1.106 dtucker 1642: return 1;
1643: }
1.112 djm 1644:
1645:
1646: /*
1647: * Splits 's' into an argument vector. Handles quoted string and basic
1648: * escape characters (\\, \", \'). Caller must free the argument vector
1649: * and its members.
1650: */
1651: int
1652: argv_split(const char *s, int *argcp, char ***argvp)
1653: {
1654: int r = SSH_ERR_INTERNAL_ERROR;
1655: int argc = 0, quote, i, j;
1656: char *arg, **argv = xcalloc(1, sizeof(*argv));
1657:
1658: *argvp = NULL;
1659: *argcp = 0;
1660:
1661: for (i = 0; s[i] != '\0'; i++) {
1662: /* Skip leading whitespace */
1663: if (s[i] == ' ' || s[i] == '\t')
1664: continue;
1665:
1666: /* Start of a token */
1667: quote = 0;
1668: if (s[i] == '\\' &&
1669: (s[i + 1] == '\'' || s[i + 1] == '\"' || s[i + 1] == '\\'))
1670: i++;
1671: else if (s[i] == '\'' || s[i] == '"')
1672: quote = s[i++];
1673:
1674: argv = xreallocarray(argv, (argc + 2), sizeof(*argv));
1675: arg = argv[argc++] = xcalloc(1, strlen(s + i) + 1);
1676: argv[argc] = NULL;
1677:
1678: /* Copy the token in, removing escapes */
1679: for (j = 0; s[i] != '\0'; i++) {
1680: if (s[i] == '\\') {
1681: if (s[i + 1] == '\'' ||
1682: s[i + 1] == '\"' ||
1683: s[i + 1] == '\\') {
1684: i++; /* Skip '\' */
1685: arg[j++] = s[i];
1686: } else {
1687: /* Unrecognised escape */
1688: arg[j++] = s[i];
1689: }
1690: } else if (quote == 0 && (s[i] == ' ' || s[i] == '\t'))
1691: break; /* done */
1692: else if (quote != 0 && s[i] == quote)
1693: break; /* done */
1694: else
1695: arg[j++] = s[i];
1696: }
1697: if (s[i] == '\0') {
1698: if (quote != 0) {
1699: /* Ran out of string looking for close quote */
1700: r = SSH_ERR_INVALID_FORMAT;
1701: goto out;
1702: }
1703: break;
1704: }
1705: }
1706: /* Success */
1707: *argcp = argc;
1708: *argvp = argv;
1709: argc = 0;
1710: argv = NULL;
1711: r = 0;
1712: out:
1713: if (argc != 0 && argv != NULL) {
1714: for (i = 0; i < argc; i++)
1715: free(argv[i]);
1716: free(argv);
1717: }
1718: return r;
1719: }
1720:
1721: /*
1722: * Reassemble an argument vector into a string, quoting and escaping as
1723: * necessary. Caller must free returned string.
1724: */
1725: char *
1726: argv_assemble(int argc, char **argv)
1727: {
1728: int i, j, ws, r;
1729: char c, *ret;
1730: struct sshbuf *buf, *arg;
1731:
1732: if ((buf = sshbuf_new()) == NULL || (arg = sshbuf_new()) == NULL)
1733: fatal("%s: sshbuf_new failed", __func__);
1734:
1735: for (i = 0; i < argc; i++) {
1736: ws = 0;
1737: sshbuf_reset(arg);
1738: for (j = 0; argv[i][j] != '\0'; j++) {
1739: r = 0;
1740: c = argv[i][j];
1741: switch (c) {
1742: case ' ':
1743: case '\t':
1744: ws = 1;
1745: r = sshbuf_put_u8(arg, c);
1746: break;
1747: case '\\':
1748: case '\'':
1749: case '"':
1750: if ((r = sshbuf_put_u8(arg, '\\')) != 0)
1751: break;
1752: /* FALLTHROUGH */
1753: default:
1754: r = sshbuf_put_u8(arg, c);
1755: break;
1756: }
1757: if (r != 0)
1758: fatal("%s: sshbuf_put_u8: %s",
1759: __func__, ssh_err(r));
1760: }
1761: if ((i != 0 && (r = sshbuf_put_u8(buf, ' ')) != 0) ||
1762: (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0) ||
1763: (r = sshbuf_putb(buf, arg)) != 0 ||
1764: (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0))
1765: fatal("%s: buffer error: %s", __func__, ssh_err(r));
1766: }
1767: if ((ret = malloc(sshbuf_len(buf) + 1)) == NULL)
1768: fatal("%s: malloc failed", __func__);
1769: memcpy(ret, sshbuf_ptr(buf), sshbuf_len(buf));
1770: ret[sshbuf_len(buf)] = '\0';
1771: sshbuf_free(buf);
1772: sshbuf_free(arg);
1773: return ret;
1774: }
1775:
1776: /* Returns 0 if pid exited cleanly, non-zero otherwise */
1777: int
1.113 djm 1778: exited_cleanly(pid_t pid, const char *tag, const char *cmd, int quiet)
1.112 djm 1779: {
1780: int status;
1781:
1782: while (waitpid(pid, &status, 0) == -1) {
1783: if (errno != EINTR) {
1784: error("%s: waitpid: %s", tag, strerror(errno));
1785: return -1;
1786: }
1787: }
1788: if (WIFSIGNALED(status)) {
1789: error("%s %s exited on signal %d", tag, cmd, WTERMSIG(status));
1790: return -1;
1791: } else if (WEXITSTATUS(status) != 0) {
1.113 djm 1792: do_log2(quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_INFO,
1793: "%s %s failed, status %d", tag, cmd, WEXITSTATUS(status));
1.112 djm 1794: return -1;
1795: }
1796: return 0;
1797: }
1798:
1799: /*
1800: * Check a given path for security. This is defined as all components
1801: * of the path to the file must be owned by either the owner of
1802: * of the file or root and no directories must be group or world writable.
1803: *
1804: * XXX Should any specific check be done for sym links ?
1805: *
1806: * Takes a file name, its stat information (preferably from fstat() to
1807: * avoid races), the uid of the expected owner, their home directory and an
1808: * error buffer plus max size as arguments.
1809: *
1810: * Returns 0 on success and -1 on failure
1811: */
1812: int
1813: safe_path(const char *name, struct stat *stp, const char *pw_dir,
1814: uid_t uid, char *err, size_t errlen)
1815: {
1816: char buf[PATH_MAX], homedir[PATH_MAX];
1817: char *cp;
1818: int comparehome = 0;
1819: struct stat st;
1820:
1821: if (realpath(name, buf) == NULL) {
1822: snprintf(err, errlen, "realpath %s failed: %s", name,
1823: strerror(errno));
1824: return -1;
1825: }
1826: if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL)
1827: comparehome = 1;
1828:
1829: if (!S_ISREG(stp->st_mode)) {
1830: snprintf(err, errlen, "%s is not a regular file", buf);
1831: return -1;
1832: }
1833: if ((stp->st_uid != 0 && stp->st_uid != uid) ||
1834: (stp->st_mode & 022) != 0) {
1835: snprintf(err, errlen, "bad ownership or modes for file %s",
1836: buf);
1837: return -1;
1838: }
1839:
1840: /* for each component of the canonical path, walking upwards */
1841: for (;;) {
1842: if ((cp = dirname(buf)) == NULL) {
1843: snprintf(err, errlen, "dirname() failed");
1844: return -1;
1845: }
1846: strlcpy(buf, cp, sizeof(buf));
1847:
1.139 deraadt 1848: if (stat(buf, &st) == -1 ||
1.112 djm 1849: (st.st_uid != 0 && st.st_uid != uid) ||
1850: (st.st_mode & 022) != 0) {
1851: snprintf(err, errlen,
1852: "bad ownership or modes for directory %s", buf);
1853: return -1;
1854: }
1855:
1856: /* If are past the homedir then we can stop */
1857: if (comparehome && strcmp(homedir, buf) == 0)
1858: break;
1859:
1860: /*
1861: * dirname should always complete with a "/" path,
1862: * but we can be paranoid and check for "." too
1863: */
1864: if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
1865: break;
1866: }
1867: return 0;
1868: }
1869:
1870: /*
1871: * Version of safe_path() that accepts an open file descriptor to
1872: * avoid races.
1873: *
1874: * Returns 0 on success and -1 on failure
1875: */
1876: int
1877: safe_path_fd(int fd, const char *file, struct passwd *pw,
1878: char *err, size_t errlen)
1879: {
1880: struct stat st;
1881:
1882: /* check the open file to avoid races */
1.139 deraadt 1883: if (fstat(fd, &st) == -1) {
1.112 djm 1884: snprintf(err, errlen, "cannot stat file %s: %s",
1885: file, strerror(errno));
1886: return -1;
1887: }
1888: return safe_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen);
1889: }
1890:
1891: /*
1892: * Sets the value of the given variable in the environment. If the variable
1893: * already exists, its value is overridden.
1894: */
1895: void
1896: child_set_env(char ***envp, u_int *envsizep, const char *name,
1897: const char *value)
1898: {
1899: char **env;
1900: u_int envsize;
1901: u_int i, namelen;
1902:
1903: if (strchr(name, '=') != NULL) {
1904: error("Invalid environment variable \"%.100s\"", name);
1905: return;
1906: }
1907:
1908: /*
1909: * Find the slot where the value should be stored. If the variable
1910: * already exists, we reuse the slot; otherwise we append a new slot
1911: * at the end of the array, expanding if necessary.
1912: */
1913: env = *envp;
1914: namelen = strlen(name);
1915: for (i = 0; env[i]; i++)
1916: if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
1917: break;
1918: if (env[i]) {
1919: /* Reuse the slot. */
1920: free(env[i]);
1921: } else {
1922: /* New variable. Expand if necessary. */
1923: envsize = *envsizep;
1924: if (i >= envsize - 1) {
1925: if (envsize >= 1000)
1926: fatal("child_set_env: too many env vars");
1927: envsize += 50;
1928: env = (*envp) = xreallocarray(env, envsize, sizeof(char *));
1929: *envsizep = envsize;
1930: }
1931: /* Need to set the NULL pointer at end of array beyond the new slot. */
1932: env[i + 1] = NULL;
1933: }
1934:
1935: /* Allocate space and format the variable in the appropriate slot. */
1.125 djm 1936: /* XXX xasprintf */
1.112 djm 1937: env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
1938: snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
1939: }
1940:
1.114 millert 1941: /*
1942: * Check and optionally lowercase a domain name, also removes trailing '.'
1943: * Returns 1 on success and 0 on failure, storing an error message in errstr.
1944: */
1945: int
1946: valid_domain(char *name, int makelower, const char **errstr)
1947: {
1948: size_t i, l = strlen(name);
1949: u_char c, last = '\0';
1950: static char errbuf[256];
1951:
1952: if (l == 0) {
1953: strlcpy(errbuf, "empty domain name", sizeof(errbuf));
1954: goto bad;
1955: }
1956: if (!isalpha((u_char)name[0]) && !isdigit((u_char)name[0])) {
1957: snprintf(errbuf, sizeof(errbuf), "domain name \"%.100s\" "
1958: "starts with invalid character", name);
1959: goto bad;
1960: }
1961: for (i = 0; i < l; i++) {
1962: c = tolower((u_char)name[i]);
1963: if (makelower)
1964: name[i] = (char)c;
1965: if (last == '.' && c == '.') {
1966: snprintf(errbuf, sizeof(errbuf), "domain name "
1967: "\"%.100s\" contains consecutive separators", name);
1968: goto bad;
1969: }
1970: if (c != '.' && c != '-' && !isalnum(c) &&
1971: c != '_') /* technically invalid, but common */ {
1972: snprintf(errbuf, sizeof(errbuf), "domain name "
1973: "\"%.100s\" contains invalid characters", name);
1974: goto bad;
1975: }
1976: last = c;
1977: }
1978: if (name[l - 1] == '.')
1979: name[l - 1] = '\0';
1980: if (errstr != NULL)
1981: *errstr = NULL;
1982: return 1;
1983: bad:
1984: if (errstr != NULL)
1985: *errstr = errbuf;
1986: return 0;
1.132 djm 1987: }
1988:
1989: /*
1990: * Verify that a environment variable name (not including initial '$') is
1991: * valid; consisting of one or more alphanumeric or underscore characters only.
1992: * Returns 1 on valid, 0 otherwise.
1993: */
1994: int
1995: valid_env_name(const char *name)
1996: {
1997: const char *cp;
1998:
1999: if (name[0] == '\0')
2000: return 0;
2001: for (cp = name; *cp != '\0'; cp++) {
2002: if (!isalnum((u_char)*cp) && *cp != '_')
2003: return 0;
2004: }
2005: return 1;
1.120 dtucker 2006: }
2007:
2008: const char *
2009: atoi_err(const char *nptr, int *val)
2010: {
2011: const char *errstr = NULL;
2012: long long num;
2013:
2014: if (nptr == NULL || *nptr == '\0')
2015: return "missing";
2016: num = strtonum(nptr, 0, INT_MAX, &errstr);
2017: if (errstr == NULL)
2018: *val = (int)num;
2019: return errstr;
1.127 djm 2020: }
2021:
2022: int
2023: parse_absolute_time(const char *s, uint64_t *tp)
2024: {
2025: struct tm tm;
2026: time_t tt;
2027: char buf[32], *fmt;
2028:
2029: *tp = 0;
2030:
2031: /*
2032: * POSIX strptime says "The application shall ensure that there
2033: * is white-space or other non-alphanumeric characters between
2034: * any two conversion specifications" so arrange things this way.
2035: */
2036: switch (strlen(s)) {
2037: case 8: /* YYYYMMDD */
2038: fmt = "%Y-%m-%d";
2039: snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
2040: break;
2041: case 12: /* YYYYMMDDHHMM */
2042: fmt = "%Y-%m-%dT%H:%M";
2043: snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s",
2044: s, s + 4, s + 6, s + 8, s + 10);
2045: break;
2046: case 14: /* YYYYMMDDHHMMSS */
2047: fmt = "%Y-%m-%dT%H:%M:%S";
2048: snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
2049: s, s + 4, s + 6, s + 8, s + 10, s + 12);
2050: break;
2051: default:
2052: return SSH_ERR_INVALID_FORMAT;
2053: }
2054:
2055: memset(&tm, 0, sizeof(tm));
2056: if (strptime(buf, fmt, &tm) == NULL)
2057: return SSH_ERR_INVALID_FORMAT;
2058: if ((tt = mktime(&tm)) < 0)
2059: return SSH_ERR_INVALID_FORMAT;
2060: /* success */
2061: *tp = (uint64_t)tt;
2062: return 0;
2063: }
2064:
2065: void
2066: format_absolute_time(uint64_t t, char *buf, size_t len)
2067: {
2068: time_t tt = t > INT_MAX ? INT_MAX : t; /* XXX revisit in 2038 :P */
2069: struct tm tm;
2070:
2071: localtime_r(&tt, &tm);
2072: strftime(buf, len, "%Y-%m-%dT%H:%M:%S", &tm);
1.134 djm 2073: }
2074:
2075: /* check if path is absolute */
2076: int
2077: path_absolute(const char *path)
2078: {
2079: return (*path == '/') ? 1 : 0;
1.141 djm 2080: }
2081:
2082: void
2083: skip_space(char **cpp)
2084: {
2085: char *cp;
2086:
2087: for (cp = *cpp; *cp == ' ' || *cp == '\t'; cp++)
2088: ;
2089: *cpp = cp;
1.114 millert 2090: }
1.142 djm 2091:
2092: /* authorized_key-style options parsing helpers */
2093:
2094: /*
2095: * Match flag 'opt' in *optsp, and if allow_negate is set then also match
2096: * 'no-opt'. Returns -1 if option not matched, 1 if option matches or 0
2097: * if negated option matches.
2098: * If the option or negated option matches, then *optsp is updated to
2099: * point to the first character after the option.
2100: */
2101: int
2102: opt_flag(const char *opt, int allow_negate, const char **optsp)
2103: {
2104: size_t opt_len = strlen(opt);
2105: const char *opts = *optsp;
2106: int negate = 0;
2107:
2108: if (allow_negate && strncasecmp(opts, "no-", 3) == 0) {
2109: opts += 3;
2110: negate = 1;
2111: }
2112: if (strncasecmp(opts, opt, opt_len) == 0) {
2113: *optsp = opts + opt_len;
2114: return negate ? 0 : 1;
2115: }
2116: return -1;
2117: }
2118:
2119: char *
2120: opt_dequote(const char **sp, const char **errstrp)
2121: {
2122: const char *s = *sp;
2123: char *ret;
2124: size_t i;
2125:
2126: *errstrp = NULL;
2127: if (*s != '"') {
2128: *errstrp = "missing start quote";
2129: return NULL;
2130: }
2131: s++;
2132: if ((ret = malloc(strlen((s)) + 1)) == NULL) {
2133: *errstrp = "memory allocation failed";
2134: return NULL;
2135: }
2136: for (i = 0; *s != '\0' && *s != '"';) {
2137: if (s[0] == '\\' && s[1] == '"')
2138: s++;
2139: ret[i++] = *s++;
2140: }
2141: if (*s == '\0') {
2142: *errstrp = "missing end quote";
2143: free(ret);
2144: return NULL;
2145: }
2146: ret[i] = '\0';
2147: s++;
2148: *sp = s;
2149: return ret;
2150: }
2151:
2152: int
2153: opt_match(const char **opts, const char *term)
2154: {
2155: if (strncasecmp((*opts), term, strlen(term)) == 0 &&
2156: (*opts)[strlen(term)] == '=') {
2157: *opts += strlen(term) + 1;
2158: return 1;
2159: }
2160: return 0;
2161: }
2162:
1.144 dtucker 2163: sshsig_t
2164: ssh_signal(int signum, sshsig_t handler)
2165: {
2166: struct sigaction sa, osa;
2167:
2168: /* mask all other signals while in handler */
2169: bzero(&sa, sizeof(sa));
2170: sa.sa_handler = handler;
2171: sigfillset(&sa.sa_mask);
2172: if (signum != SIGALRM)
2173: sa.sa_flags = SA_RESTART;
2174: if (sigaction(signum, &sa, &osa) == -1) {
2175: debug3("sigaction(%s): %s", strsignal(signum), strerror(errno));
2176: return SIG_ERR;
2177: }
2178: return osa.sa_handler;
2179: }