[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.68

1.68    ! dtucker     1: /* $OpenBSD: misc.c,v 1.67 2008/01/01 08:47:04 dtucker Exp $ */
1.1       markus      2: /*
                      3:  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
1.52      djm         4:  * Copyright (c) 2005,2006 Damien Miller.  All rights reserved.
1.1       markus      5:  *
                      6:  * Redistribution and use in source and binary forms, with or without
                      7:  * modification, are permitted provided that the following conditions
                      8:  * are met:
                      9:  * 1. Redistributions of source code must retain the above copyright
                     10:  *    notice, this list of conditions and the following disclaimer.
                     11:  * 2. Redistributions in binary form must reproduce the above copyright
                     12:  *    notice, this list of conditions and the following disclaimer in the
                     13:  *    documentation and/or other materials provided with the distribution.
                     14:  *
                     15:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     16:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     17:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     18:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     19:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     20:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     21:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     22:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     23:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     24:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                     25:  */
                     26:
1.64      deraadt    27: #include <sys/types.h>
1.45      stevesk    28: #include <sys/ioctl.h>
1.53      stevesk    29: #include <sys/socket.h>
1.61      stevesk    30: #include <sys/param.h>
1.38      stevesk    31:
                     32: #include <net/if.h>
1.53      stevesk    33: #include <netinet/in.h>
1.44      stevesk    34: #include <netinet/tcp.h>
1.43      stevesk    35:
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.57      stevesk    41: #include <stdarg.h>
1.63      stevesk    42: #include <stdio.h>
1.62      stevesk    43: #include <stdlib.h>
1.60      stevesk    44: #include <string.h>
1.59      stevesk    45: #include <unistd.h>
1.1       markus     46:
1.64      deraadt    47: #include "xmalloc.h"
1.1       markus     48: #include "misc.h"
                     49: #include "log.h"
1.56      dtucker    50: #include "ssh.h"
1.1       markus     51:
1.12      markus     52: /* remove newline at end of string */
1.1       markus     53: char *
                     54: chop(char *s)
                     55: {
                     56:        char *t = s;
                     57:        while (*t) {
1.13      deraadt    58:                if (*t == '\n' || *t == '\r') {
1.1       markus     59:                        *t = '\0';
                     60:                        return s;
                     61:                }
                     62:                t++;
                     63:        }
                     64:        return s;
                     65:
                     66: }
                     67:
1.12      markus     68: /* set/unset filedescriptor to non-blocking */
1.24      djm        69: int
1.1       markus     70: set_nonblock(int fd)
                     71: {
                     72:        int val;
1.8       markus     73:
1.1       markus     74:        val = fcntl(fd, F_GETFL, 0);
                     75:        if (val < 0) {
                     76:                error("fcntl(%d, F_GETFL, 0): %s", fd, strerror(errno));
1.24      djm        77:                return (-1);
1.1       markus     78:        }
                     79:        if (val & O_NONBLOCK) {
1.24      djm        80:                debug3("fd %d is O_NONBLOCK", fd);
                     81:                return (0);
1.1       markus     82:        }
1.21      markus     83:        debug2("fd %d setting O_NONBLOCK", fd);
1.1       markus     84:        val |= O_NONBLOCK;
1.24      djm        85:        if (fcntl(fd, F_SETFL, val) == -1) {
                     86:                debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
                     87:                    strerror(errno));
                     88:                return (-1);
                     89:        }
                     90:        return (0);
1.8       markus     91: }
                     92:
1.24      djm        93: int
1.8       markus     94: unset_nonblock(int fd)
                     95: {
                     96:        int val;
                     97:
                     98:        val = fcntl(fd, F_GETFL, 0);
                     99:        if (val < 0) {
                    100:                error("fcntl(%d, F_GETFL, 0): %s", fd, strerror(errno));
1.24      djm       101:                return (-1);
1.8       markus    102:        }
                    103:        if (!(val & O_NONBLOCK)) {
1.24      djm       104:                debug3("fd %d is not O_NONBLOCK", fd);
                    105:                return (0);
1.8       markus    106:        }
1.10      markus    107:        debug("fd %d clearing O_NONBLOCK", fd);
1.8       markus    108:        val &= ~O_NONBLOCK;
1.24      djm       109:        if (fcntl(fd, F_SETFL, val) == -1) {
                    110:                debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
1.18      markus    111:                    fd, strerror(errno));
1.24      djm       112:                return (-1);
                    113:        }
                    114:        return (0);
