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

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