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

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