[BACK]Return to misc.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / ssh

Annotation of src/usr.bin/ssh/misc.c, Revision 1.182

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