1.66      dtucker   115: }
                    116:
                    117: const char *
                    118: ssh_gai_strerror(int gaierr)
                    119: {
1.67      dtucker   120:        if (gaierr == EAI_SYSTEM)
                    121:                return strerror(errno);
                    122:        return gai_strerror(gaierr);
1.15      stevesk   123: }
                    124:
                    125: /* disable nagle on socket */
                    126: void
                    127: set_nodelay(int fd)
                    128: {
1.17      stevesk   129:        int opt;
                    130:        socklen_t optlen;
1.15      stevesk   131:
1.16      stevesk   132:        optlen = sizeof opt;
                    133:        if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
1.23      markus    134:                debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
1.16      stevesk   135:                return;
                    136:        }
                    137:        if (opt == 1) {
                    138:                debug2("fd %d is TCP_NODELAY", fd);
                    139:                return;
                    140:        }
                    141:        opt = 1;
1.20      markus    142:        debug2("fd %d setting TCP_NODELAY", fd);
1.16      stevesk   143:        if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
1.15      stevesk   144:                error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
1.1       markus    145: }
                    146:
                    147: /* Characters considered whitespace in strsep calls. */
                    148: #define WHITESPACE " \t\r\n"
1.46      dtucker   149: #define QUOTE  "\""
1.1       markus    150:
1.12      markus    151: /* return next token in configuration line */
1.1       markus    152: char *
                    153: strdelim(char **s)
                    154: {
                    155:        char *old;
                    156:        int wspace = 0;
                    157:
                    158:        if (*s == NULL)
                    159:                return NULL;
                    160:
                    161:        old = *s;
                    162:
1.46      dtucker   163:        *s = strpbrk(*s, WHITESPACE QUOTE "=");
1.1       markus    164:        if (*s == NULL)
                    165:                return (old);
                    166:
1.46      dtucker   167:        if (*s[0] == '\"') {
                    168:                memmove(*s, *s + 1, strlen(*s)); /* move nul too */
                    169:                /* Find matching quote */
                    170:                if ((*s = strpbrk(*s, QUOTE)) == NULL) {
                    171:                        return (NULL);          /* no matching quote */
                    172:                } else {
                    173:                        *s[0] = '\0';
                    174:                        return (old);
                    175:                }
                    176:        }
                    177:
1.1       markus    178:        /* Allow only one '=' to be skipped */
                    179:        if (*s[0] == '=')
                    180:                wspace = 1;
                    181:        *s[0] = '\0';
                    182:
1.46      dtucker   183:        /* Skip any extra whitespace after first token */
1.1       markus    184:        *s += strspn(*s + 1, WHITESPACE) + 1;
                    185:        if (*s[0] == '=' && !wspace)
                    186:                *s += strspn(*s + 1, WHITESPACE) + 1;
                    187:
                    188:        return (old);
1.2       markus    189: }
                    190:
                    191: struct passwd *
                    192: pwcopy(struct passwd *pw)
                    193: {
1.49      djm       194:        struct passwd *copy = xcalloc(1, sizeof(*copy));
1.4       deraadt   195:
1.2       markus    196:        copy->pw_name = xstrdup(pw->pw_name);
                    197:        copy->pw_passwd = xstrdup(pw->pw_passwd);
1.4       deraadt   198:        copy->pw_gecos = xstrdup(pw->pw_gecos);
1.2       markus    199:        copy->pw_uid = pw->pw_uid;
                    200:        copy->pw_gid = pw->pw_gid;
1.11      markus    201:        copy->pw_expire = pw->pw_expire;
                    202:        copy->pw_change = pw->pw_change;
1.2       markus    203:        copy->pw_class = xstrdup(pw->pw_class);
                    204:        copy->pw_dir = xstrdup(pw->pw_dir);
                    205:        copy->pw_shell = xstrdup(pw->pw_shell);
                    206:        return copy;
1.5       stevesk   207: }
                    208:
