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