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

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