1.12      markus    209: /*
                    210:  * Convert ASCII string to TCP/IP port number.
                    211:  * Port must be >0 and <=65535.
                    212:  * Return 0 if invalid.
                    213:  */
                    214: int
                    215: a2port(const char *s)
1.5       stevesk   216: {
                    217:        long port;
                    218:        char *endp;
                    219:
                    220:        errno = 0;
                    221:        port = strtol(s, &endp, 0);
                    222:        if (s == endp || *endp != '\0' ||
                    223:            (errno == ERANGE && (port == LONG_MIN || port == LONG_MAX)) ||
                    224:            port <= 0 || port > 65535)
                    225:                return 0;
                    226:
                    227:        return port;
1.9       stevesk   228: }
                    229:
1.36      reyk      230: int
                    231: a2tun(const char *s, int *remote)
                    232: {
                    233:        const char *errstr = NULL;
                    234:        char *sp, *ep;
                    235:        int tun;
                    236:
                    237:        if (remote != NULL) {
1.37      reyk      238:                *remote = SSH_TUNID_ANY;
1.36      reyk      239:                sp = xstrdup(s);
                    240:                if ((ep = strchr(sp, ':')) == NULL) {
                    241:                        xfree(sp);
                    242:                        return (a2tun(s, NULL));
                    243:                }
                    244:                ep[0] = '\0'; ep++;
                    245:                *remote = a2tun(ep, NULL);
                    246:                tun = a2tun(sp, NULL);
                    247:                xfree(sp);
1.37      reyk      248:                return (*remote == SSH_TUNID_ERR ? *remote : tun);
1.36      reyk      249:        }
                    250:
                    251:        if (strcasecmp(s, "any") == 0)
1.37      reyk      252:                return (SSH_TUNID_ANY);
1.36      reyk      253:
1.37      reyk      254:        tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
                    255:        if (errstr != NULL)
                    256:                return (SSH_TUNID_ERR);
1.36      reyk      257:
                    258:        return (tun);
                    259: }
                    260:
1.9       stevesk   261: #define SECONDS                1
                    262: #define MINUTES                (SECONDS * 60)
                    263: #define HOURS          (MINUTES * 60)
                    264: #define DAYS           (HOURS * 24)
                    265: #define WEEKS          (DAYS * 7)
                    266:
1.12      markus    267: /*
                    268:  * Convert a time string into seconds; format is
                    269:  * a sequence of:
                    270:  *      time[qualifier]
                    271:  *
                    272:  * Valid time qualifiers are:
                    273:  *      <none>  seconds
                    274:  *      s|S     seconds
                    275:  *      m|M     minutes
                    276:  *      h|H     hours
                    277:  *      d|D     days
                    278:  *      w|W     weeks
                    279:  *
                    280:  * Examples:
                    281:  *      90m     90 minutes
                    282:  *      1h30m   90 minutes
                    283:  *      2d      2 days
                    284:  *      1w      1 week
                    285:  *
                    286:  * Return -1 if time string is invalid.
                    287:  */
                    288: long
                    289: convtime(const char *s)
