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

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