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

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