1.9       stevesk   290: {
                    291:        long total, secs;
                    292:        const char *p;
                    293:        char *endp;
                    294:
                    295:        errno = 0;
                    296:        total = 0;
                    297:        p = s;
                    298:
                    299:        if (p == NULL || *p == '\0')
                    300:                return -1;
                    301:
                    302:        while (*p) {
                    303:                secs = strtol(p, &endp, 10);
                    304:                if (p == endp ||
                    305:                    (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
                    306:                    secs < 0)
                    307:                        return -1;
                    308:
                    309:                switch (*endp++) {
                    310:                case '\0':
                    311:                        endp--;
1.48      deraadt   312:                        break;
1.9       stevesk   313:                case 's':
                    314:                case 'S':
                    315:                        break;
                    316:                case 'm':
                    317:                case 'M':
                    318:                        secs *= MINUTES;
                    319:                        break;
                    320:                case 'h':
                    321:                case 'H':
                    322:                        secs *= HOURS;
                    323:                        break;
                    324:                case 'd':
                    325:                case 'D':
                    326:                        secs *= DAYS;
                    327:                        break;
                    328:                case 'w':
                    329:                case 'W':
                    330:                        secs *= WEEKS;
                    331:                        break;
                    332:                default:
                    333:                        return -1;
                    334:                }
                    335:                total += secs;
                    336:                if (total < 0)
                    337:                        return -1;
                    338:                p = endp;
                    339:        }
                    340:
                    341:        return total;
1.56      dtucker   342: }
                    343:
                    344: /*
                    345:  * Returns a standardized host+port identifier string.
                    346:  * Caller must free returned string.
                    347:  */
                    348: char *
                    349: put_host_port(const char *host, u_short port)
                    350: {
                    351:        char *hoststr;
                    352:
                    353:        if (port == 0 || port == SSH_DEFAULT_PORT)
                    354:                return(xstrdup(host));
                    355:        if (asprintf(&hoststr, "[%s]:%d", host, (int)port) < 0)
                    356:                fatal("put_host_port: asprintf: %s", strerror(errno));
                    357:        debug3("put_host_port: %s", hoststr);
                    358:        return hoststr;
1.28      djm       359: }
                    360:
                    361: /*
                    362:  * Search for next delimiter between hostnames/addresses and ports.
                    363:  * Argument may be modified (for termination).
                    364:  * Returns *cp if parsing succeeds.
                    365:  * *cp is set to the start of the next delimiter, if one was found.
                    366:  * If this is the last field, *cp is set to NULL.
                    367:  */
                    368: char *
                    369: hpdelim(char **cp)
                    370: {
                    371:        char *s, *old;
                    372:
                    373:        if (cp == NULL || *cp == NULL)
                    374:                return NULL;
                    375:
                    376:        old = s = *cp;
                    377:        if (*s == '[') {
                    378:                if ((s = strchr(s, ']')) == NULL)
                    379:                        return NULL;
                    380:                else
                    381:                        s++;
                    382:        } else if ((s = strpbrk(s, ":/")) == NULL)
                    383:                s = *cp + strlen(*cp); /* skip to end (see first case below) */
                    384:
                    385:        switch (*s) {
                    386:        case '\0':
                    387:                *cp = NULL;     /* no more fields*/
                    388:                break;
1.29      deraadt   389:
1.28      djm       390:        case ':':
                    391:        case '/':
                    392:                *s = '\0';      /* terminate */
                    393:                *cp = s + 1;
                    394:                break;
1.29      deraadt   395:
1.28      djm       396:        default:
                    397:                return NULL;
                    398:        }
                    399:
                    400:        return old;
1.6       mouring   401: }
                    402:
                    403: char *
                    404: cleanhostname(char *host)
                    405: {
                    406:        if (*host == '[' && host[strlen(host) - 1] == ']') {
                    407:                host[strlen(host) - 1] = '\0';
                    408:                return (host + 1);
                    409:        } else
                    410:                return host;
                    411: }
                    412:
                    413: char *
                    414: colon(char *cp)
                    415: {
                    416:        int flag = 0;
                    417:
                    418:        if (*cp == ':')         /* Leading colon is part of file name. */
                    419:                return (0);
                    420:        if (*cp == '[')
                    421:                flag = 1;
                    422:
                    423:        for (; *cp; ++cp) {
                    424:                if (*cp == '@' && *(cp+1) == '[')
                    425:                        flag = 1;
                    426:                if (*cp == ']' && *(cp+1) == ':' && flag)
                    427:                        return (cp+1);
                    428:                if (*cp == ':' && !flag)
                    429:                        return (cp);
                    430:                if (*cp == '/')
                    431:                        return (0);
                    432:        }
                    433:        return (0);
1.7       mouring   434: }
                    435:
1.12      markus    436: /* function to assist building execv() arguments */
1.7       mouring   437: void
                    438: addargs(arglist *args, char *fmt, ...)
                    439: {
                    440:        va_list ap;
1.42      djm       441:        char *cp;
1.25      avsm      442:        u_int nalloc;
1.42      djm       443:        int r;
1.7       mouring   444:
                    445:        va_start(ap, fmt);
1.42      djm       446:        r = vasprintf(&cp, fmt, ap);
1.7       mouring   447:        va_end(ap);
1.42      djm       448:        if (r == -1)
                    449:                fatal("addargs: argument too long");
1.7       mouring   450:
1.22      markus    451:        nalloc = args->nalloc;
1.7       mouring   452:        if (args->list == NULL) {
1.22      markus    453:                nalloc = 32;
1.7       mouring   454:                args->num = 0;
1.22      markus    455:        } else if (args->num+2 >= nalloc)
                    456:                nalloc *= 2;
1.7       mouring   457:
1.50      djm       458:        args->list = xrealloc(args->list, nalloc, sizeof(char *));
1.22      markus    459:        args->nalloc = nalloc;
1.42      djm       460:        args->list[args->num++] = cp;
1.7       mouring   461:        args->list[args->num] = NULL;
1.42      djm       462: }
                    463:
                    464: void
                    465: replacearg(arglist *args, u_int which, char *fmt, ...)
                    466: {
                    467:        va_list ap;
                    468:        char *cp;
                    469:        int r;
                    470:
                    471:        va_start(ap, fmt);
                    472:        r = vasprintf(&cp, fmt, ap);
                    473:        va_end(ap);
                    474:        if (r == -1)
                    475:                fatal("replacearg: argument too long");
                    476:
                    477:        if (which >= args->num)
                    478:                fatal("replacearg: tried to replace invalid arg %d >= %d",
                    479:                    which, args->num);
                    480:        xfree(args->list[which]);
                    481:        args->list[which] = cp;
                    482: }
                    483:
                    484: void
                    485: freeargs(arglist *args)
                    486: {
                    487:        u_int i;
                    488:
                    489:        if (args->list != NULL) {
                    490:                for (i = 0; i < args->num; i++)
                    491:                        xfree(args->list[i]);
                    492:                xfree(args->list);
                    493:                args->nalloc = args->num = 0;
                    494:                args->list = NULL;
                    495:        }
1.30      djm       496: }
                    497:
                    498: /*
                    499:  * Expands tildes in the file name.  Returns data allocated by xmalloc.
                    500:  * Warning: this calls getpw*.
                    501:  */
                    502: char *
                    503: tilde_expand_filename(const char *filename, uid_t uid)
                    504: {
                    505:        const char *path;
                    506:        char user[128], ret[MAXPATHLEN];
                    507:        struct passwd *pw;
1.32      djm       508:        u_int len, slash;
1.30      djm       509:
                    510:        if (*filename != '~')
                    511:                return (xstrdup(filename));
                    512:        filename++;
                    513:
                    514:        path = strchr(filename, '/');
                    515:        if (path != NULL && path > filename) {          /* ~user/path */
1.32      djm       516:                slash = path - filename;
                    517:                if (slash > sizeof(user) - 1)
1.30      djm       518:                        fatal("tilde_expand_filename: ~username too long");
1.32      djm       519:                memcpy(user, filename, slash);
                    520:                user[slash] = '\0';
1.30      djm       521:                if ((pw = getpwnam(user)) == NULL)
                    522:                        fatal("tilde_expand_filename: No such user %s", user);
                    523:        } else if ((pw = getpwuid(uid)) == NULL)        /* ~/path */
                    524:                fatal("tilde_expand_filename: No such uid %d", uid);
                    525:
                    526:        if (strlcpy(ret, pw->pw_dir, sizeof(ret)) >= sizeof(ret))
                    527:                fatal("tilde_expand_filename: Path too long");
                    528:
                    529:        /* Make sure directory has a trailing '/' */
                    530:        len = strlen(pw->pw_dir);
                    531:        if ((len == 0 || pw->pw_dir[len - 1] != '/') &&
                    532:            strlcat(ret, "/", sizeof(ret)) >= sizeof(ret))
                    533:                fatal("tilde_expand_filename: Path too long");
                    534:
                    535:        /* Skip leading '/' from specified path */
                    536:        if (path != NULL)
                    537:                filename = path + 1;
                    538:        if (strlcat(ret, filename, sizeof(ret)) >= sizeof(ret))
                    539:                fatal("tilde_expand_filename: Path too long");
                    540:
                    541:        return (xstrdup(ret));
1.31      djm       542: }
                    543:
                    544: /*
                    545:  * Expand a string with a set of %[char] escapes. A number of escapes may be
                    546:  * specified as (char *escape_chars, char *replacement) pairs. The list must
1.34      dtucker   547:  * be terminated by a NULL escape_char. Returns replaced string in memory
1.31      djm       548:  * allocated by xmalloc.
                    549:  */
                    550: char *
                    551: percent_expand(const char *string, ...)
                    552: {
                    553: #define EXPAND_MAX_KEYS        16
                    554:        struct {
                    555:                const char *key;
                    556:                const char *repl;
                    557:        } keys[EXPAND_MAX_KEYS];
1.32      djm       558:        u_int num_keys, i, j;
1.31      djm       559:        char buf[4096];
                    560:        va_list ap;
                    561:
                    562:        /* Gather keys */
                    563:        va_start(ap, string);
                    564:        for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
                    565:                keys[num_keys].key = va_arg(ap, char *);
                    566:                if (keys[num_keys].key == NULL)
                    567:                        break;
                    568:                keys[num_keys].repl = va_arg(ap, char *);
                    569:                if (keys[num_keys].repl == NULL)
                    570:                        fatal("percent_expand: NULL replacement");
                    571:        }
                    572:        va_end(ap);
                    573:
                    574:        if (num_keys >= EXPAND_MAX_KEYS)
                    575:                fatal("percent_expand: too many keys");
                    576:
                    577:        /* Expand string */
                    578:        *buf = '\0';
                    579:        for (i = 0; *string != '\0'; string++) {
                    580:                if (*string != '%') {
                    581:  append:
                    582:                        buf[i++] = *string;
                    583:                        if (i >= sizeof(buf))
                    584:                                fatal("percent_expand: string too long");
                    585:                        buf[i] = '\0';
                    586:                        continue;
                    587:                }
                    588:                string++;
                    589:                if (*string == '%')
                    590:                        goto append;
                    591:                for (j = 0; j < num_keys; j++) {
                    592:                        if (strchr(keys[j].key, *string) != NULL) {
                    593:                                i = strlcat(buf, keys[j].repl, sizeof(buf));
                    594:                                if (i >= sizeof(buf))
                    595:                                        fatal("percent_expand: string too long");
                    596:                                break;
                    597:                        }
                    598:                }
                    599:                if (j >= num_keys)
                    600:                        fatal("percent_expand: unknown key %%%c", *string);
                    601:        }
                    602:        return (xstrdup(buf));
                    603: #undef EXPAND_MAX_KEYS
1.26      dtucker   604: }
                    605:
                    606: /*
                    607:  * Read an entire line from a public key file into a static buffer, discarding
                    608:  * lines that exceed the buffer size.  Returns 0 on success, -1 on failure.
                    609:  */
                    610: int
                    611: read_keyfile_line(FILE *f, const char *filename, char *buf, size_t bufsz,
1.27      dtucker   612:    u_long *lineno)
1.26      dtucker   613: {
                    614:        while (fgets(buf, bufsz, f) != NULL) {
1.65      ray       615:                if (buf[0] == '\0')
                    616:                        continue;
1.26      dtucker   617:                (*lineno)++;
                    618:                if (buf[strlen(buf) - 1] == '\n' || feof(f)) {
                    619:                        return 0;
                    620:                } else {
1.27      dtucker   621:                        debug("%s: %s line %lu exceeds size limit", __func__,
                    622:                            filename, *lineno);
1.26      dtucker   623:                        /* discard remainder of line */
1.29      deraadt   624:                        while (fgetc(f) != '\n' && !feof(f))
1.26      dtucker   625:                                ;       /* nothing */
                    626:                }
                    627:        }
                    628:        return -1;
1.36      reyk      629: }
                    630:
                    631: int
