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

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