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

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