1.37      reyk      632: tun_open(int tun, int mode)
1.36      reyk      633: {
1.37      reyk      634:        struct ifreq ifr;
1.36      reyk      635:        char name[100];
1.37      reyk      636:        int fd = -1, sock;
1.36      reyk      637:
1.37      reyk      638:        /* Open the tunnel device */
                    639:        if (tun <= SSH_TUNID_MAX) {
1.36      reyk      640:                snprintf(name, sizeof(name), "/dev/tun%d", tun);
1.37      reyk      641:                fd = open(name, O_RDWR);
                    642:        } else if (tun == SSH_TUNID_ANY) {
                    643:                for (tun = 100; tun >= 0; tun--) {
                    644:                        snprintf(name, sizeof(name), "/dev/tun%d", tun);
                    645:                        if ((fd = open(name, O_RDWR)) >= 0)
                    646:                                break;
1.36      reyk      647:                }
                    648:        } else {
1.39      stevesk   649:                debug("%s: invalid tunnel %u", __func__, tun);
1.37      reyk      650:                return (-1);
                    651:        }
                    652:
                    653:        if (fd < 0) {
                    654:                debug("%s: %s open failed: %s", __func__, name, strerror(errno));
                    655:                return (-1);
1.36      reyk      656:        }
1.37      reyk      657:
                    658:        debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
                    659:
                    660:        /* Set the tunnel device operation mode */
                    661:        snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "tun%d", tun);
                    662:        if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
                    663:                goto failed;
                    664:
                    665:        if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1)
                    666:                goto failed;
