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

1.181   ! millert     1: /* $OpenBSD: sftp.c,v 1.180 2017/06/10 06:33:34 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.100     djm        23: #include <sys/statvfs.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.111     djm        30: #include <libgen.h>
1.146     dtucker    31: #include <locale.h>
1.74      stevesk    32: #include <signal.h>
1.174     schwarze   33: #include <stdarg.h>
1.89      stevesk    34: #include <stdlib.h>
1.90      stevesk    35: #include <stdio.h>
1.87      stevesk    36: #include <string.h>
1.86      stevesk    37: #include <unistd.h>
1.170     deraadt    38: #include <limits.h>
1.100     djm        39: #include <util.h>
1.91      deraadt    40: #include <stdarg.h>
1.1       djm        41:
                     42: #include "xmalloc.h"
                     43: #include "log.h"
                     44: #include "pathnames.h"
1.16      mouring    45: #include "misc.h"
1.174     schwarze   46: #include "utf8.h"
1.1       djm        47:
                     48: #include "sftp.h"
1.169     djm        49: #include "ssherr.h"
                     50: #include "sshbuf.h"
1.1       djm        51: #include "sftp-common.h"
                     52: #include "sftp-client.h"
1.43      djm        53:
1.112     djm        54: #define DEFAULT_COPY_BUFLEN    32768   /* Size of buffer for up/download */
                     55: #define DEFAULT_NUM_REQUESTS   64      /* # concurrent outstanding requests */
                     56:
1.44      djm        57: /* File to read commands from */
                     58: FILE* infile;
1.15      mouring    59:
1.44      djm        60: /* Are we in batchfile mode? */
1.39      djm        61: int batchmode = 0;
1.44      djm        62:
                     63: /* PID of ssh transport process */
1.36      djm        64: static pid_t sshpid = -1;
1.7       markus     65:
1.143     djm        66: /* Suppress diagnositic messages */
                     67: int quiet = 0;
                     68:
1.44      djm        69: /* This is set to 0 if the progressmeter is not desired. */
1.45      djm        70: int showprogress = 1;
1.44      djm        71:
1.111     djm        72: /* When this option is set, we always recursively download/upload directories */
                     73: int global_rflag = 0;
                     74:
1.159     logan      75: /* When this option is set, we resume download or upload if possible */
1.148     djm        76: int global_aflag = 0;
                     77:
1.111     djm        78: /* When this option is set, the file transfers will always preserve times */
                     79: int global_pflag = 0;
                     80:
1.156     djm        81: /* When this option is set, transfers will have fsync() called on each file */
                     82: int global_fflag = 0;
                     83:
1.46      djm        84: /* SIGINT received during command processing */
                     85: volatile sig_atomic_t interrupted = 0;
                     86:
1.52      djm        87: /* I wish qsort() took a separate ctx for the comparison function...*/
                     88: int sort_flag;
1.180     djm        89: glob_t *sort_glob;
1.52      djm        90:
1.116     djm        91: /* Context used for commandline completion */
                     92: struct complete_ctx {
                     93:        struct sftp_conn *conn;
                     94:        char **remote_pathp;
                     95: };
                     96:
1.44      djm        97: int remote_glob(struct sftp_conn *, const char *, int,
                     98:     int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
                     99:
                    100: /* Separators for interactive commands */
                    101: #define WHITESPACE " \t\r\n"
                    102:
1.52      djm       103: /* ls flags */
1.119     djm       104: #define LS_LONG_VIEW   0x0001  /* Full view ala ls -l */
                    105: #define LS_SHORT_VIEW  0x0002  /* Single row view ala ls -1 */
                    106: #define LS_NUMERIC_VIEW        0x0004  /* Long view with numeric uid/gid */
                    107: #define LS_NAME_SORT   0x0008  /* Sort by name (default) */
                    108: #define LS_TIME_SORT   0x0010  /* Sort by mtime */
                    109: #define LS_SIZE_SORT   0x0020  /* Sort by file size */
                    110: #define LS_REVERSE_SORT        0x0040  /* Reverse sort order */
                    111: #define LS_SHOW_ALL    0x0080  /* Don't skip filenames starting with '.' */
                    112: #define LS_SI_UNITS    0x0100  /* Display sizes as K, M, G, etc. */
1.52      djm       113:
1.119     djm       114: #define VIEW_FLAGS     (LS_LONG_VIEW|LS_SHORT_VIEW|LS_NUMERIC_VIEW|LS_SI_UNITS)
1.53      djm       115: #define SORT_FLAGS     (LS_NAME_SORT|LS_TIME_SORT|LS_SIZE_SORT)
1.44      djm       116:
                    117: /* Commands for interactive mode */
1.149     djm       118: enum sftp_command {
                    119:        I_CHDIR = 1,
                    120:        I_CHGRP,
                    121:        I_CHMOD,
                    122:        I_CHOWN,
                    123:        I_DF,
                    124:        I_GET,
                    125:        I_HELP,
                    126:        I_LCHDIR,
                    127:        I_LINK,
                    128:        I_LLS,
                    129:        I_LMKDIR,
                    130:        I_LPWD,
                    131:        I_LS,
                    132:        I_LUMASK,
                    133:        I_MKDIR,
                    134:        I_PUT,
                    135:        I_PWD,
                    136:        I_QUIT,
1.160     logan     137:        I_REGET,
1.149     djm       138:        I_RENAME,
1.160     logan     139:        I_REPUT,
1.149     djm       140:        I_RM,
                    141:        I_RMDIR,
                    142:        I_SHELL,
                    143:        I_SYMLINK,
                    144:        I_VERSION,
                    145:        I_PROGRESS,
                    146: };
1.44      djm       147:
                    148: struct CMD {
                    149:        const char *c;
                    150:        const int n;
1.116     djm       151:        const int t;
1.44      djm       152: };
                    153:
1.116     djm       154: /* Type of completion */
                    155: #define NOARGS 0
                    156: #define REMOTE 1
                    157: #define LOCAL  2
                    158:
1.44      djm       159: static const struct CMD cmds[] = {
1.116     djm       160:        { "bye",        I_QUIT,         NOARGS  },
                    161:        { "cd",         I_CHDIR,        REMOTE  },
                    162:        { "chdir",      I_CHDIR,        REMOTE  },
                    163:        { "chgrp",      I_CHGRP,        REMOTE  },
                    164:        { "chmod",      I_CHMOD,        REMOTE  },
                    165:        { "chown",      I_CHOWN,        REMOTE  },
                    166:        { "df",         I_DF,           REMOTE  },
                    167:        { "dir",        I_LS,           REMOTE  },
                    168:        { "exit",       I_QUIT,         NOARGS  },
                    169:        { "get",        I_GET,          REMOTE  },
                    170:        { "help",       I_HELP,         NOARGS  },
                    171:        { "lcd",        I_LCHDIR,       LOCAL   },
                    172:        { "lchdir",     I_LCHDIR,       LOCAL   },
                    173:        { "lls",        I_LLS,          LOCAL   },
                    174:        { "lmkdir",     I_LMKDIR,       LOCAL   },
1.132     djm       175:        { "ln",         I_LINK,         REMOTE  },
1.116     djm       176:        { "lpwd",       I_LPWD,         LOCAL   },
                    177:        { "ls",         I_LS,           REMOTE  },
                    178:        { "lumask",     I_LUMASK,       NOARGS  },
                    179:        { "mkdir",      I_MKDIR,        REMOTE  },
1.124     dtucker   180:        { "mget",       I_GET,          REMOTE  },
                    181:        { "mput",       I_PUT,          LOCAL   },
1.116     djm       182:        { "progress",   I_PROGRESS,     NOARGS  },
                    183:        { "put",        I_PUT,          LOCAL   },
                    184:        { "pwd",        I_PWD,          REMOTE  },
                    185:        { "quit",       I_QUIT,         NOARGS  },
1.148     djm       186:        { "reget",      I_REGET,        REMOTE  },
1.116     djm       187:        { "rename",     I_RENAME,       REMOTE  },
1.167     djm       188:        { "reput",      I_REPUT,        LOCAL   },
1.116     djm       189:        { "rm",         I_RM,           REMOTE  },
                    190:        { "rmdir",      I_RMDIR,        REMOTE  },
                    191:        { "symlink",    I_SYMLINK,      REMOTE  },
                    192:        { "version",    I_VERSION,      NOARGS  },
                    193:        { "!",          I_SHELL,        NOARGS  },
                    194:        { "?",          I_HELP,         NOARGS  },
                    195:        { NULL,         -1,             -1      }
1.44      djm       196: };
                    197:
1.112     djm       198: int interactive_loop(struct sftp_conn *, char *file1, char *file2);
1.44      djm       199:
1.96      stevesk   200: /* ARGSUSED */
1.44      djm       201: static void
1.46      djm       202: killchild(int signo)
                    203: {
1.61      dtucker   204:        if (sshpid > 1) {
1.46      djm       205:                kill(sshpid, SIGTERM);
1.61      dtucker   206:                waitpid(sshpid, NULL, 0);
                    207:        }
1.46      djm       208:
                    209:        _exit(1);
                    210: }
                    211:
1.96      stevesk   212: /* ARGSUSED */
1.46      djm       213: static void
1.177     millert   214: suspchild(int signo)
                    215: {
                    216:        if (sshpid > 1) {
                    217:                kill(sshpid, signo);
                    218:                while (waitpid(sshpid, NULL, WUNTRACED) == -1 && errno == EINTR)
                    219:                        continue;
                    220:        }
                    221:        kill(getpid(), SIGSTOP);
                    222: }
                    223:
                    224: /* ARGSUSED */
                    225: static void
1.46      djm       226: cmd_interrupt(int signo)
                    227: {
                    228:        const char msg[] = "\rInterrupt  \n";
1.59      djm       229:        int olderrno = errno;
1.46      djm       230:
1.144     dtucker   231:        (void)write(STDERR_FILENO, msg, sizeof(msg) - 1);
1.46      djm       232:        interrupted = 1;
1.59      djm       233:        errno = olderrno;
1.46      djm       234: }
                    235:
                    236: static void
1.44      djm       237: help(void)
                    238: {
1.106     sobrado   239:        printf("Available commands:\n"
                    240:            "bye                                Quit sftp\n"
                    241:            "cd path                            Change remote directory to 'path'\n"
                    242:            "chgrp grp path                     Change group of file 'path' to 'grp'\n"
                    243:            "chmod mode path                    Change permissions of file 'path' to 'mode'\n"
                    244:            "chown own path                     Change owner of file 'path' to 'own'\n"
                    245:            "df [-hi] [path]                    Display statistics for current directory or\n"
                    246:            "                                   filesystem containing 'path'\n"
                    247:            "exit                               Quit sftp\n"
1.167     djm       248:            "get [-afPpRr] remote [local]       Download file\n"
                    249:            "reget [-fPpRr] remote [local]      Resume download file\n"
                    250:            "reput [-fPpRr] [local] remote      Resume upload file\n"
1.106     sobrado   251:            "help                               Display this help text\n"
                    252:            "lcd path                           Change local directory to 'path'\n"
                    253:            "lls [ls-options [path]]            Display local directory listing\n"
                    254:            "lmkdir path                        Create local directory\n"
1.132     djm       255:            "ln [-s] oldpath newpath            Link remote file (-s for symlink)\n"
1.106     sobrado   256:            "lpwd                               Print local working directory\n"
1.121     jmc       257:            "ls [-1afhlnrSt] [path]             Display remote directory listing\n"
1.106     sobrado   258:            "lumask umask                       Set local umask to 'umask'\n"
                    259:            "mkdir path                         Create remote directory\n"
                    260:            "progress                           Toggle display of progress meter\n"
1.167     djm       261:            "put [-afPpRr] local [remote]       Upload file\n"
1.106     sobrado   262:            "pwd                                Display remote working directory\n"
                    263:            "quit                               Quit sftp\n"
                    264:            "rename oldpath newpath             Rename remote file\n"
                    265:            "rm path                            Delete remote file\n"
                    266:            "rmdir path                         Remove remote directory\n"
                    267:            "symlink oldpath newpath            Symlink remote file\n"
                    268:            "version                            Show SFTP version\n"
                    269:            "!command                           Execute 'command' in local shell\n"
                    270:            "!                                  Escape to local shell\n"
                    271:            "?                                  Synonym for help\n");
1.44      djm       272: }
                    273:
                    274: static void
                    275: local_do_shell(const char *args)
                    276: {
                    277:        int status;
                    278:        char *shell;
                    279:        pid_t pid;
                    280:
                    281:        if (!*args)
                    282:                args = NULL;
                    283:
1.130     djm       284:        if ((shell = getenv("SHELL")) == NULL || *shell == '\0')
1.44      djm       285:                shell = _PATH_BSHELL;
                    286:
                    287:        if ((pid = fork()) == -1)
                    288:                fatal("Couldn't fork: %s", strerror(errno));
                    289:
                    290:        if (pid == 0) {
                    291:                /* XXX: child has pipe fds to ssh subproc open - issue? */
                    292:                if (args) {
                    293:                        debug3("Executing %s -c \"%s\"", shell, args);
                    294:                        execl(shell, shell, "-c", args, (char *)NULL);
                    295:                } else {
                    296:                        debug3("Executing %s", shell);
                    297:                        execl(shell, shell, (char *)NULL);
                    298:                }
                    299:                fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell,
                    300:                    strerror(errno));
                    301:                _exit(1);
                    302:        }
                    303:        while (waitpid(pid, &status, 0) == -1)
                    304:                if (errno != EINTR)
                    305:                        fatal("Couldn't wait for child: %s", strerror(errno));
                    306:        if (!WIFEXITED(status))
1.78      djm       307:                error("Shell exited abnormally");
1.44      djm       308:        else if (WEXITSTATUS(status))
                    309:                error("Shell exited with status %d", WEXITSTATUS(status));
                    310: }
                    311:
                    312: static void
                    313: local_do_ls(const char *args)
                    314: {
                    315:        if (!args || !*args)
                    316:                local_do_shell(_PATH_LS);
                    317:        else {
                    318:                int len = strlen(_PATH_LS " ") + strlen(args) + 1;
                    319:                char *buf = xmalloc(len);
                    320:
                    321:                /* XXX: quoting - rip quoting code from ftp? */
                    322:                snprintf(buf, len, _PATH_LS " %s", args);
                    323:                local_do_shell(buf);
1.145     djm       324:                free(buf);
1.44      djm       325:        }
                    326: }
                    327:
                    328: /* Strip one path (usually the pwd) from the start of another */
                    329: static char *
1.175     djm       330: path_strip(const char *path, const char *strip)
1.44      djm       331: {
                    332:        size_t len;
                    333:
                    334:        if (strip == NULL)
                    335:                return (xstrdup(path));
                    336:
                    337:        len = strlen(strip);
1.59      djm       338:        if (strncmp(path, strip, len) == 0) {
1.44      djm       339:                if (strip[len - 1] != '/' && path[len] == '/')
                    340:                        len++;
                    341:                return (xstrdup(path + len));
                    342:        }
                    343:
                    344:        return (xstrdup(path));
                    345: }
                    346:
                    347: static char *
1.175     djm       348: make_absolute(char *p, const char *pwd)
1.44      djm       349: {
1.51      avsm      350:        char *abs_str;
1.44      djm       351:
                    352:        /* Derelativise */
                    353:        if (p && p[0] != '/') {
1.51      avsm      354:                abs_str = path_append(pwd, p);
1.145     djm       355:                free(p);
1.51      avsm      356:                return(abs_str);
1.44      djm       357:        } else
                    358:                return(p);
                    359: }
                    360:
                    361: static int
1.148     djm       362: parse_getput_flags(const char *cmd, char **argv, int argc,
1.156     djm       363:     int *aflag, int *fflag, int *pflag, int *rflag)
1.44      djm       364: {
1.102     martynas  365:        extern int opterr, optind, optopt, optreset;
1.97      djm       366:        int ch;
1.44      djm       367:
1.97      djm       368:        optind = optreset = 1;
                    369:        opterr = 0;
                    370:
1.156     djm       371:        *aflag = *fflag = *rflag = *pflag = 0;
                    372:        while ((ch = getopt(argc, argv, "afPpRr")) != -1) {
1.97      djm       373:                switch (ch) {
1.148     djm       374:                case 'a':
                    375:                        *aflag = 1;
                    376:                        break;
1.156     djm       377:                case 'f':
                    378:                        *fflag = 1;
                    379:                        break;
1.44      djm       380:                case 'p':
                    381:                case 'P':
                    382:                        *pflag = 1;
                    383:                        break;
1.111     djm       384:                case 'r':
                    385:                case 'R':
                    386:                        *rflag = 1;
                    387:                        break;
1.44      djm       388:                default:
1.102     martynas  389:                        error("%s: Invalid flag -%c", cmd, optopt);
1.97      djm       390:                        return -1;
1.44      djm       391:                }
                    392:        }
                    393:
1.97      djm       394:        return optind;
1.44      djm       395: }
                    396:
                    397: static int
1.132     djm       398: parse_link_flags(const char *cmd, char **argv, int argc, int *sflag)
                    399: {
                    400:        extern int opterr, optind, optopt, optreset;
                    401:        int ch;
                    402:
                    403:        optind = optreset = 1;
                    404:        opterr = 0;
                    405:
                    406:        *sflag = 0;
                    407:        while ((ch = getopt(argc, argv, "s")) != -1) {
                    408:                switch (ch) {
                    409:                case 's':
                    410:                        *sflag = 1;
                    411:                        break;
                    412:                default:
                    413:                        error("%s: Invalid flag -%c", cmd, optopt);
                    414:                        return -1;
                    415:                }
                    416:        }
                    417:
                    418:        return optind;
                    419: }
                    420:
                    421: static int
1.152     djm       422: parse_rename_flags(const char *cmd, char **argv, int argc, int *lflag)
                    423: {
                    424:        extern int opterr, optind, optopt, optreset;
                    425:        int ch;
                    426:
                    427:        optind = optreset = 1;
                    428:        opterr = 0;
                    429:
                    430:        *lflag = 0;
                    431:        while ((ch = getopt(argc, argv, "l")) != -1) {
                    432:                switch (ch) {
                    433:                case 'l':
                    434:                        *lflag = 1;
                    435:                        break;
                    436:                default:
                    437:                        error("%s: Invalid flag -%c", cmd, optopt);
                    438:                        return -1;
                    439:                }
                    440:        }
                    441:
                    442:        return optind;
                    443: }
                    444:
                    445: static int
1.97      djm       446: parse_ls_flags(char **argv, int argc, int *lflag)
1.44      djm       447: {
1.102     martynas  448:        extern int opterr, optind, optopt, optreset;
1.97      djm       449:        int ch;
                    450:
                    451:        optind = optreset = 1;
                    452:        opterr = 0;
1.44      djm       453:
1.53      djm       454:        *lflag = LS_NAME_SORT;
1.119     djm       455:        while ((ch = getopt(argc, argv, "1Safhlnrt")) != -1) {
1.97      djm       456:                switch (ch) {
                    457:                case '1':
                    458:                        *lflag &= ~VIEW_FLAGS;
                    459:                        *lflag |= LS_SHORT_VIEW;
                    460:                        break;
                    461:                case 'S':
                    462:                        *lflag &= ~SORT_FLAGS;
                    463:                        *lflag |= LS_SIZE_SORT;
                    464:                        break;
                    465:                case 'a':
                    466:                        *lflag |= LS_SHOW_ALL;
                    467:                        break;
                    468:                case 'f':
                    469:                        *lflag &= ~SORT_FLAGS;
                    470:                        break;
1.119     djm       471:                case 'h':
                    472:                        *lflag |= LS_SI_UNITS;
                    473:                        break;
1.97      djm       474:                case 'l':
1.119     djm       475:                        *lflag &= ~LS_SHORT_VIEW;
1.97      djm       476:                        *lflag |= LS_LONG_VIEW;
                    477:                        break;
                    478:                case 'n':
1.119     djm       479:                        *lflag &= ~LS_SHORT_VIEW;
1.97      djm       480:                        *lflag |= LS_NUMERIC_VIEW|LS_LONG_VIEW;
                    481:                        break;
                    482:                case 'r':
                    483:                        *lflag |= LS_REVERSE_SORT;
                    484:                        break;
                    485:                case 't':
                    486:                        *lflag &= ~SORT_FLAGS;
                    487:                        *lflag |= LS_TIME_SORT;
                    488:                        break;
                    489:                default:
1.102     martynas  490:                        error("ls: Invalid flag -%c", optopt);
1.97      djm       491:                        return -1;
1.44      djm       492:                }
                    493:        }
                    494:
1.97      djm       495:        return optind;
1.44      djm       496: }
                    497:
                    498: static int
1.100     djm       499: parse_df_flags(const char *cmd, char **argv, int argc, int *hflag, int *iflag)
                    500: {
1.102     martynas  501:        extern int opterr, optind, optopt, optreset;
1.100     djm       502:        int ch;
                    503:
                    504:        optind = optreset = 1;
                    505:        opterr = 0;
                    506:
                    507:        *hflag = *iflag = 0;
                    508:        while ((ch = getopt(argc, argv, "hi")) != -1) {
                    509:                switch (ch) {
                    510:                case 'h':
                    511:                        *hflag = 1;
                    512:                        break;
                    513:                case 'i':
                    514:                        *iflag = 1;
                    515:                        break;
                    516:                default:
1.102     martynas  517:                        error("%s: Invalid flag -%c", cmd, optopt);
1.100     djm       518:                        return -1;
                    519:                }
                    520:        }
                    521:
                    522:        return optind;
                    523: }
                    524:
                    525: static int
1.153     djm       526: parse_no_flags(const char *cmd, char **argv, int argc)
                    527: {
                    528:        extern int opterr, optind, optopt, optreset;
                    529:        int ch;
                    530:
                    531:        optind = optreset = 1;
                    532:        opterr = 0;
                    533:
                    534:        while ((ch = getopt(argc, argv, "")) != -1) {
                    535:                switch (ch) {
                    536:                default:
                    537:                        error("%s: Invalid flag -%c", cmd, optopt);
                    538:                        return -1;
                    539:                }
                    540:        }
                    541:
                    542:        return optind;
                    543: }
                    544:
                    545: static int
1.175     djm       546: is_dir(const char *path)
1.44      djm       547: {
                    548:        struct stat sb;
                    549:
                    550:        /* XXX: report errors? */
                    551:        if (stat(path, &sb) == -1)
                    552:                return(0);
                    553:
1.92      otto      554:        return(S_ISDIR(sb.st_mode));
1.44      djm       555: }
                    556:
                    557: static int
1.175     djm       558: remote_is_dir(struct sftp_conn *conn, const char *path)
1.44      djm       559: {
                    560:        Attrib *a;
                    561:
                    562:        /* XXX: report errors? */
                    563:        if ((a = do_stat(conn, path, 1)) == NULL)
                    564:                return(0);
                    565:        if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
                    566:                return(0);
1.92      otto      567:        return(S_ISDIR(a->perm));
1.44      djm       568: }
                    569:
1.111     djm       570: /* Check whether path returned from glob(..., GLOB_MARK, ...) is a directory */
                    571: static int
1.175     djm       572: pathname_is_dir(const char *pathname)
1.111     djm       573: {
                    574:        size_t l = strlen(pathname);
                    575:
                    576:        return l > 0 && pathname[l - 1] == '/';
                    577: }
                    578:
1.44      djm       579: static int
1.175     djm       580: process_get(struct sftp_conn *conn, const char *src, const char *dst,
                    581:     const char *pwd, int pflag, int rflag, int resume, int fflag)
1.44      djm       582: {
                    583:        char *abs_src = NULL;
                    584:        char *abs_dst = NULL;
                    585:        glob_t g;
1.111     djm       586:        char *filename, *tmp=NULL;
1.164     djm       587:        int i, r, err = 0;
1.44      djm       588:
                    589:        abs_src = xstrdup(src);
                    590:        abs_src = make_absolute(abs_src, pwd);
1.111     djm       591:        memset(&g, 0, sizeof(g));
1.44      djm       592:
                    593:        debug3("Looking up %s", abs_src);
1.164     djm       594:        if ((r = remote_glob(conn, abs_src, GLOB_MARK, NULL, &g)) != 0) {
                    595:                if (r == GLOB_NOSPACE) {
                    596:                        error("Too many matches for \"%s\".", abs_src);
                    597:                } else {
                    598:                        error("File \"%s\" not found.", abs_src);
                    599:                }
1.44      djm       600:                err = -1;
                    601:                goto out;
                    602:        }
                    603:
1.111     djm       604:        /*
                    605:         * If multiple matches then dst must be a directory or
                    606:         * unspecified.
                    607:         */
                    608:        if (g.gl_matchc > 1 && dst != NULL && !is_dir(dst)) {
                    609:                error("Multiple source paths, but destination "
                    610:                    "\"%s\" is not a directory", dst);
1.44      djm       611:                err = -1;
                    612:                goto out;
                    613:        }
                    614:
1.46      djm       615:        for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1.111     djm       616:                tmp = xstrdup(g.gl_pathv[i]);
                    617:                if ((filename = basename(tmp)) == NULL) {
                    618:                        error("basename %s: %s", tmp, strerror(errno));
1.145     djm       619:                        free(tmp);
1.44      djm       620:                        err = -1;
                    621:                        goto out;
                    622:                }
                    623:
                    624:                if (g.gl_matchc == 1 && dst) {
                    625:                        if (is_dir(dst)) {
1.111     djm       626:                                abs_dst = path_append(dst, filename);
                    627:                        } else {
1.44      djm       628:                                abs_dst = xstrdup(dst);
1.111     djm       629:                        }
1.44      djm       630:                } else if (dst) {
1.111     djm       631:                        abs_dst = path_append(dst, filename);
                    632:                } else {
                    633:                        abs_dst = xstrdup(filename);
                    634:                }
1.145     djm       635:                free(tmp);
1.44      djm       636:
1.148     djm       637:                resume |= global_aflag;
                    638:                if (!quiet && resume)
1.174     schwarze  639:                        mprintf("Resuming %s to %s\n",
                    640:                            g.gl_pathv[i], abs_dst);
1.148     djm       641:                else if (!quiet && !resume)
1.174     schwarze  642:                        mprintf("Fetching %s to %s\n",
                    643:                            g.gl_pathv[i], abs_dst);
1.111     djm       644:                if (pathname_is_dir(g.gl_pathv[i]) && (rflag || global_rflag)) {
1.148     djm       645:                        if (download_dir(conn, g.gl_pathv[i], abs_dst, NULL,
1.156     djm       646:                            pflag || global_pflag, 1, resume,
                    647:                            fflag || global_fflag) == -1)
1.111     djm       648:                                err = -1;
                    649:                } else {
                    650:                        if (do_download(conn, g.gl_pathv[i], abs_dst, NULL,
1.156     djm       651:                            pflag || global_pflag, resume,
                    652:                            fflag || global_fflag) == -1)
1.111     djm       653:                                err = -1;
                    654:                }
1.145     djm       655:                free(abs_dst);
1.44      djm       656:                abs_dst = NULL;
                    657:        }
                    658:
                    659: out:
1.145     djm       660:        free(abs_src);
1.44      djm       661:        globfree(&g);
                    662:        return(err);
                    663: }
                    664:
                    665: static int
1.175     djm       666: process_put(struct sftp_conn *conn, const char *src, const char *dst,
                    667:     const char *pwd, int pflag, int rflag, int resume, int fflag)
