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

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