1.40      reyk      667:
                    668:        /* Set interface mode */
                    669:        ifr.ifr_flags &= ~IFF_UP;
                    670:        if (mode == SSH_TUNMODE_ETHERNET)
1.37      reyk      671:                ifr.ifr_flags |= IFF_LINK0;
1.40      reyk      672:        else
                    673:                ifr.ifr_flags &= ~IFF_LINK0;
                    674:        if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1)
                    675:                goto failed;
                    676:
                    677:        /* Bring interface up */
1.37      reyk      678:        ifr.ifr_flags |= IFF_UP;
                    679:        if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1)
                    680:                goto failed;
                    681:
                    682:        close(sock);
                    683:        return (fd);
                    684:
                    685:  failed:
                    686:        if (fd >= 0)
                    687:                close(fd);
                    688:        if (sock >= 0)
                    689:                close(sock);
                    690:        debug("%s: failed to set %s mode %d: %s", __func__, name,
                    691:            mode, strerror(errno));
1.36      reyk      692:        return (-1);
1.35      djm       693: }
                    694:
                    695: void
                    696: sanitise_stdfd(void)
                    697: {
1.41      djm       698:        int nullfd, dupfd;
1.35      djm       699:
1.41      djm       700:        if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1.35      djm       701:                fprintf(stderr, "Couldn't open /dev/null: %s", strerror(errno));
                    702:                exit(1);
                    703:        }
