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

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