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

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