1.41      djm       704:        while (++dupfd <= 2) {
                    705:                /* Only clobber closed fds */
                    706:                if (fcntl(dupfd, F_GETFL, 0) >= 0)
                    707:                        continue;
                    708:                if (dup2(nullfd, dupfd) == -1) {
1.35      djm       709:                        fprintf(stderr, "dup2: %s", strerror(errno));
                    710:                        exit(1);
                    711:                }
                    712:        }
                    713:        if (nullfd > 2)
                    714:                close(nullfd);
1.1       markus    715: }
1.33      djm       716:
                    717: char *
1.52      djm       718: tohex(const void *vp, size_t l)
1.33      djm       719: {
1.52      djm       720:        const u_char *p = (const u_char *)vp;
1.33      djm       721:        char b[3], *r;
1.52      djm       722:        size_t i, hl;
                    723:
                    724:        if (l > 65536)
                    725:                return xstrdup("tohex: length > 65536");
1.33      djm       726:
                    727:        hl = l * 2 + 1;
1.49      djm       728:        r = xcalloc(1, hl);
1.33      djm       729:        for (i = 0; i < l; i++) {
1.52      djm       730:                snprintf(b, sizeof(b), "%02x", p[i]);
1.33      djm       731:                strlcat(r, b, hl);
                    732:        }
                    733:        return (r);
                    734: }
                    735:
1.52      djm       736: u_int64_t
                    737: get_u64(const void *vp)
                    738: {
                    739:        const u_char *p = (const u_char *)vp;
                    740:        u_int64_t v;
                    741:
                    742:        v  = (u_int64_t)p[0] << 56;
                    743:        v |= (u_int64_t)p[1] << 48;
                    744:        v |= (u_int64_t)p[2] << 40;
                    745:        v |= (u_int64_t)p[3] << 32;
                    746:        v |= (u_int64_t)p[4] << 24;
                    747:        v |= (u_int64_t)p[5] << 16;
                    748:        v |= (u_int64_t)p[6] << 8;
                    749:        v |= (u_int64_t)p[7];
                    750:
                    751:        return (v);
                    752: }
                    753:
                    754: u_int32_t
                    755: get_u32(const void *vp)
                    756: {
                    757:        const u_char *p = (const u_char *)vp;
                    758:        u_int32_t v;
                    759:
                    760:        v  = (u_int32_t)p[0] << 24;
                    761:        v |= (u_int32_t)p[1] << 16;
                    762:        v |= (u_int32_t)p[2] << 8;
                    763:        v |= (u_int32_t)p[3];
                    764:
                    765:        return (v);
                    766: }
                    767:
                    768: u_int16_t
                    769: get_u16(const void *vp)
                    770: {
                    771:        const u_char *p = (const u_char *)vp;
                    772:        u_int16_t v;
                    773:
                    774:        v  = (u_int16_t)p[0] << 8;
                    775:        v |= (u_int16_t)p[1];
                    776:
                    777:        return (v);
                    778: }
                    779:
                    780: void
                    781: put_u64(void *vp, u_int64_t v)
                    782: {
                    783:        u_char *p = (u_char *)vp;
                    784:
                    785:        p[0] = (u_char)(v >> 56) & 0xff;
                    786:        p[1] = (u_char)(v >> 48) & 0xff;
                    787:        p[2] = (u_char)(v >> 40) & 0xff;
                    788:        p[3] = (u_char)(v >> 32) & 0xff;
                    789:        p[4] = (u_char)(v >> 24) & 0xff;
                    790:        p[5] = (u_char)(v >> 16) & 0xff;
                    791:        p[6] = (u_char)(v >> 8) & 0xff;
                    792:        p[7] = (u_char)v & 0xff;
                    793: }
                    794:
                    795: void
                    796: put_u32(void *vp, u_int32_t v)
                    797: {
                    798:        u_char *p = (u_char *)vp;
                    799:
                    800:        p[0] = (u_char)(v >> 24) & 0xff;
                    801:        p[1] = (u_char)(v >> 16) & 0xff;
                    802:        p[2] = (u_char)(v >> 8) & 0xff;
                    803:        p[3] = (u_char)v & 0xff;
                    804: }
                    805:
                    806:
                    807: void
                    808: put_u16(void *vp, u_int16_t v)
                    809: {
                    810:        u_char *p = (u_char *)vp;
                    811:
                    812:        p[0] = (u_char)(v >> 8) & 0xff;
                    813:        p[1] = (u_char)v & 0xff;
                    814: }
1.68    ! dtucker   815:
        !           816: void
        !           817: ms_subtract_diff(struct timeval *start, int *ms)
        !           818: {
        !           819:        struct timeval diff, finish;
        !           820:
        !           821:        gettimeofday(&finish, NULL);
        !           822:        timersub(&finish, start, &diff);
        !           823:        *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
        !           824: }
        !           825:
        !           826: void
        !           827: ms_to_timeval(struct timeval *tv, int ms)
        !           828: {
        !           829:        if (ms < 0)
        !           830:                ms = 0;
        !           831:        tv->tv_sec = ms / 1000;
        !           832:        tv->tv_usec = (ms % 1000) * 1000;
        !           833: }
        !           834: