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

1.1       djm         1: /*
1.42      djm         2:  * Copyright (c) 2001-2004 Damien Miller <djm@openbsd.org>
1.1       djm         3:  *
1.42      djm         4:  * Permission to use, copy, modify, and distribute this software for any
                      5:  * purpose with or without fee is hereby granted, provided that the above
                      6:  * copyright notice and this permission notice appear in all copies.
1.1       djm         7:  *
1.42      djm         8:  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
                      9:  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
                     10:  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
                     11:  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
                     12:  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
                     13:  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
                     14:  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1.1       djm        15:  */
                     16:
                     17: #include "includes.h"
1.72    ! stevesk    18: RCSID("$OpenBSD: sftp.c,v 1.71 2006/02/08 12:15:27 stevesk Exp $");
1.1       djm        19:
1.72    ! stevesk    20: #include <sys/ioctl.h>
1.44      djm        21:
                     22: #include <glob.h>
1.57      djm        23: #include <histedit.h>
1.71      stevesk    24: #include <paths.h>
1.1       djm        25:
                     26: #include "buffer.h"
                     27: #include "xmalloc.h"
                     28: #include "log.h"
                     29: #include "pathnames.h"
1.16      mouring    30: #include "misc.h"
1.1       djm        31:
                     32: #include "sftp.h"
                     33: #include "sftp-common.h"
                     34: #include "sftp-client.h"
1.43      djm        35:
1.44      djm        36: /* File to read commands from */
                     37: FILE* infile;
1.15      mouring    38:
1.44      djm        39: /* Are we in batchfile mode? */
1.39      djm        40: int batchmode = 0;
1.44      djm        41:
                     42: /* Size of buffer used when copying files */
1.24      djm        43: size_t copy_buffer_len = 32768;
1.44      djm        44:
                     45: /* Number of concurrent outstanding requests */
1.26      djm        46: size_t num_requests = 16;
1.44      djm        47:
                     48: /* PID of ssh transport process */
1.36      djm        49: static pid_t sshpid = -1;
1.7       markus     50:
1.44      djm        51: /* This is set to 0 if the progressmeter is not desired. */
1.45      djm        52: int showprogress = 1;
1.44      djm        53:
1.46      djm        54: /* SIGINT received during command processing */
                     55: volatile sig_atomic_t interrupted = 0;
                     56:
1.52      djm        57: /* I wish qsort() took a separate ctx for the comparison function...*/
                     58: int sort_flag;
                     59:
1.44      djm        60: int remote_glob(struct sftp_conn *, const char *, int,
                     61:     int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
                     62:
                     63: /* Separators for interactive commands */
                     64: #define WHITESPACE " \t\r\n"
                     65:
1.52      djm        66: /* ls flags */
1.53      djm        67: #define LS_LONG_VIEW   0x01    /* Full view ala ls -l */
                     68: #define LS_SHORT_VIEW  0x02    /* Single row view ala ls -1 */
                     69: #define LS_NUMERIC_VIEW        0x04    /* Long view with numeric uid/gid */
                     70: #define LS_NAME_SORT   0x08    /* Sort by name (default) */
                     71: #define LS_TIME_SORT   0x10    /* Sort by mtime */
                     72: #define LS_SIZE_SORT   0x20    /* Sort by file size */
                     73: #define LS_REVERSE_SORT        0x40    /* Reverse sort order */
1.54      djm        74: #define LS_SHOW_ALL    0x80    /* Don't skip filenames starting with '.' */
1.52      djm        75:
1.53      djm        76: #define VIEW_FLAGS     (LS_LONG_VIEW|LS_SHORT_VIEW|LS_NUMERIC_VIEW)
                     77: #define SORT_FLAGS     (LS_NAME_SORT|LS_TIME_SORT|LS_SIZE_SORT)
1.44      djm        78:
                     79: /* Commands for interactive mode */
                     80: #define I_CHDIR                1
                     81: #define I_CHGRP                2
                     82: #define I_CHMOD                3
                     83: #define I_CHOWN                4
                     84: #define I_GET          5
                     85: #define I_HELP         6
                     86: #define I_LCHDIR       7
                     87: #define I_LLS          8
                     88: #define I_LMKDIR       9
                     89: #define I_LPWD         10
                     90: #define I_LS           11
                     91: #define I_LUMASK       12
                     92: #define I_MKDIR                13
                     93: #define I_PUT          14
                     94: #define I_PWD          15
                     95: #define I_QUIT         16
                     96: #define I_RENAME       17
                     97: #define I_RM           18
                     98: #define I_RMDIR                19
                     99: #define I_SHELL                20
                    100: #define I_SYMLINK      21
                    101: #define I_VERSION      22
                    102: #define I_PROGRESS     23
                    103:
                    104: struct CMD {
                    105:        const char *c;
                    106:        const int n;
                    107: };
                    108:
                    109: static const struct CMD cmds[] = {
                    110:        { "bye",        I_QUIT },
                    111:        { "cd",         I_CHDIR },
                    112:        { "chdir",      I_CHDIR },
                    113:        { "chgrp",      I_CHGRP },
                    114:        { "chmod",      I_CHMOD },
                    115:        { "chown",      I_CHOWN },
                    116:        { "dir",        I_LS },
                    117:        { "exit",       I_QUIT },
                    118:        { "get",        I_GET },
                    119:        { "mget",       I_GET },
                    120:        { "help",       I_HELP },
                    121:        { "lcd",        I_LCHDIR },
                    122:        { "lchdir",     I_LCHDIR },
                    123:        { "lls",        I_LLS },
                    124:        { "lmkdir",     I_LMKDIR },
                    125:        { "ln",         I_SYMLINK },
                    126:        { "lpwd",       I_LPWD },
                    127:        { "ls",         I_LS },
                    128:        { "lumask",     I_LUMASK },
                    129:        { "mkdir",      I_MKDIR },
                    130:        { "progress",   I_PROGRESS },
                    131:        { "put",        I_PUT },
                    132:        { "mput",       I_PUT },
                    133:        { "pwd",        I_PWD },
                    134:        { "quit",       I_QUIT },
                    135:        { "rename",     I_RENAME },
                    136:        { "rm",         I_RM },
                    137:        { "rmdir",      I_RMDIR },
                    138:        { "symlink",    I_SYMLINK },
                    139:        { "version",    I_VERSION },
                    140:        { "!",          I_SHELL },
                    141:        { "?",          I_HELP },
                    142:        { NULL,                 -1}
                    143: };
                    144:
                    145: int interactive_loop(int fd_in, int fd_out, char *file1, char *file2);
                    146:
                    147: static void
1.46      djm       148: killchild(int signo)
                    149: {
1.61      dtucker   150:        if (sshpid > 1) {
1.46      djm       151:                kill(sshpid, SIGTERM);
1.61      dtucker   152:                waitpid(sshpid, NULL, 0);
                    153:        }
1.46      djm       154:
                    155:        _exit(1);
                    156: }
                    157:
                    158: static void
                    159: cmd_interrupt(int signo)
                    160: {
                    161:        const char msg[] = "\rInterrupt  \n";
1.59      djm       162:        int olderrno = errno;
1.46      djm       163:
                    164:        write(STDERR_FILENO, msg, sizeof(msg) - 1);
                    165:        interrupted = 1;
1.59      djm       166:        errno = olderrno;
1.46      djm       167: }
                    168:
                    169: static void
1.44      djm       170: help(void)
                    171: {
                    172:        printf("Available commands:\n");
                    173:        printf("cd path                       Change remote directory to 'path'\n");
                    174:        printf("lcd path                      Change local directory to 'path'\n");
                    175:        printf("chgrp grp path                Change group of file 'path' to 'grp'\n");
                    176:        printf("chmod mode path               Change permissions of file 'path' to 'mode'\n");
                    177:        printf("chown own path                Change owner of file 'path' to 'own'\n");
                    178:        printf("help                          Display this help text\n");
                    179:        printf("get remote-path [local-path]  Download file\n");
                    180:        printf("lls [ls-options [path]]       Display local directory listing\n");
                    181:        printf("ln oldpath newpath            Symlink remote file\n");
                    182:        printf("lmkdir path                   Create local directory\n");
                    183:        printf("lpwd                          Print local working directory\n");
                    184:        printf("ls [path]                     Display remote directory listing\n");
                    185:        printf("lumask umask                  Set local umask to 'umask'\n");
                    186:        printf("mkdir path                    Create remote directory\n");
                    187:        printf("progress                      Toggle display of progress meter\n");
                    188:        printf("put local-path [remote-path]  Upload file\n");
                    189:        printf("pwd                           Display remote working directory\n");
                    190:        printf("exit                          Quit sftp\n");
                    191:        printf("quit                          Quit sftp\n");
                    192:        printf("rename oldpath newpath        Rename remote file\n");
                    193:        printf("rmdir path                    Remove remote directory\n");
                    194:        printf("rm path                       Delete remote file\n");
                    195:        printf("symlink oldpath newpath       Symlink remote file\n");
                    196:        printf("version                       Show SFTP version\n");
                    197:        printf("!command                      Execute 'command' in local shell\n");
                    198:        printf("!                             Escape to local shell\n");
                    199:        printf("?                             Synonym for help\n");
                    200: }
                    201:
                    202: static void
                    203: local_do_shell(const char *args)
                    204: {
                    205:        int status;
                    206:        char *shell;
                    207:        pid_t pid;
                    208:
                    209:        if (!*args)
                    210:                args = NULL;
                    211:
                    212:        if ((shell = getenv("SHELL")) == NULL)
                    213:                shell = _PATH_BSHELL;
                    214:
                    215:        if ((pid = fork()) == -1)
                    216:                fatal("Couldn't fork: %s", strerror(errno));
                    217:
                    218:        if (pid == 0) {
                    219:                /* XXX: child has pipe fds to ssh subproc open - issue? */
                    220:                if (args) {
                    221:                        debug3("Executing %s -c \"%s\"", shell, args);
                    222:                        execl(shell, shell, "-c", args, (char *)NULL);
                    223:                } else {
                    224:                        debug3("Executing %s", shell);
                    225:                        execl(shell, shell, (char *)NULL);
                    226:                }
                    227:                fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell,
                    228:                    strerror(errno));
                    229:                _exit(1);
                    230:        }
                    231:        while (waitpid(pid, &status, 0) == -1)
                    232:                if (errno != EINTR)
                    233:                        fatal("Couldn't wait for child: %s", strerror(errno));
                    234:        if (!WIFEXITED(status))
                    235:                error("Shell exited abormally");
                    236:        else if (WEXITSTATUS(status))
                    237:                error("Shell exited with status %d", WEXITSTATUS(status));
                    238: }
                    239:
                    240: static void
                    241: local_do_ls(const char *args)
                    242: {
                    243:        if (!args || !*args)
                    244:                local_do_shell(_PATH_LS);
                    245:        else {
                    246:                int len = strlen(_PATH_LS " ") + strlen(args) + 1;
                    247:                char *buf = xmalloc(len);
                    248:
                    249:                /* XXX: quoting - rip quoting code from ftp? */
                    250:                snprintf(buf, len, _PATH_LS " %s", args);
                    251:                local_do_shell(buf);
                    252:                xfree(buf);
                    253:        }
                    254: }
                    255:
                    256: /* Strip one path (usually the pwd) from the start of another */
                    257: static char *
                    258: path_strip(char *path, char *strip)
                    259: {
                    260:        size_t len;
                    261:
                    262:        if (strip == NULL)
                    263:                return (xstrdup(path));
                    264:
                    265:        len = strlen(strip);
1.59      djm       266:        if (strncmp(path, strip, len) == 0) {
1.44      djm       267:                if (strip[len - 1] != '/' && path[len] == '/')
                    268:                        len++;
                    269:                return (xstrdup(path + len));
                    270:        }
                    271:
                    272:        return (xstrdup(path));
                    273: }
                    274:
                    275: static char *
                    276: path_append(char *p1, char *p2)
                    277: {
                    278:        char *ret;
                    279:        int len = strlen(p1) + strlen(p2) + 2;
                    280:
                    281:        ret = xmalloc(len);
                    282:        strlcpy(ret, p1, len);
                    283:        if (p1[strlen(p1) - 1] != '/')
                    284:                strlcat(ret, "/", len);
                    285:        strlcat(ret, p2, len);
                    286:
                    287:        return(ret);
                    288: }
                    289:
                    290: static char *
                    291: make_absolute(char *p, char *pwd)
                    292: {
1.51      avsm      293:        char *abs_str;
1.44      djm       294:
                    295:        /* Derelativise */
                    296:        if (p && p[0] != '/') {
1.51      avsm      297:                abs_str = path_append(pwd, p);
1.44      djm       298:                xfree(p);
1.51      avsm      299:                return(abs_str);
1.44      djm       300:        } else
                    301:                return(p);
                    302: }
                    303:
                    304: static int
                    305: infer_path(const char *p, char **ifp)
                    306: {
                    307:        char *cp;
                    308:
                    309:        cp = strrchr(p, '/');
                    310:        if (cp == NULL) {
                    311:                *ifp = xstrdup(p);
                    312:                return(0);
                    313:        }
                    314:
                    315:        if (!cp[1]) {
                    316:                error("Invalid path");
                    317:                return(-1);
                    318:        }
                    319:
                    320:        *ifp = xstrdup(cp + 1);
                    321:        return(0);
                    322: }
                    323:
                    324: static int
                    325: parse_getput_flags(const char **cpp, int *pflag)
                    326: {
                    327:        const char *cp = *cpp;
                    328:
                    329:        /* Check for flags */
                    330:        if (cp[0] == '-' && cp[1] && strchr(WHITESPACE, cp[2])) {
                    331:                switch (cp[1]) {
                    332:                case 'p':
                    333:                case 'P':
                    334:                        *pflag = 1;
                    335:                        break;
                    336:                default:
                    337:                        error("Invalid flag -%c", cp[1]);
                    338:                        return(-1);
                    339:                }
                    340:                cp += 2;
                    341:                *cpp = cp + strspn(cp, WHITESPACE);
                    342:        }
                    343:
                    344:        return(0);
                    345: }
                    346:
                    347: static int
                    348: parse_ls_flags(const char **cpp, int *lflag)
                    349: {
                    350:        const char *cp = *cpp;
                    351:
1.52      djm       352:        /* Defaults */
1.53      djm       353:        *lflag = LS_NAME_SORT;
1.52      djm       354:
1.44      djm       355:        /* Check for flags */
                    356:        if (cp++[0] == '-') {
1.63      deraadt   357:                for (; strchr(WHITESPACE, *cp) == NULL; cp++) {
1.44      djm       358:                        switch (*cp) {
                    359:                        case 'l':
1.50      djm       360:                                *lflag &= ~VIEW_FLAGS;
1.53      djm       361:                                *lflag |= LS_LONG_VIEW;
1.44      djm       362:                                break;
                    363:                        case '1':
1.50      djm       364:                                *lflag &= ~VIEW_FLAGS;
1.53      djm       365:                                *lflag |= LS_SHORT_VIEW;
1.50      djm       366:                                break;
                    367:                        case 'n':
                    368:                                *lflag &= ~VIEW_FLAGS;
1.53      djm       369:                                *lflag |= LS_NUMERIC_VIEW|LS_LONG_VIEW;
1.44      djm       370:                                break;
1.52      djm       371:                        case 'S':
                    372:                                *lflag &= ~SORT_FLAGS;
1.53      djm       373:                                *lflag |= LS_SIZE_SORT;
1.52      djm       374:                                break;
                    375:                        case 't':
                    376:                                *lflag &= ~SORT_FLAGS;
1.53      djm       377:                                *lflag |= LS_TIME_SORT;
1.52      djm       378:                                break;
                    379:                        case 'r':
1.53      djm       380:                                *lflag |= LS_REVERSE_SORT;
1.52      djm       381:                                break;
                    382:                        case 'f':
                    383:                                *lflag &= ~SORT_FLAGS;
                    384:                                break;
1.54      djm       385:                        case 'a':
                    386:                                *lflag |= LS_SHOW_ALL;
                    387:                                break;
1.44      djm       388:                        default:
                    389:                                error("Invalid flag -%c", *cp);
                    390:                                return(-1);
                    391:                        }
                    392:                }
                    393:                *cpp = cp + strspn(cp, WHITESPACE);
                    394:        }
                    395:
                    396:        return(0);
                    397: }
                    398:
                    399: static int
                    400: get_pathname(const char **cpp, char **path)
                    401: {
                    402:        const char *cp = *cpp, *end;
                    403:        char quot;
1.64      djm       404:        u_int i, j;
1.44      djm       405:
                    406:        cp += strspn(cp, WHITESPACE);
                    407:        if (!*cp) {
                    408:                *cpp = cp;
                    409:                *path = NULL;
                    410:                return (0);
                    411:        }
                    412:
                    413:        *path = xmalloc(strlen(cp) + 1);
                    414:
                    415:        /* Check for quoted filenames */
                    416:        if (*cp == '\"' || *cp == '\'') {
                    417:                quot = *cp++;
                    418:
                    419:                /* Search for terminating quote, unescape some chars */
                    420:                for (i = j = 0; i <= strlen(cp); i++) {
                    421:                        if (cp[i] == quot) {    /* Found quote */
                    422:                                i++;
                    423:                                (*path)[j] = '\0';
                    424:                                break;
                    425:                        }
                    426:                        if (cp[i] == '\0') {    /* End of string */
                    427:                                error("Unterminated quote");
                    428:                                goto fail;
                    429:                        }
                    430:                        if (cp[i] == '\\') {    /* Escaped characters */
                    431:                                i++;
                    432:                                if (cp[i] != '\'' && cp[i] != '\"' &&
                    433:                                    cp[i] != '\\') {
1.55      djm       434:                                        error("Bad escaped character '\\%c'",
1.44      djm       435:                                            cp[i]);
                    436:                                        goto fail;
                    437:                                }
                    438:                        }
                    439:                        (*path)[j++] = cp[i];
                    440:                }
                    441:
                    442:                if (j == 0) {
                    443:                        error("Empty quotes");
                    444:                        goto fail;
                    445:                }
                    446:                *cpp = cp + i + strspn(cp + i, WHITESPACE);
                    447:        } else {
                    448:                /* Read to end of filename */
                    449:                end = strpbrk(cp, WHITESPACE);
                    450:                if (end == NULL)
                    451:                        end = strchr(cp, '\0');
                    452:                *cpp = end + strspn(end, WHITESPACE);
                    453:
                    454:                memcpy(*path, cp, end - cp);
                    455:                (*path)[end - cp] = '\0';
                    456:        }
                    457:        return (0);
                    458:
                    459:  fail:
                    460:        xfree(*path);
                    461:        *path = NULL;
                    462:        return (-1);
                    463: }
                    464:
                    465: static int
                    466: is_dir(char *path)
                    467: {
                    468:        struct stat sb;
                    469:
                    470:        /* XXX: report errors? */
                    471:        if (stat(path, &sb) == -1)
                    472:                return(0);
                    473:
                    474:        return(sb.st_mode & S_IFDIR);
                    475: }
                    476:
                    477: static int
                    478: is_reg(char *path)
                    479: {
                    480:        struct stat sb;
                    481:
                    482:        if (stat(path, &sb) == -1)
                    483:                fatal("stat %s: %s", path, strerror(errno));
                    484:
                    485:        return(S_ISREG(sb.st_mode));
                    486: }
                    487:
                    488: static int
                    489: remote_is_dir(struct sftp_conn *conn, char *path)
                    490: {
                    491:        Attrib *a;
                    492:
                    493:        /* XXX: report errors? */
                    494:        if ((a = do_stat(conn, path, 1)) == NULL)
                    495:                return(0);
                    496:        if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
                    497:                return(0);
                    498:        return(a->perm & S_IFDIR);
                    499: }
                    500:
                    501: static int
                    502: process_get(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
                    503: {
                    504:        char *abs_src = NULL;
                    505:        char *abs_dst = NULL;
                    506:        char *tmp;
                    507:        glob_t g;
                    508:        int err = 0;
                    509:        int i;
                    510:
                    511:        abs_src = xstrdup(src);
                    512:        abs_src = make_absolute(abs_src, pwd);
                    513:
                    514:        memset(&g, 0, sizeof(g));
                    515:        debug3("Looking up %s", abs_src);
                    516:        if (remote_glob(conn, abs_src, 0, NULL, &g)) {
                    517:                error("File \"%s\" not found.", abs_src);
                    518:                err = -1;
                    519:                goto out;
                    520:        }
                    521:
                    522:        /* If multiple matches, dst must be a directory or unspecified */
                    523:        if (g.gl_matchc > 1 && dst && !is_dir(dst)) {
                    524:                error("Multiple files match, but \"%s\" is not a directory",
                    525:                    dst);
                    526:                err = -1;
                    527:                goto out;
                    528:        }
                    529:
1.46      djm       530:        for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1.44      djm       531:                if (infer_path(g.gl_pathv[i], &tmp)) {
                    532:                        err = -1;
                    533:                        goto out;
                    534:                }
                    535:
                    536:                if (g.gl_matchc == 1 && dst) {
                    537:                        /* If directory specified, append filename */
                    538:                        if (is_dir(dst)) {
                    539:                                if (infer_path(g.gl_pathv[0], &tmp)) {
                    540:                                        err = 1;
                    541:                                        goto out;
                    542:                                }
                    543:                                abs_dst = path_append(dst, tmp);
                    544:                                xfree(tmp);
                    545:                        } else
                    546:                                abs_dst = xstrdup(dst);
                    547:                } else if (dst) {
                    548:                        abs_dst = path_append(dst, tmp);
                    549:                        xfree(tmp);
                    550:                } else
                    551:                        abs_dst = tmp;
                    552:
                    553:                printf("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
                    554:                if (do_download(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
                    555:                        err = -1;
                    556:                xfree(abs_dst);
                    557:                abs_dst = NULL;
                    558:        }
                    559:
                    560: out:
                    561:        xfree(abs_src);
                    562:        if (abs_dst)
                    563:                xfree(abs_dst);
                    564:        globfree(&g);
                    565:        return(err);
                    566: }
                    567:
                    568: static int
                    569: process_put(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
                    570: {
                    571:        char *tmp_dst = NULL;
                    572:        char *abs_dst = NULL;
                    573:        char *tmp;
                    574:        glob_t g;
                    575:        int err = 0;
                    576:        int i;
                    577:
                    578:        if (dst) {
                    579:                tmp_dst = xstrdup(dst);
                    580:                tmp_dst = make_absolute(tmp_dst, pwd);
                    581:        }
                    582:
                    583:        memset(&g, 0, sizeof(g));
                    584:        debug3("Looking up %s", src);
                    585:        if (glob(src, 0, NULL, &g)) {
                    586:                error("File \"%s\" not found.", src);
                    587:                err = -1;
                    588:                goto out;
                    589:        }
                    590:
                    591:        /* If multiple matches, dst may be directory or unspecified */
                    592:        if (g.gl_matchc > 1 && tmp_dst && !remote_is_dir(conn, tmp_dst)) {
                    593:                error("Multiple files match, but \"%s\" is not a directory",
                    594:                    tmp_dst);
                    595:                err = -1;
                    596:                goto out;
                    597:        }
                    598:
1.46      djm       599:        for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1.44      djm       600:                if (!is_reg(g.gl_pathv[i])) {
                    601:                        error("skipping non-regular file %s",
                    602:                            g.gl_pathv[i]);
                    603:                        continue;
                    604:                }
                    605:                if (infer_path(g.gl_pathv[i], &tmp)) {
                    606:                        err = -1;
                    607:                        goto out;
                    608:                }
                    609:
                    610:                if (g.gl_matchc == 1 && tmp_dst) {
                    611:                        /* If directory specified, append filename */
                    612:                        if (remote_is_dir(conn, tmp_dst)) {
                    613:                                if (infer_path(g.gl_pathv[0], &tmp)) {
                    614:                                        err = 1;
                    615:                                        goto out;
                    616:                                }
                    617:                                abs_dst = path_append(tmp_dst, tmp);
                    618:                                xfree(tmp);
                    619:                        } else
                    620:                                abs_dst = xstrdup(tmp_dst);
                    621:
                    622:                } else if (tmp_dst) {
                    623:                        abs_dst = path_append(tmp_dst, tmp);
                    624:                        xfree(tmp);
                    625:                } else
                    626:                        abs_dst = make_absolute(tmp, pwd);
                    627:
                    628:                printf("Uploading %s to %s\n", g.gl_pathv[i], abs_dst);
                    629:                if (do_upload(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
                    630:                        err = -1;
                    631:        }
                    632:
                    633: out:
                    634:        if (abs_dst)
                    635:                xfree(abs_dst);
                    636:        if (tmp_dst)
                    637:                xfree(tmp_dst);
                    638:        globfree(&g);
                    639:        return(err);
                    640: }
                    641:
                    642: static int
                    643: sdirent_comp(const void *aa, const void *bb)
                    644: {
                    645:        SFTP_DIRENT *a = *(SFTP_DIRENT **)aa;
                    646:        SFTP_DIRENT *b = *(SFTP_DIRENT **)bb;
1.53      djm       647:        int rmul = sort_flag & LS_REVERSE_SORT ? -1 : 1;
1.44      djm       648:
1.52      djm       649: #define NCMP(a,b) (a == b ? 0 : (a < b ? 1 : -1))
1.53      djm       650:        if (sort_flag & LS_NAME_SORT)
1.52      djm       651:                return (rmul * strcmp(a->filename, b->filename));
1.53      djm       652:        else if (sort_flag & LS_TIME_SORT)
1.52      djm       653:                return (rmul * NCMP(a->a.mtime, b->a.mtime));
1.53      djm       654:        else if (sort_flag & LS_SIZE_SORT)
1.52      djm       655:                return (rmul * NCMP(a->a.size, b->a.size));
                    656:
                    657:        fatal("Unknown ls sort type");
1.44      djm       658: }
                    659:
                    660: /* sftp ls.1 replacement for directories */
                    661: static int
                    662: do_ls_dir(struct sftp_conn *conn, char *path, char *strip_path, int lflag)
                    663: {
1.64      djm       664:        int n;
                    665:        u_int c = 1, colspace = 0, columns = 1;
1.44      djm       666:        SFTP_DIRENT **d;
                    667:
                    668:        if ((n = do_readdir(conn, path, &d)) != 0)
                    669:                return (n);
                    670:
1.53      djm       671:        if (!(lflag & LS_SHORT_VIEW)) {
1.64      djm       672:                u_int m = 0, width = 80;
1.44      djm       673:                struct winsize ws;
                    674:                char *tmp;
                    675:
                    676:                /* Count entries for sort and find longest filename */
1.54      djm       677:                for (n = 0; d[n] != NULL; n++) {
                    678:                        if (d[n]->filename[0] != '.' || (lflag & LS_SHOW_ALL))
                    679:                                m = MAX(m, strlen(d[n]->filename));
                    680:                }
1.44      djm       681:
                    682:                /* Add any subpath that also needs to be counted */
                    683:                tmp = path_strip(path, strip_path);
                    684:                m += strlen(tmp);
                    685:                xfree(tmp);
                    686:
                    687:                if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
                    688:                        width = ws.ws_col;
                    689:
                    690:                columns = width / (m + 2);
                    691:                columns = MAX(columns, 1);
                    692:                colspace = width / columns;
                    693:                colspace = MIN(colspace, width);
                    694:        }
                    695:
1.52      djm       696:        if (lflag & SORT_FLAGS) {
1.68      dtucker   697:                for (n = 0; d[n] != NULL; n++)
                    698:                        ;       /* count entries */
1.53      djm       699:                sort_flag = lflag & (SORT_FLAGS|LS_REVERSE_SORT);
1.52      djm       700:                qsort(d, n, sizeof(*d), sdirent_comp);
                    701:        }
1.44      djm       702:
1.46      djm       703:        for (n = 0; d[n] != NULL && !interrupted; n++) {
1.44      djm       704:                char *tmp, *fname;
1.54      djm       705:
                    706:                if (d[n]->filename[0] == '.' && !(lflag & LS_SHOW_ALL))
                    707:                        continue;
1.44      djm       708:
                    709:                tmp = path_append(path, d[n]->filename);
                    710:                fname = path_strip(tmp, strip_path);
                    711:                xfree(tmp);
                    712:
1.53      djm       713:                if (lflag & LS_LONG_VIEW) {
                    714:                        if (lflag & LS_NUMERIC_VIEW) {
1.50      djm       715:                                char *lname;
                    716:                                struct stat sb;
                    717:
                    718:                                memset(&sb, 0, sizeof(sb));
                    719:                                attrib_to_stat(&d[n]->a, &sb);
                    720:                                lname = ls_file(fname, &sb, 1);
                    721:                                printf("%s\n", lname);
                    722:                                xfree(lname);
                    723:                        } else
                    724:                                printf("%s\n", d[n]->longname);
1.44      djm       725:                } else {
                    726:                        printf("%-*s", colspace, fname);
                    727:                        if (c >= columns) {
                    728:                                printf("\n");
                    729:                                c = 1;
                    730:                        } else
                    731:                                c++;
                    732:                }
                    733:
                    734:                xfree(fname);
                    735:        }
                    736:
1.53      djm       737:        if (!(lflag & LS_LONG_VIEW) && (c != 1))
1.44      djm       738:                printf("\n");
                    739:
                    740:        free_sftp_dirents(d);
                    741:        return (0);
                    742: }
                    743:
                    744: /* sftp ls.1 replacement which handles path globs */
                    745: static int
                    746: do_globbed_ls(struct sftp_conn *conn, char *path, char *strip_path,
                    747:     int lflag)
                    748: {
                    749:        glob_t g;
1.64      djm       750:        u_int i, c = 1, colspace = 0, columns = 1;
1.60      fgsch     751:        Attrib *a = NULL;
1.44      djm       752:
                    753:        memset(&g, 0, sizeof(g));
                    754:
                    755:        if (remote_glob(conn, path, GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE,
1.60      fgsch     756:            NULL, &g) || (g.gl_pathc && !g.gl_matchc)) {
                    757:                if (g.gl_pathc)
                    758:                        globfree(&g);
1.44      djm       759:                error("Can't ls: \"%s\" not found", path);
                    760:                return (-1);
                    761:        }
                    762:
1.46      djm       763:        if (interrupted)
                    764:                goto out;
                    765:
1.44      djm       766:        /*
1.60      fgsch     767:         * If the glob returns a single match and it is a directory,
                    768:         * then just list its contents.
1.44      djm       769:         */
1.60      fgsch     770:        if (g.gl_matchc == 1) {
                    771:                if ((a = do_lstat(conn, g.gl_pathv[0], 1)) == NULL) {
1.44      djm       772:                        globfree(&g);
                    773:                        return (-1);
                    774:                }
                    775:                if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
                    776:                    S_ISDIR(a->perm)) {
1.60      fgsch     777:                        int err;
                    778:
                    779:                        err = do_ls_dir(conn, g.gl_pathv[0], strip_path, lflag);
1.44      djm       780:                        globfree(&g);
1.60      fgsch     781:                        return (err);
1.44      djm       782:                }
                    783:        }
                    784:
1.53      djm       785:        if (!(lflag & LS_SHORT_VIEW)) {
1.64      djm       786:                u_int m = 0, width = 80;
1.44      djm       787:                struct winsize ws;
                    788:
                    789:                /* Count entries for sort and find longest filename */
                    790:                for (i = 0; g.gl_pathv[i]; i++)
                    791:                        m = MAX(m, strlen(g.gl_pathv[i]));
                    792:
                    793:                if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
                    794:                        width = ws.ws_col;
                    795:
                    796:                columns = width / (m + 2);
                    797:                columns = MAX(columns, 1);
                    798:                colspace = width / columns;
                    799:        }
                    800:
1.60      fgsch     801:        for (i = 0; g.gl_pathv[i] && !interrupted; i++, a = NULL) {
1.44      djm       802:                char *fname;
                    803:
                    804:                fname = path_strip(g.gl_pathv[i], strip_path);
                    805:
1.53      djm       806:                if (lflag & LS_LONG_VIEW) {
1.44      djm       807:                        char *lname;
                    808:                        struct stat sb;
                    809:
                    810:                        /*
                    811:                         * XXX: this is slow - 1 roundtrip per path
                    812:                         * A solution to this is to fork glob() and
                    813:                         * build a sftp specific version which keeps the
                    814:                         * attribs (which currently get thrown away)
                    815:                         * that the server returns as well as the filenames.
                    816:                         */
                    817:                        memset(&sb, 0, sizeof(sb));
1.60      fgsch     818:                        if (a == NULL)
                    819:                                a = do_lstat(conn, g.gl_pathv[i], 1);
1.44      djm       820:                        if (a != NULL)
                    821:                                attrib_to_stat(a, &sb);
                    822:                        lname = ls_file(fname, &sb, 1);
                    823:                        printf("%s\n", lname);
                    824:                        xfree(lname);
                    825:                } else {
                    826:                        printf("%-*s", colspace, fname);
                    827:                        if (c >= columns) {
                    828:                                printf("\n");
                    829:                                c = 1;
                    830:                        } else
                    831:                                c++;
                    832:                }
                    833:                xfree(fname);
                    834:        }
                    835:
1.53      djm       836:        if (!(lflag & LS_LONG_VIEW) && (c != 1))
1.44      djm       837:                printf("\n");
                    838:
1.46      djm       839:  out:
1.44      djm       840:        if (g.gl_pathc)
                    841:                globfree(&g);
                    842:
                    843:        return (0);
                    844: }
                    845:
                    846: static int
                    847: parse_args(const char **cpp, int *pflag, int *lflag, int *iflag,
                    848:     unsigned long *n_arg, char **path1, char **path2)
                    849: {
                    850:        const char *cmd, *cp = *cpp;
                    851:        char *cp2;
                    852:        int base = 0;
                    853:        long l;
                    854:        int i, cmdnum;
                    855:
                    856:        /* Skip leading whitespace */
                    857:        cp = cp + strspn(cp, WHITESPACE);
                    858:
                    859:        /* Ignore blank lines and lines which begin with comment '#' char */
                    860:        if (*cp == '\0' || *cp == '#')
                    861:                return (0);
                    862:
                    863:        /* Check for leading '-' (disable error processing) */
                    864:        *iflag = 0;
                    865:        if (*cp == '-') {
                    866:                *iflag = 1;
                    867:                cp++;
                    868:        }
                    869:
                    870:        /* Figure out which command we have */
                    871:        for (i = 0; cmds[i].c; i++) {
                    872:                int cmdlen = strlen(cmds[i].c);
                    873:
                    874:                /* Check for command followed by whitespace */
                    875:                if (!strncasecmp(cp, cmds[i].c, cmdlen) &&
                    876:                    strchr(WHITESPACE, cp[cmdlen])) {
                    877:                        cp += cmdlen;
                    878:                        cp = cp + strspn(cp, WHITESPACE);
                    879:                        break;
                    880:                }
                    881:        }
                    882:        cmdnum = cmds[i].n;
                    883:        cmd = cmds[i].c;
                    884:
                    885:        /* Special case */
                    886:        if (*cp == '!') {
                    887:                cp++;
                    888:                cmdnum = I_SHELL;
                    889:        } else if (cmdnum == -1) {
                    890:                error("Invalid command.");
                    891:                return (-1);
                    892:        }
                    893:
                    894:        /* Get arguments and parse flags */
                    895:        *lflag = *pflag = *n_arg = 0;
                    896:        *path1 = *path2 = NULL;
                    897:        switch (cmdnum) {
                    898:        case I_GET:
                    899:        case I_PUT:
                    900:                if (parse_getput_flags(&cp, pflag))
                    901:                        return(-1);
                    902:                /* Get first pathname (mandatory) */
                    903:                if (get_pathname(&cp, path1))
                    904:                        return(-1);
                    905:                if (*path1 == NULL) {
                    906:                        error("You must specify at least one path after a "
                    907:                            "%s command.", cmd);
                    908:                        return(-1);
                    909:                }
                    910:                /* Try to get second pathname (optional) */
                    911:                if (get_pathname(&cp, path2))
                    912:                        return(-1);
                    913:                break;
                    914:        case I_RENAME:
                    915:        case I_SYMLINK:
                    916:                if (get_pathname(&cp, path1))
                    917:                        return(-1);
                    918:                if (get_pathname(&cp, path2))
                    919:                        return(-1);
                    920:                if (!*path1 || !*path2) {
                    921:                        error("You must specify two paths after a %s "
                    922:                            "command.", cmd);
                    923:                        return(-1);
                    924:                }
                    925:                break;
                    926:        case I_RM:
                    927:        case I_MKDIR:
                    928:        case I_RMDIR:
                    929:        case I_CHDIR:
                    930:        case I_LCHDIR:
                    931:        case I_LMKDIR:
                    932:                /* Get pathname (mandatory) */
                    933:                if (get_pathname(&cp, path1))
                    934:                        return(-1);
                    935:                if (*path1 == NULL) {
                    936:                        error("You must specify a path after a %s command.",
                    937:                            cmd);
                    938:                        return(-1);
                    939:                }
                    940:                break;
                    941:        case I_LS:
                    942:                if (parse_ls_flags(&cp, lflag))
                    943:                        return(-1);
                    944:                /* Path is optional */
                    945:                if (get_pathname(&cp, path1))
                    946:                        return(-1);
                    947:                break;
                    948:        case I_LLS:
                    949:        case I_SHELL:
                    950:                /* Uses the rest of the line */
                    951:                break;
                    952:        case I_LUMASK:
                    953:                base = 8;
                    954:        case I_CHMOD:
                    955:                base = 8;
                    956:        case I_CHOWN:
                    957:        case I_CHGRP:
                    958:                /* Get numeric arg (mandatory) */
                    959:                l = strtol(cp, &cp2, base);
                    960:                if (cp2 == cp || ((l == LONG_MIN || l == LONG_MAX) &&
                    961:                    errno == ERANGE) || l < 0) {
                    962:                        error("You must supply a numeric argument "
                    963:                            "to the %s command.", cmd);
                    964:                        return(-1);
                    965:                }
                    966:                cp = cp2;
                    967:                *n_arg = l;
                    968:                if (cmdnum == I_LUMASK && strchr(WHITESPACE, *cp))
                    969:                        break;
                    970:                if (cmdnum == I_LUMASK || !strchr(WHITESPACE, *cp)) {
                    971:                        error("You must supply a numeric argument "
                    972:                            "to the %s command.", cmd);
                    973:                        return(-1);
                    974:                }
                    975:                cp += strspn(cp, WHITESPACE);
                    976:
                    977:                /* Get pathname (mandatory) */
                    978:                if (get_pathname(&cp, path1))
                    979:                        return(-1);
                    980:                if (*path1 == NULL) {
                    981:                        error("You must specify a path after a %s command.",
                    982:                            cmd);
                    983:                        return(-1);
                    984:                }
                    985:                break;
                    986:        case I_QUIT:
                    987:        case I_PWD:
                    988:        case I_LPWD:
                    989:        case I_HELP:
                    990:        case I_VERSION:
                    991:        case I_PROGRESS:
                    992:                break;
                    993:        default:
                    994:                fatal("Command not implemented");
                    995:        }
                    996:
                    997:        *cpp = cp;
                    998:        return(cmdnum);
                    999: }
                   1000:
                   1001: static int
                   1002: parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
                   1003:     int err_abort)
                   1004: {
                   1005:        char *path1, *path2, *tmp;
                   1006:        int pflag, lflag, iflag, cmdnum, i;
                   1007:        unsigned long n_arg;
                   1008:        Attrib a, *aa;
                   1009:        char path_buf[MAXPATHLEN];
                   1010:        int err = 0;
                   1011:        glob_t g;
                   1012:
                   1013:        path1 = path2 = NULL;
                   1014:        cmdnum = parse_args(&cmd, &pflag, &lflag, &iflag, &n_arg,
                   1015:            &path1, &path2);
                   1016:
                   1017:        if (iflag != 0)
                   1018:                err_abort = 0;
                   1019:
                   1020:        memset(&g, 0, sizeof(g));
                   1021:
                   1022:        /* Perform command */
                   1023:        switch (cmdnum) {
                   1024:        case 0:
                   1025:                /* Blank line */
                   1026:                break;
                   1027:        case -1:
                   1028:                /* Unrecognized command */
                   1029:                err = -1;
                   1030:                break;
                   1031:        case I_GET:
                   1032:                err = process_get(conn, path1, path2, *pwd, pflag);
                   1033:                break;
                   1034:        case I_PUT:
                   1035:                err = process_put(conn, path1, path2, *pwd, pflag);
                   1036:                break;
                   1037:        case I_RENAME:
                   1038:                path1 = make_absolute(path1, *pwd);
                   1039:                path2 = make_absolute(path2, *pwd);
                   1040:                err = do_rename(conn, path1, path2);
                   1041:                break;
                   1042:        case I_SYMLINK:
                   1043:                path2 = make_absolute(path2, *pwd);
                   1044:                err = do_symlink(conn, path1, path2);
                   1045:                break;
                   1046:        case I_RM:
                   1047:                path1 = make_absolute(path1, *pwd);
                   1048:                remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1.46      djm      1049:                for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1.44      djm      1050:                        printf("Removing %s\n", g.gl_pathv[i]);
                   1051:                        err = do_rm(conn, g.gl_pathv[i]);
                   1052:                        if (err != 0 && err_abort)
                   1053:                                break;
                   1054:                }
                   1055:                break;
                   1056:        case I_MKDIR:
                   1057:                path1 = make_absolute(path1, *pwd);
                   1058:                attrib_clear(&a);
                   1059:                a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
                   1060:                a.perm = 0777;
                   1061:                err = do_mkdir(conn, path1, &a);
                   1062:                break;
                   1063:        case I_RMDIR:
                   1064:                path1 = make_absolute(path1, *pwd);
                   1065:                err = do_rmdir(conn, path1);
                   1066:                break;
                   1067:        case I_CHDIR:
                   1068:                path1 = make_absolute(path1, *pwd);
                   1069:                if ((tmp = do_realpath(conn, path1)) == NULL) {
                   1070:                        err = 1;
                   1071:                        break;
                   1072:                }
                   1073:                if ((aa = do_stat(conn, tmp, 0)) == NULL) {
                   1074:                        xfree(tmp);
                   1075:                        err = 1;
                   1076:                        break;
                   1077:                }
                   1078:                if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
                   1079:                        error("Can't change directory: Can't check target");
                   1080:                        xfree(tmp);
                   1081:                        err = 1;
                   1082:                        break;
                   1083:                }
                   1084:                if (!S_ISDIR(aa->perm)) {
                   1085:                        error("Can't change directory: \"%s\" is not "
                   1086:                            "a directory", tmp);
                   1087:                        xfree(tmp);
                   1088:                        err = 1;
                   1089:                        break;
                   1090:                }
                   1091:                xfree(*pwd);
                   1092:                *pwd = tmp;
                   1093:                break;
                   1094:        case I_LS:
                   1095:                if (!path1) {
                   1096:                        do_globbed_ls(conn, *pwd, *pwd, lflag);
                   1097:                        break;
                   1098:                }
                   1099:
                   1100:                /* Strip pwd off beginning of non-absolute paths */
                   1101:                tmp = NULL;
                   1102:                if (*path1 != '/')
                   1103:                        tmp = *pwd;
                   1104:
                   1105:                path1 = make_absolute(path1, *pwd);
                   1106:                err = do_globbed_ls(conn, path1, tmp, lflag);
                   1107:                break;
                   1108:        case I_LCHDIR:
                   1109:                if (chdir(path1) == -1) {
                   1110:                        error("Couldn't change local directory to "
                   1111:                            "\"%s\": %s", path1, strerror(errno));
                   1112:                        err = 1;
                   1113:                }
                   1114:                break;
                   1115:        case I_LMKDIR:
                   1116:                if (mkdir(path1, 0777) == -1) {
                   1117:                        error("Couldn't create local directory "
                   1118:                            "\"%s\": %s", path1, strerror(errno));
                   1119:                        err = 1;
                   1120:                }
                   1121:                break;
                   1122:        case I_LLS:
                   1123:                local_do_ls(cmd);
                   1124:                break;
                   1125:        case I_SHELL:
                   1126:                local_do_shell(cmd);
                   1127:                break;
                   1128:        case I_LUMASK:
                   1129:                umask(n_arg);
                   1130:                printf("Local umask: %03lo\n", n_arg);
                   1131:                break;
                   1132:        case I_CHMOD:
                   1133:                path1 = make_absolute(path1, *pwd);
                   1134:                attrib_clear(&a);
                   1135:                a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
                   1136:                a.perm = n_arg;
                   1137:                remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1.46      djm      1138:                for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1.44      djm      1139:                        printf("Changing mode on %s\n", g.gl_pathv[i]);
                   1140:                        err = do_setstat(conn, g.gl_pathv[i], &a);
                   1141:                        if (err != 0 && err_abort)
                   1142:                                break;
                   1143:                }
                   1144:                break;
                   1145:        case I_CHOWN:
                   1146:        case I_CHGRP:
                   1147:                path1 = make_absolute(path1, *pwd);
                   1148:                remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
1.46      djm      1149:                for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1.44      djm      1150:                        if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
                   1151:                                if (err != 0 && err_abort)
                   1152:                                        break;
                   1153:                                else
                   1154:                                        continue;
                   1155:                        }
                   1156:                        if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
                   1157:                                error("Can't get current ownership of "
                   1158:                                    "remote file \"%s\"", g.gl_pathv[i]);
                   1159:                                if (err != 0 && err_abort)
                   1160:                                        break;
                   1161:                                else
                   1162:                                        continue;
                   1163:                        }
                   1164:                        aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
                   1165:                        if (cmdnum == I_CHOWN) {
                   1166:                                printf("Changing owner on %s\n", g.gl_pathv[i]);
                   1167:                                aa->uid = n_arg;
                   1168:                        } else {
                   1169:                                printf("Changing group on %s\n", g.gl_pathv[i]);
                   1170:                                aa->gid = n_arg;
                   1171:                        }
                   1172:                        err = do_setstat(conn, g.gl_pathv[i], aa);
                   1173:                        if (err != 0 && err_abort)
                   1174:                                break;
                   1175:                }
                   1176:                break;
                   1177:        case I_PWD:
                   1178:                printf("Remote working directory: %s\n", *pwd);
                   1179:                break;
                   1180:        case I_LPWD:
                   1181:                if (!getcwd(path_buf, sizeof(path_buf))) {
                   1182:                        error("Couldn't get local cwd: %s", strerror(errno));
                   1183:                        err = -1;
                   1184:                        break;
                   1185:                }
                   1186:                printf("Local working directory: %s\n", path_buf);
                   1187:                break;
                   1188:        case I_QUIT:
                   1189:                /* Processed below */
                   1190:                break;
                   1191:        case I_HELP:
                   1192:                help();
                   1193:                break;
                   1194:        case I_VERSION:
                   1195:                printf("SFTP protocol version %u\n", sftp_proto_version(conn));
                   1196:                break;
                   1197:        case I_PROGRESS:
                   1198:                showprogress = !showprogress;
                   1199:                if (showprogress)
                   1200:                        printf("Progress meter enabled\n");
                   1201:                else
                   1202:                        printf("Progress meter disabled\n");
                   1203:                break;
                   1204:        default:
                   1205:                fatal("%d is not implemented", cmdnum);
                   1206:        }
                   1207:
                   1208:        if (g.gl_pathc)
                   1209:                globfree(&g);
                   1210:        if (path1)
                   1211:                xfree(path1);
                   1212:        if (path2)
                   1213:                xfree(path2);
                   1214:
                   1215:        /* If an unignored error occurs in batch mode we should abort. */
                   1216:        if (err_abort && err != 0)
                   1217:                return (-1);
                   1218:        else if (cmdnum == I_QUIT)
                   1219:                return (1);
                   1220:
                   1221:        return (0);
                   1222: }
                   1223:
1.57      djm      1224: static char *
                   1225: prompt(EditLine *el)
                   1226: {
                   1227:        return ("sftp> ");
                   1228: }
                   1229:
1.44      djm      1230: int
                   1231: interactive_loop(int fd_in, int fd_out, char *file1, char *file2)
                   1232: {
                   1233:        char *pwd;
                   1234:        char *dir = NULL;
                   1235:        char cmd[2048];
                   1236:        struct sftp_conn *conn;
1.66      jaredy   1237:        int err, interactive;
1.57      djm      1238:        EditLine *el = NULL;
                   1239:        History *hl = NULL;
                   1240:        HistEvent hev;
                   1241:        extern char *__progname;
                   1242:
                   1243:        if (!batchmode && isatty(STDIN_FILENO)) {
                   1244:                if ((el = el_init(__progname, stdin, stdout, stderr)) == NULL)
                   1245:                        fatal("Couldn't initialise editline");
                   1246:                if ((hl = history_init()) == NULL)
                   1247:                        fatal("Couldn't initialise editline history");
                   1248:                history(hl, &hev, H_SETSIZE, 100);
                   1249:                el_set(el, EL_HIST, history, hl);
                   1250:
                   1251:                el_set(el, EL_PROMPT, prompt);
                   1252:                el_set(el, EL_EDITOR, "emacs");
                   1253:                el_set(el, EL_TERMINAL, NULL);
                   1254:                el_set(el, EL_SIGNAL, 1);
                   1255:                el_source(el, NULL);
                   1256:        }
1.44      djm      1257:
                   1258:        conn = do_init(fd_in, fd_out, copy_buffer_len, num_requests);
                   1259:        if (conn == NULL)
                   1260:                fatal("Couldn't initialise connection to server");
                   1261:
                   1262:        pwd = do_realpath(conn, ".");
                   1263:        if (pwd == NULL)
                   1264:                fatal("Need cwd");
                   1265:
                   1266:        if (file1 != NULL) {
                   1267:                dir = xstrdup(file1);
                   1268:                dir = make_absolute(dir, pwd);
                   1269:
                   1270:                if (remote_is_dir(conn, dir) && file2 == NULL) {
                   1271:                        printf("Changing to: %s\n", dir);
                   1272:                        snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
1.58      markus   1273:                        if (parse_dispatch_command(conn, cmd, &pwd, 1) != 0) {
                   1274:                                xfree(dir);
                   1275:                                xfree(pwd);
1.44      djm      1276:                                return (-1);
1.58      markus   1277:                        }
1.44      djm      1278:                } else {
                   1279:                        if (file2 == NULL)
                   1280:                                snprintf(cmd, sizeof cmd, "get %s", dir);
                   1281:                        else
                   1282:                                snprintf(cmd, sizeof cmd, "get %s %s", dir,
                   1283:                                    file2);
                   1284:
                   1285:                        err = parse_dispatch_command(conn, cmd, &pwd, 1);
                   1286:                        xfree(dir);
                   1287:                        xfree(pwd);
                   1288:                        return (err);
                   1289:                }
                   1290:                xfree(dir);
                   1291:        }
                   1292:
                   1293:        setvbuf(stdout, NULL, _IOLBF, 0);
                   1294:        setvbuf(infile, NULL, _IOLBF, 0);
                   1295:
1.66      jaredy   1296:        interactive = !batchmode && isatty(STDIN_FILENO);
1.44      djm      1297:        err = 0;
                   1298:        for (;;) {
                   1299:                char *cp;
1.57      djm      1300:                const char *line;
                   1301:                int count = 0;
1.44      djm      1302:
1.46      djm      1303:                signal(SIGINT, SIG_IGN);
                   1304:
1.57      djm      1305:                if (el == NULL) {
1.66      jaredy   1306:                        if (interactive)
                   1307:                                printf("sftp> ");
1.57      djm      1308:                        if (fgets(cmd, sizeof(cmd), infile) == NULL) {
1.66      jaredy   1309:                                if (interactive)
                   1310:                                        printf("\n");
1.57      djm      1311:                                break;
                   1312:                        }
1.66      jaredy   1313:                        if (!interactive) { /* Echo command */
                   1314:                                printf("sftp> %s", cmd);
                   1315:                                if (strlen(cmd) > 0 &&
                   1316:                                    cmd[strlen(cmd) - 1] != '\n')
                   1317:                                        printf("\n");
                   1318:                        }
1.57      djm      1319:                } else {
1.66      jaredy   1320:                        if ((line = el_gets(el, &count)) == NULL || count <= 0) {
                   1321:                                printf("\n");
1.57      djm      1322:                                break;
1.66      jaredy   1323:                        }
1.57      djm      1324:                        history(hl, &hev, H_ENTER, line);
                   1325:                        if (strlcpy(cmd, line, sizeof(cmd)) >= sizeof(cmd)) {
                   1326:                                fprintf(stderr, "Error: input line too long\n");
                   1327:                                continue;
                   1328:                        }
1.44      djm      1329:                }
                   1330:
                   1331:                cp = strrchr(cmd, '\n');
                   1332:                if (cp)
                   1333:                        *cp = '\0';
                   1334:
1.46      djm      1335:                /* Handle user interrupts gracefully during commands */
                   1336:                interrupted = 0;
                   1337:                signal(SIGINT, cmd_interrupt);
                   1338:
1.44      djm      1339:                err = parse_dispatch_command(conn, cmd, &pwd, batchmode);
                   1340:                if (err != 0)
                   1341:                        break;
                   1342:        }
                   1343:        xfree(pwd);
1.66      jaredy   1344:
                   1345:        if (el != NULL)
                   1346:                el_end(el);
1.44      djm      1347:
                   1348:        /* err == 1 signifies normal "quit" exit */
                   1349:        return (err >= 0 ? 0 : -1);
                   1350: }
1.34      fgsch    1351:
1.18      itojun   1352: static void
1.36      djm      1353: connect_to_server(char *path, char **args, int *in, int *out)
1.1       djm      1354: {
                   1355:        int c_in, c_out;
1.30      deraadt  1356:
1.1       djm      1357: #ifdef USE_PIPES
                   1358:        int pin[2], pout[2];
1.30      deraadt  1359:
1.1       djm      1360:        if ((pipe(pin) == -1) || (pipe(pout) == -1))
                   1361:                fatal("pipe: %s", strerror(errno));
                   1362:        *in = pin[0];
                   1363:        *out = pout[1];
                   1364:        c_in = pout[0];
                   1365:        c_out = pin[1];
                   1366: #else /* USE_PIPES */
                   1367:        int inout[2];
1.30      deraadt  1368:
1.1       djm      1369:        if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1)
                   1370:                fatal("socketpair: %s", strerror(errno));
                   1371:        *in = *out = inout[0];
                   1372:        c_in = c_out = inout[1];
                   1373: #endif /* USE_PIPES */
                   1374:
1.36      djm      1375:        if ((sshpid = fork()) == -1)
1.1       djm      1376:                fatal("fork: %s", strerror(errno));
1.36      djm      1377:        else if (sshpid == 0) {
1.1       djm      1378:                if ((dup2(c_in, STDIN_FILENO) == -1) ||
                   1379:                    (dup2(c_out, STDOUT_FILENO) == -1)) {
                   1380:                        fprintf(stderr, "dup2: %s\n", strerror(errno));
1.47      djm      1381:                        _exit(1);
1.1       djm      1382:                }
                   1383:                close(*in);
                   1384:                close(*out);
                   1385:                close(c_in);
                   1386:                close(c_out);
1.46      djm      1387:
                   1388:                /*
                   1389:                 * The underlying ssh is in the same process group, so we must
1.56      deraadt  1390:                 * ignore SIGINT if we want to gracefully abort commands,
                   1391:                 * otherwise the signal will make it to the ssh process and
1.46      djm      1392:                 * kill it too
                   1393:                 */
                   1394:                signal(SIGINT, SIG_IGN);
1.49      dtucker  1395:                execvp(path, args);
1.23      djm      1396:                fprintf(stderr, "exec: %s: %s\n", path, strerror(errno));
1.47      djm      1397:                _exit(1);
1.1       djm      1398:        }
                   1399:
1.36      djm      1400:        signal(SIGTERM, killchild);
                   1401:        signal(SIGINT, killchild);
                   1402:        signal(SIGHUP, killchild);
1.1       djm      1403:        close(c_in);
                   1404:        close(c_out);
                   1405: }
                   1406:
1.18      itojun   1407: static void
1.1       djm      1408: usage(void)
                   1409: {
1.25      mpech    1410:        extern char *__progname;
1.27      markus   1411:
1.19      stevesk  1412:        fprintf(stderr,
1.38      jmc      1413:            "usage: %s [-1Cv] [-B buffer_size] [-b batchfile] [-F ssh_config]\n"
                   1414:            "            [-o ssh_option] [-P sftp_server_path] [-R num_requests]\n"
                   1415:            "            [-S program] [-s subsystem | sftp_server] host\n"
                   1416:            "       %s [[user@]host[:file [file]]]\n"
                   1417:            "       %s [[user@]host[:dir[/]]]\n"
                   1418:            "       %s -b batchfile [user@]host\n", __progname, __progname, __progname, __progname);
1.1       djm      1419:        exit(1);
                   1420: }
                   1421:
1.2       stevesk  1422: int
1.1       djm      1423: main(int argc, char **argv)
                   1424: {
1.33      djm      1425:        int in, out, ch, err;
1.48      pedro    1426:        char *host, *userhost, *cp, *file2 = NULL;
1.17      mouring  1427:        int debug_level = 0, sshver = 2;
                   1428:        char *file1 = NULL, *sftp_server = NULL;
1.23      djm      1429:        char *ssh_program = _PATH_SSH_PROGRAM, *sftp_direct = NULL;
1.17      mouring  1430:        LogLevel ll = SYSLOG_LEVEL_INFO;
                   1431:        arglist args;
1.3       djm      1432:        extern int optind;
                   1433:        extern char *optarg;
1.67      djm      1434:
                   1435:        /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
                   1436:        sanitise_stdfd();
1.1       djm      1437:
1.70      djm      1438:        memset(&args, '\0', sizeof(args));
1.17      mouring  1439:        args.list = NULL;
1.70      djm      1440:        addargs(&args, ssh_program);
1.17      mouring  1441:        addargs(&args, "-oForwardX11 no");
                   1442:        addargs(&args, "-oForwardAgent no");
1.69      reyk     1443:        addargs(&args, "-oPermitLocalCommand no");
1.21      stevesk  1444:        addargs(&args, "-oClearAllForwardings yes");
1.40      djm      1445:
1.17      mouring  1446:        ll = SYSLOG_LEVEL_INFO;
1.40      djm      1447:        infile = stdin;
1.3       djm      1448:
1.26      djm      1449:        while ((ch = getopt(argc, argv, "1hvCo:s:S:b:B:F:P:R:")) != -1) {
1.3       djm      1450:                switch (ch) {
                   1451:                case 'C':
1.17      mouring  1452:                        addargs(&args, "-C");
1.3       djm      1453:                        break;
                   1454:                case 'v':
1.17      mouring  1455:                        if (debug_level < 3) {
                   1456:                                addargs(&args, "-v");
                   1457:                                ll = SYSLOG_LEVEL_DEBUG1 + debug_level;
                   1458:                        }
                   1459:                        debug_level++;
1.3       djm      1460:                        break;
1.19      stevesk  1461:                case 'F':
1.3       djm      1462:                case 'o':
1.19      stevesk  1463:                        addargs(&args, "-%c%s", ch, optarg);
1.7       markus   1464:                        break;
                   1465:                case '1':
1.17      mouring  1466:                        sshver = 1;
1.7       markus   1467:                        if (sftp_server == NULL)
                   1468:                                sftp_server = _PATH_SFTP_SERVER;
                   1469:                        break;
                   1470:                case 's':
                   1471:                        sftp_server = optarg;
                   1472:                        break;
                   1473:                case 'S':
                   1474:                        ssh_program = optarg;
1.70      djm      1475:                        replacearg(&args, 0, "%s", ssh_program);
1.3       djm      1476:                        break;
1.10      deraadt  1477:                case 'b':
1.39      djm      1478:                        if (batchmode)
                   1479:                                fatal("Batch file already specified.");
                   1480:
                   1481:                        /* Allow "-" as stdin */
1.56      deraadt  1482:                        if (strcmp(optarg, "-") != 0 &&
1.65      djm      1483:                            (infile = fopen(optarg, "r")) == NULL)
1.39      djm      1484:                                fatal("%s (%s).", strerror(errno), optarg);
1.34      fgsch    1485:                        showprogress = 0;
1.39      djm      1486:                        batchmode = 1;
1.62      djm      1487:                        addargs(&args, "-obatchmode yes");
1.10      deraadt  1488:                        break;
1.23      djm      1489:                case 'P':
                   1490:                        sftp_direct = optarg;
1.24      djm      1491:                        break;
                   1492:                case 'B':
                   1493:                        copy_buffer_len = strtol(optarg, &cp, 10);
                   1494:                        if (copy_buffer_len == 0 || *cp != '\0')
                   1495:                                fatal("Invalid buffer size \"%s\"", optarg);
1.26      djm      1496:                        break;
                   1497:                case 'R':
                   1498:                        num_requests = strtol(optarg, &cp, 10);
                   1499:                        if (num_requests == 0 || *cp != '\0')
1.27      markus   1500:                                fatal("Invalid number of requests \"%s\"",
1.26      djm      1501:                                    optarg);
1.23      djm      1502:                        break;
1.3       djm      1503:                case 'h':
                   1504:                default:
1.1       djm      1505:                        usage();
                   1506:                }
                   1507:        }
1.45      djm      1508:
                   1509:        if (!isatty(STDERR_FILENO))
                   1510:                showprogress = 0;
1.1       djm      1511:
1.29      markus   1512:        log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);
                   1513:
1.23      djm      1514:        if (sftp_direct == NULL) {
                   1515:                if (optind == argc || argc > (optind + 2))
                   1516:                        usage();
                   1517:
                   1518:                userhost = xstrdup(argv[optind]);
                   1519:                file2 = argv[optind+1];
1.1       djm      1520:
1.32      markus   1521:                if ((host = strrchr(userhost, '@')) == NULL)
1.23      djm      1522:                        host = userhost;
                   1523:                else {
                   1524:                        *host++ = '\0';
                   1525:                        if (!userhost[0]) {
                   1526:                                fprintf(stderr, "Missing username\n");
                   1527:                                usage();
                   1528:                        }
                   1529:                        addargs(&args, "-l%s",userhost);
1.41      djm      1530:                }
                   1531:
                   1532:                if ((cp = colon(host)) != NULL) {
                   1533:                        *cp++ = '\0';
                   1534:                        file1 = cp;
1.23      djm      1535:                }
1.3       djm      1536:
1.23      djm      1537:                host = cleanhostname(host);
                   1538:                if (!*host) {
                   1539:                        fprintf(stderr, "Missing hostname\n");
1.1       djm      1540:                        usage();
                   1541:                }
                   1542:
1.23      djm      1543:                addargs(&args, "-oProtocol %d", sshver);
                   1544:
                   1545:                /* no subsystem if the server-spec contains a '/' */
                   1546:                if (sftp_server == NULL || strchr(sftp_server, '/') == NULL)
                   1547:                        addargs(&args, "-s");
                   1548:
                   1549:                addargs(&args, "%s", host);
1.27      markus   1550:                addargs(&args, "%s", (sftp_server != NULL ?
1.23      djm      1551:                    sftp_server : "sftp"));
                   1552:
1.39      djm      1553:                if (!batchmode)
                   1554:                        fprintf(stderr, "Connecting to %s...\n", host);
1.36      djm      1555:                connect_to_server(ssh_program, args.list, &in, &out);
1.23      djm      1556:        } else {
                   1557:                args.list = NULL;
                   1558:                addargs(&args, "sftp-server");
                   1559:
1.39      djm      1560:                if (!batchmode)
                   1561:                        fprintf(stderr, "Attaching to %s...\n", sftp_direct);
1.36      djm      1562:                connect_to_server(sftp_direct, args.list, &in, &out);
1.1       djm      1563:        }
1.70      djm      1564:        freeargs(&args);
1.1       djm      1565:
1.33      djm      1566:        err = interactive_loop(in, out, file1, file2);
1.1       djm      1567:
                   1568:        close(in);
                   1569:        close(out);
1.39      djm      1570:        if (batchmode)
1.10      deraadt  1571:                fclose(infile);
1.1       djm      1572:
1.28      markus   1573:        while (waitpid(sshpid, NULL, 0) == -1)
                   1574:                if (errno != EINTR)
                   1575:                        fatal("Couldn't wait for ssh process: %s",
                   1576:                            strerror(errno));
1.1       djm      1577:
1.33      djm      1578:        exit(err == 0 ? 0 : 1);
1.1       djm      1579: }