1.44      djm       668: {
                    669:        char *tmp_dst = NULL;
                    670:        char *abs_dst = NULL;
1.111     djm       671:        char *tmp = NULL, *filename = NULL;
1.44      djm       672:        glob_t g;
                    673:        int err = 0;
1.111     djm       674:        int i, dst_is_dir = 1;
1.99      djm       675:        struct stat sb;
1.44      djm       676:
                    677:        if (dst) {
                    678:                tmp_dst = xstrdup(dst);
                    679:                tmp_dst = make_absolute(tmp_dst, pwd);
                    680:        }
                    681:
                    682:        memset(&g, 0, sizeof(g));
                    683:        debug3("Looking up %s", src);
1.111     djm       684:        if (glob(src, GLOB_NOCHECK | GLOB_MARK, NULL, &g)) {
1.44      djm       685:                error("File \"%s\" not found.", src);
                    686:                err = -1;
                    687:                goto out;
                    688:        }
                    689:
1.111     djm       690:        /* If we aren't fetching to pwd then stash this status for later */
                    691:        if (tmp_dst != NULL)
                    692:                dst_is_dir = remote_is_dir(conn, tmp_dst);
                    693:
1.44      djm       694:        /* If multiple matches, dst may be directory or unspecified */
1.111     djm       695:        if (g.gl_matchc > 1 && tmp_dst && !dst_is_dir) {
                    696:                error("Multiple paths match, but destination "
                    697:                    "\"%s\" is not a directory", tmp_dst);
1.44      djm       698:                err = -1;
                    699:                goto out;
                    700:        }
                    701:
1.46      djm       702:        for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1.99      djm       703:                if (stat(g.gl_pathv[i], &sb) == -1) {
                    704:                        err = -1;
                    705:                        error("stat %s: %s", g.gl_pathv[i], strerror(errno));
                    706:                        continue;
                    707:                }
1.149     djm       708:
1.111     djm       709:                tmp = xstrdup(g.gl_pathv[i]);
                    710:                if ((filename = basename(tmp)) == NULL) {
                    711:                        error("basename %s: %s", tmp, strerror(errno));
1.145     djm       712:                        free(tmp);
1.44      djm       713:                        err = -1;
                    714:                        goto out;
                    715:                }
                    716:
                    717:                if (g.gl_matchc == 1 && tmp_dst) {
                    718:                        /* If directory specified, append filename */
1.111     djm       719:                        if (dst_is_dir)
                    720:                                abs_dst = path_append(tmp_dst, filename);
                    721:                        else
1.44      djm       722:                                abs_dst = xstrdup(tmp_dst);
                    723:                } else if (tmp_dst) {
1.111     djm       724:                        abs_dst = path_append(tmp_dst, filename);
                    725:                } else {
                    726:                        abs_dst = make_absolute(xstrdup(filename), pwd);
                    727:                }
1.145     djm       728:                free(tmp);
1.44      djm       729:
1.159     logan     730:                 resume |= global_aflag;
                    731:                if (!quiet && resume)
1.174     schwarze  732:                        mprintf("Resuming upload of %s to %s\n",
                    733:                            g.gl_pathv[i], abs_dst);
1.159     logan     734:                else if (!quiet && !resume)
1.174     schwarze  735:                        mprintf("Uploading %s to %s\n",
                    736:                            g.gl_pathv[i], abs_dst);
1.111     djm       737:                if (pathname_is_dir(g.gl_pathv[i]) && (rflag || global_rflag)) {
                    738:                        if (upload_dir(conn, g.gl_pathv[i], abs_dst,
1.159     logan     739:                            pflag || global_pflag, 1, resume,
1.156     djm       740:                            fflag || global_fflag) == -1)
1.111     djm       741:                                err = -1;
                    742:                } else {
                    743:                        if (do_upload(conn, g.gl_pathv[i], abs_dst,
1.159     logan     744:                            pflag || global_pflag, resume,
1.156     djm       745:                            fflag || global_fflag) == -1)
1.111     djm       746:                                err = -1;
                    747:                }
1.44      djm       748:        }
                    749:
                    750: out:
1.145     djm       751:        free(abs_dst);
                    752:        free(tmp_dst);
1.44      djm       753:        globfree(&g);
                    754:        return(err);
                    755: }
                    756:
                    757: static int
                    758: sdirent_comp(const void *aa, const void *bb)
                    759: {
                    760:        SFTP_DIRENT *a = *(SFTP_DIRENT **)aa;
                    761:        SFTP_DIRENT *b = *(SFTP_DIRENT **)bb;
1.53      djm       762:        int rmul = sort_flag & LS_REVERSE_SORT ? -1 : 1;
1.44      djm       763:
1.52      djm       764: #define NCMP(a,b) (a == b ? 0 : (a < b ? 1 : -1))
1.53      djm       765:        if (sort_flag & LS_NAME_SORT)
1.52      djm       766:                return (rmul * strcmp(a->filename, b->filename));
1.53      djm       767:        else if (sort_flag & LS_TIME_SORT)
1.52      djm       768:                return (rmul * NCMP(a->a.mtime, b->a.mtime));
1.53      djm       769:        else if (sort_flag & LS_SIZE_SORT)
1.52      djm       770:                return (rmul * NCMP(a->a.size, b->a.size));
                    771:
                    772:        fatal("Unknown ls sort type");
1.44      djm       773: }
                    774:
                    775: /* sftp ls.1 replacement for directories */
                    776: static int
1.175     djm       777: do_ls_dir(struct sftp_conn *conn, const char *path,
                    778:     const char *strip_path, int lflag)
1.44      djm       779: {
1.64      djm       780:        int n;
                    781:        u_int c = 1, colspace = 0, columns = 1;
1.44      djm       782:        SFTP_DIRENT **d;
                    783:
                    784:        if ((n = do_readdir(conn, path, &d)) != 0)
                    785:                return (n);
                    786:
1.53      djm       787:        if (!(lflag & LS_SHORT_VIEW)) {
1.64      djm       788:                u_int m = 0, width = 80;
1.44      djm       789:                struct winsize ws;
                    790:                char *tmp;
                    791:
                    792:                /* Count entries for sort and find longest filename */
1.54      djm       793:                for (n = 0; d[n] != NULL; n++) {
                    794:                        if (d[n]->filename[0] != '.' || (lflag & LS_SHOW_ALL))
1.176     deraadt   795:                                m = MAXIMUM(m, strlen(d[n]->filename));
1.54      djm       796:                }
1.44      djm       797:
                    798:                /* Add any subpath that also needs to be counted */
                    799:                tmp = path_strip(path, strip_path);
                    800:                m += strlen(tmp);
1.145     djm       801:                free(tmp);
1.44      djm       802:
                    803:                if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
                    804:                        width = ws.ws_col;
                    805:
                    806:                columns = width / (m + 2);
1.176     deraadt   807:                columns = MAXIMUM(columns, 1);
1.44      djm       808:                colspace = width / columns;
1.176     deraadt   809:                colspace = MINIMUM(colspace, width);
1.44      djm       810:        }
                    811:
1.52      djm       812:        if (lflag & SORT_FLAGS) {
1.68      dtucker   813:                for (n = 0; d[n] != NULL; n++)
                    814:                        ;       /* count entries */
1.53      djm       815:                sort_flag = lflag & (SORT_FLAGS|LS_REVERSE_SORT);
1.52      djm       816:                qsort(d, n, sizeof(*d), sdirent_comp);
                    817:        }
1.44      djm       818:
1.46      djm       819:        for (n = 0; d[n] != NULL && !interrupted; n++) {
1.44      djm       820:                char *tmp, *fname;
1.54      djm       821:
                    822:                if (d[n]->filename[0] == '.' && !(lflag & LS_SHOW_ALL))
                    823:                        continue;
1.44      djm       824:
                    825:                tmp = path_append(path, d[n]->filename);
                    826:                fname = path_strip(tmp, strip_path);
1.145     djm       827:                free(tmp);
1.44      djm       828:
1.53      djm       829:                if (lflag & LS_LONG_VIEW) {
1.119     djm       830:                        if (lflag & (LS_NUMERIC_VIEW|LS_SI_UNITS)) {
1.50      djm       831:                                char *lname;
                    832:                                struct stat sb;
                    833:
                    834:                                memset(&sb, 0, sizeof(sb));
                    835:                                attrib_to_stat(&d[n]->a, &sb);
1.119     djm       836:                                lname = ls_file(fname, &sb, 1,
                    837:                                    (lflag & LS_SI_UNITS));
1.174     schwarze  838:                                mprintf("%s\n", lname);
1.145     djm       839:                                free(lname);
1.50      djm       840:                        } else
1.174     schwarze  841:                                mprintf("%s\n", d[n]->longname);
1.44      djm       842:                } else {
1.174     schwarze  843:                        mprintf("%-*s", colspace, fname);
1.44      djm       844:                        if (c >= columns) {
                    845:                                printf("\n");
                    846:                                c = 1;
                    847:                        } else
                    848:                                c++;
                    849:                }
                    850:
1.145     djm       851:                free(fname);
1.44      djm       852:        }
                    853:
1.53      djm       854:        if (!(lflag & LS_LONG_VIEW) && (c != 1))
1.44      djm       855:                printf("\n");
                    856:
                    857:        free_sftp_dirents(d);
                    858:        return (0);
                    859: }
                    860:
1.180     djm       861: static int
                    862: sglob_comp(const void *aa, const void *bb)
                    863: {
                    864:        u_int a = *(const u_int *)aa;
                    865:        u_int b = *(const u_int *)bb;
                    866:        const char *ap = sort_glob->gl_pathv[a];
                    867:        const char *bp = sort_glob->gl_pathv[b];
                    868:        const struct stat *as = sort_glob->gl_statv[a];
                    869:        const struct stat *bs = sort_glob->gl_statv[b];
                    870:        int rmul = sort_flag & LS_REVERSE_SORT ? -1 : 1;
                    871:
                    872: #define NCMP(a,b) (a == b ? 0 : (a < b ? 1 : -1))
                    873:        if (sort_flag & LS_NAME_SORT)
                    874:                return (rmul * strcmp(ap, bp));
                    875:        else if (sort_flag & LS_TIME_SORT)
                    876:                return (rmul * timespeccmp(&as->st_mtim, &bs->st_mtim, <));
                    877:        else if (sort_flag & LS_SIZE_SORT)
                    878:                return (rmul * NCMP(as->st_size, bs->st_size));
                    879:
                    880:        fatal("Unknown ls sort type");
                    881: }
                    882:
1.44      djm       883: /* sftp ls.1 replacement which handles path globs */
                    884: static int
1.175     djm       885: do_globbed_ls(struct sftp_conn *conn, const char *path,
                    886:     const char *strip_path, int lflag)
1.44      djm       887: {
1.129     djm       888:        char *fname, *lname;
1.44      djm       889:        glob_t g;
1.164     djm       890:        int err, r;
1.129     djm       891:        struct winsize ws;
1.180     djm       892:        u_int i, j, nentries, *indices = NULL, c = 1;
                    893:        u_int colspace = 0, columns = 1, m = 0, width = 80;
1.44      djm       894:
                    895:        memset(&g, 0, sizeof(g));
                    896:
1.164     djm       897:        if ((r = remote_glob(conn, path,
1.133     djm       898:            GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE|GLOB_KEEPSTAT|GLOB_NOSORT,
1.164     djm       899:            NULL, &g)) != 0 ||
1.128     djm       900:            (g.gl_pathc && !g.gl_matchc)) {
1.60      fgsch     901:                if (g.gl_pathc)
                    902:                        globfree(&g);
1.164     djm       903:                if (r == GLOB_NOSPACE) {
                    904:                        error("Can't ls: Too many matches for \"%s\"", path);
                    905:                } else {
                    906:                        error("Can't ls: \"%s\" not found", path);
                    907:                }
1.128     djm       908:                return -1;
1.44      djm       909:        }
                    910:
1.46      djm       911:        if (interrupted)
                    912:                goto out;
                    913:
1.44      djm       914:        /*
1.60      fgsch     915:         * If the glob returns a single match and it is a directory,
                    916:         * then just list its contents.
1.44      djm       917:         */
1.128     djm       918:        if (g.gl_matchc == 1 && g.gl_statv[0] != NULL &&
                    919:            S_ISDIR(g.gl_statv[0]->st_mode)) {
                    920:                err = do_ls_dir(conn, g.gl_pathv[0], strip_path, lflag);
                    921:                globfree(&g);
                    922:                return err;
1.44      djm       923:        }
                    924:
1.129     djm       925:        if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
                    926:                width = ws.ws_col;
                    927:
1.53      djm       928:        if (!(lflag & LS_SHORT_VIEW)) {
1.44      djm       929:                /* Count entries for sort and find longest filename */
                    930:                for (i = 0; g.gl_pathv[i]; i++)
1.176     deraadt   931:                        m = MAXIMUM(m, strlen(g.gl_pathv[i]));
1.44      djm       932:
                    933:                columns = width / (m + 2);
1.176     deraadt   934:                columns = MAXIMUM(columns, 1);
1.44      djm       935:                colspace = width / columns;
                    936:        }
                    937:
1.180     djm       938:        /*
                    939:         * Sorting: rather than mess with the contents of glob_t, prepare
                    940:         * an array of indices into it and sort that. For the usual
                    941:         * unsorted case, the indices are just the identity 1=1, 2=2, etc.
                    942:         */
                    943:        for (nentries = 0; g.gl_pathv[nentries] != NULL; nentries++)
                    944:                ;       /* count entries */
                    945:        indices = calloc(nentries, sizeof(*indices));
                    946:        for (i = 0; i < nentries; i++)
                    947:                indices[i] = i;
                    948:
                    949:        if (lflag & SORT_FLAGS) {
                    950:                sort_glob = &g;
                    951:                sort_flag = lflag & (SORT_FLAGS|LS_REVERSE_SORT);
                    952:                qsort(indices, nentries, sizeof(*indices), sglob_comp);
                    953:                sort_glob = NULL;
                    954:        }
                    955:
                    956:        for (j = 0; j < nentries && !interrupted; j++) {
                    957:                i = indices[j];
1.44      djm       958:                fname = path_strip(g.gl_pathv[i], strip_path);
1.53      djm       959:                if (lflag & LS_LONG_VIEW) {
1.128     djm       960:                        if (g.gl_statv[i] == NULL) {
                    961:                                error("no stat information for %s", fname);
                    962:                                continue;
                    963:                        }
                    964:                        lname = ls_file(fname, g.gl_statv[i], 1,
                    965:                            (lflag & LS_SI_UNITS));
1.174     schwarze  966:                        mprintf("%s\n", lname);
1.145     djm       967:                        free(lname);
1.44      djm       968:                } else {
1.174     schwarze  969:                        mprintf("%-*s", colspace, fname);
1.44      djm       970:                        if (c >= columns) {
                    971:                                printf("\n");
                    972:                                c = 1;
                    973:                        } else
                    974:                                c++;
                    975:                }
1.145     djm       976:                free(fname);
1.44      djm       977:        }
                    978:
1.53      djm       979:        if (!(lflag & LS_LONG_VIEW) && (c != 1))
1.44      djm       980:                printf("\n");
                    981:
1.46      djm       982:  out:
1.44      djm       983:        if (g.gl_pathc)
                    984:                globfree(&g);
1.180     djm       985:        free(indices);
1.44      djm       986:
1.128     djm       987:        return 0;
1.44      djm       988: }
                    989:
1.100     djm       990: static int
1.175     djm       991: do_df(struct sftp_conn *conn, const char *path, int hflag, int iflag)
1.100     djm       992: {
1.101     dtucker   993:        struct sftp_statvfs st;
1.178     djm       994:        char s_used[FMT_SCALED_STRSIZE], s_avail[FMT_SCALED_STRSIZE];
                    995:        char s_root[FMT_SCALED_STRSIZE], s_total[FMT_SCALED_STRSIZE];
                    996:        char s_icapacity[16], s_dcapacity[16];
1.100     djm       997:
                    998:        if (do_statvfs(conn, path, &st, 1) == -1)
                    999:                return -1;
1.178     djm      1000:        if (st.f_files == 0)
                   1001:                strlcpy(s_icapacity, "ERR", sizeof(s_icapacity));
                   1002:        else {
                   1003:                snprintf(s_icapacity, sizeof(s_icapacity), "%3llu%%",
                   1004:                    (unsigned long long)(100 * (st.f_files - st.f_ffree) /
                   1005:                    st.f_files));
                   1006:        }
                   1007:        if (st.f_blocks == 0)
                   1008:                strlcpy(s_dcapacity, "ERR", sizeof(s_dcapacity));
                   1009:        else {
                   1010:                snprintf(s_dcapacity, sizeof(s_dcapacity), "%3llu%%",
                   1011:                    (unsigned long long)(100 * (st.f_blocks - st.f_bfree) /
                   1012:                    st.f_blocks));
                   1013:        }
1.100     djm      1014:        if (iflag) {
                   1015:                printf("     Inodes        Used       Avail      "
                   1016:                    "(root)    %%Capacity\n");
1.178     djm      1017:                printf("%11llu %11llu %11llu %11llu         %s\n",
1.100     djm      1018:                    (unsigned long long)st.f_files,
                   1019:                    (unsigned long long)(st.f_files - st.f_ffree),
                   1020:                    (unsigned long long)st.f_favail,
1.178     djm      1021:                    (unsigned long long)st.f_ffree, s_icapacity);
1.100     djm      1022:        } else if (hflag) {
                   1023:                strlcpy(s_used, "error", sizeof(s_used));
                   1024:                strlcpy(s_avail, "error", sizeof(s_avail));
                   1025:                strlcpy(s_root, "error", sizeof(s_root));
                   1026:                strlcpy(s_total, "error", sizeof(s_total));
                   1027:                fmt_scaled((st.f_blocks - st.f_bfree) * st.f_frsize, s_used);
                   1028:                fmt_scaled(st.f_bavail * st.f_frsize, s_avail);
                   1029:                fmt_scaled(st.f_bfree * st.f_frsize, s_root);
                   1030:                fmt_scaled(st.f_blocks * st.f_frsize, s_total);
                   1031:                printf("    Size     Used    Avail   (root)    %%Capacity\n");
1.178     djm      1032:                printf("%7sB %7sB %7sB %7sB         %s\n",
                   1033:                    s_total, s_used, s_avail, s_root, s_dcapacity);
1.100     djm      1034:        } else {
                   1035:                printf("        Size         Used        Avail       "
                   1036:                    "(root)    %%Capacity\n");
1.178     djm      1037:                printf("%12llu %12llu %12llu %12llu         %s\n",
1.100     djm      1038:                    (unsigned long long)(st.f_frsize * st.f_blocks / 1024),
                   1039:                    (unsigned long long)(st.f_frsize *
                   1040:                    (st.f_blocks - st.f_bfree) / 1024),
                   1041:                    (unsigned long long)(st.f_frsize * st.f_bavail / 1024),
                   1042:                    (unsigned long long)(st.f_frsize * st.f_bfree / 1024),
1.178     djm      1043:                    s_dcapacity);
1.100     djm      1044:        }
                   1045:        return 0;
                   1046: }
                   1047:
1.97      djm      1048: /*
                   1049:  * Undo escaping of glob sequences in place. Used to undo extra escaping
                   1050:  * applied in makeargv() when the string is destined for a function that
                   1051:  * does not glob it.
                   1052:  */
                   1053: static void
                   1054: undo_glob_escape(char *s)
                   1055: {
                   1056:        size_t i, j;
                   1057:
                   1058:        for (i = j = 0;;) {
                   1059:                if (s[i] == '\0') {
                   1060:                        s[j] = '\0';
                   1061:                        return;
                   1062:                }
                   1063:                if (s[i] != '\\') {
                   1064:                        s[j++] = s[i++];
                   1065:                        continue;
                   1066:                }
                   1067:                /* s[i] == '\\' */
                   1068:                ++i;
                   1069:                switch (s[i]) {
                   1070:                case '?':
                   1071:                case '[':
                   1072:                case '*':
                   1073:                case '\\':
                   1074:                        s[j++] = s[i++];
                   1075:                        break;
                   1076:                case '\0':
                   1077:                        s[j++] = '\\';
                   1078:                        s[j] = '\0';
                   1079:                        return;
                   1080:                default:
                   1081:                        s[j++] = '\\';
                   1082:                        s[j++] = s[i++];
                   1083:                        break;
                   1084:                }
                   1085:        }
                   1086: }
                   1087:
                   1088: /*
                   1089:  * Split a string into an argument vector using sh(1)-style quoting,
                   1090:  * comment and escaping rules, but with some tweaks to handle glob(3)
                   1091:  * wildcards.
1.116     djm      1092:  * The "sloppy" flag allows for recovery from missing terminating quote, for
                   1093:  * use in parsing incomplete commandlines during tab autocompletion.
                   1094:  *
1.97      djm      1095:  * Returns NULL on error or a NULL-terminated array of arguments.
1.116     djm      1096:  *
                   1097:  * If "lastquote" is not NULL, the quoting character used for the last
                   1098:  * argument is placed in *lastquote ("\0", "'" or "\"").
1.149     djm      1099:  *
1.116     djm      1100:  * If "terminated" is not NULL, *terminated will be set to 1 when the
                   1101:  * last argument's quote has been properly terminated or 0 otherwise.
                   1102:  * This parameter is only of use if "sloppy" is set.
1.97      djm      1103:  */
                   1104: #define MAXARGS        128
                   1105: #define MAXARGLEN      8192
                   1106: static char **
1.116     djm      1107: makeargv(const char *arg, int *argcp, int sloppy, char *lastquote,
                   1108:     u_int *terminated)
1.97      djm      1109: {
                   1110:        int argc, quot;
                   1111:        size_t i, j;
                   1112:        static char argvs[MAXARGLEN];
                   1113:        static char *argv[MAXARGS + 1];
                   1114:        enum { MA_START, MA_SQUOTE, MA_DQUOTE, MA_UNQUOTED } state, q;
                   1115:
                   1116:        *argcp = argc = 0;
                   1117:        if (strlen(arg) > sizeof(argvs) - 1) {
                   1118:  args_too_longs:
                   1119:                error("string too long");
                   1120:                return NULL;
                   1121:        }
1.116     djm      1122:        if (terminated != NULL)
                   1123:                *terminated = 1;
                   1124:        if (lastquote != NULL)
                   1125:                *lastquote = '\0';
1.97      djm      1126:        state = MA_START;
                   1127:        i = j = 0;
                   1128:        for (;;) {
1.141     markus   1129:                if ((size_t)argc >= sizeof(argv) / sizeof(*argv)){
1.138     dtucker  1130:                        error("Too many arguments.");
                   1131:                        return NULL;
                   1132:                }
1.158     deraadt  1133:                if (isspace((unsigned char)arg[i])) {
1.97      djm      1134:                        if (state == MA_UNQUOTED) {
                   1135:                                /* Terminate current argument */
                   1136:                                argvs[j++] = '\0';
                   1137:                                argc++;
                   1138:                                state = MA_START;
                   1139:                        } else if (state != MA_START)
                   1140:                                argvs[j++] = arg[i];
                   1141:                } else if (arg[i] == '"' || arg[i] == '\'') {
                   1142:                        q = arg[i] == '"' ? MA_DQUOTE : MA_SQUOTE;
                   1143:                        if (state == MA_START) {
                   1144:                                argv[argc] = argvs + j;
                   1145:                                state = q;
1.116     djm      1146:                                if (lastquote != NULL)
                   1147:                                        *lastquote = arg[i];
1.149     djm      1148:                        } else if (state == MA_UNQUOTED)
1.97      djm      1149:                                state = q;
                   1150:                        else if (state == q)
                   1151:                                state = MA_UNQUOTED;
                   1152:                        else
                   1153:                                argvs[j++] = arg[i];
                   1154:                } else if (arg[i] == '\\') {
                   1155:                        if (state == MA_SQUOTE || state == MA_DQUOTE) {
                   1156:                                quot = state == MA_SQUOTE ? '\'' : '"';
                   1157:                                /* Unescape quote we are in */
                   1158:                                /* XXX support \n and friends? */
                   1159:                                if (arg[i + 1] == quot) {
                   1160:                                        i++;
                   1161:                                        argvs[j++] = arg[i];
                   1162:                                } else if (arg[i + 1] == '?' ||
                   1163:                                    arg[i + 1] == '[' || arg[i + 1] == '*') {
                   1164:                                        /*
                   1165:                                         * Special case for sftp: append
                   1166:                                         * double-escaped glob sequence -
                   1167:                                         * glob will undo one level of
                   1168:                                         * escaping. NB. string can grow here.
                   1169:                                         */
                   1170:                                        if (j >= sizeof(argvs) - 5)
                   1171:                                                goto args_too_longs;
                   1172:                                        argvs[j++] = '\\';
                   1173:                                        argvs[j++] = arg[i++];
                   1174:                                        argvs[j++] = '\\';
                   1175:                                        argvs[j++] = arg[i];
                   1176:                                } else {
                   1177:                                        argvs[j++] = arg[i++];
                   1178:                                        argvs[j++] = arg[i];
                   1179:                                }
                   1180:                        } else {
                   1181:                                if (state == MA_START) {
                   1182:                                        argv[argc] = argvs + j;
                   1183:                                        state = MA_UNQUOTED;
1.116     djm      1184:                                        if (lastquote != NULL)
                   1185:                                                *lastquote = '\0';
1.97      djm      1186:                                }
                   1187:                                if (arg[i + 1] == '?' || arg[i + 1] == '[' ||
                   1188:                                    arg[i + 1] == '*' || arg[i + 1] == '\\') {
                   1189:                                        /*
                   1190:                                         * Special case for sftp: append
                   1191:                                         * escaped glob sequence -
                   1192:                                         * glob will undo one level of
                   1193:                                         * escaping.
                   1194:                                         */
                   1195:                                        argvs[j++] = arg[i++];
                   1196:                                        argvs[j++] = arg[i];
                   1197:                                } else {
                   1198:                                        /* Unescape everything */
                   1199:                                        /* XXX support \n and friends? */
                   1200:                                        i++;
                   1201:                                        argvs[j++] = arg[i];
                   1202:                                }
                   1203:                        }
                   1204:                } else if (arg[i] == '#') {
                   1205:                        if (state == MA_SQUOTE || state == MA_DQUOTE)
                   1206:                                argvs[j++] = arg[i];
                   1207:                        else
                   1208:                                goto string_done;
                   1209:                } else if (arg[i] == '\0') {
                   1210:                        if (state == MA_SQUOTE || state == MA_DQUOTE) {
1.116     djm      1211:                                if (sloppy) {
                   1212:                                        state = MA_UNQUOTED;
                   1213:                                        if (terminated != NULL)
                   1214:                                                *terminated = 0;
                   1215:                                        goto string_done;
                   1216:                                }
1.97      djm      1217:                                error("Unterminated quoted argument");
                   1218:                                return NULL;
                   1219:                        }
                   1220:  string_done:
                   1221:                        if (state == MA_UNQUOTED) {
                   1222:                                argvs[j++] = '\0';
                   1223:                                argc++;
                   1224:                        }
                   1225:                        break;
                   1226:                } else {
                   1227:                        if (state == MA_START) {
                   1228:                                argv[argc] = argvs + j;
                   1229:                                state = MA_UNQUOTED;
1.116     djm      1230:                                if (lastquote != NULL)
                   1231:                                        *lastquote = '\0';
1.97      djm      1232:                        }
                   1233:                        if ((state == MA_SQUOTE || state == MA_DQUOTE) &&
                   1234:                            (arg[i] == '?' || arg[i] == '[' || arg[i] == '*')) {
                   1235:                                /*
                   1236:                                 * Special case for sftp: escape quoted
                   1237:                                 * glob(3) wildcards. NB. string can grow
                   1238:                                 * here.
                   1239:                                 */
                   1240:                                if (j >= sizeof(argvs) - 3)
                   1241:                                        goto args_too_longs;
                   1242:                                argvs[j++] = '\\';
                   1243:                                argvs[j++] = arg[i];
                   1244:                        } else
                   1245:                                argvs[j++] = arg[i];
                   1246:                }
                   1247:                i++;
                   1248:        }
                   1249:        *argcp = argc;
                   1250:        return argv;
                   1251: }
                   1252:
1.44      djm      1253: static int
1.159     logan    1254: parse_args(const char **cpp, int *ignore_errors, int *aflag,
1.173     djm      1255:          int *fflag, int *hflag, int *iflag, int *lflag, int *pflag,
1.159     logan    1256:          int *rflag, int *sflag,
1.156     djm      1257:     unsigned long *n_arg, char **path1, char **path2)
1.44      djm      1258: {
                   1259:        const char *cmd, *cp = *cpp;
1.97      djm      1260:        char *cp2, **argv;
1.44      djm      1261:        int base = 0;
                   1262:        long l;
1.97      djm      1263:        int i, cmdnum, optidx, argc;
1.44      djm      1264:
                   1265:        /* Skip leading whitespace */
                   1266:        cp = cp + strspn(cp, WHITESPACE);
                   1267:
                   1268:        /* Check for leading '-' (disable error processing) */
1.156     djm      1269:        *ignore_errors = 0;
1.44      djm      1270:        if (*cp == '-') {
1.156     djm      1271:                *ignore_errors = 1;
1.44      djm      1272:                cp++;
1.118     dtucker  1273:                cp = cp + strspn(cp, WHITESPACE);
1.44      djm      1274:        }
1.118     dtucker  1275:
                   1276:        /* Ignore blank lines and lines which begin with comment '#' char */
                   1277:        if (*cp == '\0' || *cp == '#')
                   1278:                return (0);
1.44      djm      1279:
1.116     djm      1280:        if ((argv = makeargv(cp, &argc, 0, NULL, NULL)) == NULL)
1.97      djm      1281:                return -1;
                   1282:
1.44      djm      1283:        /* Figure out which command we have */
1.97      djm      1284:        for (i = 0; cmds[i].c != NULL; i++) {
1.142     djm      1285:                if (argv[0] != NULL && strcasecmp(cmds[i].c, argv[0]) == 0)
1.44      djm      1286:                        break;
                   1287:        }
                   1288:        cmdnum = cmds[i].n;
                   1289:        cmd = cmds[i].c;
                   1290:
                   1291:        /* Special case */
                   1292:        if (*cp == '!') {
                   1293:                cp++;
                   1294:                cmdnum = I_SHELL;
                   1295:        } else if (cmdnum == -1) {
                   1296:                error("Invalid command.");
1.97      djm      1297:                return -1;
1.44      djm      1298:        }
                   1299:
                   1300:        /* Get arguments and parse flags */
1.156     djm      1301:        *aflag = *fflag = *hflag = *iflag = *lflag = *pflag = 0;
                   1302:        *rflag = *sflag = 0;
1.44      djm      1303:        *path1 = *path2 = NULL;
1.97      djm      1304:        optidx = 1;
1.44      djm      1305:        switch (cmdnum) {
                   1306:        case I_GET:
1.148     djm      1307:        case I_REGET:
1.159     logan    1308:        case I_REPUT:
1.44      djm      1309:        case I_PUT:
1.132     djm      1310:                if ((optidx = parse_getput_flags(cmd, argv, argc,
1.156     djm      1311:                    aflag, fflag, pflag, rflag)) == -1)
1.97      djm      1312:                        return -1;
1.44      djm      1313:                /* Get first pathname (mandatory) */
1.97      djm      1314:                if (argc - optidx < 1) {
1.44      djm      1315:                        error("You must specify at least one path after a "
                   1316:                            "%s command.", cmd);
1.97      djm      1317:                        return -1;
                   1318:                }
                   1319:                *path1 = xstrdup(argv[optidx]);
                   1320:                /* Get second pathname (optional) */
                   1321:                if (argc - optidx > 1) {
                   1322:                        *path2 = xstrdup(argv[optidx + 1]);
                   1323:                        /* Destination is not globbed */
                   1324:                        undo_glob_escape(*path2);
1.44      djm      1325:                }
                   1326:                break;
1.132     djm      1327:        case I_LINK:
                   1328:                if ((optidx = parse_link_flags(cmd, argv, argc, sflag)) == -1)
                   1329:                        return -1;
1.152     djm      1330:                goto parse_two_paths;
                   1331:        case I_RENAME:
                   1332:                if ((optidx = parse_rename_flags(cmd, argv, argc, lflag)) == -1)
                   1333:                        return -1;
                   1334:                goto parse_two_paths;
1.132     djm      1335:        case I_SYMLINK:
1.153     djm      1336:                if ((optidx = parse_no_flags(cmd, argv, argc)) == -1)
                   1337:                        return -1;
1.152     djm      1338:  parse_two_paths:
1.97      djm      1339:                if (argc - optidx < 2) {
1.44      djm      1340:                        error("You must specify two paths after a %s "
                   1341:                            "command.", cmd);
1.97      djm      1342:                        return -1;
1.44      djm      1343:                }
1.97      djm      1344:                *path1 = xstrdup(argv[optidx]);
                   1345:                *path2 = xstrdup(argv[optidx + 1]);
                   1346:                /* Paths are not globbed */
                   1347:                undo_glob_escape(*path1);
                   1348:                undo_glob_escape(*path2);
1.44      djm      1349:                break;
                   1350:        case I_RM:
                   1351:        case I_MKDIR:
                   1352:        case I_RMDIR:
                   1353:        case I_CHDIR:
                   1354:        case I_LCHDIR:
                   1355:        case I_LMKDIR:
1.153     djm      1356:                if ((optidx = parse_no_flags(cmd, argv, argc)) == -1)
                   1357:                        return -1;
1.44      djm      1358:                /* Get pathname (mandatory) */
1.97      djm      1359:                if (argc - optidx < 1) {
1.44      djm      1360:                        error("You must specify a path after a %s command.",
                   1361:                            cmd);
1.97      djm      1362:                        return -1;
1.44      djm      1363:                }
1.97      djm      1364:                *path1 = xstrdup(argv[optidx]);
                   1365:                /* Only "rm" globs */
                   1366:                if (cmdnum != I_RM)
                   1367:                        undo_glob_escape(*path1);
1.44      djm      1368:                break;
1.100     djm      1369:        case I_DF:
                   1370:                if ((optidx = parse_df_flags(cmd, argv, argc, hflag,
                   1371:                    iflag)) == -1)
                   1372:                        return -1;
                   1373:                /* Default to current directory if no path specified */
                   1374:                if (argc - optidx < 1)
                   1375:                        *path1 = NULL;
                   1376:                else {
                   1377:                        *path1 = xstrdup(argv[optidx]);
                   1378:                        undo_glob_escape(*path1);
                   1379:                }
                   1380:                break;
1.44      djm      1381:        case I_LS:
1.97      djm      1382:                if ((optidx = parse_ls_flags(argv, argc, lflag)) == -1)
1.44      djm      1383:                        return(-1);
                   1384:                /* Path is optional */
1.97      djm      1385:                if (argc - optidx > 0)
                   1386:                        *path1 = xstrdup(argv[optidx]);
1.44      djm      1387:                break;
                   1388:        case I_LLS:
1.98      djm      1389:                /* Skip ls command and following whitespace */
                   1390:                cp = cp + strlen(cmd) + strspn(cp, WHITESPACE);
1.44      djm      1391:        case I_SHELL:
                   1392:                /* Uses the rest of the line */
                   1393:                break;
                   1394:        case I_LUMASK:
                   1395:        case I_CHMOD:
                   1396:                base = 8;
                   1397:        case I_CHOWN:
                   1398:        case I_CHGRP:
1.153     djm      1399:                if ((optidx = parse_no_flags(cmd, argv, argc)) == -1)
                   1400:                        return -1;
1.44      djm      1401:                /* Get numeric arg (mandatory) */
1.97      djm      1402:                if (argc - optidx < 1)
                   1403:                        goto need_num_arg;
1.93      ray      1404:                errno = 0;
1.97      djm      1405:                l = strtol(argv[optidx], &cp2, base);
                   1406:                if (cp2 == argv[optidx] || *cp2 != '\0' ||
                   1407:                    ((l == LONG_MIN || l == LONG_MAX) && errno == ERANGE) ||
                   1408:                    l < 0) {
                   1409:  need_num_arg:
1.44      djm      1410:                        error("You must supply a numeric argument "
                   1411:                            "to the %s command.", cmd);
1.97      djm      1412:                        return -1;
1.44      djm      1413:                }
                   1414:                *n_arg = l;
1.97      djm      1415:                if (cmdnum == I_LUMASK)
1.44      djm      1416:                        break;
                   1417:                /* Get pathname (mandatory) */
1.97      djm      1418:                if (argc - optidx < 2) {
1.44      djm      1419:                        error("You must specify a path after a %s command.",
                   1420:                            cmd);
1.97      djm      1421:                        return -1;
1.44      djm      1422:                }
1.97      djm      1423:                *path1 = xstrdup(argv[optidx + 1]);
1.44      djm      1424:                break;
                   1425:        case I_QUIT:
                   1426:        case I_PWD:
                   1427:        case I_LPWD:
                   1428:        case I_HELP:
                   1429:        case I_VERSION:
                   1430:        case I_PROGRESS:
1.153     djm      1431:                if ((optidx = parse_no_flags(cmd, argv, argc)) == -1)
                   1432:                        return -1;
1.44      djm      1433:                break;
                   1434:        default:
                   1435:                fatal("Command not implemented");
                   1436:        }
                   1437:
                   1438:        *cpp = cp;
                   1439:        return(cmdnum);
                   1440: }
                   1441:
                   1442: static int
                   1443: parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
                   1444:     int err_abort)
                   1445: {
                   1446:        char *path1, *path2, *tmp;
1.173     djm      1447:        int ignore_errors = 0, aflag = 0, fflag = 0, hflag = 0,
1.159     logan    1448:        iflag = 0;
1.156     djm      1449:        int lflag = 0, pflag = 0, rflag = 0, sflag = 0;
1.132     djm      1450:        int cmdnum, i;
1.107     dtucker  1451:        unsigned long n_arg = 0;
1.44      djm      1452:        Attrib a, *aa;
1.170     deraadt  1453:        char path_buf[PATH_MAX];
1.44      djm      1454:        int err = 0;
                   1455:        glob_t g;
                   1456:
                   1457:        path1 = path2 = NULL;
1.156     djm      1458:        cmdnum = parse_args(&cmd, &ignore_errors, &aflag, &fflag, &hflag,
                   1459:            &iflag, &lflag, &pflag, &rflag, &sflag, &n_arg, &path1, &path2);
                   1460:        if (ignore_errors != 0)
1.44      djm      1461:                err_abort = 0;
                   1462:
                   1463:        memset(&g, 0, sizeof(g));
                   1464:
                   1465:        /* Perform command */
                   1466:        switch (cmdnum) {
                   1467:        case 0:
                   1468:                /* Blank line */
                   1469:                break;
                   1470:        case -1:
                   1471:                /* Unrecognized command */
                   1472:                err = -1;
                   1473:                break;
1.148     djm      1474:        case I_REGET:
                   1475:                aflag = 1;
                   1476:                /* FALLTHROUGH */
1.44      djm      1477:        case I_GET:
1.148     djm      1478:                err = process_get(conn, path1, path2, *pwd, pflag,
1.156     djm      1479:                    rflag, aflag, fflag);
1.44      djm      1480:                break;
1.159     logan    1481:        case I_REPUT:
                   1482:                aflag = 1;
                   1483:                /* FALLTHROUGH */
1.44      djm      1484:        case I_PUT:
1.156     djm      1485:                err = process_put(conn, path1, path2, *pwd, pflag,
1.159     logan    1486:                    rflag, aflag, fflag);
1.44      djm      1487:                break;
                   1488:        case I_RENAME:
                   1489:                path1 = make_absolute(path1, *pwd);
                   1490:                path2 = make_absolute(path2, *pwd);
1.152     djm      1491:                err = do_rename(conn, path1, path2, lflag);
1.44      djm      1492:                break;
                   1493:        case I_SYMLINK:
1.132     djm      1494:                sflag = 1;
                   1495:        case I_LINK:
1.151     djm      1496:                if (!sflag)
                   1497:                        path1 = make_absolute(path1, *pwd);
1.44      djm      1498:                path2 = make_absolute(path2, *pwd);
1.132     djm      1499:                err = (sflag ? do_symlink : do_hardlink)(conn, path1, path2);
1.44      djm      1500:                break;
                   1501:        case I_RM:
                   1502:                path1 = make_absolute(path1, *pwd);
                   1503:                remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1.46      djm      1504:                for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1.143     djm      1505:                        if (!quiet)
1.174     schwarze 1506:                                mprintf("Removing %s\n", g.gl_pathv[i]);
1.44      djm      1507:                        err = do_rm(conn, g.gl_pathv[i]);
                   1508:                        if (err != 0 && err_abort)
                   1509:                                break;
                   1510:                }
                   1511:                break;
                   1512:        case I_MKDIR:
                   1513:                path1 = make_absolute(path1, *pwd);
                   1514:                attrib_clear(&a);
                   1515:                a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
                   1516:                a.perm = 0777;
1.111     djm      1517:                err = do_mkdir(conn, path1, &a, 1);
1.44      djm      1518:                break;
                   1519:        case I_RMDIR:
                   1520:                path1 = make_absolute(path1, *pwd);
                   1521:                err = do_rmdir(conn, path1);
                   1522:                break;
                   1523:        case I_CHDIR:
                   1524:                path1 = make_absolute(path1, *pwd);
                   1525:                if ((tmp = do_realpath(conn, path1)) == NULL) {
                   1526:                        err = 1;
                   1527:                        break;
                   1528:                }
                   1529:                if ((aa = do_stat(conn, tmp, 0)) == NULL) {
1.145     djm      1530:                        free(tmp);
1.44      djm      1531:                        err = 1;
                   1532:                        break;
                   1533:                }
                   1534:                if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
                   1535:                        error("Can't change directory: Can't check target");
1.145     djm      1536:                        free(tmp);
1.44      djm      1537:                        err = 1;
                   1538:                        break;
                   1539:                }
                   1540:                if (!S_ISDIR(aa->perm)) {
                   1541:                        error("Can't change directory: \"%s\" is not "
                   1542:                            "a directory", tmp);
1.145     djm      1543:                        free(tmp);
1.44      djm      1544:                        err = 1;
                   1545:                        break;
                   1546:                }
1.145     djm      1547:                free(*pwd);
1.44      djm      1548:                *pwd = tmp;
                   1549:                break;
                   1550:        case I_LS:
                   1551:                if (!path1) {
1.125     djm      1552:                        do_ls_dir(conn, *pwd, *pwd, lflag);
1.44      djm      1553:                        break;
                   1554:                }
                   1555:
                   1556:                /* Strip pwd off beginning of non-absolute paths */
                   1557:                tmp = NULL;
                   1558:                if (*path1 != '/')
                   1559:                        tmp = *pwd;
                   1560:
                   1561:                path1 = make_absolute(path1, *pwd);
                   1562:                err = do_globbed_ls(conn, path1, tmp, lflag);
1.100     djm      1563:                break;
                   1564:        case I_DF:
                   1565:                /* Default to current directory if no path specified */
                   1566:                if (path1 == NULL)
                   1567:                        path1 = xstrdup(*pwd);
                   1568:                path1 = make_absolute(path1, *pwd);
                   1569:                err = do_df(conn, path1, hflag, iflag);
1.44      djm      1570:                break;
                   1571:        case I_LCHDIR:
1.166     deraadt  1572:                tmp = tilde_expand_filename(path1, getuid());
1.165     djm      1573:                free(path1);
                   1574:                path1 = tmp;
1.44      djm      1575:                if (chdir(path1) == -1) {
                   1576:                        error("Couldn't change local directory to "
                   1577:                            "\"%s\": %s", path1, strerror(errno));
                   1578:                        err = 1;
                   1579:                }
                   1580:                break;
                   1581:        case I_LMKDIR:
                   1582:                if (mkdir(path1, 0777) == -1) {
                   1583:                        error("Couldn't create local directory "
                   1584:                            "\"%s\": %s", path1, strerror(errno));
                   1585:                        err = 1;
                   1586:                }
                   1587:                break;
                   1588:        case I_LLS:
                   1589:                local_do_ls(cmd);
                   1590:                break;
                   1591:        case I_SHELL:
                   1592:                local_do_shell(cmd);
                   1593:                break;
                   1594:        case I_LUMASK:
                   1595:                umask(n_arg);
                   1596:                printf("Local umask: %03lo\n", n_arg);
                   1597:                break;
                   1598:        case I_CHMOD:
                   1599:                path1 = make_absolute(path1, *pwd);
                   1600:                attrib_clear(&a);
                   1601:                a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
                   1602:                a.perm = n_arg;
                   1603:                remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1.46      djm      1604:                for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1.143     djm      1605:                        if (!quiet)
1.174     schwarze 1606:                                mprintf("Changing mode on %s\n",
                   1607:                                    g.gl_pathv[i]);
1.44      djm      1608:                        err = do_setstat(conn, g.gl_pathv[i], &a);
                   1609:                        if (err != 0 && err_abort)
                   1610:                                break;
                   1611:                }
                   1612:                break;
                   1613:        case I_CHOWN:
                   1614:        case I_CHGRP:
                   1615:                path1 = make_absolute(path1, *pwd);
                   1616:                remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1.46      djm      1617:                for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1.44      djm      1618:                        if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
1.104     djm      1619:                                if (err_abort) {
                   1620:                                        err = -1;
1.44      djm      1621:                                        break;
1.104     djm      1622:                                } else
1.44      djm      1623:                                        continue;
                   1624:                        }
                   1625:                        if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
                   1626:                                error("Can't get current ownership of "
                   1627:                                    "remote file \"%s\"", g.gl_pathv[i]);
1.104     djm      1628:                                if (err_abort) {
                   1629:                                        err = -1;
1.44      djm      1630:                                        break;
1.104     djm      1631:                                } else
1.44      djm      1632:                                        continue;
                   1633:                        }
                   1634:                        aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
                   1635:                        if (cmdnum == I_CHOWN) {
1.143     djm      1636:                                if (!quiet)
1.174     schwarze 1637:                                        mprintf("Changing owner on %s\n",
1.143     djm      1638:                                            g.gl_pathv[i]);
1.44      djm      1639:                                aa->uid = n_arg;
                   1640:                        } else {
1.143     djm      1641:                                if (!quiet)
1.174     schwarze 1642:                                        mprintf("Changing group on %s\n",
1.143     djm      1643:                                            g.gl_pathv[i]);
1.44      djm      1644:                                aa->gid = n_arg;
                   1645:                        }
                   1646:                        err = do_setstat(conn, g.gl_pathv[i], aa);
                   1647:                        if (err != 0 && err_abort)
                   1648:                                break;
                   1649:                }
                   1650:                break;
                   1651:        case I_PWD:
1.174     schwarze 1652:                mprintf("Remote working directory: %s\n", *pwd);
1.44      djm      1653:                break;
                   1654:        case I_LPWD:
                   1655:                if (!getcwd(path_buf, sizeof(path_buf))) {
                   1656:                        error("Couldn't get local cwd: %s", strerror(errno));
                   1657:                        err = -1;
                   1658:                        break;
                   1659:                }
1.174     schwarze 1660:                mprintf("Local working directory: %s\n", path_buf);
1.44      djm      1661:                break;
                   1662:        case I_QUIT:
                   1663:                /* Processed below */
                   1664:                break;
                   1665:        case I_HELP:
                   1666:                help();
                   1667:                break;
                   1668:        case I_VERSION:
                   1669:                printf("SFTP protocol version %u\n", sftp_proto_version(conn));
                   1670:                break;
                   1671:        case I_PROGRESS:
                   1672:                showprogress = !showprogress;
                   1673:                if (showprogress)
                   1674:                        printf("Progress meter enabled\n");
                   1675:                else
                   1676:                        printf("Progress meter disabled\n");
                   1677:                break;
                   1678:        default:
                   1679:                fatal("%d is not implemented", cmdnum);
                   1680:        }
                   1681:
                   1682:        if (g.gl_pathc)
                   1683:                globfree(&g);
1.145     djm      1684:        free(path1);
                   1685:        free(path2);
1.44      djm      1686:
                   1687:        /* If an unignored error occurs in batch mode we should abort. */
                   1688:        if (err_abort && err != 0)
                   1689:                return (-1);
                   1690:        else if (cmdnum == I_QUIT)
                   1691:                return (1);
                   1692:
                   1693:        return (0);
                   1694: }
                   1695:
1.57      djm      1696: static char *
                   1697: prompt(EditLine *el)
                   1698: {
                   1699:        return ("sftp> ");
                   1700: }
                   1701:
1.116     djm      1702: /* Display entries in 'list' after skipping the first 'len' chars */
                   1703: static void
                   1704: complete_display(char **list, u_int len)
                   1705: {
                   1706:        u_int y, m = 0, width = 80, columns = 1, colspace = 0, llen;
                   1707:        struct winsize ws;
                   1708:        char *tmp;
                   1709:
                   1710:        /* Count entries for sort and find longest */
1.149     djm      1711:        for (y = 0; list[y]; y++)
1.176     deraadt  1712:                m = MAXIMUM(m, strlen(list[y]));
1.116     djm      1713:
                   1714:        if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
                   1715:                width = ws.ws_col;
                   1716:
                   1717:        m = m > len ? m - len : 0;
                   1718:        columns = width / (m + 2);
1.176     deraadt  1719:        columns = MAXIMUM(columns, 1);
1.116     djm      1720:        colspace = width / columns;
1.176     deraadt  1721:        colspace = MINIMUM(colspace, width);
1.116     djm      1722:
                   1723:        printf("\n");
                   1724:        m = 1;
                   1725:        for (y = 0; list[y]; y++) {
                   1726:                llen = strlen(list[y]);
                   1727:                tmp = llen > len ? list[y] + len : "";
1.174     schwarze 1728:                mprintf("%-*s", colspace, tmp);
1.116     djm      1729:                if (m >= columns) {
                   1730:                        printf("\n");
                   1731:                        m = 1;
                   1732:                } else
                   1733:                        m++;
                   1734:        }
                   1735:        printf("\n");
                   1736: }
                   1737:
                   1738: /*
                   1739:  * Given a "list" of words that begin with a common prefix of "word",
                   1740:  * attempt to find an autocompletion to extends "word" by the next
                   1741:  * characters common to all entries in "list".
                   1742:  */
                   1743: static char *
                   1744: complete_ambiguous(const char *word, char **list, size_t count)
                   1745: {
                   1746:        if (word == NULL)
                   1747:                return NULL;
                   1748:
                   1749:        if (count > 0) {
                   1750:                u_int y, matchlen = strlen(list[0]);
                   1751:
                   1752:                /* Find length of common stem */
                   1753:                for (y = 1; list[y]; y++) {
                   1754:                        u_int x;
                   1755:
1.149     djm      1756:                        for (x = 0; x < matchlen; x++)
                   1757:                                if (list[0][x] != list[y][x])
1.116     djm      1758:                                        break;
                   1759:
                   1760:                        matchlen = x;
                   1761:                }
                   1762:
                   1763:                if (matchlen > strlen(word)) {
                   1764:                        char *tmp = xstrdup(list[0]);
                   1765:
1.117     dtucker  1766:                        tmp[matchlen] = '\0';
1.116     djm      1767:                        return tmp;
                   1768:                }
1.149     djm      1769:        }
1.116     djm      1770:
                   1771:        return xstrdup(word);
                   1772: }
                   1773:
                   1774: /* Autocomplete a sftp command */
                   1775: static int
                   1776: complete_cmd_parse(EditLine *el, char *cmd, int lastarg, char quote,
                   1777:     int terminated)
                   1778: {
                   1779:        u_int y, count = 0, cmdlen, tmplen;
                   1780:        char *tmp, **list, argterm[3];
                   1781:        const LineInfo *lf;
                   1782:
                   1783:        list = xcalloc((sizeof(cmds) / sizeof(*cmds)) + 1, sizeof(char *));
                   1784:
                   1785:        /* No command specified: display all available commands */
                   1786:        if (cmd == NULL) {
                   1787:                for (y = 0; cmds[y].c; y++)
                   1788:                        list[count++] = xstrdup(cmds[y].c);
1.149     djm      1789:
1.116     djm      1790:                list[count] = NULL;
                   1791:                complete_display(list, 0);
                   1792:
1.149     djm      1793:                for (y = 0; list[y] != NULL; y++)
                   1794:                        free(list[y]);
1.145     djm      1795:                free(list);
1.116     djm      1796:                return count;
                   1797:        }
                   1798:
                   1799:        /* Prepare subset of commands that start with "cmd" */
                   1800:        cmdlen = strlen(cmd);
                   1801:        for (y = 0; cmds[y].c; y++)  {
1.149     djm      1802:                if (!strncasecmp(cmd, cmds[y].c, cmdlen))
1.116     djm      1803:                        list[count++] = xstrdup(cmds[y].c);
                   1804:        }
                   1805:        list[count] = NULL;
                   1806:
1.134     oga      1807:        if (count == 0) {
1.145     djm      1808:                free(list);
1.116     djm      1809:                return 0;
1.134     oga      1810:        }
1.116     djm      1811:
                   1812:        /* Complete ambigious command */
                   1813:        tmp = complete_ambiguous(cmd, list, count);
                   1814:        if (count > 1)
                   1815:                complete_display(list, 0);
                   1816:
1.149     djm      1817:        for (y = 0; list[y]; y++)
                   1818:                free(list[y]);
1.145     djm      1819:        free(list);
1.116     djm      1820:
                   1821:        if (tmp != NULL) {
                   1822:                tmplen = strlen(tmp);
                   1823:                cmdlen = strlen(cmd);
                   1824:                /* If cmd may be extended then do so */
                   1825:                if (tmplen > cmdlen)
                   1826:                        if (el_insertstr(el, tmp + cmdlen) == -1)
                   1827:                                fatal("el_insertstr failed.");
                   1828:                lf = el_line(el);
                   1829:                /* Terminate argument cleanly */
                   1830:                if (count == 1) {
                   1831:                        y = 0;
                   1832:                        if (!terminated)
                   1833:                                argterm[y++] = quote;
                   1834:                        if (lastarg || *(lf->cursor) != ' ')
                   1835:                                argterm[y++] = ' ';
                   1836:                        argterm[y] = '\0';
                   1837:                        if (y > 0 && el_insertstr(el, argterm) == -1)
                   1838:                                fatal("el_insertstr failed.");
                   1839:                }
1.145     djm      1840:                free(tmp);
1.116     djm      1841:        }
                   1842:
                   1843:        return count;
                   1844: }
                   1845:
                   1846: /*
                   1847:  * Determine whether a particular sftp command's arguments (if any)
                   1848:  * represent local or remote files.
                   1849:  */
                   1850: static int
                   1851: complete_is_remote(char *cmd) {
                   1852:        int i;
                   1853:
                   1854:        if (cmd == NULL)
                   1855:                return -1;
                   1856:
                   1857:        for (i = 0; cmds[i].c; i++) {
1.149     djm      1858:                if (!strncasecmp(cmd, cmds[i].c, strlen(cmds[i].c)))
1.116     djm      1859:                        return cmds[i].t;
                   1860:        }
                   1861:
                   1862:        return -1;
                   1863: }
                   1864:
                   1865: /* Autocomplete a filename "file" */
                   1866: static int
                   1867: complete_match(EditLine *el, struct sftp_conn *conn, char *remote_path,
                   1868:     char *file, int remote, int lastarg, char quote, int terminated)
                   1869: {
                   1870:        glob_t g;
1.146     dtucker  1871:        char *tmp, *tmp2, ins[8];
1.140     dtucker  1872:        u_int i, hadglob, pwdlen, len, tmplen, filelen, cesc, isesc, isabs;
1.146     dtucker  1873:        int clen;
1.116     djm      1874:        const LineInfo *lf;
1.149     djm      1875:
1.116     djm      1876:        /* Glob from "file" location */
                   1877:        if (file == NULL)
                   1878:                tmp = xstrdup("*");
                   1879:        else
                   1880:                xasprintf(&tmp, "%s*", file);
                   1881:
1.139     dtucker  1882:        /* Check if the path is absolute. */
                   1883:        isabs = tmp[0] == '/';
                   1884:
1.116     djm      1885:        memset(&g, 0, sizeof(g));
                   1886:        if (remote != LOCAL) {
                   1887:                tmp = make_absolute(tmp, remote_path);
                   1888:                remote_glob(conn, tmp, GLOB_DOOFFS|GLOB_MARK, NULL, &g);
1.149     djm      1889:        } else
1.116     djm      1890:                glob(tmp, GLOB_DOOFFS|GLOB_MARK, NULL, &g);
1.149     djm      1891:
1.116     djm      1892:        /* Determine length of pwd so we can trim completion display */
                   1893:        for (hadglob = tmplen = pwdlen = 0; tmp[tmplen] != 0; tmplen++) {
                   1894:                /* Terminate counting on first unescaped glob metacharacter */
                   1895:                if (tmp[tmplen] == '*' || tmp[tmplen] == '?') {
                   1896:                        if (tmp[tmplen] != '*' || tmp[tmplen + 1] != '\0')
                   1897:                                hadglob = 1;
                   1898:                        break;
                   1899:                }
                   1900:                if (tmp[tmplen] == '\\' && tmp[tmplen + 1] != '\0')
                   1901:                        tmplen++;
                   1902:                if (tmp[tmplen] == '/')
                   1903:                        pwdlen = tmplen + 1;    /* track last seen '/' */
                   1904:        }
1.145     djm      1905:        free(tmp);
1.161     dtucker  1906:        tmp = NULL;
1.116     djm      1907:
1.149     djm      1908:        if (g.gl_matchc == 0)
1.116     djm      1909:                goto out;
                   1910:
                   1911:        if (g.gl_matchc > 1)
                   1912:                complete_display(g.gl_pathv, pwdlen);
                   1913:
                   1914:        /* Don't try to extend globs */
                   1915:        if (file == NULL || hadglob)
                   1916:                goto out;
                   1917:
                   1918:        tmp2 = complete_ambiguous(file, g.gl_pathv, g.gl_matchc);
1.139     dtucker  1919:        tmp = path_strip(tmp2, isabs ? NULL : remote_path);
1.145     djm      1920:        free(tmp2);
1.116     djm      1921:
                   1922:        if (tmp == NULL)
                   1923:                goto out;
                   1924:
                   1925:        tmplen = strlen(tmp);
                   1926:        filelen = strlen(file);
                   1927:
1.140     dtucker  1928:        /* Count the number of escaped characters in the input string. */
                   1929:        cesc = isesc = 0;
                   1930:        for (i = 0; i < filelen; i++) {
                   1931:                if (!isesc && file[i] == '\\' && i + 1 < filelen){
                   1932:                        isesc = 1;
                   1933:                        cesc++;
                   1934:                } else
                   1935:                        isesc = 0;
                   1936:        }
                   1937:
                   1938:        if (tmplen > (filelen - cesc)) {
                   1939:                tmp2 = tmp + filelen - cesc;
1.149     djm      1940:                len = strlen(tmp2);
1.116     djm      1941:                /* quote argument on way out */
1.146     dtucker  1942:                for (i = 0; i < len; i += clen) {
                   1943:                        if ((clen = mblen(tmp2 + i, len - i)) < 0 ||
                   1944:                            (size_t)clen > sizeof(ins) - 2)
                   1945:                                fatal("invalid multibyte character");
1.116     djm      1946:                        ins[0] = '\\';
1.146     dtucker  1947:                        memcpy(ins + 1, tmp2 + i, clen);
                   1948:                        ins[clen + 1] = '\0';
1.116     djm      1949:                        switch (tmp2[i]) {
                   1950:                        case '\'':
                   1951:                        case '"':
                   1952:                        case '\\':
                   1953:                        case '\t':
1.131     sthen    1954:                        case '[':
1.116     djm      1955:                        case ' ':
1.140     dtucker  1956:                        case '#':
                   1957:                        case '*':
1.116     djm      1958:                                if (quote == '\0' || tmp2[i] == quote) {
                   1959:                                        if (el_insertstr(el, ins) == -1)
                   1960:                                                fatal("el_insertstr "
                   1961:                                                    "failed.");
                   1962:                                        break;
                   1963:                                }
                   1964:                                /* FALLTHROUGH */
                   1965:                        default:
                   1966:                                if (el_insertstr(el, ins + 1) == -1)
                   1967:                                        fatal("el_insertstr failed.");
                   1968:                                break;
                   1969:                        }
                   1970:                }
                   1971:        }
                   1972:
                   1973:        lf = el_line(el);
                   1974:        if (g.gl_matchc == 1) {
                   1975:                i = 0;
1.162     dtucker  1976:                if (!terminated && quote != '\0')
1.116     djm      1977:                        ins[i++] = quote;
1.120     djm      1978:                if (*(lf->cursor - 1) != '/' &&
                   1979:                    (lastarg || *(lf->cursor) != ' '))
1.116     djm      1980:                        ins[i++] = ' ';
                   1981:                ins[i] = '\0';
                   1982:                if (i > 0 && el_insertstr(el, ins) == -1)
                   1983:                        fatal("el_insertstr failed.");
                   1984:        }
1.145     djm      1985:        free(tmp);
1.116     djm      1986:
                   1987:  out:
                   1988:        globfree(&g);
                   1989:        return g.gl_matchc;
                   1990: }
                   1991:
                   1992: /* tab-completion hook function, called via libedit */
                   1993: static unsigned char
                   1994: complete(EditLine *el, int ch)
                   1995: {
1.149     djm      1996:        char **argv, *line, quote;
1.147     djm      1997:        int argc, carg;
                   1998:        u_int cursor, len, terminated, ret = CC_ERROR;
1.116     djm      1999:        const LineInfo *lf;
                   2000:        struct complete_ctx *complete_ctx;
                   2001:
                   2002:        lf = el_line(el);
                   2003:        if (el_get(el, EL_CLIENTDATA, (void**)&complete_ctx) != 0)
                   2004:                fatal("%s: el_get failed", __func__);
                   2005:
                   2006:        /* Figure out which argument the cursor points to */
                   2007:        cursor = lf->cursor - lf->buffer;
1.171     deraadt  2008:        line = xmalloc(cursor + 1);
1.116     djm      2009:        memcpy(line, lf->buffer, cursor);
                   2010:        line[cursor] = '\0';
                   2011:        argv = makeargv(line, &carg, 1, &quote, &terminated);
1.145     djm      2012:        free(line);
1.116     djm      2013:
                   2014:        /* Get all the arguments on the line */
                   2015:        len = lf->lastchar - lf->buffer;
1.171     deraadt  2016:        line = xmalloc(len + 1);
1.116     djm      2017:        memcpy(line, lf->buffer, len);
                   2018:        line[len] = '\0';
                   2019:        argv = makeargv(line, &argc, 1, NULL, NULL);
                   2020:
                   2021:        /* Ensure cursor is at EOL or a argument boundary */
                   2022:        if (line[cursor] != ' ' && line[cursor] != '\0' &&
                   2023:            line[cursor] != '\n') {
1.145     djm      2024:                free(line);
1.116     djm      2025:                return ret;
                   2026:        }
                   2027:
                   2028:        if (carg == 0) {
                   2029:                /* Show all available commands */
                   2030:                complete_cmd_parse(el, NULL, argc == carg, '\0', 1);
                   2031:                ret = CC_REDISPLAY;
                   2032:        } else if (carg == 1 && cursor > 0 && line[cursor - 1] != ' ')  {
                   2033:                /* Handle the command parsing */
                   2034:                if (complete_cmd_parse(el, argv[0], argc == carg,
1.149     djm      2035:                    quote, terminated) != 0)
1.116     djm      2036:                        ret = CC_REDISPLAY;
                   2037:        } else if (carg >= 1) {
                   2038:                /* Handle file parsing */
                   2039:                int remote = complete_is_remote(argv[0]);
                   2040:                char *filematch = NULL;
                   2041:
                   2042:                if (carg > 1 && line[cursor-1] != ' ')
                   2043:                        filematch = argv[carg - 1];
                   2044:
                   2045:                if (remote != 0 &&
                   2046:                    complete_match(el, complete_ctx->conn,
                   2047:                    *complete_ctx->remote_pathp, filematch,
1.149     djm      2048:                    remote, carg == argc, quote, terminated) != 0)
1.116     djm      2049:                        ret = CC_REDISPLAY;
                   2050:        }
                   2051:
1.149     djm      2052:        free(line);
1.116     djm      2053:        return ret;
                   2054: }
                   2055:
1.44      djm      2056: int
1.112     djm      2057: interactive_loop(struct sftp_conn *conn, char *file1, char *file2)
1.44      djm      2058: {
1.116     djm      2059:        char *remote_path;
1.44      djm      2060:        char *dir = NULL;
                   2061:        char cmd[2048];
1.66      jaredy   2062:        int err, interactive;
1.57      djm      2063:        EditLine *el = NULL;
                   2064:        History *hl = NULL;
                   2065:        HistEvent hev;
                   2066:        extern char *__progname;
1.116     djm      2067:        struct complete_ctx complete_ctx;
1.57      djm      2068:
                   2069:        if (!batchmode && isatty(STDIN_FILENO)) {
                   2070:                if ((el = el_init(__progname, stdin, stdout, stderr)) == NULL)
                   2071:                        fatal("Couldn't initialise editline");
                   2072:                if ((hl = history_init()) == NULL)
                   2073:                        fatal("Couldn't initialise editline history");
                   2074:                history(hl, &hev, H_SETSIZE, 100);
                   2075:                el_set(el, EL_HIST, history, hl);
                   2076:
                   2077:                el_set(el, EL_PROMPT, prompt);
                   2078:                el_set(el, EL_EDITOR, "emacs");
                   2079:                el_set(el, EL_TERMINAL, NULL);
                   2080:                el_set(el, EL_SIGNAL, 1);
                   2081:                el_source(el, NULL);
1.116     djm      2082:
                   2083:                /* Tab Completion */
1.149     djm      2084:                el_set(el, EL_ADDFN, "ftp-complete",
1.131     sthen    2085:                    "Context sensitive argument completion", complete);
1.116     djm      2086:                complete_ctx.conn = conn;
                   2087:                complete_ctx.remote_pathp = &remote_path;
                   2088:                el_set(el, EL_CLIENTDATA, (void*)&complete_ctx);
                   2089:                el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
1.154     djm      2090:                /* enable ctrl-left-arrow and ctrl-right-arrow */
                   2091:                el_set(el, EL_BIND, "\\e[1;5C", "em-next-word", NULL);
                   2092:                el_set(el, EL_BIND, "\\e[5C", "em-next-word", NULL);
                   2093:                el_set(el, EL_BIND, "\\e[1;5D", "ed-prev-word", NULL);
                   2094:                el_set(el, EL_BIND, "\\e\\e[D", "ed-prev-word", NULL);
1.155     djm      2095:                /* make ^w match ksh behaviour */
                   2096:                el_set(el, EL_BIND, "^w", "ed-delete-prev-word", NULL);
1.57      djm      2097:        }
1.44      djm      2098:
1.116     djm      2099:        remote_path = do_realpath(conn, ".");
                   2100:        if (remote_path == NULL)
1.44      djm      2101:                fatal("Need cwd");
                   2102:
                   2103:        if (file1 != NULL) {
                   2104:                dir = xstrdup(file1);
1.116     djm      2105:                dir = make_absolute(dir, remote_path);
1.44      djm      2106:
                   2107:                if (remote_is_dir(conn, dir) && file2 == NULL) {
1.143     djm      2108:                        if (!quiet)
1.174     schwarze 2109:                                mprintf("Changing to: %s\n", dir);
1.44      djm      2110:                        snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
1.116     djm      2111:                        if (parse_dispatch_command(conn, cmd,
                   2112:                            &remote_path, 1) != 0) {
1.145     djm      2113:                                free(dir);
                   2114:                                free(remote_path);
                   2115:                                free(conn);
1.44      djm      2116:                                return (-1);
1.58      markus   2117:                        }
1.44      djm      2118:                } else {
1.137     djm      2119:                        /* XXX this is wrong wrt quoting */
1.148     djm      2120:                        snprintf(cmd, sizeof cmd, "get%s %s%s%s",
                   2121:                            global_aflag ? " -a" : "", dir,
                   2122:                            file2 == NULL ? "" : " ",
                   2123:                            file2 == NULL ? "" : file2);
1.116     djm      2124:                        err = parse_dispatch_command(conn, cmd,
                   2125:                            &remote_path, 1);
1.145     djm      2126:                        free(dir);
                   2127:                        free(remote_path);
                   2128:                        free(conn);
1.44      djm      2129:                        return (err);
                   2130:                }
1.145     djm      2131:                free(dir);
1.44      djm      2132:        }
                   2133:
1.168     millert  2134:        setvbuf(stdout, NULL, _IOLBF, 0);
                   2135:        setvbuf(infile, NULL, _IOLBF, 0);
1.44      djm      2136:
1.66      jaredy   2137:        interactive = !batchmode && isatty(STDIN_FILENO);
1.44      djm      2138:        err = 0;
                   2139:        for (;;) {
                   2140:                char *cp;
1.57      djm      2141:                const char *line;
                   2142:                int count = 0;
1.44      djm      2143:
1.46      djm      2144:                signal(SIGINT, SIG_IGN);
                   2145:
1.57      djm      2146:                if (el == NULL) {
1.66      jaredy   2147:                        if (interactive)
                   2148:                                printf("sftp> ");
1.57      djm      2149:                        if (fgets(cmd, sizeof(cmd), infile) == NULL) {
1.66      jaredy   2150:                                if (interactive)
                   2151:                                        printf("\n");
1.57      djm      2152:                                break;
                   2153:                        }
1.66      jaredy   2154:                        if (!interactive) { /* Echo command */
1.174     schwarze 2155:                                mprintf("sftp> %s", cmd);
1.66      jaredy   2156:                                if (strlen(cmd) > 0 &&
                   2157:                                    cmd[strlen(cmd) - 1] != '\n')
                   2158:                                        printf("\n");
                   2159:                        }
1.57      djm      2160:                } else {
1.116     djm      2161:                        if ((line = el_gets(el, &count)) == NULL ||
                   2162:                            count <= 0) {
1.66      jaredy   2163:                                printf("\n");
1.57      djm      2164:                                break;
1.66      jaredy   2165:                        }
1.57      djm      2166:                        history(hl, &hev, H_ENTER, line);
                   2167:                        if (strlcpy(cmd, line, sizeof(cmd)) >= sizeof(cmd)) {
                   2168:                                fprintf(stderr, "Error: input line too long\n");
                   2169:                                continue;
                   2170:                        }
1.44      djm      2171:                }
                   2172:
                   2173:                cp = strrchr(cmd, '\n');
                   2174:                if (cp)
                   2175:                        *cp = '\0';
                   2176:
1.46      djm      2177:                /* Handle user interrupts gracefully during commands */
                   2178:                interrupted = 0;
                   2179:                signal(SIGINT, cmd_interrupt);
                   2180:
1.116     djm      2181:                err = parse_dispatch_command(conn, cmd, &remote_path,
                   2182:                    batchmode);
1.44      djm      2183:                if (err != 0)
                   2184:                        break;
                   2185:        }
1.145     djm      2186:        free(remote_path);
                   2187:        free(conn);
1.66      jaredy   2188:
                   2189:        if (el != NULL)
                   2190:                el_end(el);
1.44      djm      2191:
                   2192:        /* err == 1 signifies normal "quit" exit */
                   2193:        return (err >= 0 ? 0 : -1);
                   2194: }
