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

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