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

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