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

1.1       markus      1: /*
                      2:  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
1.31      djm         3:  * Copyright (c) 2005 Damien Miller.  All rights reserved.
1.1       markus      4:  *
                      5:  * Redistribution and use in source and binary forms, with or without
                      6:  * modification, are permitted provided that the following conditions
                      7:  * are met:
                      8:  * 1. Redistributions of source code must retain the above copyright
                      9:  *    notice, this list of conditions and the following disclaimer.
                     10:  * 2. Redistributions in binary form must reproduce the above copyright
                     11:  *    notice, this list of conditions and the following disclaimer in the
                     12:  *    documentation and/or other materials provided with the distribution.
                     13:  *
                     14:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     15:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     16:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     17:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     18:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     19:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     20:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     21:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     22:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     23:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                     24:  */
                     25:
                     26: #include "includes.h"
1.33    ! djm        27: RCSID("$OpenBSD: misc.c,v 1.32 2005/06/17 02:44:32 djm Exp $");
1.1       markus     28:
                     29: #include "misc.h"
                     30: #include "log.h"
1.3       deraadt    31: #include "xmalloc.h"
1.1       markus     32:
1.12      markus     33: /* remove newline at end of string */
1.1       markus     34: char *
                     35: chop(char *s)
                     36: {
                     37:        char *t = s;
                     38:        while (*t) {
1.13      deraadt    39:                if (*t == '\n' || *t == '\r') {
1.1       markus     40:                        *t = '\0';
                     41:                        return s;
                     42:                }
                     43:                t++;
                     44:        }
                     45:        return s;
                     46:
                     47: }
                     48:
1.12      markus     49: /* set/unset filedescriptor to non-blocking */
1.24      djm        50: int
1.1       markus     51: set_nonblock(int fd)
                     52: {
                     53:        int val;
1.8       markus     54:
1.1       markus     55:        val = fcntl(fd, F_GETFL, 0);
                     56:        if (val < 0) {
                     57:                error("fcntl(%d, F_GETFL, 0): %s", fd, strerror(errno));
1.24      djm        58:                return (-1);
1.1       markus     59:        }
                     60:        if (val & O_NONBLOCK) {
1.24      djm        61:                debug3("fd %d is O_NONBLOCK", fd);
                     62:                return (0);
1.1       markus     63:        }
1.21      markus     64:        debug2("fd %d setting O_NONBLOCK", fd);
1.1       markus     65:        val |= O_NONBLOCK;
1.24      djm        66:        if (fcntl(fd, F_SETFL, val) == -1) {
                     67:                debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
                     68:                    strerror(errno));
                     69:                return (-1);
                     70:        }
                     71:        return (0);
1.8       markus     72: }
                     73:
1.24      djm        74: int
1.8       markus     75: unset_nonblock(int fd)
                     76: {
                     77:        int val;
                     78:
                     79:        val = fcntl(fd, F_GETFL, 0);
                     80:        if (val < 0) {
                     81:                error("fcntl(%d, F_GETFL, 0): %s", fd, strerror(errno));
1.24      djm        82:                return (-1);
1.8       markus     83:        }
                     84:        if (!(val & O_NONBLOCK)) {
1.24      djm        85:                debug3("fd %d is not O_NONBLOCK", fd);
                     86:                return (0);
1.8       markus     87:        }
1.10      markus     88:        debug("fd %d clearing O_NONBLOCK", fd);
1.8       markus     89:        val &= ~O_NONBLOCK;
1.24      djm        90:        if (fcntl(fd, F_SETFL, val) == -1) {
                     91:                debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
1.18      markus     92:                    fd, strerror(errno));
1.24      djm        93:                return (-1);
                     94:        }
                     95:        return (0);
1.15      stevesk    96: }
                     97:
                     98: /* disable nagle on socket */
                     99: void
                    100: set_nodelay(int fd)
                    101: {
1.17      stevesk   102:        int opt;
                    103:        socklen_t optlen;
1.15      stevesk   104:
1.16      stevesk   105:        optlen = sizeof opt;
                    106:        if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
1.23      markus    107:                debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
1.16      stevesk   108:                return;
                    109:        }
                    110:        if (opt == 1) {
                    111:                debug2("fd %d is TCP_NODELAY", fd);
                    112:                return;
                    113:        }
                    114:        opt = 1;
1.20      markus    115:        debug2("fd %d setting TCP_NODELAY", fd);
1.16      stevesk   116:        if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
1.15      stevesk   117:                error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
1.1       markus    118: }
                    119:
                    120: /* Characters considered whitespace in strsep calls. */
                    121: #define WHITESPACE " \t\r\n"
                    122:
1.12      markus    123: /* return next token in configuration line */
1.1       markus    124: char *
                    125: strdelim(char **s)
                    126: {
                    127:        char *old;
                    128:        int wspace = 0;
                    129:
                    130:        if (*s == NULL)
                    131:                return NULL;
                    132:
                    133:        old = *s;
                    134:
                    135:        *s = strpbrk(*s, WHITESPACE "=");
                    136:        if (*s == NULL)
                    137:                return (old);
                    138:
                    139:        /* Allow only one '=' to be skipped */
                    140:        if (*s[0] == '=')
                    141:                wspace = 1;
                    142:        *s[0] = '\0';
                    143:
                    144:        *s += strspn(*s + 1, WHITESPACE) + 1;
                    145:        if (*s[0] == '=' && !wspace)
                    146:                *s += strspn(*s + 1, WHITESPACE) + 1;
                    147:
                    148:        return (old);
1.2       markus    149: }
                    150:
                    151: struct passwd *
                    152: pwcopy(struct passwd *pw)
                    153: {
                    154:        struct passwd *copy = xmalloc(sizeof(*copy));
1.4       deraadt   155:
1.2       markus    156:        memset(copy, 0, sizeof(*copy));
                    157:        copy->pw_name = xstrdup(pw->pw_name);
                    158:        copy->pw_passwd = xstrdup(pw->pw_passwd);
1.4       deraadt   159:        copy->pw_gecos = xstrdup(pw->pw_gecos);
1.2       markus    160:        copy->pw_uid = pw->pw_uid;
                    161:        copy->pw_gid = pw->pw_gid;
1.11      markus    162:        copy->pw_expire = pw->pw_expire;
                    163:        copy->pw_change = pw->pw_change;
1.2       markus    164:        copy->pw_class = xstrdup(pw->pw_class);
                    165:        copy->pw_dir = xstrdup(pw->pw_dir);
                    166:        copy->pw_shell = xstrdup(pw->pw_shell);
                    167:        return copy;
1.5       stevesk   168: }
                    169:
1.12      markus    170: /*
                    171:  * Convert ASCII string to TCP/IP port number.
                    172:  * Port must be >0 and <=65535.
                    173:  * Return 0 if invalid.
                    174:  */
                    175: int
                    176: a2port(const char *s)
1.5       stevesk   177: {
                    178:        long port;
                    179:        char *endp;
                    180:
                    181:        errno = 0;
                    182:        port = strtol(s, &endp, 0);
                    183:        if (s == endp || *endp != '\0' ||
                    184:            (errno == ERANGE && (port == LONG_MIN || port == LONG_MAX)) ||
                    185:            port <= 0 || port > 65535)
                    186:                return 0;
                    187:
                    188:        return port;
1.9       stevesk   189: }
                    190:
                    191: #define SECONDS                1
                    192: #define MINUTES                (SECONDS * 60)
                    193: #define HOURS          (MINUTES * 60)
                    194: #define DAYS           (HOURS * 24)
                    195: #define WEEKS          (DAYS * 7)
                    196:
1.12      markus    197: /*
                    198:  * Convert a time string into seconds; format is
                    199:  * a sequence of:
                    200:  *      time[qualifier]
                    201:  *
                    202:  * Valid time qualifiers are:
                    203:  *      <none>  seconds
                    204:  *      s|S     seconds
                    205:  *      m|M     minutes
                    206:  *      h|H     hours
                    207:  *      d|D     days
                    208:  *      w|W     weeks
                    209:  *
                    210:  * Examples:
                    211:  *      90m     90 minutes
                    212:  *      1h30m   90 minutes
                    213:  *      2d      2 days
                    214:  *      1w      1 week
                    215:  *
                    216:  * Return -1 if time string is invalid.
                    217:  */
                    218: long
                    219: convtime(const char *s)
1.9       stevesk   220: {
                    221:        long total, secs;
                    222:        const char *p;
                    223:        char *endp;
                    224:
                    225:        errno = 0;
                    226:        total = 0;
                    227:        p = s;
                    228:
                    229:        if (p == NULL || *p == '\0')
                    230:                return -1;
                    231:
                    232:        while (*p) {
                    233:                secs = strtol(p, &endp, 10);
                    234:                if (p == endp ||
                    235:                    (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
                    236:                    secs < 0)
                    237:                        return -1;
                    238:
                    239:                switch (*endp++) {
                    240:                case '\0':
                    241:                        endp--;
                    242:                case 's':
                    243:                case 'S':
                    244:                        break;
                    245:                case 'm':
                    246:                case 'M':
                    247:                        secs *= MINUTES;
                    248:                        break;
                    249:                case 'h':
                    250:                case 'H':
                    251:                        secs *= HOURS;
                    252:                        break;
                    253:                case 'd':
                    254:                case 'D':
                    255:                        secs *= DAYS;
                    256:                        break;
                    257:                case 'w':
                    258:                case 'W':
                    259:                        secs *= WEEKS;
                    260:                        break;
                    261:                default:
                    262:                        return -1;
                    263:                }
                    264:                total += secs;
                    265:                if (total < 0)
                    266:                        return -1;
                    267:                p = endp;
                    268:        }
                    269:
                    270:        return total;
1.28      djm       271: }
                    272:
                    273: /*
                    274:  * Search for next delimiter between hostnames/addresses and ports.
                    275:  * Argument may be modified (for termination).
                    276:  * Returns *cp if parsing succeeds.
                    277:  * *cp is set to the start of the next delimiter, if one was found.
                    278:  * If this is the last field, *cp is set to NULL.
                    279:  */
                    280: char *
                    281: hpdelim(char **cp)
                    282: {
                    283:        char *s, *old;
                    284:
                    285:        if (cp == NULL || *cp == NULL)
                    286:                return NULL;
                    287:
                    288:        old = s = *cp;
                    289:        if (*s == '[') {
                    290:                if ((s = strchr(s, ']')) == NULL)
                    291:                        return NULL;
                    292:                else
                    293:                        s++;
                    294:        } else if ((s = strpbrk(s, ":/")) == NULL)
                    295:                s = *cp + strlen(*cp); /* skip to end (see first case below) */
                    296:
                    297:        switch (*s) {
                    298:        case '\0':
                    299:                *cp = NULL;     /* no more fields*/
                    300:                break;
1.29      deraadt   301:
1.28      djm       302:        case ':':
                    303:        case '/':
                    304:                *s = '\0';      /* terminate */
                    305:                *cp = s + 1;
                    306:                break;
1.29      deraadt   307:
1.28      djm       308:        default:
                    309:                return NULL;
                    310:        }
                    311:
                    312:        return old;
1.6       mouring   313: }
                    314:
                    315: char *
                    316: cleanhostname(char *host)
                    317: {
                    318:        if (*host == '[' && host[strlen(host) - 1] == ']') {
                    319:                host[strlen(host) - 1] = '\0';
                    320:                return (host + 1);
                    321:        } else
                    322:                return host;
                    323: }
                    324:
                    325: char *
                    326: colon(char *cp)
                    327: {
                    328:        int flag = 0;
                    329:
                    330:        if (*cp == ':')         /* Leading colon is part of file name. */
                    331:                return (0);
                    332:        if (*cp == '[')
                    333:                flag = 1;
                    334:
                    335:        for (; *cp; ++cp) {
                    336:                if (*cp == '@' && *(cp+1) == '[')
                    337:                        flag = 1;
                    338:                if (*cp == ']' && *(cp+1) == ':' && flag)
                    339:                        return (cp+1);
                    340:                if (*cp == ':' && !flag)
                    341:                        return (cp);
                    342:                if (*cp == '/')
                    343:                        return (0);
                    344:        }
                    345:        return (0);
1.7       mouring   346: }
                    347:
1.12      markus    348: /* function to assist building execv() arguments */
1.7       mouring   349: void
                    350: addargs(arglist *args, char *fmt, ...)
                    351: {
                    352:        va_list ap;
                    353:        char buf[1024];
1.25      avsm      354:        u_int nalloc;
1.7       mouring   355:
                    356:        va_start(ap, fmt);
                    357:        vsnprintf(buf, sizeof(buf), fmt, ap);
                    358:        va_end(ap);
                    359:
1.22      markus    360:        nalloc = args->nalloc;
1.7       mouring   361:        if (args->list == NULL) {
1.22      markus    362:                nalloc = 32;
1.7       mouring   363:                args->num = 0;
1.22      markus    364:        } else if (args->num+2 >= nalloc)
                    365:                nalloc *= 2;
1.7       mouring   366:
1.22      markus    367:        args->list = xrealloc(args->list, nalloc * sizeof(char *));
                    368:        args->nalloc = nalloc;
1.7       mouring   369:        args->list[args->num++] = xstrdup(buf);
                    370:        args->list[args->num] = NULL;
1.30      djm       371: }
                    372:
                    373: /*
                    374:  * Expands tildes in the file name.  Returns data allocated by xmalloc.
                    375:  * Warning: this calls getpw*.
                    376:  */
                    377: char *
                    378: tilde_expand_filename(const char *filename, uid_t uid)
                    379: {
                    380:        const char *path;
                    381:        char user[128], ret[MAXPATHLEN];
                    382:        struct passwd *pw;
1.32      djm       383:        u_int len, slash;
1.30      djm       384:
                    385:        if (*filename != '~')
                    386:                return (xstrdup(filename));
                    387:        filename++;
                    388:
                    389:        path = strchr(filename, '/');
                    390:        if (path != NULL && path > filename) {          /* ~user/path */
1.32      djm       391:                slash = path - filename;
                    392:                if (slash > sizeof(user) - 1)
1.30      djm       393:                        fatal("tilde_expand_filename: ~username too long");
1.32      djm       394:                memcpy(user, filename, slash);
                    395:                user[slash] = '\0';
1.30      djm       396:                if ((pw = getpwnam(user)) == NULL)
                    397:                        fatal("tilde_expand_filename: No such user %s", user);
                    398:        } else if ((pw = getpwuid(uid)) == NULL)        /* ~/path */
                    399:                fatal("tilde_expand_filename: No such uid %d", uid);
                    400:
                    401:        if (strlcpy(ret, pw->pw_dir, sizeof(ret)) >= sizeof(ret))
                    402:                fatal("tilde_expand_filename: Path too long");
                    403:
                    404:        /* Make sure directory has a trailing '/' */
                    405:        len = strlen(pw->pw_dir);
                    406:        if ((len == 0 || pw->pw_dir[len - 1] != '/') &&
                    407:            strlcat(ret, "/", sizeof(ret)) >= sizeof(ret))
                    408:                fatal("tilde_expand_filename: Path too long");
                    409:
                    410:        /* Skip leading '/' from specified path */
                    411:        if (path != NULL)
                    412:                filename = path + 1;
                    413:        if (strlcat(ret, filename, sizeof(ret)) >= sizeof(ret))
                    414:                fatal("tilde_expand_filename: Path too long");
                    415:
                    416:        return (xstrdup(ret));
1.31      djm       417: }
                    418:
                    419: /*
                    420:  * Expand a string with a set of %[char] escapes. A number of escapes may be
                    421:  * specified as (char *escape_chars, char *replacement) pairs. The list must
                    422:  * be terminated by an escape_char of -1. Returns replaced string in memory
                    423:  * allocated by xmalloc.
                    424:  */
                    425: char *
                    426: percent_expand(const char *string, ...)
                    427: {
                    428: #define EXPAND_MAX_KEYS        16
                    429:        struct {
                    430:                const char *key;
                    431:                const char *repl;
                    432:        } keys[EXPAND_MAX_KEYS];
1.32      djm       433:        u_int num_keys, i, j;
1.31      djm       434:        char buf[4096];
                    435:        va_list ap;
                    436:
                    437:        /* Gather keys */
                    438:        va_start(ap, string);
                    439:        for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
                    440:                keys[num_keys].key = va_arg(ap, char *);
                    441:                if (keys[num_keys].key == NULL)
                    442:                        break;
                    443:                keys[num_keys].repl = va_arg(ap, char *);
                    444:                if (keys[num_keys].repl == NULL)
                    445:                        fatal("percent_expand: NULL replacement");
                    446:        }
                    447:        va_end(ap);
                    448:
                    449:        if (num_keys >= EXPAND_MAX_KEYS)
                    450:                fatal("percent_expand: too many keys");
                    451:
                    452:        /* Expand string */
                    453:        *buf = '\0';
                    454:        for (i = 0; *string != '\0'; string++) {
                    455:                if (*string != '%') {
                    456:  append:
                    457:                        buf[i++] = *string;
                    458:                        if (i >= sizeof(buf))
                    459:                                fatal("percent_expand: string too long");
                    460:                        buf[i] = '\0';
                    461:                        continue;
                    462:                }
                    463:                string++;
                    464:                if (*string == '%')
                    465:                        goto append;
                    466:                for (j = 0; j < num_keys; j++) {
                    467:                        if (strchr(keys[j].key, *string) != NULL) {
                    468:                                i = strlcat(buf, keys[j].repl, sizeof(buf));
                    469:                                if (i >= sizeof(buf))
                    470:                                        fatal("percent_expand: string too long");
                    471:                                break;
                    472:                        }
                    473:                }
                    474:                if (j >= num_keys)
                    475:                        fatal("percent_expand: unknown key %%%c", *string);
                    476:        }
                    477:        return (xstrdup(buf));
                    478: #undef EXPAND_MAX_KEYS
1.26      dtucker   479: }
                    480:
                    481: /*
                    482:  * Read an entire line from a public key file into a static buffer, discarding
                    483:  * lines that exceed the buffer size.  Returns 0 on success, -1 on failure.
                    484:  */
                    485: int
                    486: read_keyfile_line(FILE *f, const char *filename, char *buf, size_t bufsz,
1.27      dtucker   487:    u_long *lineno)
1.26      dtucker   488: {
                    489:        while (fgets(buf, bufsz, f) != NULL) {
                    490:                (*lineno)++;
                    491:                if (buf[strlen(buf) - 1] == '\n' || feof(f)) {
                    492:                        return 0;
                    493:                } else {
1.27      dtucker   494:                        debug("%s: %s line %lu exceeds size limit", __func__,
                    495:                            filename, *lineno);
1.26      dtucker   496:                        /* discard remainder of line */
1.29      deraadt   497:                        while (fgetc(f) != '\n' && !feof(f))
1.26      dtucker   498:                                ;       /* nothing */
                    499:                }
                    500:        }
                    501:        return -1;
1.1       markus    502: }
1.33    ! djm       503:
        !           504: char *
        !           505: tohex(const u_char *d, u_int l)
        !           506: {
        !           507:        char b[3], *r;
        !           508:        u_int i, hl;
        !           509:
        !           510:        hl = l * 2 + 1;
        !           511:        r = xmalloc(hl);
        !           512:        *r = '\0';
        !           513:        for (i = 0; i < l; i++) {
        !           514:                snprintf(b, sizeof(b), "%02x", d[i]);
        !           515:                strlcat(r, b, hl);
        !           516:        }
        !           517:        return (r);
        !           518: }
        !           519: