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

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