1.34      fgsch    2195:
1.18      itojun   2196: static void
1.36      djm      2197: connect_to_server(char *path, char **args, int *in, int *out)
1.1       djm      2198: {
                   2199:        int c_in, c_out;
1.30      deraadt  2200:
1.1       djm      2201:        int inout[2];
1.30      deraadt  2202:
1.1       djm      2203:        if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1)
                   2204:                fatal("socketpair: %s", strerror(errno));
                   2205:        *in = *out = inout[0];
                   2206:        c_in = c_out = inout[1];
                   2207:
1.36      djm      2208:        if ((sshpid = fork()) == -1)
1.1       djm      2209:                fatal("fork: %s", strerror(errno));
1.36      djm      2210:        else if (sshpid == 0) {
1.1       djm      2211:                if ((dup2(c_in, STDIN_FILENO) == -1) ||
                   2212:                    (dup2(c_out, STDOUT_FILENO) == -1)) {
                   2213:                        fprintf(stderr, "dup2: %s\n", strerror(errno));
1.47      djm      2214:                        _exit(1);
1.1       djm      2215:                }
                   2216:                close(*in);
                   2217:                close(*out);
                   2218:                close(c_in);
                   2219:                close(c_out);
1.46      djm      2220:
                   2221:                /*
                   2222:                 * The underlying ssh is in the same process group, so we must
1.56      deraadt  2223:                 * ignore SIGINT if we want to gracefully abort commands,
                   2224:                 * otherwise the signal will make it to the ssh process and
1.122     guenther 2225:                 * kill it too.  Contrawise, since sftp sends SIGTERMs to the
                   2226:                 * underlying ssh, it must *not* ignore that signal.
1.46      djm      2227:                 */
                   2228:                signal(SIGINT, SIG_IGN);
1.122     guenther 2229:                signal(SIGTERM, SIG_DFL);
1.49      dtucker  2230:                execvp(path, args);
1.23      djm      2231:                fprintf(stderr, "exec: %s: %s\n", path, strerror(errno));
1.47      djm      2232:                _exit(1);
1.1       djm      2233:        }
                   2234:
1.36      djm      2235:        signal(SIGTERM, killchild);
                   2236:        signal(SIGINT, killchild);
                   2237:        signal(SIGHUP, killchild);
1.177     millert  2238:        signal(SIGTSTP, suspchild);
                   2239:        signal(SIGTTIN, suspchild);
                   2240:        signal(SIGTTOU, suspchild);
1.1       djm      2241:        close(c_in);
                   2242:        close(c_out);
                   2243: }
                   2244:
1.18      itojun   2245: static void
1.1       djm      2246: usage(void)
                   2247: {
1.25      mpech    2248:        extern char *__progname;
1.27      markus   2249:
1.19      stevesk  2250:        fprintf(stderr,
1.179     djm      2251:            "usage: %s [-46aCfpqrv] [-B buffer_size] [-b batchfile] [-c cipher]\n"
1.110     jmc      2252:            "          [-D sftp_server_path] [-F ssh_config] "
1.127     jmc      2253:            "[-i identity_file] [-l limit]\n"
1.110     jmc      2254:            "          [-o ssh_option] [-P port] [-R num_requests] "
                   2255:            "[-S program]\n"
1.181   ! millert  2256:            "          [-s subsystem | sftp_server] destination\n",
        !          2257:            __progname);
1.1       djm      2258:        exit(1);
                   2259: }
                   2260:
1.2       stevesk  2261: int
1.1       djm      2262: main(int argc, char **argv)
                   2263: {
1.181   ! millert  2264:        int in, out, ch, err, tmp, port = -1;
        !          2265:        char *host = NULL, *user, *cp, *file2 = NULL;
1.17      mouring  2266:        int debug_level = 0, sshver = 2;
                   2267:        char *file1 = NULL, *sftp_server = NULL;
1.23      djm      2268:        char *ssh_program = _PATH_SSH_PROGRAM, *sftp_direct = NULL;
1.126     djm      2269:        const char *errstr;
1.17      mouring  2270:        LogLevel ll = SYSLOG_LEVEL_INFO;
                   2271:        arglist args;
1.3       djm      2272:        extern int optind;
                   2273:        extern char *optarg;
1.112     djm      2274:        struct sftp_conn *conn;
                   2275:        size_t copy_buffer_len = DEFAULT_COPY_BUFLEN;
                   2276:        size_t num_requests = DEFAULT_NUM_REQUESTS;
1.126     djm      2277:        long long limit_kbps = 0;
1.67      djm      2278:
1.172     dtucker  2279:        ssh_malloc_init();      /* must be called before any mallocs */
1.67      djm      2280:        /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
                   2281:        sanitise_stdfd();
1.146     dtucker  2282:        setlocale(LC_CTYPE, "");
1.1       djm      2283:
1.70      djm      2284:        memset(&args, '\0', sizeof(args));
1.17      mouring  2285:        args.list = NULL;
1.80      djm      2286:        addargs(&args, "%s", ssh_program);
1.17      mouring  2287:        addargs(&args, "-oForwardX11 no");
                   2288:        addargs(&args, "-oForwardAgent no");
1.69      reyk     2289:        addargs(&args, "-oPermitLocalCommand no");
1.21      stevesk  2290:        addargs(&args, "-oClearAllForwardings yes");
1.40      djm      2291:
1.17      mouring  2292:        ll = SYSLOG_LEVEL_INFO;
1.40      djm      2293:        infile = stdin;
1.3       djm      2294:
1.109     djm      2295:        while ((ch = getopt(argc, argv,
1.156     djm      2296:            "1246afhpqrvCc:D:i:l:o:s:S:b:B:F:P:R:")) != -1) {
1.3       djm      2297:                switch (ch) {
1.108     djm      2298:                /* Passed through to ssh(1) */
                   2299:                case '4':
                   2300:                case '6':
1.3       djm      2301:                case 'C':
1.108     djm      2302:                        addargs(&args, "-%c", ch);
                   2303:                        break;
                   2304:                /* Passed through to ssh(1) with argument */
                   2305:                case 'F':
                   2306:                case 'c':
                   2307:                case 'i':
                   2308:                case 'o':
1.113     halex    2309:                        addargs(&args, "-%c", ch);
                   2310:                        addargs(&args, "%s", optarg);
1.108     djm      2311:                        break;
                   2312:                case 'q':
1.143     djm      2313:                        ll = SYSLOG_LEVEL_ERROR;
                   2314:                        quiet = 1;
1.108     djm      2315:                        showprogress = 0;
                   2316:                        addargs(&args, "-%c", ch);
1.3       djm      2317:                        break;
1.109     djm      2318:                case 'P':
1.181   ! millert  2319:                        port = a2port(optarg);
        !          2320:                        if (port <= 0)
        !          2321:                                fatal("Bad port \"%s\"\n", optarg);
1.109     djm      2322:                        break;
1.3       djm      2323:                case 'v':
1.17      mouring  2324:                        if (debug_level < 3) {
                   2325:                                addargs(&args, "-v");
                   2326:                                ll = SYSLOG_LEVEL_DEBUG1 + debug_level;
                   2327:                        }
                   2328:                        debug_level++;
1.3       djm      2329:                        break;
1.7       markus   2330:                case '1':
1.17      mouring  2331:                        sshver = 1;
1.7       markus   2332:                        if (sftp_server == NULL)
                   2333:                                sftp_server = _PATH_SFTP_SERVER;
                   2334:                        break;
1.108     djm      2335:                case '2':
                   2336:                        sshver = 2;
1.148     djm      2337:                        break;
                   2338:                case 'a':
                   2339:                        global_aflag = 1;
1.7       markus   2340:                        break;
1.108     djm      2341:                case 'B':
                   2342:                        copy_buffer_len = strtol(optarg, &cp, 10);
                   2343:                        if (copy_buffer_len == 0 || *cp != '\0')
                   2344:                                fatal("Invalid buffer size \"%s\"", optarg);
1.3       djm      2345:                        break;
1.10      deraadt  2346:                case 'b':
1.39      djm      2347:                        if (batchmode)
                   2348:                                fatal("Batch file already specified.");
                   2349:
                   2350:                        /* Allow "-" as stdin */
1.56      deraadt  2351:                        if (strcmp(optarg, "-") != 0 &&
1.65      djm      2352:                            (infile = fopen(optarg, "r")) == NULL)
1.39      djm      2353:                                fatal("%s (%s).", strerror(errno), optarg);
1.34      fgsch    2354:                        showprogress = 0;
1.143     djm      2355:                        quiet = batchmode = 1;
1.62      djm      2356:                        addargs(&args, "-obatchmode yes");
1.156     djm      2357:                        break;
                   2358:                case 'f':
                   2359:                        global_fflag = 1;
1.10      deraadt  2360:                        break;
1.111     djm      2361:                case 'p':
                   2362:                        global_pflag = 1;
                   2363:                        break;
1.109     djm      2364:                case 'D':
1.23      djm      2365:                        sftp_direct = optarg;
1.111     djm      2366:                        break;
1.126     djm      2367:                case 'l':
                   2368:                        limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,
                   2369:                            &errstr);
                   2370:                        if (errstr != NULL)
                   2371:                                usage();
                   2372:                        limit_kbps *= 1024; /* kbps */
                   2373:                        break;
1.111     djm      2374:                case 'r':
                   2375:                        global_rflag = 1;
1.24      djm      2376:                        break;
1.26      djm      2377:                case 'R':
                   2378:                        num_requests = strtol(optarg, &cp, 10);
                   2379:                        if (num_requests == 0 || *cp != '\0')
1.27      markus   2380:                                fatal("Invalid number of requests \"%s\"",
1.26      djm      2381:                                    optarg);
1.108     djm      2382:                        break;
                   2383:                case 's':
                   2384:                        sftp_server = optarg;
                   2385:                        break;
                   2386:                case 'S':
                   2387:                        ssh_program = optarg;
                   2388:                        replacearg(&args, 0, "%s", ssh_program);
1.23      djm      2389:                        break;
1.3       djm      2390:                case 'h':
                   2391:                default:
1.1       djm      2392:                        usage();
                   2393:                }
                   2394:        }
1.45      djm      2395:
                   2396:        if (!isatty(STDERR_FILENO))
                   2397:                showprogress = 0;
1.1       djm      2398:
1.29      markus   2399:        log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);
                   2400:
1.23      djm      2401:        if (sftp_direct == NULL) {
                   2402:                if (optind == argc || argc > (optind + 2))
                   2403:                        usage();
1.181   ! millert  2404:                argv += optind;
1.23      djm      2405:
1.181   ! millert  2406:                switch (parse_uri("sftp", *argv, &user, &host, &tmp, &file1)) {
        !          2407:                case -1:
        !          2408:                        usage();
        !          2409:                        break;
        !          2410:                case 0:
        !          2411:                        if (tmp != -1)
        !          2412:                                port = tmp;
        !          2413:                        break;
        !          2414:                default:
        !          2415:                        if (parse_user_host_path(*argv, &user, &host,
        !          2416:                            &file1) == -1) {
        !          2417:                                /* Treat as a plain hostname. */
        !          2418:                                host = xstrdup(*argv);
        !          2419:                                host = cleanhostname(host);
1.23      djm      2420:                        }
1.181   ! millert  2421:                        break;
1.23      djm      2422:                }
1.181   ! millert  2423:                file2 = *(argv + 1);
1.3       djm      2424:
1.23      djm      2425:                if (!*host) {
                   2426:                        fprintf(stderr, "Missing hostname\n");
1.1       djm      2427:                        usage();
                   2428:                }
                   2429:
1.181   ! millert  2430:                if (port != -1)
        !          2431:                        addargs(&args, "-oPort %d", port);
        !          2432:                if (user != NULL) {
        !          2433:                        addargs(&args, "-l");
        !          2434:                        addargs(&args, "%s", user);
        !          2435:                }
1.23      djm      2436:                addargs(&args, "-oProtocol %d", sshver);
                   2437:
                   2438:                /* no subsystem if the server-spec contains a '/' */
                   2439:                if (sftp_server == NULL || strchr(sftp_server, '/') == NULL)
                   2440:                        addargs(&args, "-s");
                   2441:
1.115     guenther 2442:                addargs(&args, "--");
1.23      djm      2443:                addargs(&args, "%s", host);
1.27      markus   2444:                addargs(&args, "%s", (sftp_server != NULL ?
1.23      djm      2445:                    sftp_server : "sftp"));
                   2446:
1.36      djm      2447:                connect_to_server(ssh_program, args.list, &in, &out);
1.23      djm      2448:        } else {
                   2449:                args.list = NULL;
                   2450:                addargs(&args, "sftp-server");
                   2451:
1.36      djm      2452:                connect_to_server(sftp_direct, args.list, &in, &out);
1.1       djm      2453:        }
1.70      djm      2454:        freeargs(&args);
1.1       djm      2455:
1.126     djm      2456:        conn = do_init(in, out, copy_buffer_len, num_requests, limit_kbps);
1.112     djm      2457:        if (conn == NULL)
                   2458:                fatal("Couldn't initialise connection to server");
                   2459:
1.143     djm      2460:        if (!quiet) {
1.112     djm      2461:                if (sftp_direct == NULL)
                   2462:                        fprintf(stderr, "Connected to %s.\n", host);
                   2463:                else
                   2464:                        fprintf(stderr, "Attached to %s.\n", sftp_direct);
                   2465:        }
                   2466:
                   2467:        err = interactive_loop(conn, file1, file2);
1.1       djm      2468:
                   2469:        close(in);
                   2470:        close(out);
1.39      djm      2471:        if (batchmode)
1.10      deraadt  2472:                fclose(infile);
1.1       djm      2473:
1.28      markus   2474:        while (waitpid(sshpid, NULL, 0) == -1)
                   2475:                if (errno != EINTR)
                   2476:                        fatal("Couldn't wait for ssh process: %s",
                   2477:                            strerror(errno));
1.1       djm      2478:
1.33      djm      2479:        exit(err == 0 ? 0 : 1);
1.1       djm      2480: }