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

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