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

Annotation of src/usr.bin/ssh/sftp.c, Revision 1.52

1.1       djm         1: /*
1.42      djm         2:  * Copyright (c) 2001-2004 Damien Miller <djm@openbsd.org>
1.1       djm         3:  *
1.42      djm         4:  * Permission to use, copy, modify, and distribute this software for any
                      5:  * purpose with or without fee is hereby granted, provided that the above
                      6:  * copyright notice and this permission notice appear in all copies.
1.1       djm         7:  *
1.42      djm         8:  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
                      9:  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
                     10:  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
                     11:  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
                     12:  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
                     13:  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
                     14:  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1.1       djm        15:  */
                     16:
                     17: #include "includes.h"
                     18:
1.52    ! djm        19: RCSID("$OpenBSD: sftp.c,v 1.51 2004/06/21 17:36:31 avsm Exp $");
1.44      djm        20:
                     21: #include <glob.h>
1.1       djm        22:
                     23: #include "buffer.h"
                     24: #include "xmalloc.h"
                     25: #include "log.h"
                     26: #include "pathnames.h"
1.16      mouring    27: #include "misc.h"
1.1       djm        28:
                     29: #include "sftp.h"
                     30: #include "sftp-common.h"
                     31: #include "sftp-client.h"
1.43      djm        32:
1.44      djm        33: /* File to read commands from */
                     34: FILE* infile;
1.15      mouring    35:
1.44      djm        36: /* Are we in batchfile mode? */
1.39      djm        37: int batchmode = 0;
1.44      djm        38:
                     39: /* Size of buffer used when copying files */
1.24      djm        40: size_t copy_buffer_len = 32768;
1.44      djm        41:
                     42: /* Number of concurrent outstanding requests */
1.26      djm        43: size_t num_requests = 16;
1.44      djm        44:
                     45: /* PID of ssh transport process */
1.36      djm        46: static pid_t sshpid = -1;
1.7       markus     47:
1.44      djm        48: /* This is set to 0 if the progressmeter is not desired. */
1.45      djm        49: int showprogress = 1;
1.44      djm        50:
1.46      djm        51: /* SIGINT received during command processing */
                     52: volatile sig_atomic_t interrupted = 0;
                     53:
1.52    ! djm        54: /* I wish qsort() took a separate ctx for the comparison function...*/
        !            55: int sort_flag;
        !            56:
1.44      djm        57: int remote_glob(struct sftp_conn *, const char *, int,
                     58:     int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
                     59:
                     60: /* Separators for interactive commands */
                     61: #define WHITESPACE " \t\r\n"
                     62:
1.52    ! djm        63: /* ls flags */
        !            64: #define LONG_VIEW      0x01    /* Full view ala ls -l */
        !            65: #define SHORT_VIEW     0x02    /* Single row view ala ls -1 */
        !            66: #define NUMERIC_VIEW   0x04    /* Long view with numeric uid/gid */
        !            67: #define NAME_SORT      0x08    /* Sort by name (default) */
        !            68: #define TIME_SORT      0x10    /* Sort by mtime */
        !            69: #define SIZE_SORT      0x20    /* Sort by file size */
        !            70: #define REVERSE_SORT   0x40    /* Reverse sort order */
        !            71:
1.50      djm        72: #define VIEW_FLAGS     (LONG_VIEW|SHORT_VIEW|NUMERIC_VIEW)
1.52    ! djm        73: #define SORT_FLAGS     (NAME_SORT|TIME_SORT|SIZE_SORT)
1.44      djm        74:
                     75: /* Commands for interactive mode */
                     76: #define I_CHDIR                1
                     77: #define I_CHGRP                2
                     78: #define I_CHMOD                3
                     79: #define I_CHOWN                4
                     80: #define I_GET          5
                     81: #define I_HELP         6
                     82: #define I_LCHDIR       7
                     83: #define I_LLS          8
                     84: #define I_LMKDIR       9
                     85: #define I_LPWD         10
                     86: #define I_LS           11
                     87: #define I_LUMASK       12
                     88: #define I_MKDIR                13
                     89: #define I_PUT          14
                     90: #define I_PWD          15
                     91: #define I_QUIT         16
                     92: #define I_RENAME       17
                     93: #define I_RM           18
                     94: #define I_RMDIR                19
                     95: #define I_SHELL                20
                     96: #define I_SYMLINK      21
                     97: #define I_VERSION      22
                     98: #define I_PROGRESS     23
                     99:
                    100: struct CMD {
                    101:        const char *c;
                    102:        const int n;
                    103: };
                    104:
                    105: static const struct CMD cmds[] = {
                    106:        { "bye",        I_QUIT },
                    107:        { "cd",         I_CHDIR },
                    108:        { "chdir",      I_CHDIR },
                    109:        { "chgrp",      I_CHGRP },
                    110:        { "chmod",      I_CHMOD },
                    111:        { "chown",      I_CHOWN },
                    112:        { "dir",        I_LS },
                    113:        { "exit",       I_QUIT },
                    114:        { "get",        I_GET },
                    115:        { "mget",       I_GET },
                    116:        { "help",       I_HELP },
                    117:        { "lcd",        I_LCHDIR },
                    118:        { "lchdir",     I_LCHDIR },
                    119:        { "lls",        I_LLS },
                    120:        { "lmkdir",     I_LMKDIR },
                    121:        { "ln",         I_SYMLINK },
                    122:        { "lpwd",       I_LPWD },
                    123:        { "ls",         I_LS },
                    124:        { "lumask",     I_LUMASK },
                    125:        { "mkdir",      I_MKDIR },
                    126:        { "progress",   I_PROGRESS },
                    127:        { "put",        I_PUT },
                    128:        { "mput",       I_PUT },
                    129:        { "pwd",        I_PWD },
                    130:        { "quit",       I_QUIT },
                    131:        { "rename",     I_RENAME },
                    132:        { "rm",         I_RM },
                    133:        { "rmdir",      I_RMDIR },
                    134:        { "symlink",    I_SYMLINK },
                    135:        { "version",    I_VERSION },
                    136:        { "!",          I_SHELL },
                    137:        { "?",          I_HELP },
                    138:        { NULL,                 -1}
                    139: };
                    140:
                    141: int interactive_loop(int fd_in, int fd_out, char *file1, char *file2);
                    142:
                    143: static void
1.46      djm       144: killchild(int signo)
                    145: {
                    146:        if (sshpid > 1)
                    147:                kill(sshpid, SIGTERM);
                    148:
                    149:        _exit(1);
                    150: }
                    151:
                    152: static void
                    153: cmd_interrupt(int signo)
                    154: {
                    155:        const char msg[] = "\rInterrupt  \n";
                    156:
                    157:        write(STDERR_FILENO, msg, sizeof(msg) - 1);
                    158:        interrupted = 1;
                    159: }
                    160:
                    161: static void
1.44      djm       162: help(void)
                    163: {
                    164:        printf("Available commands:\n");
                    165:        printf("cd path                       Change remote directory to 'path'\n");
                    166:        printf("lcd path                      Change local directory to 'path'\n");
                    167:        printf("chgrp grp path                Change group of file 'path' to 'grp'\n");
                    168:        printf("chmod mode path               Change permissions of file 'path' to 'mode'\n");
                    169:        printf("chown own path                Change owner of file 'path' to 'own'\n");
                    170:        printf("help                          Display this help text\n");
                    171:        printf("get remote-path [local-path]  Download file\n");
                    172:        printf("lls [ls-options [path]]       Display local directory listing\n");
                    173:        printf("ln oldpath newpath            Symlink remote file\n");
                    174:        printf("lmkdir path                   Create local directory\n");
                    175:        printf("lpwd                          Print local working directory\n");
                    176:        printf("ls [path]                     Display remote directory listing\n");
                    177:        printf("lumask umask                  Set local umask to 'umask'\n");
                    178:        printf("mkdir path                    Create remote directory\n");
                    179:        printf("progress                      Toggle display of progress meter\n");
                    180:        printf("put local-path [remote-path]  Upload file\n");
                    181:        printf("pwd                           Display remote working directory\n");
                    182:        printf("exit                          Quit sftp\n");
                    183:        printf("quit                          Quit sftp\n");
                    184:        printf("rename oldpath newpath        Rename remote file\n");
                    185:        printf("rmdir path                    Remove remote directory\n");
                    186:        printf("rm path                       Delete remote file\n");
                    187:        printf("symlink oldpath newpath       Symlink remote file\n");
                    188:        printf("version                       Show SFTP version\n");
                    189:        printf("!command                      Execute 'command' in local shell\n");
                    190:        printf("!                             Escape to local shell\n");
                    191:        printf("?                             Synonym for help\n");
                    192: }
                    193:
                    194: static void
                    195: local_do_shell(const char *args)
                    196: {
                    197:        int status;
                    198:        char *shell;
                    199:        pid_t pid;
                    200:
                    201:        if (!*args)
                    202:                args = NULL;
                    203:
                    204:        if ((shell = getenv("SHELL")) == NULL)
                    205:                shell = _PATH_BSHELL;
                    206:
                    207:        if ((pid = fork()) == -1)
                    208:                fatal("Couldn't fork: %s", strerror(errno));
                    209:
                    210:        if (pid == 0) {
                    211:                /* XXX: child has pipe fds to ssh subproc open - issue? */
                    212:                if (args) {
                    213:                        debug3("Executing %s -c \"%s\"", shell, args);
                    214:                        execl(shell, shell, "-c", args, (char *)NULL);
                    215:                } else {
                    216:                        debug3("Executing %s", shell);
                    217:                        execl(shell, shell, (char *)NULL);
                    218:                }
                    219:                fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell,
                    220:                    strerror(errno));
                    221:                _exit(1);
                    222:        }
                    223:        while (waitpid(pid, &status, 0) == -1)
                    224:                if (errno != EINTR)
                    225:                        fatal("Couldn't wait for child: %s", strerror(errno));
                    226:        if (!WIFEXITED(status))
                    227:                error("Shell exited abormally");
                    228:        else if (WEXITSTATUS(status))
                    229:                error("Shell exited with status %d", WEXITSTATUS(status));
                    230: }
                    231:
                    232: static void
                    233: local_do_ls(const char *args)
                    234: {
                    235:        if (!args || !*args)
                    236:                local_do_shell(_PATH_LS);
                    237:        else {
                    238:                int len = strlen(_PATH_LS " ") + strlen(args) + 1;
                    239:                char *buf = xmalloc(len);
                    240:
                    241:                /* XXX: quoting - rip quoting code from ftp? */
                    242:                snprintf(buf, len, _PATH_LS " %s", args);
                    243:                local_do_shell(buf);
                    244:                xfree(buf);
                    245:        }
                    246: }
                    247:
                    248: /* Strip one path (usually the pwd) from the start of another */
                    249: static char *
                    250: path_strip(char *path, char *strip)
                    251: {
                    252:        size_t len;
                    253:
                    254:        if (strip == NULL)
                    255:                return (xstrdup(path));
                    256:
                    257:        len = strlen(strip);
                    258:        if (strip != NULL && strncmp(path, strip, len) == 0) {
                    259:                if (strip[len - 1] != '/' && path[len] == '/')
                    260:                        len++;
                    261:                return (xstrdup(path + len));
                    262:        }
                    263:
                    264:        return (xstrdup(path));
                    265: }
                    266:
                    267: static char *
                    268: path_append(char *p1, char *p2)
                    269: {
                    270:        char *ret;
                    271:        int len = strlen(p1) + strlen(p2) + 2;
                    272:
                    273:        ret = xmalloc(len);
                    274:        strlcpy(ret, p1, len);
                    275:        if (p1[strlen(p1) - 1] != '/')
                    276:                strlcat(ret, "/", len);
                    277:        strlcat(ret, p2, len);
                    278:
                    279:        return(ret);
                    280: }
                    281:
                    282: static char *
                    283: make_absolute(char *p, char *pwd)
                    284: {
1.51      avsm      285:        char *abs_str;
1.44      djm       286:
                    287:        /* Derelativise */
                    288:        if (p && p[0] != '/') {
1.51      avsm      289:                abs_str = path_append(pwd, p);
1.44      djm       290:                xfree(p);
1.51      avsm      291:                return(abs_str);
1.44      djm       292:        } else
                    293:                return(p);
                    294: }
                    295:
                    296: static int
                    297: infer_path(const char *p, char **ifp)
                    298: {
                    299:        char *cp;
                    300:
                    301:        cp = strrchr(p, '/');
                    302:        if (cp == NULL) {
                    303:                *ifp = xstrdup(p);
                    304:                return(0);
                    305:        }
                    306:
                    307:        if (!cp[1]) {
                    308:                error("Invalid path");
                    309:                return(-1);
                    310:        }
                    311:
                    312:        *ifp = xstrdup(cp + 1);
                    313:        return(0);
                    314: }
                    315:
                    316: static int
                    317: parse_getput_flags(const char **cpp, int *pflag)
                    318: {
                    319:        const char *cp = *cpp;
                    320:
                    321:        /* Check for flags */
                    322:        if (cp[0] == '-' && cp[1] && strchr(WHITESPACE, cp[2])) {
                    323:                switch (cp[1]) {
                    324:                case 'p':
                    325:                case 'P':
                    326:                        *pflag = 1;
                    327:                        break;
                    328:                default:
                    329:                        error("Invalid flag -%c", cp[1]);
                    330:                        return(-1);
                    331:                }
                    332:                cp += 2;
                    333:                *cpp = cp + strspn(cp, WHITESPACE);
                    334:        }
                    335:
                    336:        return(0);
                    337: }
                    338:
                    339: static int
                    340: parse_ls_flags(const char **cpp, int *lflag)
                    341: {
                    342:        const char *cp = *cpp;
                    343:
1.52    ! djm       344:        /* Defaults */
        !           345:        *lflag = NAME_SORT;
        !           346:
1.44      djm       347:        /* Check for flags */
                    348:        if (cp++[0] == '-') {
                    349:                for(; strchr(WHITESPACE, *cp) == NULL; cp++) {
                    350:                        switch (*cp) {
                    351:                        case 'l':
1.50      djm       352:                                *lflag &= ~VIEW_FLAGS;
                    353:                                *lflag |= LONG_VIEW;
1.44      djm       354:                                break;
                    355:                        case '1':
1.50      djm       356:                                *lflag &= ~VIEW_FLAGS;
                    357:                                *lflag |= SHORT_VIEW;
                    358:                                break;
                    359:                        case 'n':
                    360:                                *lflag &= ~VIEW_FLAGS;
                    361:                                *lflag |= NUMERIC_VIEW|LONG_VIEW;
1.44      djm       362:                                break;
1.52    ! djm       363:                        case 'S':
        !           364:                                *lflag &= ~SORT_FLAGS;
        !           365:                                *lflag |= SIZE_SORT;
        !           366:                                break;
        !           367:                        case 't':
        !           368:                                *lflag &= ~SORT_FLAGS;
        !           369:                                *lflag |= TIME_SORT;
        !           370:                                break;
        !           371:                        case 'r':
        !           372:                                *lflag |= REVERSE_SORT;
        !           373:                                break;
        !           374:                        case 'f':
        !           375:                                *lflag &= ~SORT_FLAGS;
        !           376:                                break;
1.44      djm       377:                        default:
                    378:                                error("Invalid flag -%c", *cp);
                    379:                                return(-1);
                    380:                        }
                    381:                }
                    382:                *cpp = cp + strspn(cp, WHITESPACE);
                    383:        }
                    384:
                    385:        return(0);
                    386: }
                    387:
                    388: static int
                    389: get_pathname(const char **cpp, char **path)
                    390: {
                    391:        const char *cp = *cpp, *end;
                    392:        char quot;
                    393:        int i, j;
                    394:
                    395:        cp += strspn(cp, WHITESPACE);
                    396:        if (!*cp) {
                    397:                *cpp = cp;
                    398:                *path = NULL;
                    399:                return (0);
                    400:        }
                    401:
                    402:        *path = xmalloc(strlen(cp) + 1);
                    403:
                    404:        /* Check for quoted filenames */
                    405:        if (*cp == '\"' || *cp == '\'') {
                    406:                quot = *cp++;
                    407:
                    408:                /* Search for terminating quote, unescape some chars */
                    409:                for (i = j = 0; i <= strlen(cp); i++) {
                    410:                        if (cp[i] == quot) {    /* Found quote */
                    411:                                i++;
                    412:                                (*path)[j] = '\0';
                    413:                                break;
                    414:                        }
                    415:                        if (cp[i] == '\0') {    /* End of string */
                    416:                                error("Unterminated quote");
                    417:                                goto fail;
                    418:                        }
                    419:                        if (cp[i] == '\\') {    /* Escaped characters */
                    420:                                i++;
                    421:                                if (cp[i] != '\'' && cp[i] != '\"' &&
                    422:                                    cp[i] != '\\') {
                    423:                                        error("Bad escaped character '\%c'",
                    424:                                            cp[i]);
                    425:                                        goto fail;
                    426:                                }
                    427:                        }
                    428:                        (*path)[j++] = cp[i];
                    429:                }
                    430:
                    431:                if (j == 0) {
                    432:                        error("Empty quotes");
                    433:                        goto fail;
                    434:                }
                    435:                *cpp = cp + i + strspn(cp + i, WHITESPACE);
                    436:        } else {
                    437:                /* Read to end of filename */
                    438:                end = strpbrk(cp, WHITESPACE);
                    439:                if (end == NULL)
                    440:                        end = strchr(cp, '\0');
                    441:                *cpp = end + strspn(end, WHITESPACE);
                    442:
                    443:                memcpy(*path, cp, end - cp);
                    444:                (*path)[end - cp] = '\0';
                    445:        }
                    446:        return (0);
                    447:
                    448:  fail:
                    449:        xfree(*path);
                    450:        *path = NULL;
                    451:        return (-1);
                    452: }
                    453:
                    454: static int
                    455: is_dir(char *path)
                    456: {
                    457:        struct stat sb;
                    458:
                    459:        /* XXX: report errors? */
                    460:        if (stat(path, &sb) == -1)
                    461:                return(0);
                    462:
                    463:        return(sb.st_mode & S_IFDIR);
                    464: }
                    465:
                    466: static int
                    467: is_reg(char *path)
                    468: {
                    469:        struct stat sb;
                    470:
                    471:        if (stat(path, &sb) == -1)
                    472:                fatal("stat %s: %s", path, strerror(errno));
                    473:
                    474:        return(S_ISREG(sb.st_mode));
                    475: }
                    476:
                    477: static int
                    478: remote_is_dir(struct sftp_conn *conn, char *path)
                    479: {
                    480:        Attrib *a;
                    481:
                    482:        /* XXX: report errors? */
                    483:        if ((a = do_stat(conn, path, 1)) == NULL)
                    484:                return(0);
                    485:        if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
                    486:                return(0);
                    487:        return(a->perm & S_IFDIR);
                    488: }
                    489:
                    490: static int
                    491: process_get(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
                    492: {
                    493:        char *abs_src = NULL;
                    494:        char *abs_dst = NULL;
                    495:        char *tmp;
                    496:        glob_t g;
                    497:        int err = 0;
                    498:        int i;
                    499:
                    500:        abs_src = xstrdup(src);
                    501:        abs_src = make_absolute(abs_src, pwd);
                    502:
                    503:        memset(&g, 0, sizeof(g));
                    504:        debug3("Looking up %s", abs_src);
                    505:        if (remote_glob(conn, abs_src, 0, NULL, &g)) {
                    506:                error("File \"%s\" not found.", abs_src);
                    507:                err = -1;
                    508:                goto out;
                    509:        }
                    510:
                    511:        /* If multiple matches, dst must be a directory or unspecified */
                    512:        if (g.gl_matchc > 1 && dst && !is_dir(dst)) {
                    513:                error("Multiple files match, but \"%s\" is not a directory",
                    514:                    dst);
                    515:                err = -1;
                    516:                goto out;
                    517:        }
                    518:
1.46      djm       519:        for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1.44      djm       520:                if (infer_path(g.gl_pathv[i], &tmp)) {
                    521:                        err = -1;
                    522:                        goto out;
                    523:                }
                    524:
                    525:                if (g.gl_matchc == 1 && dst) {
                    526:                        /* If directory specified, append filename */
                    527:                        if (is_dir(dst)) {
                    528:                                if (infer_path(g.gl_pathv[0], &tmp)) {
                    529:                                        err = 1;
                    530:                                        goto out;
                    531:                                }
                    532:                                abs_dst = path_append(dst, tmp);
                    533:                                xfree(tmp);
                    534:                        } else
                    535:                                abs_dst = xstrdup(dst);
                    536:                } else if (dst) {
                    537:                        abs_dst = path_append(dst, tmp);
                    538:                        xfree(tmp);
                    539:                } else
                    540:                        abs_dst = tmp;
                    541:
                    542:                printf("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
                    543:                if (do_download(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
                    544:                        err = -1;
                    545:                xfree(abs_dst);
                    546:                abs_dst = NULL;
                    547:        }
                    548:
                    549: out:
                    550:        xfree(abs_src);
                    551:        if (abs_dst)
                    552:                xfree(abs_dst);
                    553:        globfree(&g);
                    554:        return(err);
                    555: }
                    556:
                    557: static int
                    558: process_put(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
                    559: {
                    560:        char *tmp_dst = NULL;
                    561:        char *abs_dst = NULL;
                    562:        char *tmp;
                    563:        glob_t g;
                    564:        int err = 0;
                    565:        int i;
                    566:
                    567:        if (dst) {
                    568:                tmp_dst = xstrdup(dst);
                    569:                tmp_dst = make_absolute(tmp_dst, pwd);
                    570:        }
                    571:
                    572:        memset(&g, 0, sizeof(g));
                    573:        debug3("Looking up %s", src);
                    574:        if (glob(src, 0, NULL, &g)) {
                    575:                error("File \"%s\" not found.", src);
                    576:                err = -1;
                    577:                goto out;
                    578:        }
                    579:
                    580:        /* If multiple matches, dst may be directory or unspecified */
                    581:        if (g.gl_matchc > 1 && tmp_dst && !remote_is_dir(conn, tmp_dst)) {
                    582:                error("Multiple files match, but \"%s\" is not a directory",
                    583:                    tmp_dst);
                    584:                err = -1;
                    585:                goto out;
                    586:        }
                    587:
1.46      djm       588:        for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1.44      djm       589:                if (!is_reg(g.gl_pathv[i])) {
                    590:                        error("skipping non-regular file %s",
                    591:                            g.gl_pathv[i]);
                    592:                        continue;
                    593:                }
                    594:                if (infer_path(g.gl_pathv[i], &tmp)) {
                    595:                        err = -1;
                    596:                        goto out;
                    597:                }
                    598:
                    599:                if (g.gl_matchc == 1 && tmp_dst) {
                    600:                        /* If directory specified, append filename */
                    601:                        if (remote_is_dir(conn, tmp_dst)) {
                    602:                                if (infer_path(g.gl_pathv[0], &tmp)) {
                    603:                                        err = 1;
                    604:                                        goto out;
                    605:                                }
                    606:                                abs_dst = path_append(tmp_dst, tmp);
                    607:                                xfree(tmp);
                    608:                        } else
                    609:                                abs_dst = xstrdup(tmp_dst);
                    610:
                    611:                } else if (tmp_dst) {
                    612:                        abs_dst = path_append(tmp_dst, tmp);
                    613:                        xfree(tmp);
                    614:                } else
                    615:                        abs_dst = make_absolute(tmp, pwd);
                    616:
                    617:                printf("Uploading %s to %s\n", g.gl_pathv[i], abs_dst);
                    618:                if (do_upload(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
                    619:                        err = -1;
                    620:        }
                    621:
                    622: out:
                    623:        if (abs_dst)
                    624:                xfree(abs_dst);
                    625:        if (tmp_dst)
                    626:                xfree(tmp_dst);
                    627:        globfree(&g);
                    628:        return(err);
                    629: }
                    630:
                    631: static int
                    632: sdirent_comp(const void *aa, const void *bb)
                    633: {
                    634:        SFTP_DIRENT *a = *(SFTP_DIRENT **)aa;
                    635:        SFTP_DIRENT *b = *(SFTP_DIRENT **)bb;
1.52    ! djm       636:        int rmul = sort_flag & REVERSE_SORT ? -1 : 1;
1.44      djm       637:
1.52    ! djm       638: #define NCMP(a,b) (a == b ? 0 : (a < b ? 1 : -1))
        !           639:        if (sort_flag & NAME_SORT)
        !           640:                return (rmul * strcmp(a->filename, b->filename));
        !           641:        else if (sort_flag & TIME_SORT)
        !           642:                return (rmul * NCMP(a->a.mtime, b->a.mtime));
        !           643:        else if (sort_flag & SIZE_SORT)
        !           644:                return (rmul * NCMP(a->a.size, b->a.size));
        !           645:
        !           646:        fatal("Unknown ls sort type");
1.44      djm       647: }
                    648:
                    649: /* sftp ls.1 replacement for directories */
                    650: static int
                    651: do_ls_dir(struct sftp_conn *conn, char *path, char *strip_path, int lflag)
                    652: {
                    653:        int n, c = 1, colspace = 0, columns = 1;
                    654:        SFTP_DIRENT **d;
                    655:
                    656:        if ((n = do_readdir(conn, path, &d)) != 0)
                    657:                return (n);
                    658:
                    659:        if (!(lflag & SHORT_VIEW)) {
                    660:                int m = 0, width = 80;
                    661:                struct winsize ws;
                    662:                char *tmp;
                    663:
                    664:                /* Count entries for sort and find longest filename */
                    665:                for (n = 0; d[n] != NULL; n++)
                    666:                        m = MAX(m, strlen(d[n]->filename));
                    667:
                    668:                /* Add any subpath that also needs to be counted */
                    669:                tmp = path_strip(path, strip_path);
                    670:                m += strlen(tmp);
                    671:                xfree(tmp);
                    672:
                    673:                if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
                    674:                        width = ws.ws_col;
                    675:
                    676:                columns = width / (m + 2);
                    677:                columns = MAX(columns, 1);
                    678:                colspace = width / columns;
                    679:                colspace = MIN(colspace, width);
                    680:        }
                    681:
1.52    ! djm       682:        if (lflag & SORT_FLAGS) {
        !           683:                sort_flag = lflag & (SORT_FLAGS|REVERSE_SORT);
        !           684:                qsort(d, n, sizeof(*d), sdirent_comp);
        !           685:        }
1.44      djm       686:
1.46      djm       687:        for (n = 0; d[n] != NULL && !interrupted; n++) {
1.44      djm       688:                char *tmp, *fname;
                    689:
                    690:                tmp = path_append(path, d[n]->filename);
                    691:                fname = path_strip(tmp, strip_path);
                    692:                xfree(tmp);
                    693:
                    694:                if (lflag & LONG_VIEW) {
1.50      djm       695:                        if (lflag & NUMERIC_VIEW) {
                    696:                                char *lname;
                    697:                                struct stat sb;
                    698:
                    699:                                memset(&sb, 0, sizeof(sb));
                    700:                                attrib_to_stat(&d[n]->a, &sb);
                    701:                                lname = ls_file(fname, &sb, 1);
                    702:                                printf("%s\n", lname);
                    703:                                xfree(lname);
                    704:                        } else
                    705:                                printf("%s\n", d[n]->longname);
1.44      djm       706:                } else {
                    707:                        printf("%-*s", colspace, fname);
                    708:                        if (c >= columns) {
                    709:                                printf("\n");
                    710:                                c = 1;
                    711:                        } else
                    712:                                c++;
                    713:                }
                    714:
                    715:                xfree(fname);
                    716:        }
                    717:
                    718:        if (!(lflag & LONG_VIEW) && (c != 1))
                    719:                printf("\n");
                    720:
                    721:        free_sftp_dirents(d);
                    722:        return (0);
                    723: }
                    724:
                    725: /* sftp ls.1 replacement which handles path globs */
                    726: static int
                    727: do_globbed_ls(struct sftp_conn *conn, char *path, char *strip_path,
                    728:     int lflag)
                    729: {
                    730:        glob_t g;
                    731:        int i, c = 1, colspace = 0, columns = 1;
                    732:        Attrib *a;
                    733:
                    734:        memset(&g, 0, sizeof(g));
                    735:
                    736:        if (remote_glob(conn, path, GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE,
                    737:            NULL, &g)) {
                    738:                error("Can't ls: \"%s\" not found", path);
                    739:                return (-1);
                    740:        }
                    741:
1.46      djm       742:        if (interrupted)
                    743:                goto out;
                    744:
1.44      djm       745:        /*
                    746:         * If the glob returns a single match, which is the same as the
                    747:         * input glob, and it is a directory, then just list its contents
                    748:         */
                    749:        if (g.gl_pathc == 1 &&
                    750:            strncmp(path, g.gl_pathv[0], strlen(g.gl_pathv[0]) - 1) == 0) {
                    751:                if ((a = do_lstat(conn, path, 1)) == NULL) {
                    752:                        globfree(&g);
                    753:                        return (-1);
                    754:                }
                    755:                if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
                    756:                    S_ISDIR(a->perm)) {
                    757:                        globfree(&g);
                    758:                        return (do_ls_dir(conn, path, strip_path, lflag));
                    759:                }
                    760:        }
                    761:
                    762:        if (!(lflag & SHORT_VIEW)) {
                    763:                int m = 0, width = 80;
                    764:                struct winsize ws;
                    765:
                    766:                /* Count entries for sort and find longest filename */
                    767:                for (i = 0; g.gl_pathv[i]; i++)
                    768:                        m = MAX(m, strlen(g.gl_pathv[i]));
                    769:
                    770:                if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
                    771:                        width = ws.ws_col;
                    772:
                    773:                columns = width / (m + 2);
                    774:                columns = MAX(columns, 1);
                    775:                colspace = width / columns;
                    776:        }
                    777:
1.46      djm       778:        for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1.44      djm       779:                char *fname;
                    780:
                    781:                fname = path_strip(g.gl_pathv[i], strip_path);
                    782:
                    783:                if (lflag & LONG_VIEW) {
                    784:                        char *lname;
                    785:                        struct stat sb;
                    786:
                    787:                        /*
                    788:                         * XXX: this is slow - 1 roundtrip per path
                    789:                         * A solution to this is to fork glob() and
                    790:                         * build a sftp specific version which keeps the
                    791:                         * attribs (which currently get thrown away)
                    792:                         * that the server returns as well as the filenames.
                    793:                         */
                    794:                        memset(&sb, 0, sizeof(sb));
                    795:                        a = do_lstat(conn, g.gl_pathv[i], 1);
                    796:                        if (a != NULL)
                    797:                                attrib_to_stat(a, &sb);
                    798:                        lname = ls_file(fname, &sb, 1);
                    799:                        printf("%s\n", lname);
                    800:                        xfree(lname);
                    801:                } else {
                    802:                        printf("%-*s", colspace, fname);
                    803:                        if (c >= columns) {
                    804:                                printf("\n");
                    805:                                c = 1;
                    806:                        } else
                    807:                                c++;
                    808:                }
                    809:                xfree(fname);
                    810:        }
                    811:
                    812:        if (!(lflag & LONG_VIEW) && (c != 1))
                    813:                printf("\n");
                    814:
1.46      djm       815:  out:
1.44      djm       816:        if (g.gl_pathc)
                    817:                globfree(&g);
                    818:
                    819:        return (0);
                    820: }
                    821:
                    822: static int
                    823: parse_args(const char **cpp, int *pflag, int *lflag, int *iflag,
                    824:     unsigned long *n_arg, char **path1, char **path2)
                    825: {
                    826:        const char *cmd, *cp = *cpp;
                    827:        char *cp2;
                    828:        int base = 0;
                    829:        long l;
                    830:        int i, cmdnum;
                    831:
                    832:        /* Skip leading whitespace */
                    833:        cp = cp + strspn(cp, WHITESPACE);
                    834:
                    835:        /* Ignore blank lines and lines which begin with comment '#' char */
                    836:        if (*cp == '\0' || *cp == '#')
                    837:                return (0);
                    838:
                    839:        /* Check for leading '-' (disable error processing) */
                    840:        *iflag = 0;
                    841:        if (*cp == '-') {
                    842:                *iflag = 1;
                    843:                cp++;
                    844:        }
                    845:
                    846:        /* Figure out which command we have */
                    847:        for (i = 0; cmds[i].c; i++) {
                    848:                int cmdlen = strlen(cmds[i].c);
                    849:
                    850:                /* Check for command followed by whitespace */
                    851:                if (!strncasecmp(cp, cmds[i].c, cmdlen) &&
                    852:                    strchr(WHITESPACE, cp[cmdlen])) {
                    853:                        cp += cmdlen;
                    854:                        cp = cp + strspn(cp, WHITESPACE);
                    855:                        break;
                    856:                }
                    857:        }
                    858:        cmdnum = cmds[i].n;
                    859:        cmd = cmds[i].c;
                    860:
                    861:        /* Special case */
                    862:        if (*cp == '!') {
                    863:                cp++;
                    864:                cmdnum = I_SHELL;
                    865:        } else if (cmdnum == -1) {
                    866:                error("Invalid command.");
                    867:                return (-1);
                    868:        }
                    869:
                    870:        /* Get arguments and parse flags */
                    871:        *lflag = *pflag = *n_arg = 0;
                    872:        *path1 = *path2 = NULL;
                    873:        switch (cmdnum) {
                    874:        case I_GET:
                    875:        case I_PUT:
                    876:                if (parse_getput_flags(&cp, pflag))
                    877:                        return(-1);
                    878:                /* Get first pathname (mandatory) */
                    879:                if (get_pathname(&cp, path1))
                    880:                        return(-1);
                    881:                if (*path1 == NULL) {
                    882:                        error("You must specify at least one path after a "
                    883:                            "%s command.", cmd);
                    884:                        return(-1);
                    885:                }
                    886:                /* Try to get second pathname (optional) */
                    887:                if (get_pathname(&cp, path2))
                    888:                        return(-1);
                    889:                break;
                    890:        case I_RENAME:
                    891:        case I_SYMLINK:
                    892:                if (get_pathname(&cp, path1))
                    893:                        return(-1);
                    894:                if (get_pathname(&cp, path2))
                    895:                        return(-1);
                    896:                if (!*path1 || !*path2) {
                    897:                        error("You must specify two paths after a %s "
                    898:                            "command.", cmd);
                    899:                        return(-1);
                    900:                }
                    901:                break;
                    902:        case I_RM:
                    903:        case I_MKDIR:
                    904:        case I_RMDIR:
                    905:        case I_CHDIR:
                    906:        case I_LCHDIR:
                    907:        case I_LMKDIR:
                    908:                /* Get pathname (mandatory) */
                    909:                if (get_pathname(&cp, path1))
                    910:                        return(-1);
                    911:                if (*path1 == NULL) {
                    912:                        error("You must specify a path after a %s command.",
                    913:                            cmd);
                    914:                        return(-1);
                    915:                }
                    916:                break;
                    917:        case I_LS:
                    918:                if (parse_ls_flags(&cp, lflag))
                    919:                        return(-1);
                    920:                /* Path is optional */
                    921:                if (get_pathname(&cp, path1))
                    922:                        return(-1);
                    923:                break;
                    924:        case I_LLS:
                    925:        case I_SHELL:
                    926:                /* Uses the rest of the line */
                    927:                break;
                    928:        case I_LUMASK:
                    929:                base = 8;
                    930:        case I_CHMOD:
                    931:                base = 8;
                    932:        case I_CHOWN:
                    933:        case I_CHGRP:
                    934:                /* Get numeric arg (mandatory) */
                    935:                l = strtol(cp, &cp2, base);
                    936:                if (cp2 == cp || ((l == LONG_MIN || l == LONG_MAX) &&
                    937:                    errno == ERANGE) || l < 0) {
                    938:                        error("You must supply a numeric argument "
                    939:                            "to the %s command.", cmd);
                    940:                        return(-1);
                    941:                }
                    942:                cp = cp2;
                    943:                *n_arg = l;
                    944:                if (cmdnum == I_LUMASK && strchr(WHITESPACE, *cp))
                    945:                        break;
                    946:                if (cmdnum == I_LUMASK || !strchr(WHITESPACE, *cp)) {
                    947:                        error("You must supply a numeric argument "
                    948:                            "to the %s command.", cmd);
                    949:                        return(-1);
                    950:                }
                    951:                cp += strspn(cp, WHITESPACE);
                    952:
                    953:                /* Get pathname (mandatory) */
                    954:                if (get_pathname(&cp, path1))
                    955:                        return(-1);
                    956:                if (*path1 == NULL) {
                    957:                        error("You must specify a path after a %s command.",
                    958:                            cmd);
                    959:                        return(-1);
                    960:                }
                    961:                break;
                    962:        case I_QUIT:
                    963:        case I_PWD:
                    964:        case I_LPWD:
                    965:        case I_HELP:
                    966:        case I_VERSION:
                    967:        case I_PROGRESS:
                    968:                break;
                    969:        default:
                    970:                fatal("Command not implemented");
                    971:        }
                    972:
                    973:        *cpp = cp;
                    974:        return(cmdnum);
                    975: }
                    976:
                    977: static int
                    978: parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
                    979:     int err_abort)
                    980: {
                    981:        char *path1, *path2, *tmp;
                    982:        int pflag, lflag, iflag, cmdnum, i;
                    983:        unsigned long n_arg;
                    984:        Attrib a, *aa;
                    985:        char path_buf[MAXPATHLEN];
                    986:        int err = 0;
                    987:        glob_t g;
                    988:
                    989:        path1 = path2 = NULL;
                    990:        cmdnum = parse_args(&cmd, &pflag, &lflag, &iflag, &n_arg,
                    991:            &path1, &path2);
                    992:
                    993:        if (iflag != 0)
                    994:                err_abort = 0;
                    995:
                    996:        memset(&g, 0, sizeof(g));
                    997:
                    998:        /* Perform command */
                    999:        switch (cmdnum) {
                   1000:        case 0:
                   1001:                /* Blank line */
                   1002:                break;
                   1003:        case -1:
                   1004:                /* Unrecognized command */
                   1005:                err = -1;
                   1006:                break;
                   1007:        case I_GET:
                   1008:                err = process_get(conn, path1, path2, *pwd, pflag);
                   1009:                break;
                   1010:        case I_PUT:
                   1011:                err = process_put(conn, path1, path2, *pwd, pflag);
                   1012:                break;
                   1013:        case I_RENAME:
                   1014:                path1 = make_absolute(path1, *pwd);
                   1015:                path2 = make_absolute(path2, *pwd);
                   1016:                err = do_rename(conn, path1, path2);
                   1017:                break;
                   1018:        case I_SYMLINK:
                   1019:                path2 = make_absolute(path2, *pwd);
                   1020:                err = do_symlink(conn, path1, path2);
                   1021:                break;
                   1022:        case I_RM:
                   1023:                path1 = make_absolute(path1, *pwd);
                   1024:                remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1.46      djm      1025:                for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1.44      djm      1026:                        printf("Removing %s\n", g.gl_pathv[i]);
                   1027:                        err = do_rm(conn, g.gl_pathv[i]);
                   1028:                        if (err != 0 && err_abort)
                   1029:                                break;
                   1030:                }
                   1031:                break;
                   1032:        case I_MKDIR:
                   1033:                path1 = make_absolute(path1, *pwd);
                   1034:                attrib_clear(&a);
                   1035:                a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
                   1036:                a.perm = 0777;
                   1037:                err = do_mkdir(conn, path1, &a);
                   1038:                break;
                   1039:        case I_RMDIR:
                   1040:                path1 = make_absolute(path1, *pwd);
                   1041:                err = do_rmdir(conn, path1);
                   1042:                break;
                   1043:        case I_CHDIR:
                   1044:                path1 = make_absolute(path1, *pwd);
                   1045:                if ((tmp = do_realpath(conn, path1)) == NULL) {
                   1046:                        err = 1;
                   1047:                        break;
                   1048:                }
                   1049:                if ((aa = do_stat(conn, tmp, 0)) == NULL) {
                   1050:                        xfree(tmp);
                   1051:                        err = 1;
                   1052:                        break;
                   1053:                }
                   1054:                if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
                   1055:                        error("Can't change directory: Can't check target");
                   1056:                        xfree(tmp);
                   1057:                        err = 1;
                   1058:                        break;
                   1059:                }
                   1060:                if (!S_ISDIR(aa->perm)) {
                   1061:                        error("Can't change directory: \"%s\" is not "
                   1062:                            "a directory", tmp);
                   1063:                        xfree(tmp);
                   1064:                        err = 1;
                   1065:                        break;
                   1066:                }
                   1067:                xfree(*pwd);
                   1068:                *pwd = tmp;
                   1069:                break;
                   1070:        case I_LS:
                   1071:                if (!path1) {
                   1072:                        do_globbed_ls(conn, *pwd, *pwd, lflag);
                   1073:                        break;
                   1074:                }
                   1075:
                   1076:                /* Strip pwd off beginning of non-absolute paths */
                   1077:                tmp = NULL;
                   1078:                if (*path1 != '/')
                   1079:                        tmp = *pwd;
                   1080:
                   1081:                path1 = make_absolute(path1, *pwd);
                   1082:                err = do_globbed_ls(conn, path1, tmp, lflag);
                   1083:                break;
                   1084:        case I_LCHDIR:
                   1085:                if (chdir(path1) == -1) {
                   1086:                        error("Couldn't change local directory to "
                   1087:                            "\"%s\": %s", path1, strerror(errno));
                   1088:                        err = 1;
                   1089:                }
                   1090:                break;
                   1091:        case I_LMKDIR:
                   1092:                if (mkdir(path1, 0777) == -1) {
                   1093:                        error("Couldn't create local directory "
                   1094:                            "\"%s\": %s", path1, strerror(errno));
                   1095:                        err = 1;
                   1096:                }
                   1097:                break;
                   1098:        case I_LLS:
                   1099:                local_do_ls(cmd);
                   1100:                break;
                   1101:        case I_SHELL:
                   1102:                local_do_shell(cmd);
                   1103:                break;
                   1104:        case I_LUMASK:
                   1105:                umask(n_arg);
                   1106:                printf("Local umask: %03lo\n", n_arg);
                   1107:                break;
                   1108:        case I_CHMOD:
                   1109:                path1 = make_absolute(path1, *pwd);
                   1110:                attrib_clear(&a);
                   1111:                a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
                   1112:                a.perm = n_arg;
                   1113:                remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1.46      djm      1114:                for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1.44      djm      1115:                        printf("Changing mode on %s\n", g.gl_pathv[i]);
                   1116:                        err = do_setstat(conn, g.gl_pathv[i], &a);
                   1117:                        if (err != 0 && err_abort)
                   1118:                                break;
                   1119:                }
                   1120:                break;
                   1121:        case I_CHOWN:
                   1122:        case I_CHGRP:
                   1123:                path1 = make_absolute(path1, *pwd);
                   1124:                remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1.46      djm      1125:                for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1.44      djm      1126:                        if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
                   1127:                                if (err != 0 && err_abort)
                   1128:                                        break;
                   1129:                                else
                   1130:                                        continue;
                   1131:                        }
                   1132:                        if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
                   1133:                                error("Can't get current ownership of "
                   1134:                                    "remote file \"%s\"", g.gl_pathv[i]);
                   1135:                                if (err != 0 && err_abort)
                   1136:                                        break;
                   1137:                                else
                   1138:                                        continue;
                   1139:                        }
                   1140:                        aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
                   1141:                        if (cmdnum == I_CHOWN) {
                   1142:                                printf("Changing owner on %s\n", g.gl_pathv[i]);
                   1143:                                aa->uid = n_arg;
                   1144:                        } else {
                   1145:                                printf("Changing group on %s\n", g.gl_pathv[i]);
                   1146:                                aa->gid = n_arg;
                   1147:                        }
                   1148:                        err = do_setstat(conn, g.gl_pathv[i], aa);
                   1149:                        if (err != 0 && err_abort)
                   1150:                                break;
                   1151:                }
                   1152:                break;
                   1153:        case I_PWD:
                   1154:                printf("Remote working directory: %s\n", *pwd);
                   1155:                break;
                   1156:        case I_LPWD:
                   1157:                if (!getcwd(path_buf, sizeof(path_buf))) {
                   1158:                        error("Couldn't get local cwd: %s", strerror(errno));
                   1159:                        err = -1;
                   1160:                        break;
                   1161:                }
                   1162:                printf("Local working directory: %s\n", path_buf);
                   1163:                break;
                   1164:        case I_QUIT:
                   1165:                /* Processed below */
                   1166:                break;
                   1167:        case I_HELP:
                   1168:                help();
                   1169:                break;
                   1170:        case I_VERSION:
                   1171:                printf("SFTP protocol version %u\n", sftp_proto_version(conn));
                   1172:                break;
                   1173:        case I_PROGRESS:
                   1174:                showprogress = !showprogress;
                   1175:                if (showprogress)
                   1176:                        printf("Progress meter enabled\n");
                   1177:                else
                   1178:                        printf("Progress meter disabled\n");
                   1179:                break;
                   1180:        default:
                   1181:                fatal("%d is not implemented", cmdnum);
                   1182:        }
                   1183:
                   1184:        if (g.gl_pathc)
                   1185:                globfree(&g);
                   1186:        if (path1)
                   1187:                xfree(path1);
                   1188:        if (path2)
                   1189:                xfree(path2);
                   1190:
                   1191:        /* If an unignored error occurs in batch mode we should abort. */
                   1192:        if (err_abort && err != 0)
                   1193:                return (-1);
                   1194:        else if (cmdnum == I_QUIT)
                   1195:                return (1);
                   1196:
                   1197:        return (0);
                   1198: }
                   1199:
                   1200: int
                   1201: interactive_loop(int fd_in, int fd_out, char *file1, char *file2)
                   1202: {
                   1203:        char *pwd;
                   1204:        char *dir = NULL;
                   1205:        char cmd[2048];
                   1206:        struct sftp_conn *conn;
                   1207:        int err;
                   1208:
                   1209:        conn = do_init(fd_in, fd_out, copy_buffer_len, num_requests);
                   1210:        if (conn == NULL)
                   1211:                fatal("Couldn't initialise connection to server");
                   1212:
                   1213:        pwd = do_realpath(conn, ".");
                   1214:        if (pwd == NULL)
                   1215:                fatal("Need cwd");
                   1216:
                   1217:        if (file1 != NULL) {
                   1218:                dir = xstrdup(file1);
                   1219:                dir = make_absolute(dir, pwd);
                   1220:
                   1221:                if (remote_is_dir(conn, dir) && file2 == NULL) {
                   1222:                        printf("Changing to: %s\n", dir);
                   1223:                        snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
                   1224:                        if (parse_dispatch_command(conn, cmd, &pwd, 1) != 0)
                   1225:                                return (-1);
                   1226:                } else {
                   1227:                        if (file2 == NULL)
                   1228:                                snprintf(cmd, sizeof cmd, "get %s", dir);
                   1229:                        else
                   1230:                                snprintf(cmd, sizeof cmd, "get %s %s", dir,
                   1231:                                    file2);
                   1232:
                   1233:                        err = parse_dispatch_command(conn, cmd, &pwd, 1);
                   1234:                        xfree(dir);
                   1235:                        xfree(pwd);
                   1236:                        return (err);
                   1237:                }
                   1238:                xfree(dir);
                   1239:        }
                   1240:
                   1241:        setvbuf(stdout, NULL, _IOLBF, 0);
                   1242:        setvbuf(infile, NULL, _IOLBF, 0);
                   1243:
                   1244:        err = 0;
                   1245:        for (;;) {
                   1246:                char *cp;
                   1247:
1.46      djm      1248:                signal(SIGINT, SIG_IGN);
                   1249:
1.44      djm      1250:                printf("sftp> ");
                   1251:
                   1252:                /* XXX: use libedit */
                   1253:                if (fgets(cmd, sizeof(cmd), infile) == NULL) {
                   1254:                        printf("\n");
                   1255:                        break;
                   1256:                }
                   1257:
                   1258:                if (batchmode) /* Echo command */
                   1259:                        printf("%s", cmd);
                   1260:
                   1261:                cp = strrchr(cmd, '\n');
                   1262:                if (cp)
                   1263:                        *cp = '\0';
                   1264:
1.46      djm      1265:                /* Handle user interrupts gracefully during commands */
                   1266:                interrupted = 0;
                   1267:                signal(SIGINT, cmd_interrupt);
                   1268:
1.44      djm      1269:                err = parse_dispatch_command(conn, cmd, &pwd, batchmode);
                   1270:                if (err != 0)
                   1271:                        break;
                   1272:        }
                   1273:        xfree(pwd);
                   1274:
                   1275:        /* err == 1 signifies normal "quit" exit */
                   1276:        return (err >= 0 ? 0 : -1);
                   1277: }
1.34      fgsch    1278:
1.18      itojun   1279: static void
1.36      djm      1280: connect_to_server(char *path, char **args, int *in, int *out)
1.1       djm      1281: {
                   1282:        int c_in, c_out;
1.30      deraadt  1283:
1.1       djm      1284: #ifdef USE_PIPES
                   1285:        int pin[2], pout[2];
1.30      deraadt  1286:
1.1       djm      1287:        if ((pipe(pin) == -1) || (pipe(pout) == -1))
                   1288:                fatal("pipe: %s", strerror(errno));
                   1289:        *in = pin[0];
                   1290:        *out = pout[1];
                   1291:        c_in = pout[0];
                   1292:        c_out = pin[1];
                   1293: #else /* USE_PIPES */
                   1294:        int inout[2];
1.30      deraadt  1295:
1.1       djm      1296:        if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1)
                   1297:                fatal("socketpair: %s", strerror(errno));
                   1298:        *in = *out = inout[0];
                   1299:        c_in = c_out = inout[1];
                   1300: #endif /* USE_PIPES */
                   1301:
1.36      djm      1302:        if ((sshpid = fork()) == -1)
1.1       djm      1303:                fatal("fork: %s", strerror(errno));
1.36      djm      1304:        else if (sshpid == 0) {
1.1       djm      1305:                if ((dup2(c_in, STDIN_FILENO) == -1) ||
                   1306:                    (dup2(c_out, STDOUT_FILENO) == -1)) {
                   1307:                        fprintf(stderr, "dup2: %s\n", strerror(errno));
1.47      djm      1308:                        _exit(1);
1.1       djm      1309:                }
                   1310:                close(*in);
                   1311:                close(*out);
                   1312:                close(c_in);
                   1313:                close(c_out);
1.46      djm      1314:
                   1315:                /*
                   1316:                 * The underlying ssh is in the same process group, so we must
                   1317:                 * ignore SIGINT if we want to gracefully abort commands,
                   1318:                 * otherwise the signal will make it to the ssh process and
                   1319:                 * kill it too
                   1320:                 */
                   1321:                signal(SIGINT, SIG_IGN);
1.49      dtucker  1322:                execvp(path, args);
1.23      djm      1323:                fprintf(stderr, "exec: %s: %s\n", path, strerror(errno));
1.47      djm      1324:                _exit(1);
1.1       djm      1325:        }
                   1326:
1.36      djm      1327:        signal(SIGTERM, killchild);
                   1328:        signal(SIGINT, killchild);
                   1329:        signal(SIGHUP, killchild);
1.1       djm      1330:        close(c_in);
                   1331:        close(c_out);
                   1332: }
                   1333:
1.18      itojun   1334: static void
1.1       djm      1335: usage(void)
                   1336: {
1.25      mpech    1337:        extern char *__progname;
1.27      markus   1338:
1.19      stevesk  1339:        fprintf(stderr,
1.38      jmc      1340:            "usage: %s [-1Cv] [-B buffer_size] [-b batchfile] [-F ssh_config]\n"
                   1341:            "            [-o ssh_option] [-P sftp_server_path] [-R num_requests]\n"
                   1342:            "            [-S program] [-s subsystem | sftp_server] host\n"
                   1343:            "       %s [[user@]host[:file [file]]]\n"
                   1344:            "       %s [[user@]host[:dir[/]]]\n"
                   1345:            "       %s -b batchfile [user@]host\n", __progname, __progname, __progname, __progname);
1.1       djm      1346:        exit(1);
                   1347: }
                   1348:
1.2       stevesk  1349: int
1.1       djm      1350: main(int argc, char **argv)
                   1351: {
1.33      djm      1352:        int in, out, ch, err;
1.48      pedro    1353:        char *host, *userhost, *cp, *file2 = NULL;
1.17      mouring  1354:        int debug_level = 0, sshver = 2;
                   1355:        char *file1 = NULL, *sftp_server = NULL;
1.23      djm      1356:        char *ssh_program = _PATH_SSH_PROGRAM, *sftp_direct = NULL;
1.17      mouring  1357:        LogLevel ll = SYSLOG_LEVEL_INFO;
                   1358:        arglist args;
1.3       djm      1359:        extern int optind;
                   1360:        extern char *optarg;
1.1       djm      1361:
1.17      mouring  1362:        args.list = NULL;
1.22      deraadt  1363:        addargs(&args, "ssh");          /* overwritten with ssh_program */
1.17      mouring  1364:        addargs(&args, "-oForwardX11 no");
                   1365:        addargs(&args, "-oForwardAgent no");
1.21      stevesk  1366:        addargs(&args, "-oClearAllForwardings yes");
1.40      djm      1367:
1.17      mouring  1368:        ll = SYSLOG_LEVEL_INFO;
1.40      djm      1369:        infile = stdin;
1.3       djm      1370:
1.26      djm      1371:        while ((ch = getopt(argc, argv, "1hvCo:s:S:b:B:F:P:R:")) != -1) {
1.3       djm      1372:                switch (ch) {
                   1373:                case 'C':
1.17      mouring  1374:                        addargs(&args, "-C");
1.3       djm      1375:                        break;
                   1376:                case 'v':
1.17      mouring  1377:                        if (debug_level < 3) {
                   1378:                                addargs(&args, "-v");
                   1379:                                ll = SYSLOG_LEVEL_DEBUG1 + debug_level;
                   1380:                        }
                   1381:                        debug_level++;
1.3       djm      1382:                        break;
1.19      stevesk  1383:                case 'F':
1.3       djm      1384:                case 'o':
1.19      stevesk  1385:                        addargs(&args, "-%c%s", ch, optarg);
1.7       markus   1386:                        break;
                   1387:                case '1':
1.17      mouring  1388:                        sshver = 1;
1.7       markus   1389:                        if (sftp_server == NULL)
                   1390:                                sftp_server = _PATH_SFTP_SERVER;
                   1391:                        break;
                   1392:                case 's':
                   1393:                        sftp_server = optarg;
                   1394:                        break;
                   1395:                case 'S':
                   1396:                        ssh_program = optarg;
1.3       djm      1397:                        break;
1.10      deraadt  1398:                case 'b':
1.39      djm      1399:                        if (batchmode)
                   1400:                                fatal("Batch file already specified.");
                   1401:
                   1402:                        /* Allow "-" as stdin */
                   1403:                        if (strcmp(optarg, "-") != 0 &&
                   1404:                           (infile = fopen(optarg, "r")) == NULL)
                   1405:                                fatal("%s (%s).", strerror(errno), optarg);
1.34      fgsch    1406:                        showprogress = 0;
1.39      djm      1407:                        batchmode = 1;
1.10      deraadt  1408:                        break;
1.23      djm      1409:                case 'P':
                   1410:                        sftp_direct = optarg;
1.24      djm      1411:                        break;
                   1412:                case 'B':
                   1413:                        copy_buffer_len = strtol(optarg, &cp, 10);
                   1414:                        if (copy_buffer_len == 0 || *cp != '\0')
                   1415:                                fatal("Invalid buffer size \"%s\"", optarg);
1.26      djm      1416:                        break;
                   1417:                case 'R':
                   1418:                        num_requests = strtol(optarg, &cp, 10);
                   1419:                        if (num_requests == 0 || *cp != '\0')
1.27      markus   1420:                                fatal("Invalid number of requests \"%s\"",
1.26      djm      1421:                                    optarg);
1.23      djm      1422:                        break;
1.3       djm      1423:                case 'h':
                   1424:                default:
1.1       djm      1425:                        usage();
                   1426:                }
                   1427:        }
1.45      djm      1428:
                   1429:        if (!isatty(STDERR_FILENO))
                   1430:                showprogress = 0;
1.1       djm      1431:
1.29      markus   1432:        log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);
                   1433:
1.23      djm      1434:        if (sftp_direct == NULL) {
                   1435:                if (optind == argc || argc > (optind + 2))
                   1436:                        usage();
                   1437:
                   1438:                userhost = xstrdup(argv[optind]);
                   1439:                file2 = argv[optind+1];
1.1       djm      1440:
1.32      markus   1441:                if ((host = strrchr(userhost, '@')) == NULL)
1.23      djm      1442:                        host = userhost;
                   1443:                else {
                   1444:                        *host++ = '\0';
                   1445:                        if (!userhost[0]) {
                   1446:                                fprintf(stderr, "Missing username\n");
                   1447:                                usage();
                   1448:                        }
                   1449:                        addargs(&args, "-l%s",userhost);
1.41      djm      1450:                }
                   1451:
                   1452:                if ((cp = colon(host)) != NULL) {
                   1453:                        *cp++ = '\0';
                   1454:                        file1 = cp;
1.23      djm      1455:                }
1.3       djm      1456:
1.23      djm      1457:                host = cleanhostname(host);
                   1458:                if (!*host) {
                   1459:                        fprintf(stderr, "Missing hostname\n");
1.1       djm      1460:                        usage();
                   1461:                }
                   1462:
1.23      djm      1463:                addargs(&args, "-oProtocol %d", sshver);
                   1464:
                   1465:                /* no subsystem if the server-spec contains a '/' */
                   1466:                if (sftp_server == NULL || strchr(sftp_server, '/') == NULL)
                   1467:                        addargs(&args, "-s");
                   1468:
                   1469:                addargs(&args, "%s", host);
1.27      markus   1470:                addargs(&args, "%s", (sftp_server != NULL ?
1.23      djm      1471:                    sftp_server : "sftp"));
                   1472:                args.list[0] = ssh_program;
                   1473:
1.39      djm      1474:                if (!batchmode)
                   1475:                        fprintf(stderr, "Connecting to %s...\n", host);
1.36      djm      1476:                connect_to_server(ssh_program, args.list, &in, &out);
1.23      djm      1477:        } else {
                   1478:                args.list = NULL;
                   1479:                addargs(&args, "sftp-server");
                   1480:
1.39      djm      1481:                if (!batchmode)
                   1482:                        fprintf(stderr, "Attaching to %s...\n", sftp_direct);
1.36      djm      1483:                connect_to_server(sftp_direct, args.list, &in, &out);
1.1       djm      1484:        }
                   1485:
1.33      djm      1486:        err = interactive_loop(in, out, file1, file2);
1.1       djm      1487:
                   1488:        close(in);
                   1489:        close(out);
1.39      djm      1490:        if (batchmode)
1.10      deraadt  1491:                fclose(infile);
1.1       djm      1492:
1.28      markus   1493:        while (waitpid(sshpid, NULL, 0) == -1)
                   1494:                if (errno != EINTR)
                   1495:                        fatal("Couldn't wait for ssh process: %s",
                   1496:                            strerror(errno));
1.1       djm      1497:
1.33      djm      1498:        exit(err == 0 ? 0 : 1);
1.1       djm      1499: }