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

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