[BACK]Return to sftp-client.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / ssh

Annotation of src/usr.bin/ssh/sftp-client.c, Revision 1.158

1.158   ! jsg         1: /* $OpenBSD: sftp-client.c,v 1.157 2021/11/06 10:13:39 dtucker Exp $ */
1.1       djm         2: /*
1.46      djm         3:  * Copyright (c) 2001-2004 Damien Miller <djm@openbsd.org>
1.1       djm         4:  *
1.46      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.46      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:
                     18: /* XXX: memleaks */
                     19: /* XXX: signed vs unsigned */
1.23      djm        20: /* XXX: remove all logging, only return status codes */
1.1       djm        21: /* XXX: copy between two remote sites */
                     22:
1.74      deraadt    23: #include <sys/types.h>
1.93      djm        24: #include <sys/poll.h>
1.21      djm        25: #include <sys/queue.h>
1.60      stevesk    26: #include <sys/stat.h>
1.71      stevesk    27: #include <sys/time.h>
1.82      djm        28: #include <sys/statvfs.h>
1.74      deraadt    29: #include <sys/uio.h>
1.66      stevesk    30:
1.89      djm        31: #include <dirent.h>
1.67      stevesk    32: #include <errno.h>
1.66      stevesk    33: #include <fcntl.h>
1.152     djm        34: #include <poll.h>
1.70      stevesk    35: #include <signal.h>
1.87      dtucker    36: #include <stdarg.h>
1.73      stevesk    37: #include <stdio.h>
1.109     dtucker    38: #include <stdlib.h>
1.69      stevesk    39: #include <string.h>
1.68      stevesk    40: #include <unistd.h>
1.1       djm        41:
1.74      deraadt    42: #include "xmalloc.h"
1.116     djm        43: #include "ssherr.h"
                     44: #include "sshbuf.h"
1.1       djm        45: #include "log.h"
                     46: #include "atomicio.h"
1.39      fgsch      47: #include "progressmeter.h"
1.64      djm        48: #include "misc.h"
1.124     schwarze   49: #include "utf8.h"
1.1       djm        50:
                     51: #include "sftp.h"
                     52: #include "sftp-common.h"
                     53: #include "sftp-client.h"
                     54:
1.49      djm        55: extern volatile sig_atomic_t interrupted;
1.39      fgsch      56: extern int showprogress;
                     57:
1.141     djm        58: /* Default size of buffer for up/download */
                     59: #define DEFAULT_COPY_BUFLEN    32768
                     60:
                     61: /* Default number of concurrent outstanding requests */
                     62: #define DEFAULT_NUM_REQUESTS   64
                     63:
1.59      david      64: /* Minimum amount of data to read at a time */
1.21      djm        65: #define MIN_READ_SIZE  512
                     66:
1.89      djm        67: /* Maximum depth to descend in directory trees */
                     68: #define MAX_DIR_DEPTH 64
                     69:
1.23      djm        70: struct sftp_conn {
                     71:        int fd_in;
                     72:        int fd_out;
1.141     djm        73:        u_int download_buflen;
                     74:        u_int upload_buflen;
1.23      djm        75:        u_int num_requests;
                     76:        u_int version;
                     77:        u_int msg_id;
1.82      djm        78: #define SFTP_EXT_POSIX_RENAME  0x00000001
                     79: #define SFTP_EXT_STATVFS       0x00000002
                     80: #define SFTP_EXT_FSTATVFS      0x00000004
1.94      djm        81: #define SFTP_EXT_HARDLINK      0x00000008
1.107     djm        82: #define SFTP_EXT_FSYNC         0x00000010
1.131     djm        83: #define SFTP_EXT_LSETSTAT      0x00000020
1.141     djm        84: #define SFTP_EXT_LIMITS                0x00000040
1.154     djm        85: #define SFTP_EXT_PATH_EXPAND   0x00000080
1.81      djm        86:        u_int exts;
1.93      djm        87:        u_int64_t limit_kbps;
                     88:        struct bwlimit bwlimit_in, bwlimit_out;
1.23      djm        89: };
1.4       djm        90:
1.146     djm        91: /* Tracks in-progress requests during file transfers */
                     92: struct request {
                     93:        u_int id;
                     94:        size_t len;
                     95:        u_int64_t offset;
                     96:        TAILQ_ENTRY(request) tq;
                     97: };
                     98: TAILQ_HEAD(requests, request);
                     99:
1.116     djm       100: static u_char *
                    101: get_handle(struct sftp_conn *conn, u_int expected_id, size_t *len,
1.93      djm       102:     const char *errfmt, ...) __attribute__((format(printf, 4, 5)));
                    103:
1.151     djm       104: static struct request *
                    105: request_enqueue(struct requests *requests, u_int id, size_t len,
                    106:     uint64_t offset)
                    107: {
                    108:        struct request *req;
                    109:
                    110:        req = xcalloc(1, sizeof(*req));
                    111:        req->id = id;
                    112:        req->len = len;
                    113:        req->offset = offset;
                    114:        TAILQ_INSERT_TAIL(requests, req, tq);
                    115:        return req;
                    116: }
                    117:
                    118: static struct request *
                    119: request_find(struct requests *requests, u_int id)
                    120: {
                    121:        struct request *req;
                    122:
                    123:        for (req = TAILQ_FIRST(requests);
                    124:            req != NULL && req->id != id;
                    125:            req = TAILQ_NEXT(req, tq))
                    126:                ;
                    127:        return req;
                    128: }
                    129:
1.93      djm       130: /* ARGSUSED */
                    131: static int
                    132: sftpio(void *_bwlimit, size_t amount)
                    133: {
                    134:        struct bwlimit *bwlimit = (struct bwlimit *)_bwlimit;
                    135:
1.133     dtucker   136:        refresh_progress_meter(0);
1.132     dtucker   137:        if (bwlimit != NULL)
                    138:                bandwidth_limit(bwlimit, amount);
1.93      djm       139:        return 0;
                    140: }
1.88      djm       141:
1.17      itojun    142: static void
1.116     djm       143: send_msg(struct sftp_conn *conn, struct sshbuf *m)
1.1       djm       144: {
1.40      djm       145:        u_char mlen[4];
1.65      djm       146:        struct iovec iov[2];
1.40      djm       147:
1.116     djm       148:        if (sshbuf_len(m) > SFTP_MAX_MSG_LENGTH)
                    149:                fatal("Outbound message too long %zu", sshbuf_len(m));
1.40      djm       150:
                    151:        /* Send length first */
1.116     djm       152:        put_u32(mlen, sshbuf_len(m));
1.65      djm       153:        iov[0].iov_base = mlen;
                    154:        iov[0].iov_len = sizeof(mlen);
1.116     djm       155:        iov[1].iov_base = (u_char *)sshbuf_ptr(m);
                    156:        iov[1].iov_len = sshbuf_len(m);
1.74      deraadt   157:
1.132     dtucker   158:        if (atomiciov6(writev, conn->fd_out, iov, 2, sftpio,
                    159:            conn->limit_kbps > 0 ? &conn->bwlimit_out : NULL) !=
1.116     djm       160:            sshbuf_len(m) + sizeof(mlen))
1.1       djm       161:                fatal("Couldn't send packet: %s", strerror(errno));
                    162:
1.116     djm       163:        sshbuf_reset(m);
1.1       djm       164: }
                    165:
1.17      itojun    166: static void
1.128     dtucker   167: get_msg_extended(struct sftp_conn *conn, struct sshbuf *m, int initial)
1.1       djm       168: {
1.40      djm       169:        u_int msg_len;
1.116     djm       170:        u_char *p;
                    171:        int r;
1.1       djm       172:
1.144     djm       173:        sshbuf_reset(m);
1.116     djm       174:        if ((r = sshbuf_reserve(m, 4, &p)) != 0)
1.137     djm       175:                fatal_fr(r, "reserve");
1.132     dtucker   176:        if (atomicio6(read, conn->fd_in, p, 4, sftpio,
                    177:            conn->limit_kbps > 0 ? &conn->bwlimit_in : NULL) != 4) {
1.127     djm       178:                if (errno == EPIPE || errno == ECONNRESET)
1.54      avsm      179:                        fatal("Connection closed");
                    180:                else
                    181:                        fatal("Couldn't read packet: %s", strerror(errno));
                    182:        }
1.1       djm       183:
1.116     djm       184:        if ((r = sshbuf_get_u32(m, &msg_len)) != 0)
1.137     djm       185:                fatal_fr(r, "sshbuf_get_u32");
1.128     dtucker   186:        if (msg_len > SFTP_MAX_MSG_LENGTH) {
                    187:                do_log2(initial ? SYSLOG_LEVEL_ERROR : SYSLOG_LEVEL_FATAL,
                    188:                    "Received message too long %u", msg_len);
                    189:                fatal("Ensure the remote shell produces no output "
                    190:                    "for non-interactive sessions.");
                    191:        }
1.1       djm       192:
1.116     djm       193:        if ((r = sshbuf_reserve(m, msg_len, &p)) != 0)
1.137     djm       194:                fatal_fr(r, "reserve");
1.132     dtucker   195:        if (atomicio6(read, conn->fd_in, p, msg_len, sftpio,
                    196:            conn->limit_kbps > 0 ? &conn->bwlimit_in : NULL)
1.93      djm       197:            != msg_len) {
1.54      avsm      198:                if (errno == EPIPE)
                    199:                        fatal("Connection closed");
                    200:                else
                    201:                        fatal("Read packet: %s", strerror(errno));
                    202:        }
1.1       djm       203: }
                    204:
1.17      itojun    205: static void
1.128     dtucker   206: get_msg(struct sftp_conn *conn, struct sshbuf *m)
                    207: {
                    208:        get_msg_extended(conn, m, 0);
                    209: }
                    210:
                    211: static void
1.116     djm       212: send_string_request(struct sftp_conn *conn, u_int id, u_int code, const char *s,
1.1       djm       213:     u_int len)
                    214: {
1.116     djm       215:        struct sshbuf *msg;
                    216:        int r;
1.1       djm       217:
1.116     djm       218:        if ((msg = sshbuf_new()) == NULL)
1.137     djm       219:                fatal_f("sshbuf_new failed");
1.116     djm       220:        if ((r = sshbuf_put_u8(msg, code)) != 0 ||
                    221:            (r = sshbuf_put_u32(msg, id)) != 0 ||
                    222:            (r = sshbuf_put_string(msg, s, len)) != 0)
1.137     djm       223:                fatal_fr(r, "compose");
1.116     djm       224:        send_msg(conn, msg);
1.93      djm       225:        debug3("Sent message fd %d T:%u I:%u", conn->fd_out, code, id);
1.116     djm       226:        sshbuf_free(msg);
1.1       djm       227: }
                    228:
1.17      itojun    229: static void
1.93      djm       230: send_string_attrs_request(struct sftp_conn *conn, u_int id, u_int code,
1.116     djm       231:     const void *s, u_int len, Attrib *a)
1.1       djm       232: {
1.116     djm       233:        struct sshbuf *msg;
                    234:        int r;
1.1       djm       235:
1.116     djm       236:        if ((msg = sshbuf_new()) == NULL)
1.137     djm       237:                fatal_f("sshbuf_new failed");
1.116     djm       238:        if ((r = sshbuf_put_u8(msg, code)) != 0 ||
                    239:            (r = sshbuf_put_u32(msg, id)) != 0 ||
                    240:            (r = sshbuf_put_string(msg, s, len)) != 0 ||
                    241:            (r = encode_attrib(msg, a)) != 0)
1.137     djm       242:                fatal_fr(r, "compose");
1.116     djm       243:        send_msg(conn, msg);
1.148     djm       244:        debug3("Sent message fd %d T:%u I:%u F:0x%04x M:%05o",
                    245:            conn->fd_out, code, id, a->flags, a->perm);
1.116     djm       246:        sshbuf_free(msg);
1.1       djm       247: }
                    248:
1.17      itojun    249: static u_int
1.93      djm       250: get_status(struct sftp_conn *conn, u_int expected_id)
1.1       djm       251: {
1.116     djm       252:        struct sshbuf *msg;
                    253:        u_char type;
                    254:        u_int id, status;
                    255:        int r;
1.1       djm       256:
1.116     djm       257:        if ((msg = sshbuf_new()) == NULL)
1.137     djm       258:                fatal_f("sshbuf_new failed");
1.116     djm       259:        get_msg(conn, msg);
                    260:        if ((r = sshbuf_get_u8(msg, &type)) != 0 ||
                    261:            (r = sshbuf_get_u32(msg, &id)) != 0)
1.137     djm       262:                fatal_fr(r, "compose");
1.1       djm       263:
                    264:        if (id != expected_id)
1.33      deraadt   265:                fatal("ID mismatch (%u != %u)", id, expected_id);
1.1       djm       266:        if (type != SSH2_FXP_STATUS)
1.33      deraadt   267:                fatal("Expected SSH2_FXP_STATUS(%u) packet, got %u",
1.1       djm       268:                    SSH2_FXP_STATUS, type);
                    269:
1.116     djm       270:        if ((r = sshbuf_get_u32(msg, &status)) != 0)
1.137     djm       271:                fatal_fr(r, "parse");
1.116     djm       272:        sshbuf_free(msg);
1.1       djm       273:
1.33      deraadt   274:        debug3("SSH2_FXP_STATUS %u", status);
1.1       djm       275:
1.93      djm       276:        return status;
1.1       djm       277: }
                    278:
1.116     djm       279: static u_char *
                    280: get_handle(struct sftp_conn *conn, u_int expected_id, size_t *len,
1.93      djm       281:     const char *errfmt, ...)
1.1       djm       282: {
1.116     djm       283:        struct sshbuf *msg;
                    284:        u_int id, status;
                    285:        u_char type;
                    286:        u_char *handle;
                    287:        char errmsg[256];
1.88      djm       288:        va_list args;
1.116     djm       289:        int r;
1.88      djm       290:
                    291:        va_start(args, errfmt);
                    292:        if (errfmt != NULL)
                    293:                vsnprintf(errmsg, sizeof(errmsg), errfmt, args);
                    294:        va_end(args);
1.1       djm       295:
1.116     djm       296:        if ((msg = sshbuf_new()) == NULL)
1.137     djm       297:                fatal_f("sshbuf_new failed");
1.116     djm       298:        get_msg(conn, msg);
                    299:        if ((r = sshbuf_get_u8(msg, &type)) != 0 ||
                    300:            (r = sshbuf_get_u32(msg, &id)) != 0)
1.137     djm       301:                fatal_fr(r, "parse");
1.1       djm       302:
                    303:        if (id != expected_id)
1.88      djm       304:                fatal("%s: ID mismatch (%u != %u)",
                    305:                    errfmt == NULL ? __func__ : errmsg, id, expected_id);
1.1       djm       306:        if (type == SSH2_FXP_STATUS) {
1.116     djm       307:                if ((r = sshbuf_get_u32(msg, &status)) != 0)
1.137     djm       308:                        fatal_fr(r, "parse status");
1.88      djm       309:                if (errfmt != NULL)
                    310:                        error("%s: %s", errmsg, fx2txt(status));
1.116     djm       311:                sshbuf_free(msg);
1.1       djm       312:                return(NULL);
                    313:        } else if (type != SSH2_FXP_HANDLE)
1.88      djm       314:                fatal("%s: Expected SSH2_FXP_HANDLE(%u) packet, got %u",
                    315:                    errfmt == NULL ? __func__ : errmsg, SSH2_FXP_HANDLE, type);
1.1       djm       316:
1.116     djm       317:        if ((r = sshbuf_get_string(msg, &handle, len)) != 0)
1.137     djm       318:                fatal_fr(r, "parse handle");
1.116     djm       319:        sshbuf_free(msg);
1.1       djm       320:
1.116     djm       321:        return handle;
1.1       djm       322: }
                    323:
1.158   ! jsg       324: /* XXX returning &static is error-prone. Refactor to fill *Attrib argument */
1.17      itojun    325: static Attrib *
1.93      djm       326: get_decode_stat(struct sftp_conn *conn, u_int expected_id, int quiet)
1.1       djm       327: {
1.116     djm       328:        struct sshbuf *msg;
                    329:        u_int id;
                    330:        u_char type;
                    331:        int r;
                    332:        static Attrib a;
                    333:
                    334:        if ((msg = sshbuf_new()) == NULL)
1.137     djm       335:                fatal_f("sshbuf_new failed");
1.116     djm       336:        get_msg(conn, msg);
                    337:
                    338:        if ((r = sshbuf_get_u8(msg, &type)) != 0 ||
                    339:            (r = sshbuf_get_u32(msg, &id)) != 0)
1.137     djm       340:                fatal_fr(r, "parse");
1.1       djm       341:
                    342:        if (id != expected_id)
1.33      deraadt   343:                fatal("ID mismatch (%u != %u)", id, expected_id);
1.1       djm       344:        if (type == SSH2_FXP_STATUS) {
1.116     djm       345:                u_int status;
1.1       djm       346:
1.116     djm       347:                if ((r = sshbuf_get_u32(msg, &status)) != 0)
1.137     djm       348:                        fatal_fr(r, "parse status");
1.14      djm       349:                if (quiet)
                    350:                        debug("Couldn't stat remote file: %s", fx2txt(status));
                    351:                else
                    352:                        error("Couldn't stat remote file: %s", fx2txt(status));
1.116     djm       353:                sshbuf_free(msg);
1.1       djm       354:                return(NULL);
                    355:        } else if (type != SSH2_FXP_ATTRS) {
1.33      deraadt   356:                fatal("Expected SSH2_FXP_ATTRS(%u) packet, got %u",
1.1       djm       357:                    SSH2_FXP_ATTRS, type);
                    358:        }
1.116     djm       359:        if ((r = decode_attrib(msg, &a)) != 0) {
1.137     djm       360:                error_fr(r, "decode_attrib");
1.116     djm       361:                sshbuf_free(msg);
                    362:                return NULL;
                    363:        }
1.158   ! jsg       364:        debug3("Received stat reply T:%u I:%u F:0x%04x M:%05o",
1.148     djm       365:            type, id, a.flags, a.perm);
1.116     djm       366:        sshbuf_free(msg);
1.1       djm       367:
1.116     djm       368:        return &a;
1.1       djm       369: }
                    370:
1.82      djm       371: static int
1.93      djm       372: get_decode_statvfs(struct sftp_conn *conn, struct sftp_statvfs *st,
                    373:     u_int expected_id, int quiet)
1.82      djm       374: {
1.116     djm       375:        struct sshbuf *msg;
                    376:        u_char type;
                    377:        u_int id;
                    378:        u_int64_t flag;
                    379:        int r;
1.82      djm       380:
1.116     djm       381:        if ((msg = sshbuf_new()) == NULL)
1.137     djm       382:                fatal_f("sshbuf_new failed");
1.116     djm       383:        get_msg(conn, msg);
                    384:
                    385:        if ((r = sshbuf_get_u8(msg, &type)) != 0 ||
                    386:            (r = sshbuf_get_u32(msg, &id)) != 0)
1.137     djm       387:                fatal_fr(r, "parse");
1.82      djm       388:
                    389:        debug3("Received statvfs reply T:%u I:%u", type, id);
                    390:        if (id != expected_id)
                    391:                fatal("ID mismatch (%u != %u)", id, expected_id);
                    392:        if (type == SSH2_FXP_STATUS) {
1.116     djm       393:                u_int status;
1.82      djm       394:
1.116     djm       395:                if ((r = sshbuf_get_u32(msg, &status)) != 0)
1.137     djm       396:                        fatal_fr(r, "parse status");
1.82      djm       397:                if (quiet)
                    398:                        debug("Couldn't statvfs: %s", fx2txt(status));
                    399:                else
                    400:                        error("Couldn't statvfs: %s", fx2txt(status));
1.116     djm       401:                sshbuf_free(msg);
1.82      djm       402:                return -1;
                    403:        } else if (type != SSH2_FXP_EXTENDED_REPLY) {
                    404:                fatal("Expected SSH2_FXP_EXTENDED_REPLY(%u) packet, got %u",
                    405:                    SSH2_FXP_EXTENDED_REPLY, type);
                    406:        }
                    407:
1.114     tedu      408:        memset(st, 0, sizeof(*st));
1.116     djm       409:        if ((r = sshbuf_get_u64(msg, &st->f_bsize)) != 0 ||
                    410:            (r = sshbuf_get_u64(msg, &st->f_frsize)) != 0 ||
                    411:            (r = sshbuf_get_u64(msg, &st->f_blocks)) != 0 ||
                    412:            (r = sshbuf_get_u64(msg, &st->f_bfree)) != 0 ||
                    413:            (r = sshbuf_get_u64(msg, &st->f_bavail)) != 0 ||
                    414:            (r = sshbuf_get_u64(msg, &st->f_files)) != 0 ||
                    415:            (r = sshbuf_get_u64(msg, &st->f_ffree)) != 0 ||
                    416:            (r = sshbuf_get_u64(msg, &st->f_favail)) != 0 ||
                    417:            (r = sshbuf_get_u64(msg, &st->f_fsid)) != 0 ||
                    418:            (r = sshbuf_get_u64(msg, &flag)) != 0 ||
                    419:            (r = sshbuf_get_u64(msg, &st->f_namemax)) != 0)
1.137     djm       420:                fatal_fr(r, "parse statvfs");
1.82      djm       421:
                    422:        st->f_flag = (flag & SSH2_FXE_STATVFS_ST_RDONLY) ? ST_RDONLY : 0;
                    423:        st->f_flag |= (flag & SSH2_FXE_STATVFS_ST_NOSUID) ? ST_NOSUID : 0;
                    424:
1.116     djm       425:        sshbuf_free(msg);
1.82      djm       426:
                    427:        return 0;
                    428: }
                    429:
1.23      djm       430: struct sftp_conn *
1.93      djm       431: do_init(int fd_in, int fd_out, u_int transfer_buflen, u_int num_requests,
                    432:     u_int64_t limit_kbps)
1.1       djm       433: {
1.116     djm       434:        u_char type;
                    435:        struct sshbuf *msg;
1.23      djm       436:        struct sftp_conn *ret;
1.116     djm       437:        int r;
1.1       djm       438:
1.103     djm       439:        ret = xcalloc(1, sizeof(*ret));
                    440:        ret->msg_id = 1;
1.93      djm       441:        ret->fd_in = fd_in;
                    442:        ret->fd_out = fd_out;
1.141     djm       443:        ret->download_buflen = ret->upload_buflen =
                    444:            transfer_buflen ? transfer_buflen : DEFAULT_COPY_BUFLEN;
                    445:        ret->num_requests =
                    446:            num_requests ? num_requests : DEFAULT_NUM_REQUESTS;
1.93      djm       447:        ret->exts = 0;
                    448:        ret->limit_kbps = 0;
                    449:
1.116     djm       450:        if ((msg = sshbuf_new()) == NULL)
1.137     djm       451:                fatal_f("sshbuf_new failed");
1.116     djm       452:        if ((r = sshbuf_put_u8(msg, SSH2_FXP_INIT)) != 0 ||
                    453:            (r = sshbuf_put_u32(msg, SSH2_FILEXFER_VERSION)) != 0)
1.137     djm       454:                fatal_fr(r, "parse");
                    455:
1.116     djm       456:        send_msg(ret, msg);
1.1       djm       457:
1.128     dtucker   458:        get_msg_extended(ret, msg, 1);
1.1       djm       459:
1.3       stevesk   460:        /* Expecting a VERSION reply */
1.116     djm       461:        if ((r = sshbuf_get_u8(msg, &type)) != 0)
1.137     djm       462:                fatal_fr(r, "parse type");
1.116     djm       463:        if (type != SSH2_FXP_VERSION) {
1.33      deraadt   464:                error("Invalid packet back from SSH2_FXP_INIT (type %u)",
1.1       djm       465:                    type);
1.116     djm       466:                sshbuf_free(msg);
1.119     jsg       467:                free(ret);
1.23      djm       468:                return(NULL);
1.1       djm       469:        }
1.116     djm       470:        if ((r = sshbuf_get_u32(msg, &ret->version)) != 0)
1.137     djm       471:                fatal_fr(r, "parse version");
1.1       djm       472:
1.93      djm       473:        debug2("Remote version: %u", ret->version);
1.1       djm       474:
                    475:        /* Check for extensions */
1.116     djm       476:        while (sshbuf_len(msg) > 0) {
                    477:                char *name;
                    478:                u_char *value;
                    479:                size_t vlen;
1.85      djm       480:                int known = 0;
1.1       djm       481:
1.116     djm       482:                if ((r = sshbuf_get_cstring(msg, &name, NULL)) != 0 ||
                    483:                    (r = sshbuf_get_string(msg, &value, &vlen)) != 0)
1.137     djm       484:                        fatal_fr(r, "parse extension");
1.82      djm       485:                if (strcmp(name, "posix-rename@openssh.com") == 0 &&
1.116     djm       486:                    strcmp((char *)value, "1") == 0) {
1.93      djm       487:                        ret->exts |= SFTP_EXT_POSIX_RENAME;
1.85      djm       488:                        known = 1;
                    489:                } else if (strcmp(name, "statvfs@openssh.com") == 0 &&
1.116     djm       490:                    strcmp((char *)value, "2") == 0) {
1.93      djm       491:                        ret->exts |= SFTP_EXT_STATVFS;
1.85      djm       492:                        known = 1;
1.94      djm       493:                } else if (strcmp(name, "fstatvfs@openssh.com") == 0 &&
1.116     djm       494:                    strcmp((char *)value, "2") == 0) {
1.93      djm       495:                        ret->exts |= SFTP_EXT_FSTATVFS;
1.85      djm       496:                        known = 1;
1.94      djm       497:                } else if (strcmp(name, "hardlink@openssh.com") == 0 &&
1.116     djm       498:                    strcmp((char *)value, "1") == 0) {
1.94      djm       499:                        ret->exts |= SFTP_EXT_HARDLINK;
                    500:                        known = 1;
1.116     djm       501:                } else if (strcmp(name, "fsync@openssh.com") == 0 &&
                    502:                    strcmp((char *)value, "1") == 0) {
                    503:                        ret->exts |= SFTP_EXT_FSYNC;
                    504:                        known = 1;
1.131     djm       505:                } else if (strcmp(name, "lsetstat@openssh.com") == 0 &&
                    506:                    strcmp((char *)value, "1") == 0) {
                    507:                        ret->exts |= SFTP_EXT_LSETSTAT;
                    508:                        known = 1;
1.141     djm       509:                } else if (strcmp(name, "limits@openssh.com") == 0 &&
                    510:                    strcmp((char *)value, "1") == 0) {
                    511:                        ret->exts |= SFTP_EXT_LIMITS;
                    512:                        known = 1;
1.154     djm       513:                } else if (strcmp(name, "expand-path@openssh.com") == 0 &&
                    514:                    strcmp((char *)value, "1") == 0) {
                    515:                        ret->exts |= SFTP_EXT_PATH_EXPAND;
                    516:                        known = 1;
1.85      djm       517:                }
                    518:                if (known) {
                    519:                        debug2("Server supports extension \"%s\" revision %s",
                    520:                            name, value);
                    521:                } else {
                    522:                        debug2("Unrecognised server extension \"%s\"", name);
                    523:                }
1.98      djm       524:                free(name);
                    525:                free(value);
1.1       djm       526:        }
                    527:
1.116     djm       528:        sshbuf_free(msg);
1.11      djm       529:
1.141     djm       530:        /* Query the server for its limits */
                    531:        if (ret->exts & SFTP_EXT_LIMITS) {
                    532:                struct sftp_limits limits;
                    533:                if (do_limits(ret, &limits) != 0)
                    534:                        fatal_f("limits failed");
                    535:
                    536:                /* If the caller did not specify, find a good value */
                    537:                if (transfer_buflen == 0) {
                    538:                        ret->download_buflen = limits.read_length;
                    539:                        ret->upload_buflen = limits.write_length;
                    540:                        debug("Using server download size %u", ret->download_buflen);
                    541:                        debug("Using server upload size %u", ret->upload_buflen);
                    542:                }
                    543:
                    544:                /* Use the server limit to scale down our value only */
                    545:                if (num_requests == 0 && limits.open_handles) {
                    546:                        ret->num_requests =
                    547:                            MINIMUM(DEFAULT_NUM_REQUESTS, limits.open_handles);
                    548:                        debug("Server handle limit %llu; using %u",
1.142     djm       549:                            (unsigned long long)limits.open_handles,
                    550:                            ret->num_requests);
1.141     djm       551:                }
                    552:        }
                    553:
1.23      djm       554:        /* Some filexfer v.0 servers don't support large packets */
1.141     djm       555:        if (ret->version == 0) {
                    556:                ret->download_buflen = MINIMUM(ret->download_buflen, 20480);
                    557:                ret->upload_buflen = MINIMUM(ret->upload_buflen, 20480);
                    558:        }
1.23      djm       559:
1.93      djm       560:        ret->limit_kbps = limit_kbps;
                    561:        if (ret->limit_kbps > 0) {
                    562:                bandwidth_limit_init(&ret->bwlimit_in, ret->limit_kbps,
1.141     djm       563:                    ret->download_buflen);
1.93      djm       564:                bandwidth_limit_init(&ret->bwlimit_out, ret->limit_kbps,
1.141     djm       565:                    ret->upload_buflen);
1.93      djm       566:        }
                    567:
                    568:        return ret;
1.23      djm       569: }
                    570:
                    571: u_int
                    572: sftp_proto_version(struct sftp_conn *conn)
                    573: {
1.93      djm       574:        return conn->version;
1.1       djm       575: }
                    576:
                    577: int
1.141     djm       578: do_limits(struct sftp_conn *conn, struct sftp_limits *limits)
                    579: {
                    580:        u_int id, msg_id;
                    581:        u_char type;
                    582:        struct sshbuf *msg;
                    583:        int r;
                    584:
                    585:        if ((conn->exts & SFTP_EXT_LIMITS) == 0) {
                    586:                error("Server does not support limits@openssh.com extension");
                    587:                return -1;
                    588:        }
                    589:
                    590:        if ((msg = sshbuf_new()) == NULL)
                    591:                fatal_f("sshbuf_new failed");
                    592:
                    593:        id = conn->msg_id++;
                    594:        if ((r = sshbuf_put_u8(msg, SSH2_FXP_EXTENDED)) != 0 ||
                    595:            (r = sshbuf_put_u32(msg, id)) != 0 ||
                    596:            (r = sshbuf_put_cstring(msg, "limits@openssh.com")) != 0)
                    597:                fatal_fr(r, "compose");
                    598:        send_msg(conn, msg);
                    599:        debug3("Sent message limits@openssh.com I:%u", id);
                    600:
                    601:        get_msg(conn, msg);
                    602:
                    603:        if ((r = sshbuf_get_u8(msg, &type)) != 0 ||
                    604:            (r = sshbuf_get_u32(msg, &msg_id)) != 0)
                    605:                fatal_fr(r, "parse");
                    606:
                    607:        debug3("Received limits reply T:%u I:%u", type, msg_id);
                    608:        if (id != msg_id)
                    609:                fatal("ID mismatch (%u != %u)", msg_id, id);
                    610:        if (type != SSH2_FXP_EXTENDED_REPLY) {
1.143     djm       611:                debug_f("expected SSH2_FXP_EXTENDED_REPLY(%u) packet, got %u",
1.142     djm       612:                    SSH2_FXP_EXTENDED_REPLY, type);
1.143     djm       613:                /* Disable the limits extension */
                    614:                conn->exts &= ~SFTP_EXT_LIMITS;
                    615:                sshbuf_free(msg);
                    616:                return 0;
1.141     djm       617:        }
                    618:
                    619:        memset(limits, 0, sizeof(*limits));
                    620:        if ((r = sshbuf_get_u64(msg, &limits->packet_length)) != 0 ||
                    621:            (r = sshbuf_get_u64(msg, &limits->read_length)) != 0 ||
                    622:            (r = sshbuf_get_u64(msg, &limits->write_length)) != 0 ||
                    623:            (r = sshbuf_get_u64(msg, &limits->open_handles)) != 0)
                    624:                fatal_fr(r, "parse limits");
                    625:
                    626:        sshbuf_free(msg);
                    627:
                    628:        return 0;
                    629: }
                    630:
                    631: int
1.116     djm       632: do_close(struct sftp_conn *conn, const u_char *handle, u_int handle_len)
1.1       djm       633: {
                    634:        u_int id, status;
1.116     djm       635:        struct sshbuf *msg;
                    636:        int r;
1.1       djm       637:
1.116     djm       638:        if ((msg = sshbuf_new()) == NULL)
1.137     djm       639:                fatal_f("sshbuf_new failed");
1.1       djm       640:
1.23      djm       641:        id = conn->msg_id++;
1.116     djm       642:        if ((r = sshbuf_put_u8(msg, SSH2_FXP_CLOSE)) != 0 ||
                    643:            (r = sshbuf_put_u32(msg, id)) != 0 ||
                    644:            (r = sshbuf_put_string(msg, handle, handle_len)) != 0)
1.137     djm       645:                fatal_fr(r, "parse");
1.116     djm       646:        send_msg(conn, msg);
1.33      deraadt   647:        debug3("Sent message SSH2_FXP_CLOSE I:%u", id);
1.1       djm       648:
1.93      djm       649:        status = get_status(conn, id);
1.1       djm       650:        if (status != SSH2_FX_OK)
                    651:                error("Couldn't close file: %s", fx2txt(status));
                    652:
1.116     djm       653:        sshbuf_free(msg);
1.1       djm       654:
1.116     djm       655:        return status == SSH2_FX_OK ? 0 : -1;
1.1       djm       656: }
                    657:
1.12      djm       658:
1.17      itojun    659: static int
1.116     djm       660: do_lsreaddir(struct sftp_conn *conn, const char *path, int print_flag,
1.12      djm       661:     SFTP_DIRENT ***dir)
1.1       djm       662: {
1.116     djm       663:        struct sshbuf *msg;
                    664:        u_int count, id, i, expected_id, ents = 0;
                    665:        size_t handle_len;
1.123     djm       666:        u_char type, *handle;
1.111     djm       667:        int status = SSH2_FX_FAILURE;
1.116     djm       668:        int r;
1.111     djm       669:
                    670:        if (dir)
                    671:                *dir = NULL;
1.1       djm       672:
1.23      djm       673:        id = conn->msg_id++;
1.1       djm       674:
1.116     djm       675:        if ((msg = sshbuf_new()) == NULL)
1.137     djm       676:                fatal_f("sshbuf_new failed");
1.116     djm       677:        if ((r = sshbuf_put_u8(msg, SSH2_FXP_OPENDIR)) != 0 ||
                    678:            (r = sshbuf_put_u32(msg, id)) != 0 ||
                    679:            (r = sshbuf_put_cstring(msg, path)) != 0)
1.137     djm       680:                fatal_fr(r, "compose OPENDIR");
1.116     djm       681:        send_msg(conn, msg);
1.1       djm       682:
1.93      djm       683:        handle = get_handle(conn, id, &handle_len,
1.88      djm       684:            "remote readdir(\"%s\")", path);
1.96      markus    685:        if (handle == NULL) {
1.116     djm       686:                sshbuf_free(msg);
1.93      djm       687:                return -1;
1.96      markus    688:        }
1.1       djm       689:
1.12      djm       690:        if (dir) {
                    691:                ents = 0;
1.108     djm       692:                *dir = xcalloc(1, sizeof(**dir));
1.12      djm       693:                (*dir)[0] = NULL;
                    694:        }
                    695:
1.49      djm       696:        for (; !interrupted;) {
1.23      djm       697:                id = expected_id = conn->msg_id++;
1.1       djm       698:
1.33      deraadt   699:                debug3("Sending SSH2_FXP_READDIR I:%u", id);
1.1       djm       700:
1.116     djm       701:                sshbuf_reset(msg);
                    702:                if ((r = sshbuf_put_u8(msg, SSH2_FXP_READDIR)) != 0 ||
                    703:                    (r = sshbuf_put_u32(msg, id)) != 0 ||
                    704:                    (r = sshbuf_put_string(msg, handle, handle_len)) != 0)
1.137     djm       705:                        fatal_fr(r, "compose READDIR");
1.116     djm       706:                send_msg(conn, msg);
                    707:
                    708:                sshbuf_reset(msg);
                    709:
                    710:                get_msg(conn, msg);
                    711:
                    712:                if ((r = sshbuf_get_u8(msg, &type)) != 0 ||
                    713:                    (r = sshbuf_get_u32(msg, &id)) != 0)
1.137     djm       714:                        fatal_fr(r, "parse");
1.1       djm       715:
1.33      deraadt   716:                debug3("Received reply T:%u I:%u", type, id);
1.1       djm       717:
                    718:                if (id != expected_id)
1.33      deraadt   719:                        fatal("ID mismatch (%u != %u)", id, expected_id);
1.1       djm       720:
                    721:                if (type == SSH2_FXP_STATUS) {
1.116     djm       722:                        u_int rstatus;
                    723:
                    724:                        if ((r = sshbuf_get_u32(msg, &rstatus)) != 0)
1.137     djm       725:                                fatal_fr(r, "parse status");
1.116     djm       726:                        debug3("Received SSH2_FXP_STATUS %d", rstatus);
                    727:                        if (rstatus == SSH2_FX_EOF)
1.1       djm       728:                                break;
1.116     djm       729:                        error("Couldn't read directory: %s", fx2txt(rstatus));
1.111     djm       730:                        goto out;
1.1       djm       731:                } else if (type != SSH2_FXP_NAME)
1.33      deraadt   732:                        fatal("Expected SSH2_FXP_NAME(%u) packet, got %u",
1.1       djm       733:                            SSH2_FXP_NAME, type);
                    734:
1.116     djm       735:                if ((r = sshbuf_get_u32(msg, &count)) != 0)
1.137     djm       736:                        fatal_fr(r, "parse count");
1.126     djm       737:                if (count > SSHBUF_SIZE_MAX)
1.137     djm       738:                        fatal_f("nonsensical number of entries");
1.7       markus    739:                if (count == 0)
                    740:                        break;
1.8       stevesk   741:                debug3("Received %d SSH2_FXP_NAME responses", count);
1.19      deraadt   742:                for (i = 0; i < count; i++) {
1.1       djm       743:                        char *filename, *longname;
1.116     djm       744:                        Attrib a;
1.1       djm       745:
1.116     djm       746:                        if ((r = sshbuf_get_cstring(msg, &filename,
                    747:                            NULL)) != 0 ||
                    748:                            (r = sshbuf_get_cstring(msg, &longname,
                    749:                            NULL)) != 0)
1.137     djm       750:                                fatal_fr(r, "parse filenames");
1.116     djm       751:                        if ((r = decode_attrib(msg, &a)) != 0) {
1.137     djm       752:                                error_fr(r, "couldn't decode attrib");
1.116     djm       753:                                free(filename);
                    754:                                free(longname);
1.135     djm       755:                                goto out;
1.116     djm       756:                        }
1.1       djm       757:
1.105     djm       758:                        if (print_flag)
1.124     schwarze  759:                                mprintf("%s\n", longname);
1.12      djm       760:
1.89      djm       761:                        /*
                    762:                         * Directory entries should never contain '/'
                    763:                         * These can be used to attack recursive ops
                    764:                         * (e.g. send '../../../../etc/passwd')
                    765:                         */
                    766:                        if (strchr(filename, '/') != NULL) {
                    767:                                error("Server sent suspect path \"%s\" "
                    768:                                    "during readdir of \"%s\"", filename, path);
1.111     djm       769:                        } else if (dir) {
1.118     deraadt   770:                                *dir = xreallocarray(*dir, ents + 2, sizeof(**dir));
1.108     djm       771:                                (*dir)[ents] = xcalloc(1, sizeof(***dir));
1.12      djm       772:                                (*dir)[ents]->filename = xstrdup(filename);
                    773:                                (*dir)[ents]->longname = xstrdup(longname);
1.116     djm       774:                                memcpy(&(*dir)[ents]->a, &a, sizeof(a));
1.12      djm       775:                                (*dir)[++ents] = NULL;
                    776:                        }
1.98      djm       777:                        free(filename);
                    778:                        free(longname);
1.1       djm       779:                }
                    780:        }
1.111     djm       781:        status = 0;
1.1       djm       782:
1.111     djm       783:  out:
1.116     djm       784:        sshbuf_free(msg);
1.23      djm       785:        do_close(conn, handle, handle_len);
1.98      djm       786:        free(handle);
1.1       djm       787:
1.111     djm       788:        if (status != 0 && dir != NULL) {
                    789:                /* Don't return results on error */
                    790:                free_sftp_dirents(*dir);
                    791:                *dir = NULL;
                    792:        } else if (interrupted && dir != NULL && *dir != NULL) {
                    793:                /* Don't return partial matches on interrupt */
1.49      djm       794:                free_sftp_dirents(*dir);
1.108     djm       795:                *dir = xcalloc(1, sizeof(**dir));
1.49      djm       796:                **dir = NULL;
                    797:        }
                    798:
1.129     djm       799:        return status == SSH2_FX_OK ? 0 : -1;
1.12      djm       800: }
                    801:
                    802: int
1.116     djm       803: do_readdir(struct sftp_conn *conn, const char *path, SFTP_DIRENT ***dir)
1.12      djm       804: {
1.23      djm       805:        return(do_lsreaddir(conn, path, 0, dir));
1.12      djm       806: }
                    807:
                    808: void free_sftp_dirents(SFTP_DIRENT **s)
                    809: {
                    810:        int i;
1.19      deraadt   811:
1.111     djm       812:        if (s == NULL)
                    813:                return;
1.19      deraadt   814:        for (i = 0; s[i]; i++) {
1.98      djm       815:                free(s[i]->filename);
                    816:                free(s[i]->longname);
                    817:                free(s[i]);
1.12      djm       818:        }
1.98      djm       819:        free(s);
1.12      djm       820: }
                    821:
                    822: int
1.116     djm       823: do_rm(struct sftp_conn *conn, const char *path)
1.1       djm       824: {
                    825:        u_int status, id;
                    826:
                    827:        debug2("Sending SSH2_FXP_REMOVE \"%s\"", path);
                    828:
1.23      djm       829:        id = conn->msg_id++;
1.93      djm       830:        send_string_request(conn, id, SSH2_FXP_REMOVE, path, strlen(path));
                    831:        status = get_status(conn, id);
1.1       djm       832:        if (status != SSH2_FX_OK)
                    833:                error("Couldn't delete file: %s", fx2txt(status));
1.116     djm       834:        return status == SSH2_FX_OK ? 0 : -1;
1.1       djm       835: }
                    836:
                    837: int
1.116     djm       838: do_mkdir(struct sftp_conn *conn, const char *path, Attrib *a, int print_flag)
1.1       djm       839: {
                    840:        u_int status, id;
                    841:
1.23      djm       842:        id = conn->msg_id++;
1.93      djm       843:        send_string_attrs_request(conn, id, SSH2_FXP_MKDIR, path,
1.1       djm       844:            strlen(path), a);
                    845:
1.93      djm       846:        status = get_status(conn, id);
1.105     djm       847:        if (status != SSH2_FX_OK && print_flag)
1.1       djm       848:                error("Couldn't create directory: %s", fx2txt(status));
                    849:
1.116     djm       850:        return status == SSH2_FX_OK ? 0 : -1;
1.1       djm       851: }
                    852:
                    853: int
1.116     djm       854: do_rmdir(struct sftp_conn *conn, const char *path)
1.1       djm       855: {
                    856:        u_int status, id;
                    857:
1.23      djm       858:        id = conn->msg_id++;
1.93      djm       859:        send_string_request(conn, id, SSH2_FXP_RMDIR, path,
1.23      djm       860:            strlen(path));
1.1       djm       861:
1.93      djm       862:        status = get_status(conn, id);
1.1       djm       863:        if (status != SSH2_FX_OK)
                    864:                error("Couldn't remove directory: %s", fx2txt(status));
                    865:
1.116     djm       866:        return status == SSH2_FX_OK ? 0 : -1;
1.1       djm       867: }
                    868:
                    869: Attrib *
1.116     djm       870: do_stat(struct sftp_conn *conn, const char *path, int quiet)
1.1       djm       871: {
                    872:        u_int id;
                    873:
1.23      djm       874:        id = conn->msg_id++;
                    875:
1.93      djm       876:        send_string_request(conn, id,
1.28      markus    877:            conn->version == 0 ? SSH2_FXP_STAT_VERSION_0 : SSH2_FXP_STAT,
1.23      djm       878:            path, strlen(path));
                    879:
1.93      djm       880:        return(get_decode_stat(conn, id, quiet));
1.1       djm       881: }
                    882:
                    883: Attrib *
1.116     djm       884: do_lstat(struct sftp_conn *conn, const char *path, int quiet)
1.1       djm       885: {
                    886:        u_int id;
                    887:
1.23      djm       888:        if (conn->version == 0) {
                    889:                if (quiet)
                    890:                        debug("Server version does not support lstat operation");
                    891:                else
1.43      itojun    892:                        logit("Server version does not support lstat operation");
1.30      markus    893:                return(do_stat(conn, path, quiet));
1.23      djm       894:        }
                    895:
                    896:        id = conn->msg_id++;
1.93      djm       897:        send_string_request(conn, id, SSH2_FXP_LSTAT, path,
1.23      djm       898:            strlen(path));
                    899:
1.93      djm       900:        return(get_decode_stat(conn, id, quiet));
1.1       djm       901: }
                    902:
1.78      chl       903: #ifdef notyet
1.1       djm       904: Attrib *
1.116     djm       905: do_fstat(struct sftp_conn *conn, const u_char *handle, u_int handle_len,
                    906:     int quiet)
1.1       djm       907: {
                    908:        u_int id;
                    909:
1.23      djm       910:        id = conn->msg_id++;
1.93      djm       911:        send_string_request(conn, id, SSH2_FXP_FSTAT, handle,
1.23      djm       912:            handle_len);
                    913:
1.93      djm       914:        return(get_decode_stat(conn, id, quiet));
1.1       djm       915: }
1.78      chl       916: #endif
1.1       djm       917:
                    918: int
1.116     djm       919: do_setstat(struct sftp_conn *conn, const char *path, Attrib *a)
1.1       djm       920: {
                    921:        u_int status, id;
                    922:
1.23      djm       923:        id = conn->msg_id++;
1.93      djm       924:        send_string_attrs_request(conn, id, SSH2_FXP_SETSTAT, path,
1.1       djm       925:            strlen(path), a);
                    926:
1.93      djm       927:        status = get_status(conn, id);
1.1       djm       928:        if (status != SSH2_FX_OK)
                    929:                error("Couldn't setstat on \"%s\": %s", path,
                    930:                    fx2txt(status));
                    931:
1.116     djm       932:        return status == SSH2_FX_OK ? 0 : -1;
1.1       djm       933: }
                    934:
                    935: int
1.116     djm       936: do_fsetstat(struct sftp_conn *conn, const u_char *handle, u_int handle_len,
1.1       djm       937:     Attrib *a)
                    938: {
                    939:        u_int status, id;
                    940:
1.23      djm       941:        id = conn->msg_id++;
1.93      djm       942:        send_string_attrs_request(conn, id, SSH2_FXP_FSETSTAT, handle,
1.1       djm       943:            handle_len, a);
                    944:
1.93      djm       945:        status = get_status(conn, id);
1.1       djm       946:        if (status != SSH2_FX_OK)
                    947:                error("Couldn't fsetstat: %s", fx2txt(status));
                    948:
1.116     djm       949:        return status == SSH2_FX_OK ? 0 : -1;
1.1       djm       950: }
                    951:
1.154     djm       952: /* Implements both the realpath and expand-path operations */
                    953: static char *
                    954: do_realpath_expand(struct sftp_conn *conn, const char *path, int expand)
1.1       djm       955: {
1.116     djm       956:        struct sshbuf *msg;
                    957:        u_int expected_id, count, id;
1.1       djm       958:        char *filename, *longname;
1.116     djm       959:        Attrib a;
                    960:        u_char type;
                    961:        int r;
1.154     djm       962:        const char *what = "SSH2_FXP_REALPATH";
1.1       djm       963:
1.154     djm       964:        if (expand)
                    965:                what = "expand-path@openssh.com";
1.116     djm       966:        if ((msg = sshbuf_new()) == NULL)
1.137     djm       967:                fatal_f("sshbuf_new failed");
1.1       djm       968:
1.154     djm       969:        expected_id = id = conn->msg_id++;
                    970:        if (expand) {
                    971:                if ((r = sshbuf_put_u8(msg, SSH2_FXP_EXTENDED)) != 0 ||
                    972:                    (r = sshbuf_put_u32(msg, id)) != 0 ||
                    973:                    (r = sshbuf_put_cstring(msg,
                    974:                    "expand-path@openssh.com")) != 0 ||
                    975:                    (r = sshbuf_put_cstring(msg, path)) != 0)
                    976:                        fatal_fr(r, "compose %s", what);
                    977:                send_msg(conn, msg);
                    978:        } else {
                    979:                send_string_request(conn, id, SSH2_FXP_REALPATH,
                    980:                    path, strlen(path));
                    981:        }
1.116     djm       982:        get_msg(conn, msg);
                    983:        if ((r = sshbuf_get_u8(msg, &type)) != 0 ||
                    984:            (r = sshbuf_get_u32(msg, &id)) != 0)
1.137     djm       985:                fatal_fr(r, "parse");
1.1       djm       986:
                    987:        if (id != expected_id)
1.33      deraadt   988:                fatal("ID mismatch (%u != %u)", id, expected_id);
1.1       djm       989:
                    990:        if (type == SSH2_FXP_STATUS) {
1.116     djm       991:                u_int status;
1.1       djm       992:
1.116     djm       993:                if ((r = sshbuf_get_u32(msg, &status)) != 0)
1.137     djm       994:                        fatal_fr(r, "parse status");
1.107     djm       995:                error("Couldn't canonicalize: %s", fx2txt(status));
1.116     djm       996:                sshbuf_free(msg);
1.91      djm       997:                return NULL;
1.1       djm       998:        } else if (type != SSH2_FXP_NAME)
1.33      deraadt   999:                fatal("Expected SSH2_FXP_NAME(%u) packet, got %u",
1.1       djm      1000:                    SSH2_FXP_NAME, type);
                   1001:
1.116     djm      1002:        if ((r = sshbuf_get_u32(msg, &count)) != 0)
1.137     djm      1003:                fatal_fr(r, "parse count");
1.1       djm      1004:        if (count != 1)
1.154     djm      1005:                fatal("Got multiple names (%d) from %s", count, what);
1.1       djm      1006:
1.116     djm      1007:        if ((r = sshbuf_get_cstring(msg, &filename, NULL)) != 0 ||
                   1008:            (r = sshbuf_get_cstring(msg, &longname, NULL)) != 0 ||
                   1009:            (r = decode_attrib(msg, &a)) != 0)
1.137     djm      1010:                fatal_fr(r, "parse filename/attrib");
1.1       djm      1011:
1.154     djm      1012:        debug3("%s %s -> %s", what, path, filename);
1.1       djm      1013:
1.98      djm      1014:        free(longname);
1.1       djm      1015:
1.116     djm      1016:        sshbuf_free(msg);
1.1       djm      1017:
                   1018:        return(filename);
1.154     djm      1019: }
                   1020:
                   1021: char *
                   1022: do_realpath(struct sftp_conn *conn, const char *path)
                   1023: {
                   1024:        return do_realpath_expand(conn, path, 0);
                   1025: }
                   1026:
                   1027: int
                   1028: can_expand_path(struct sftp_conn *conn)
                   1029: {
                   1030:        return (conn->exts & SFTP_EXT_PATH_EXPAND) != 0;
                   1031: }
                   1032:
                   1033: char *
                   1034: do_expand_path(struct sftp_conn *conn, const char *path)
                   1035: {
                   1036:        if (!can_expand_path(conn)) {
                   1037:                debug3_f("no server support, fallback to realpath");
                   1038:                return do_realpath_expand(conn, path, 0);
                   1039:        }
                   1040:        return do_realpath_expand(conn, path, 1);
1.1       djm      1041: }
                   1042:
                   1043: int
1.116     djm      1044: do_rename(struct sftp_conn *conn, const char *oldpath, const char *newpath,
1.102     djm      1045:     int force_legacy)
1.1       djm      1046: {
1.116     djm      1047:        struct sshbuf *msg;
1.1       djm      1048:        u_int status, id;
1.116     djm      1049:        int r, use_ext = (conn->exts & SFTP_EXT_POSIX_RENAME) && !force_legacy;
1.1       djm      1050:
1.116     djm      1051:        if ((msg = sshbuf_new()) == NULL)
1.137     djm      1052:                fatal_f("sshbuf_new failed");
1.1       djm      1053:
                   1054:        /* Send rename request */
1.23      djm      1055:        id = conn->msg_id++;
1.102     djm      1056:        if (use_ext) {
1.116     djm      1057:                if ((r = sshbuf_put_u8(msg, SSH2_FXP_EXTENDED)) != 0 ||
                   1058:                    (r = sshbuf_put_u32(msg, id)) != 0 ||
                   1059:                    (r = sshbuf_put_cstring(msg,
                   1060:                    "posix-rename@openssh.com")) != 0)
1.137     djm      1061:                        fatal_fr(r, "compose posix-rename");
1.81      djm      1062:        } else {
1.116     djm      1063:                if ((r = sshbuf_put_u8(msg, SSH2_FXP_RENAME)) != 0 ||
                   1064:                    (r = sshbuf_put_u32(msg, id)) != 0)
1.137     djm      1065:                        fatal_fr(r, "compose rename");
1.116     djm      1066:        }
                   1067:        if ((r = sshbuf_put_cstring(msg, oldpath)) != 0 ||
                   1068:            (r = sshbuf_put_cstring(msg, newpath)) != 0)
1.137     djm      1069:                fatal_fr(r, "compose paths");
1.116     djm      1070:        send_msg(conn, msg);
1.81      djm      1071:        debug3("Sent message %s \"%s\" -> \"%s\"",
1.116     djm      1072:            use_ext ? "posix-rename@openssh.com" :
                   1073:            "SSH2_FXP_RENAME", oldpath, newpath);
                   1074:        sshbuf_free(msg);
1.1       djm      1075:
1.93      djm      1076:        status = get_status(conn, id);
1.1       djm      1077:        if (status != SSH2_FX_OK)
1.23      djm      1078:                error("Couldn't rename file \"%s\" to \"%s\": %s", oldpath,
1.94      djm      1079:                    newpath, fx2txt(status));
                   1080:
1.116     djm      1081:        return status == SSH2_FX_OK ? 0 : -1;
1.94      djm      1082: }
                   1083:
                   1084: int
1.116     djm      1085: do_hardlink(struct sftp_conn *conn, const char *oldpath, const char *newpath)
1.94      djm      1086: {
1.116     djm      1087:        struct sshbuf *msg;
1.94      djm      1088:        u_int status, id;
1.116     djm      1089:        int r;
1.94      djm      1090:
                   1091:        if ((conn->exts & SFTP_EXT_HARDLINK) == 0) {
                   1092:                error("Server does not support hardlink@openssh.com extension");
                   1093:                return -1;
                   1094:        }
                   1095:
1.116     djm      1096:        if ((msg = sshbuf_new()) == NULL)
1.137     djm      1097:                fatal_f("sshbuf_new failed");
1.95      markus   1098:
                   1099:        /* Send link request */
                   1100:        id = conn->msg_id++;
1.116     djm      1101:        if ((r = sshbuf_put_u8(msg, SSH2_FXP_EXTENDED)) != 0 ||
                   1102:            (r = sshbuf_put_u32(msg, id)) != 0 ||
                   1103:            (r = sshbuf_put_cstring(msg, "hardlink@openssh.com")) != 0 ||
                   1104:            (r = sshbuf_put_cstring(msg, oldpath)) != 0 ||
                   1105:            (r = sshbuf_put_cstring(msg, newpath)) != 0)
1.137     djm      1106:                fatal_fr(r, "compose");
1.116     djm      1107:        send_msg(conn, msg);
1.94      djm      1108:        debug3("Sent message hardlink@openssh.com \"%s\" -> \"%s\"",
1.142     djm      1109:            oldpath, newpath);
1.116     djm      1110:        sshbuf_free(msg);
1.94      djm      1111:
                   1112:        status = get_status(conn, id);
                   1113:        if (status != SSH2_FX_OK)
                   1114:                error("Couldn't link file \"%s\" to \"%s\": %s", oldpath,
1.23      djm      1115:                    newpath, fx2txt(status));
1.1       djm      1116:
1.116     djm      1117:        return status == SSH2_FX_OK ? 0 : -1;
1.11      djm      1118: }
                   1119:
                   1120: int
1.116     djm      1121: do_symlink(struct sftp_conn *conn, const char *oldpath, const char *newpath)
1.11      djm      1122: {
1.116     djm      1123:        struct sshbuf *msg;
1.11      djm      1124:        u_int status, id;
1.116     djm      1125:        int r;
1.11      djm      1126:
1.23      djm      1127:        if (conn->version < 3) {
                   1128:                error("This server does not support the symlink operation");
                   1129:                return(SSH2_FX_OP_UNSUPPORTED);
                   1130:        }
                   1131:
1.116     djm      1132:        if ((msg = sshbuf_new()) == NULL)
1.137     djm      1133:                fatal_f("sshbuf_new failed");
1.11      djm      1134:
1.48      djm      1135:        /* Send symlink request */
1.23      djm      1136:        id = conn->msg_id++;
1.116     djm      1137:        if ((r = sshbuf_put_u8(msg, SSH2_FXP_SYMLINK)) != 0 ||
                   1138:            (r = sshbuf_put_u32(msg, id)) != 0 ||
                   1139:            (r = sshbuf_put_cstring(msg, oldpath)) != 0 ||
                   1140:            (r = sshbuf_put_cstring(msg, newpath)) != 0)
1.137     djm      1141:                fatal_fr(r, "compose");
1.116     djm      1142:        send_msg(conn, msg);
1.11      djm      1143:        debug3("Sent message SSH2_FXP_SYMLINK \"%s\" -> \"%s\"", oldpath,
                   1144:            newpath);
1.116     djm      1145:        sshbuf_free(msg);
1.11      djm      1146:
1.93      djm      1147:        status = get_status(conn, id);
1.11      djm      1148:        if (status != SSH2_FX_OK)
1.36      markus   1149:                error("Couldn't symlink file \"%s\" to \"%s\": %s", oldpath,
1.23      djm      1150:                    newpath, fx2txt(status));
1.11      djm      1151:
1.116     djm      1152:        return status == SSH2_FX_OK ? 0 : -1;
1.11      djm      1153: }
                   1154:
1.107     djm      1155: int
1.116     djm      1156: do_fsync(struct sftp_conn *conn, u_char *handle, u_int handle_len)
1.107     djm      1157: {
1.116     djm      1158:        struct sshbuf *msg;
1.107     djm      1159:        u_int status, id;
1.116     djm      1160:        int r;
1.107     djm      1161:
                   1162:        /* Silently return if the extension is not supported */
                   1163:        if ((conn->exts & SFTP_EXT_FSYNC) == 0)
                   1164:                return -1;
                   1165:
                   1166:        /* Send fsync request */
1.116     djm      1167:        if ((msg = sshbuf_new()) == NULL)
1.137     djm      1168:                fatal_f("sshbuf_new failed");
1.107     djm      1169:        id = conn->msg_id++;
1.116     djm      1170:        if ((r = sshbuf_put_u8(msg, SSH2_FXP_EXTENDED)) != 0 ||
                   1171:            (r = sshbuf_put_u32(msg, id)) != 0 ||
                   1172:            (r = sshbuf_put_cstring(msg, "fsync@openssh.com")) != 0 ||
                   1173:            (r = sshbuf_put_string(msg, handle, handle_len)) != 0)
1.137     djm      1174:                fatal_fr(r, "compose");
1.116     djm      1175:        send_msg(conn, msg);
1.107     djm      1176:        debug3("Sent message fsync@openssh.com I:%u", id);
1.116     djm      1177:        sshbuf_free(msg);
1.107     djm      1178:
                   1179:        status = get_status(conn, id);
                   1180:        if (status != SSH2_FX_OK)
                   1181:                error("Couldn't sync file: %s", fx2txt(status));
                   1182:
1.129     djm      1183:        return status == SSH2_FX_OK ? 0 : -1;
1.107     djm      1184: }
                   1185:
1.78      chl      1186: #ifdef notyet
1.11      djm      1187: char *
1.116     djm      1188: do_readlink(struct sftp_conn *conn, const char *path)
1.11      djm      1189: {
1.116     djm      1190:        struct sshbuf *msg;
                   1191:        u_int expected_id, count, id;
1.11      djm      1192:        char *filename, *longname;
1.116     djm      1193:        Attrib a;
                   1194:        u_char type;
                   1195:        int r;
1.11      djm      1196:
1.23      djm      1197:        expected_id = id = conn->msg_id++;
1.93      djm      1198:        send_string_request(conn, id, SSH2_FXP_READLINK, path, strlen(path));
1.11      djm      1199:
1.116     djm      1200:        if ((msg = sshbuf_new()) == NULL)
1.137     djm      1201:                fatal_f("sshbuf_new failed");
1.11      djm      1202:
1.116     djm      1203:        get_msg(conn, msg);
                   1204:        if ((r = sshbuf_get_u8(msg, &type)) != 0 ||
                   1205:            (r = sshbuf_get_u32(msg, &id)) != 0)
1.137     djm      1206:                fatal_fr(r, "parse");
1.11      djm      1207:
                   1208:        if (id != expected_id)
1.33      deraadt  1209:                fatal("ID mismatch (%u != %u)", id, expected_id);
1.11      djm      1210:
                   1211:        if (type == SSH2_FXP_STATUS) {
1.116     djm      1212:                u_int status;
1.11      djm      1213:
1.116     djm      1214:                if ((r = sshbuf_get_u32(msg, &status)) != 0)
1.137     djm      1215:                        fatal_fr(r, "parse status");
1.11      djm      1216:                error("Couldn't readlink: %s", fx2txt(status));
1.116     djm      1217:                sshbuf_free(msg);
1.11      djm      1218:                return(NULL);
                   1219:        } else if (type != SSH2_FXP_NAME)
1.33      deraadt  1220:                fatal("Expected SSH2_FXP_NAME(%u) packet, got %u",
1.11      djm      1221:                    SSH2_FXP_NAME, type);
                   1222:
1.116     djm      1223:        if ((r = sshbuf_get_u32(msg, &count)) != 0)
1.137     djm      1224:                fatal_fr(r, "parse count");
1.11      djm      1225:        if (count != 1)
                   1226:                fatal("Got multiple names (%d) from SSH_FXP_READLINK", count);
                   1227:
1.116     djm      1228:        if ((r = sshbuf_get_cstring(msg, &filename, NULL)) != 0 ||
                   1229:            (r = sshbuf_get_cstring(msg, &longname, NULL)) != 0 ||
                   1230:            (r = decode_attrib(msg, &a)) != 0)
1.137     djm      1231:                fatal_fr(r, "parse filenames/attrib");
1.11      djm      1232:
                   1233:        debug3("SSH_FXP_READLINK %s -> %s", path, filename);
                   1234:
1.98      djm      1235:        free(longname);
1.11      djm      1236:
1.116     djm      1237:        sshbuf_free(msg);
1.11      djm      1238:
1.116     djm      1239:        return filename;
1.82      djm      1240: }
                   1241: #endif
                   1242:
                   1243: int
1.84      dtucker  1244: do_statvfs(struct sftp_conn *conn, const char *path, struct sftp_statvfs *st,
1.82      djm      1245:     int quiet)
                   1246: {
1.116     djm      1247:        struct sshbuf *msg;
1.82      djm      1248:        u_int id;
1.116     djm      1249:        int r;
1.82      djm      1250:
                   1251:        if ((conn->exts & SFTP_EXT_STATVFS) == 0) {
                   1252:                error("Server does not support statvfs@openssh.com extension");
                   1253:                return -1;
                   1254:        }
                   1255:
                   1256:        id = conn->msg_id++;
                   1257:
1.116     djm      1258:        if ((msg = sshbuf_new()) == NULL)
1.137     djm      1259:                fatal_f("sshbuf_new failed");
1.116     djm      1260:        if ((r = sshbuf_put_u8(msg, SSH2_FXP_EXTENDED)) != 0 ||
                   1261:            (r = sshbuf_put_u32(msg, id)) != 0 ||
                   1262:            (r = sshbuf_put_cstring(msg, "statvfs@openssh.com")) != 0 ||
                   1263:            (r = sshbuf_put_cstring(msg, path)) != 0)
1.137     djm      1264:                fatal_fr(r, "compose");
1.116     djm      1265:        send_msg(conn, msg);
                   1266:        sshbuf_free(msg);
1.82      djm      1267:
1.93      djm      1268:        return get_decode_statvfs(conn, st, id, quiet);
1.82      djm      1269: }
                   1270:
                   1271: #ifdef notyet
                   1272: int
1.116     djm      1273: do_fstatvfs(struct sftp_conn *conn, const u_char *handle, u_int handle_len,
1.84      dtucker  1274:     struct sftp_statvfs *st, int quiet)
1.82      djm      1275: {
1.116     djm      1276:        struct sshbuf *msg;
1.82      djm      1277:        u_int id;
                   1278:
                   1279:        if ((conn->exts & SFTP_EXT_FSTATVFS) == 0) {
                   1280:                error("Server does not support fstatvfs@openssh.com extension");
                   1281:                return -1;
                   1282:        }
                   1283:
                   1284:        id = conn->msg_id++;
                   1285:
1.116     djm      1286:        if ((msg = sshbuf_new()) == NULL)
1.137     djm      1287:                fatal_f("sshbuf_new failed");
1.116     djm      1288:        if ((r = sshbuf_put_u8(msg, SSH2_FXP_EXTENDED)) != 0 ||
                   1289:            (r = sshbuf_put_u32(msg, id)) != 0 ||
                   1290:            (r = sshbuf_put_cstring(msg, "fstatvfs@openssh.com")) != 0 ||
                   1291:            (r = sshbuf_put_string(msg, handle, handle_len)) != 0)
1.137     djm      1292:                fatal_fr(r, "compose");
1.116     djm      1293:        send_msg(conn, msg);
                   1294:        sshbuf_free(msg);
1.82      djm      1295:
1.93      djm      1296:        return get_decode_statvfs(conn, st, id, quiet);
1.1       djm      1297: }
1.78      chl      1298: #endif
1.1       djm      1299:
1.131     djm      1300: int
                   1301: do_lsetstat(struct sftp_conn *conn, const char *path, Attrib *a)
                   1302: {
                   1303:        struct sshbuf *msg;
                   1304:        u_int status, id;
                   1305:        int r;
                   1306:
                   1307:        if ((conn->exts & SFTP_EXT_LSETSTAT) == 0) {
                   1308:                error("Server does not support lsetstat@openssh.com extension");
                   1309:                return -1;
                   1310:        }
                   1311:
                   1312:        id = conn->msg_id++;
                   1313:        if ((msg = sshbuf_new()) == NULL)
1.137     djm      1314:                fatal_f("sshbuf_new failed");
1.131     djm      1315:        if ((r = sshbuf_put_u8(msg, SSH2_FXP_EXTENDED)) != 0 ||
                   1316:            (r = sshbuf_put_u32(msg, id)) != 0 ||
                   1317:            (r = sshbuf_put_cstring(msg, "lsetstat@openssh.com")) != 0 ||
                   1318:            (r = sshbuf_put_cstring(msg, path)) != 0 ||
                   1319:            (r = encode_attrib(msg, a)) != 0)
1.137     djm      1320:                fatal_fr(r, "compose");
1.131     djm      1321:        send_msg(conn, msg);
                   1322:        sshbuf_free(msg);
                   1323:
                   1324:        status = get_status(conn, id);
                   1325:        if (status != SSH2_FX_OK)
                   1326:                error("Couldn't setstat on \"%s\": %s", path,
                   1327:                    fx2txt(status));
                   1328:
                   1329:        return status == SSH2_FX_OK ? 0 : -1;
                   1330: }
                   1331:
1.21      djm      1332: static void
1.93      djm      1333: send_read_request(struct sftp_conn *conn, u_int id, u_int64_t offset,
1.116     djm      1334:     u_int len, const u_char *handle, u_int handle_len)
1.21      djm      1335: {
1.116     djm      1336:        struct sshbuf *msg;
                   1337:        int r;
1.28      markus   1338:
1.116     djm      1339:        if ((msg = sshbuf_new()) == NULL)
1.137     djm      1340:                fatal_f("sshbuf_new failed");
1.116     djm      1341:        if ((r = sshbuf_put_u8(msg, SSH2_FXP_READ)) != 0 ||
                   1342:            (r = sshbuf_put_u32(msg, id)) != 0 ||
                   1343:            (r = sshbuf_put_string(msg, handle, handle_len)) != 0 ||
                   1344:            (r = sshbuf_put_u64(msg, offset)) != 0 ||
                   1345:            (r = sshbuf_put_u32(msg, len)) != 0)
1.137     djm      1346:                fatal_fr(r, "compose");
1.116     djm      1347:        send_msg(conn, msg);
                   1348:        sshbuf_free(msg);
1.28      markus   1349: }
1.21      djm      1350:
1.144     djm      1351: static int
                   1352: send_open(struct sftp_conn *conn, const char *path, const char *tag,
                   1353:     u_int openmode, Attrib *a, u_char **handlep, size_t *handle_lenp)
                   1354: {
                   1355:        Attrib junk;
                   1356:        u_char *handle;
                   1357:        size_t handle_len;
                   1358:        struct sshbuf *msg;
                   1359:        int r;
                   1360:        u_int id;
                   1361:
                   1362:        *handlep = NULL;
                   1363:        *handle_lenp = 0;
                   1364:
                   1365:        if (a == NULL) {
                   1366:                attrib_clear(&junk); /* Send empty attributes */
                   1367:                a = &junk;
                   1368:        }
                   1369:        /* Send open request */
                   1370:        if ((msg = sshbuf_new()) == NULL)
                   1371:                fatal_f("sshbuf_new failed");
                   1372:        id = conn->msg_id++;
                   1373:        if ((r = sshbuf_put_u8(msg, SSH2_FXP_OPEN)) != 0 ||
                   1374:            (r = sshbuf_put_u32(msg, id)) != 0 ||
                   1375:            (r = sshbuf_put_cstring(msg, path)) != 0 ||
                   1376:            (r = sshbuf_put_u32(msg, openmode)) != 0 ||
                   1377:            (r = encode_attrib(msg, a)) != 0)
                   1378:                fatal_fr(r, "compose %s open", tag);
                   1379:        send_msg(conn, msg);
                   1380:        sshbuf_free(msg);
                   1381:        debug3("Sent %s message SSH2_FXP_OPEN I:%u P:%s M:0x%04x",
                   1382:            tag, id, path, openmode);
                   1383:        if ((handle = get_handle(conn, id, &handle_len,
                   1384:            "%s open(\"%s\")", tag, path)) == NULL)
                   1385:                return -1;
                   1386:        /* success */
                   1387:        *handlep = handle;
                   1388:        *handle_lenp = handle_len;
                   1389:        return 0;
                   1390: }
                   1391:
1.153     djm      1392: static const char *
                   1393: progress_meter_path(const char *path)
                   1394: {
                   1395:        const char *progresspath;
                   1396:
                   1397:        if ((progresspath = strrchr(path, '/')) == NULL)
                   1398:                return path;
                   1399:        progresspath++;
                   1400:        if (*progresspath == '\0')
                   1401:                return path;
                   1402:        return progresspath;
                   1403: }
                   1404:
1.1       djm      1405: int
1.116     djm      1406: do_download(struct sftp_conn *conn, const char *remote_path,
                   1407:     const char *local_path, Attrib *a, int preserve_flag, int resume_flag,
                   1408:     int fsync_flag)
1.1       djm      1409: {
1.116     djm      1410:        struct sshbuf *msg;
                   1411:        u_char *handle;
                   1412:        int local_fd = -1, write_error;
1.134     djm      1413:        int read_error, write_errno, lmodified = 0, reordered = 0, r;
1.101     djm      1414:        u_int64_t offset = 0, size, highwater;
1.116     djm      1415:        u_int mode, id, buflen, num_req, max_req, status = SSH2_FX_OK;
1.39      fgsch    1416:        off_t progress_counter;
1.116     djm      1417:        size_t handle_len;
1.101     djm      1418:        struct stat st;
1.146     djm      1419:        struct requests requests;
1.21      djm      1420:        struct request *req;
1.116     djm      1421:        u_char type;
1.21      djm      1422:
                   1423:        TAILQ_INIT(&requests);
1.1       djm      1424:
1.89      djm      1425:        if (a == NULL && (a = do_stat(conn, remote_path, 0)) == NULL)
                   1426:                return -1;
1.1       djm      1427:
1.86      djm      1428:        /* Do not preserve set[ug]id here, as we do not preserve ownership */
1.1       djm      1429:        if (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)
1.38      djm      1430:                mode = a->perm & 0777;
1.1       djm      1431:        else
                   1432:                mode = 0666;
                   1433:
1.14      djm      1434:        if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
1.41      djm      1435:            (!S_ISREG(a->perm))) {
                   1436:                error("Cannot download non-regular file: %s", remote_path);
1.14      djm      1437:                return(-1);
                   1438:        }
                   1439:
1.21      djm      1440:        if (a->flags & SSH2_FILEXFER_ATTR_SIZE)
                   1441:                size = a->size;
                   1442:        else
                   1443:                size = 0;
                   1444:
1.141     djm      1445:        buflen = conn->download_buflen;
1.1       djm      1446:
                   1447:        /* Send open request */
1.144     djm      1448:        if (send_open(conn, remote_path, "remote", SSH2_FXF_READ, NULL,
                   1449:            &handle, &handle_len) != 0)
                   1450:                return -1;
1.1       djm      1451:
1.105     djm      1452:        local_fd = open(local_path,
                   1453:            O_WRONLY | O_CREAT | (resume_flag ? 0 : O_TRUNC), mode | S_IWUSR);
1.23      djm      1454:        if (local_fd == -1) {
                   1455:                error("Couldn't open local file \"%s\" for writing: %s",
                   1456:                    local_path, strerror(errno));
1.101     djm      1457:                goto fail;
                   1458:        }
                   1459:        offset = highwater = 0;
1.105     djm      1460:        if (resume_flag) {
1.101     djm      1461:                if (fstat(local_fd, &st) == -1) {
                   1462:                        error("Unable to stat local file \"%s\": %s",
                   1463:                            local_path, strerror(errno));
                   1464:                        goto fail;
                   1465:                }
1.113     djm      1466:                if (st.st_size < 0) {
                   1467:                        error("\"%s\" has negative size", local_path);
                   1468:                        goto fail;
                   1469:                }
                   1470:                if ((u_int64_t)st.st_size > size) {
1.101     djm      1471:                        error("Unable to resume download of \"%s\": "
                   1472:                            "local file is larger than remote", local_path);
                   1473:  fail:
                   1474:                        do_close(conn, handle, handle_len);
                   1475:                        free(handle);
1.110     djm      1476:                        if (local_fd != -1)
                   1477:                                close(local_fd);
1.101     djm      1478:                        return -1;
                   1479:                }
                   1480:                offset = highwater = st.st_size;
1.23      djm      1481:        }
                   1482:
1.1       djm      1483:        /* Read from remote and write to local */
1.101     djm      1484:        write_error = read_error = write_errno = num_req = 0;
1.21      djm      1485:        max_req = 1;
1.101     djm      1486:        progress_counter = offset;
1.39      fgsch    1487:
1.153     djm      1488:        if (showprogress && size != 0) {
                   1489:                start_progress_meter(progress_meter_path(remote_path),
                   1490:                    size, &progress_counter);
                   1491:        }
1.39      fgsch    1492:
1.144     djm      1493:        if ((msg = sshbuf_new()) == NULL)
                   1494:                fatal_f("sshbuf_new failed");
                   1495:
1.21      djm      1496:        while (num_req > 0 || max_req > 0) {
1.116     djm      1497:                u_char *data;
                   1498:                size_t len;
1.1       djm      1499:
1.49      djm      1500:                /*
1.51      deraadt  1501:                 * Simulate EOF on interrupt: stop sending new requests and
1.49      djm      1502:                 * allow outstanding requests to drain gracefully
                   1503:                 */
                   1504:                if (interrupted) {
                   1505:                        if (num_req == 0) /* If we haven't started yet... */
                   1506:                                break;
                   1507:                        max_req = 0;
                   1508:                }
                   1509:
1.21      djm      1510:                /* Send some more requests */
                   1511:                while (num_req < max_req) {
1.28      markus   1512:                        debug3("Request range %llu -> %llu (%d/%d)",
1.25      itojun   1513:                            (unsigned long long)offset,
                   1514:                            (unsigned long long)offset + buflen - 1,
                   1515:                            num_req, max_req);
1.151     djm      1516:                        req = request_enqueue(&requests, conn->msg_id++,
                   1517:                            buflen, offset);
1.21      djm      1518:                        offset += buflen;
                   1519:                        num_req++;
1.93      djm      1520:                        send_read_request(conn, req->id, req->offset,
1.21      djm      1521:                            req->len, handle, handle_len);
                   1522:                }
1.1       djm      1523:
1.116     djm      1524:                sshbuf_reset(msg);
                   1525:                get_msg(conn, msg);
                   1526:                if ((r = sshbuf_get_u8(msg, &type)) != 0 ||
                   1527:                    (r = sshbuf_get_u32(msg, &id)) != 0)
1.137     djm      1528:                        fatal_fr(r, "parse");
1.33      deraadt  1529:                debug3("Received reply T:%u I:%u R:%d", type, id, max_req);
1.21      djm      1530:
                   1531:                /* Find the request in our queue */
1.151     djm      1532:                if ((req = request_find(&requests, id)) == NULL)
1.21      djm      1533:                        fatal("Unexpected reply %u", id);
                   1534:
                   1535:                switch (type) {
                   1536:                case SSH2_FXP_STATUS:
1.116     djm      1537:                        if ((r = sshbuf_get_u32(msg, &status)) != 0)
1.137     djm      1538:                                fatal_fr(r, "parse status");
1.21      djm      1539:                        if (status != SSH2_FX_EOF)
                   1540:                                read_error = 1;
                   1541:                        max_req = 0;
                   1542:                        TAILQ_REMOVE(&requests, req, tq);
1.98      djm      1543:                        free(req);
1.21      djm      1544:                        num_req--;
                   1545:                        break;
                   1546:                case SSH2_FXP_DATA:
1.116     djm      1547:                        if ((r = sshbuf_get_string(msg, &data, &len)) != 0)
1.137     djm      1548:                                fatal_fr(r, "parse data");
1.26      itojun   1549:                        debug3("Received data %llu -> %llu",
1.28      markus   1550:                            (unsigned long long)req->offset,
1.26      itojun   1551:                            (unsigned long long)req->offset + len - 1);
1.21      djm      1552:                        if (len > req->len)
                   1553:                                fatal("Received more data than asked for "
1.116     djm      1554:                                    "%zu > %zu", len, req->len);
1.134     djm      1555:                        lmodified = 1;
1.21      djm      1556:                        if ((lseek(local_fd, req->offset, SEEK_SET) == -1 ||
1.44      deraadt  1557:                            atomicio(vwrite, local_fd, data, len) != len) &&
1.21      djm      1558:                            !write_error) {
                   1559:                                write_errno = errno;
                   1560:                                write_error = 1;
                   1561:                                max_req = 0;
                   1562:                        }
1.101     djm      1563:                        else if (!reordered && req->offset <= highwater)
                   1564:                                highwater = req->offset + len;
                   1565:                        else if (!reordered && req->offset > highwater)
                   1566:                                reordered = 1;
1.39      fgsch    1567:                        progress_counter += len;
1.98      djm      1568:                        free(data);
1.1       djm      1569:
1.21      djm      1570:                        if (len == req->len) {
                   1571:                                TAILQ_REMOVE(&requests, req, tq);
1.98      djm      1572:                                free(req);
1.21      djm      1573:                                num_req--;
                   1574:                        } else {
                   1575:                                /* Resend the request for the missing data */
                   1576:                                debug3("Short data block, re-requesting "
1.26      itojun   1577:                                    "%llu -> %llu (%2d)",
1.28      markus   1578:                                    (unsigned long long)req->offset + len,
1.27      itojun   1579:                                    (unsigned long long)req->offset +
                   1580:                                    req->len - 1, num_req);
1.23      djm      1581:                                req->id = conn->msg_id++;
1.21      djm      1582:                                req->len -= len;
                   1583:                                req->offset += len;
1.93      djm      1584:                                send_read_request(conn, req->id,
1.23      djm      1585:                                    req->offset, req->len, handle, handle_len);
1.21      djm      1586:                                /* Reduce the request size */
                   1587:                                if (len < buflen)
1.125     deraadt  1588:                                        buflen = MAXIMUM(MIN_READ_SIZE, len);
1.21      djm      1589:                        }
                   1590:                        if (max_req > 0) { /* max_req = 0 iff EOF received */
                   1591:                                if (size > 0 && offset > size) {
                   1592:                                        /* Only one request at a time
                   1593:                                         * after the expected EOF */
                   1594:                                        debug3("Finish at %llu (%2d)",
1.26      itojun   1595:                                            (unsigned long long)offset,
                   1596:                                            num_req);
1.21      djm      1597:                                        max_req = 1;
1.136     djm      1598:                                } else if (max_req < conn->num_requests) {
1.21      djm      1599:                                        ++max_req;
                   1600:                                }
1.1       djm      1601:                        }
1.21      djm      1602:                        break;
                   1603:                default:
1.33      deraadt  1604:                        fatal("Expected SSH2_FXP_DATA(%u) packet, got %u",
1.1       djm      1605:                            SSH2_FXP_DATA, type);
                   1606:                }
1.21      djm      1607:        }
1.1       djm      1608:
1.39      fgsch    1609:        if (showprogress && size)
                   1610:                stop_progress_meter();
                   1611:
1.21      djm      1612:        /* Sanity check */
                   1613:        if (TAILQ_FIRST(&requests) != NULL)
                   1614:                fatal("Transfer complete, but requests still in queue");
1.101     djm      1615:        /* Truncate at highest contiguous point to avoid holes on interrupt */
                   1616:        if (read_error || write_error || interrupted) {
1.105     djm      1617:                if (reordered && resume_flag) {
1.101     djm      1618:                        error("Unable to resume download of \"%s\": "
                   1619:                            "server reordered requests", local_path);
                   1620:                }
                   1621:                debug("truncating at %llu", (unsigned long long)highwater);
1.120     djm      1622:                if (ftruncate(local_fd, highwater) == -1)
                   1623:                        error("ftruncate \"%s\": %s", local_path,
                   1624:                            strerror(errno));
1.101     djm      1625:        }
1.21      djm      1626:        if (read_error) {
1.28      markus   1627:                error("Couldn't read from remote file \"%s\" : %s",
1.21      djm      1628:                    remote_path, fx2txt(status));
1.103     djm      1629:                status = -1;
1.23      djm      1630:                do_close(conn, handle, handle_len);
1.21      djm      1631:        } else if (write_error) {
                   1632:                error("Couldn't write to \"%s\": %s", local_path,
                   1633:                    strerror(write_errno));
1.116     djm      1634:                status = SSH2_FX_FAILURE;
1.23      djm      1635:                do_close(conn, handle, handle_len);
1.21      djm      1636:        } else {
1.116     djm      1637:                if (do_close(conn, handle, handle_len) != 0 || interrupted)
                   1638:                        status = SSH2_FX_FAILURE;
                   1639:                else
                   1640:                        status = SSH2_FX_OK;
1.21      djm      1641:                /* Override umask and utimes if asked */
1.105     djm      1642:                if (preserve_flag && fchmod(local_fd, mode) == -1)
1.21      djm      1643:                        error("Couldn't set mode on \"%s\": %s", local_path,
1.37      deraadt  1644:                            strerror(errno));
1.105     djm      1645:                if (preserve_flag &&
                   1646:                    (a->flags & SSH2_FILEXFER_ATTR_ACMODTIME)) {
1.21      djm      1647:                        struct timeval tv[2];
                   1648:                        tv[0].tv_sec = a->atime;
                   1649:                        tv[1].tv_sec = a->mtime;
                   1650:                        tv[0].tv_usec = tv[1].tv_usec = 0;
                   1651:                        if (utimes(local_path, tv) == -1)
                   1652:                                error("Can't set times on \"%s\": %s",
1.37      deraadt  1653:                                    local_path, strerror(errno));
1.1       djm      1654:                }
1.134     djm      1655:                if (resume_flag && !lmodified)
                   1656:                        logit("File \"%s\" was not modified", local_path);
                   1657:                else if (fsync_flag) {
1.107     djm      1658:                        debug("syncing \"%s\"", local_path);
                   1659:                        if (fsync(local_fd) == -1)
                   1660:                                error("Couldn't sync file \"%s\": %s",
                   1661:                                    local_path, strerror(errno));
                   1662:                }
1.10      djm      1663:        }
1.5       djm      1664:        close(local_fd);
1.116     djm      1665:        sshbuf_free(msg);
1.98      djm      1666:        free(handle);
1.23      djm      1667:
1.129     djm      1668:        return status == SSH2_FX_OK ? 0 : -1;
1.1       djm      1669: }
                   1670:
1.89      djm      1671: static int
1.116     djm      1672: download_dir_internal(struct sftp_conn *conn, const char *src, const char *dst,
                   1673:     int depth, Attrib *dirattrib, int preserve_flag, int print_flag,
1.150     djm      1674:     int resume_flag, int fsync_flag, int follow_link_flag)
1.89      djm      1675: {
                   1676:        int i, ret = 0;
                   1677:        SFTP_DIRENT **dir_entries;
1.130     djm      1678:        char *filename, *new_src = NULL, *new_dst = NULL;
1.138     dtucker  1679:        mode_t mode = 0777, tmpmode = mode;
1.89      djm      1680:
                   1681:        if (depth >= MAX_DIR_DEPTH) {
                   1682:                error("Maximum directory depth exceeded: %d levels", depth);
                   1683:                return -1;
                   1684:        }
                   1685:
                   1686:        if (dirattrib == NULL &&
                   1687:            (dirattrib = do_stat(conn, src, 1)) == NULL) {
                   1688:                error("Unable to stat remote directory \"%s\"", src);
                   1689:                return -1;
                   1690:        }
                   1691:        if (!S_ISDIR(dirattrib->perm)) {
                   1692:                error("\"%s\" is not a directory", src);
                   1693:                return -1;
                   1694:        }
1.147     djm      1695:        if (print_flag && print_flag != SFTP_PROGRESS_ONLY)
1.124     schwarze 1696:                mprintf("Retrieving %s\n", src);
1.89      djm      1697:
1.138     dtucker  1698:        if (dirattrib->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) {
1.89      djm      1699:                mode = dirattrib->perm & 01777;
1.138     dtucker  1700:                tmpmode = mode | (S_IWUSR|S_IXUSR);
                   1701:        } else {
1.89      djm      1702:                debug("Server did not send permissions for "
                   1703:                    "directory \"%s\"", dst);
                   1704:        }
                   1705:
1.138     dtucker  1706:        if (mkdir(dst, tmpmode) == -1 && errno != EEXIST) {
1.89      djm      1707:                error("mkdir %s: %s", dst, strerror(errno));
                   1708:                return -1;
                   1709:        }
                   1710:
                   1711:        if (do_readdir(conn, src, &dir_entries) == -1) {
                   1712:                error("%s: Failed to get directory contents", src);
                   1713:                return -1;
                   1714:        }
                   1715:
                   1716:        for (i = 0; dir_entries[i] != NULL && !interrupted; i++) {
1.130     djm      1717:                free(new_dst);
                   1718:                free(new_src);
                   1719:
1.89      djm      1720:                filename = dir_entries[i]->filename;
                   1721:                new_dst = path_append(dst, filename);
                   1722:                new_src = path_append(src, filename);
                   1723:
                   1724:                if (S_ISDIR(dir_entries[i]->a.perm)) {
                   1725:                        if (strcmp(filename, ".") == 0 ||
                   1726:                            strcmp(filename, "..") == 0)
                   1727:                                continue;
                   1728:                        if (download_dir_internal(conn, new_src, new_dst,
1.105     djm      1729:                            depth + 1, &(dir_entries[i]->a), preserve_flag,
1.150     djm      1730:                            print_flag, resume_flag,
                   1731:                            fsync_flag, follow_link_flag) == -1)
1.89      djm      1732:                                ret = -1;
1.150     djm      1733:                } else if (S_ISREG(dir_entries[i]->a.perm) ||
                   1734:                    (follow_link_flag && S_ISLNK(dir_entries[i]->a.perm))) {
                   1735:                        /*
                   1736:                         * If this is a symlink then don't send the link's
                   1737:                         * Attrib. do_download() will do a FXP_STAT operation
                   1738:                         * and get the link target's attributes.
                   1739:                         */
1.89      djm      1740:                        if (do_download(conn, new_src, new_dst,
1.150     djm      1741:                            S_ISLNK(dir_entries[i]->a.perm) ? NULL :
                   1742:                            &(dir_entries[i]->a),
                   1743:                            preserve_flag, resume_flag, fsync_flag) == -1) {
1.89      djm      1744:                                error("Download of file %s to %s failed",
                   1745:                                    new_src, new_dst);
                   1746:                                ret = -1;
                   1747:                        }
                   1748:                } else
                   1749:                        logit("%s: not a regular file\n", new_src);
                   1750:
                   1751:        }
1.130     djm      1752:        free(new_dst);
                   1753:        free(new_src);
1.89      djm      1754:
1.105     djm      1755:        if (preserve_flag) {
1.89      djm      1756:                if (dirattrib->flags & SSH2_FILEXFER_ATTR_ACMODTIME) {
                   1757:                        struct timeval tv[2];
                   1758:                        tv[0].tv_sec = dirattrib->atime;
                   1759:                        tv[1].tv_sec = dirattrib->mtime;
                   1760:                        tv[0].tv_usec = tv[1].tv_usec = 0;
                   1761:                        if (utimes(dst, tv) == -1)
                   1762:                                error("Can't set times on \"%s\": %s",
                   1763:                                    dst, strerror(errno));
                   1764:                } else
                   1765:                        debug("Server did not send times for directory "
                   1766:                            "\"%s\"", dst);
                   1767:        }
                   1768:
1.138     dtucker  1769:        if (mode != tmpmode && chmod(dst, mode) == -1)
                   1770:                error("Can't set final mode on \"%s\": %s", dst,
                   1771:                    strerror(errno));
                   1772:
1.89      djm      1773:        free_sftp_dirents(dir_entries);
                   1774:
                   1775:        return ret;
                   1776: }
                   1777:
                   1778: int
1.116     djm      1779: download_dir(struct sftp_conn *conn, const char *src, const char *dst,
                   1780:     Attrib *dirattrib, int preserve_flag, int print_flag, int resume_flag,
1.150     djm      1781:     int fsync_flag, int follow_link_flag)
1.89      djm      1782: {
                   1783:        char *src_canon;
                   1784:        int ret;
                   1785:
                   1786:        if ((src_canon = do_realpath(conn, src)) == NULL) {
1.107     djm      1787:                error("Unable to canonicalize path \"%s\"", src);
1.89      djm      1788:                return -1;
                   1789:        }
                   1790:
1.105     djm      1791:        ret = download_dir_internal(conn, src_canon, dst, 0,
1.150     djm      1792:            dirattrib, preserve_flag, print_flag, resume_flag, fsync_flag,
                   1793:            follow_link_flag);
1.98      djm      1794:        free(src_canon);
1.89      djm      1795:        return ret;
                   1796: }
                   1797:
1.1       djm      1798: int
1.116     djm      1799: do_upload(struct sftp_conn *conn, const char *local_path,
                   1800:     const char *remote_path, int preserve_flag, int resume, int fsync_flag)
1.1       djm      1801: {
1.116     djm      1802:        int r, local_fd;
                   1803:        u_int status = SSH2_FX_OK;
                   1804:        u_int id;
                   1805:        u_char type;
1.100     dtucker  1806:        off_t offset, progress_counter;
1.116     djm      1807:        u_char *handle, *data;
                   1808:        struct sshbuf *msg;
1.1       djm      1809:        struct stat sb;
1.115     logan    1810:        Attrib a, *c = NULL;
1.21      djm      1811:        u_int32_t startid;
                   1812:        u_int32_t ackid;
1.151     djm      1813:        struct request *ack = NULL;
                   1814:        struct requests acks;
1.116     djm      1815:        size_t handle_len;
1.22      djm      1816:
                   1817:        TAILQ_INIT(&acks);
1.1       djm      1818:
1.156     deraadt  1819:        if ((local_fd = open(local_path, O_RDONLY)) == -1) {
1.1       djm      1820:                error("Couldn't open local file \"%s\" for reading: %s",
                   1821:                    local_path, strerror(errno));
                   1822:                return(-1);
                   1823:        }
                   1824:        if (fstat(local_fd, &sb) == -1) {
                   1825:                error("Couldn't fstat local file \"%s\": %s",
                   1826:                    local_path, strerror(errno));
1.41      djm      1827:                close(local_fd);
                   1828:                return(-1);
                   1829:        }
                   1830:        if (!S_ISREG(sb.st_mode)) {
                   1831:                error("%s is not a regular file", local_path);
1.1       djm      1832:                close(local_fd);
                   1833:                return(-1);
                   1834:        }
                   1835:        stat_to_attrib(&sb, &a);
                   1836:
                   1837:        a.flags &= ~SSH2_FILEXFER_ATTR_SIZE;
                   1838:        a.flags &= ~SSH2_FILEXFER_ATTR_UIDGID;
                   1839:        a.perm &= 0777;
1.105     djm      1840:        if (!preserve_flag)
1.1       djm      1841:                a.flags &= ~SSH2_FILEXFER_ATTR_ACMODTIME;
                   1842:
1.115     logan    1843:        if (resume) {
                   1844:                /* Get remote file size if it exists */
                   1845:                if ((c = do_stat(conn, remote_path, 0)) == NULL) {
1.122     djm      1846:                        close(local_fd);
1.115     logan    1847:                        return -1;
                   1848:                }
                   1849:
                   1850:                if ((off_t)c->size >= sb.st_size) {
                   1851:                        error("destination file bigger or same size as "
1.142     djm      1852:                            "source file");
1.115     logan    1853:                        close(local_fd);
                   1854:                        return -1;
                   1855:                }
                   1856:
                   1857:                if (lseek(local_fd, (off_t)c->size, SEEK_SET) == -1) {
                   1858:                        close(local_fd);
                   1859:                        return -1;
                   1860:                }
                   1861:        }
                   1862:
1.1       djm      1863:        /* Send open request */
1.144     djm      1864:        if (send_open(conn, remote_path, "dest", SSH2_FXF_WRITE|SSH2_FXF_CREAT|
                   1865:            (resume ? SSH2_FXF_APPEND : SSH2_FXF_TRUNC),
                   1866:            &a, &handle, &handle_len) != 0) {
1.1       djm      1867:                close(local_fd);
1.80      djm      1868:                return -1;
1.1       djm      1869:        }
                   1870:
1.144     djm      1871:        id = conn->msg_id;
1.21      djm      1872:        startid = ackid = id + 1;
1.141     djm      1873:        data = xmalloc(conn->upload_buflen);
1.20      djm      1874:
1.1       djm      1875:        /* Read from local and write to remote */
1.115     logan    1876:        offset = progress_counter = (resume ? c->size : 0);
1.153     djm      1877:        if (showprogress) {
                   1878:                start_progress_meter(progress_meter_path(local_path),
                   1879:                    sb.st_size, &progress_counter);
                   1880:        }
1.39      fgsch    1881:
1.144     djm      1882:        if ((msg = sshbuf_new()) == NULL)
                   1883:                fatal_f("sshbuf_new failed");
1.19      deraadt  1884:        for (;;) {
1.1       djm      1885:                int len;
                   1886:
                   1887:                /*
1.51      deraadt  1888:                 * Can't use atomicio here because it returns 0 on EOF,
1.49      djm      1889:                 * thus losing the last block of the file.
1.51      deraadt  1890:                 * Simulate an EOF on interrupt, allowing ACKs from the
1.49      djm      1891:                 * server to drain.
1.1       djm      1892:                 */
1.80      djm      1893:                if (interrupted || status != SSH2_FX_OK)
1.49      djm      1894:                        len = 0;
                   1895:                else do
1.141     djm      1896:                        len = read(local_fd, data, conn->upload_buflen);
1.1       djm      1897:                while ((len == -1) && (errno == EINTR || errno == EAGAIN));
                   1898:
                   1899:                if (len == -1)
                   1900:                        fatal("Couldn't read from \"%s\": %s", local_path,
                   1901:                            strerror(errno));
1.21      djm      1902:
                   1903:                if (len != 0) {
1.151     djm      1904:                        ack = request_enqueue(&acks, ++id, len, offset);
1.116     djm      1905:                        sshbuf_reset(msg);
                   1906:                        if ((r = sshbuf_put_u8(msg, SSH2_FXP_WRITE)) != 0 ||
                   1907:                            (r = sshbuf_put_u32(msg, ack->id)) != 0 ||
                   1908:                            (r = sshbuf_put_string(msg, handle,
                   1909:                            handle_len)) != 0 ||
                   1910:                            (r = sshbuf_put_u64(msg, offset)) != 0 ||
                   1911:                            (r = sshbuf_put_string(msg, data, len)) != 0)
1.137     djm      1912:                                fatal_fr(r, "compose");
1.116     djm      1913:                        send_msg(conn, msg);
1.33      deraadt  1914:                        debug3("Sent message SSH2_FXP_WRITE I:%u O:%llu S:%u",
1.37      deraadt  1915:                            id, (unsigned long long)offset, len);
1.22      djm      1916:                } else if (TAILQ_FIRST(&acks) == NULL)
1.1       djm      1917:                        break;
                   1918:
1.22      djm      1919:                if (ack == NULL)
                   1920:                        fatal("Unexpected ACK %u", id);
                   1921:
1.28      markus   1922:                if (id == startid || len == 0 ||
1.23      djm      1923:                    id - ackid >= conn->num_requests) {
1.116     djm      1924:                        u_int rid;
1.31      djm      1925:
1.116     djm      1926:                        sshbuf_reset(msg);
                   1927:                        get_msg(conn, msg);
                   1928:                        if ((r = sshbuf_get_u8(msg, &type)) != 0 ||
                   1929:                            (r = sshbuf_get_u32(msg, &rid)) != 0)
1.137     djm      1930:                                fatal_fr(r, "parse");
1.22      djm      1931:
                   1932:                        if (type != SSH2_FXP_STATUS)
                   1933:                                fatal("Expected SSH2_FXP_STATUS(%d) packet, "
                   1934:                                    "got %d", SSH2_FXP_STATUS, type);
                   1935:
1.116     djm      1936:                        if ((r = sshbuf_get_u32(msg, &status)) != 0)
1.137     djm      1937:                                fatal_fr(r, "parse status");
1.116     djm      1938:                        debug3("SSH2_FXP_STATUS %u", status);
1.22      djm      1939:
                   1940:                        /* Find the request in our queue */
1.151     djm      1941:                        if ((ack = request_find(&acks, rid)) == NULL)
1.116     djm      1942:                                fatal("Can't find request for ID %u", rid);
1.22      djm      1943:                        TAILQ_REMOVE(&acks, ack, tq);
1.151     djm      1944:                        debug3("In write loop, ack for %u %zu bytes at %lld",
                   1945:                            ack->id, ack->len, (unsigned long long)ack->offset);
1.21      djm      1946:                        ++ackid;
1.100     dtucker  1947:                        progress_counter += ack->len;
1.98      djm      1948:                        free(ack);
1.1       djm      1949:                }
                   1950:                offset += len;
1.77      djm      1951:                if (offset < 0)
1.137     djm      1952:                        fatal_f("offset < 0");
1.1       djm      1953:        }
1.116     djm      1954:        sshbuf_free(msg);
1.80      djm      1955:
1.39      fgsch    1956:        if (showprogress)
                   1957:                stop_progress_meter();
1.98      djm      1958:        free(data);
1.1       djm      1959:
1.80      djm      1960:        if (status != SSH2_FX_OK) {
                   1961:                error("Couldn't write to remote file \"%s\": %s",
                   1962:                    remote_path, fx2txt(status));
1.116     djm      1963:                status = SSH2_FX_FAILURE;
1.80      djm      1964:        }
                   1965:
1.1       djm      1966:        if (close(local_fd) == -1) {
                   1967:                error("Couldn't close local file \"%s\": %s", local_path,
                   1968:                    strerror(errno));
1.116     djm      1969:                status = SSH2_FX_FAILURE;
1.1       djm      1970:        }
                   1971:
1.10      djm      1972:        /* Override umask and utimes if asked */
1.105     djm      1973:        if (preserve_flag)
1.23      djm      1974:                do_fsetstat(conn, handle, handle_len, &a);
1.10      djm      1975:
1.107     djm      1976:        if (fsync_flag)
                   1977:                (void)do_fsync(conn, handle, handle_len);
                   1978:
1.121     djm      1979:        if (do_close(conn, handle, handle_len) != 0)
1.116     djm      1980:                status = SSH2_FX_FAILURE;
                   1981:
1.98      djm      1982:        free(handle);
1.5       djm      1983:
1.116     djm      1984:        return status == SSH2_FX_OK ? 0 : -1;
1.1       djm      1985: }
1.89      djm      1986:
                   1987: static int
1.116     djm      1988: upload_dir_internal(struct sftp_conn *conn, const char *src, const char *dst,
1.150     djm      1989:     int depth, int preserve_flag, int print_flag, int resume, int fsync_flag,
                   1990:     int follow_link_flag)
1.89      djm      1991: {
1.116     djm      1992:        int ret = 0;
1.89      djm      1993:        DIR *dirp;
                   1994:        struct dirent *dp;
1.130     djm      1995:        char *filename, *new_src = NULL, *new_dst = NULL;
1.89      djm      1996:        struct stat sb;
1.121     djm      1997:        Attrib a, *dirattrib;
1.138     dtucker  1998:        u_int32_t saved_perm;
1.89      djm      1999:
                   2000:        if (depth >= MAX_DIR_DEPTH) {
                   2001:                error("Maximum directory depth exceeded: %d levels", depth);
                   2002:                return -1;
                   2003:        }
                   2004:
                   2005:        if (stat(src, &sb) == -1) {
                   2006:                error("Couldn't stat directory \"%s\": %s",
                   2007:                    src, strerror(errno));
                   2008:                return -1;
                   2009:        }
                   2010:        if (!S_ISDIR(sb.st_mode)) {
                   2011:                error("\"%s\" is not a directory", src);
                   2012:                return -1;
                   2013:        }
1.147     djm      2014:        if (print_flag && print_flag != SFTP_PROGRESS_ONLY)
1.124     schwarze 2015:                mprintf("Entering %s\n", src);
1.89      djm      2016:
                   2017:        stat_to_attrib(&sb, &a);
                   2018:        a.flags &= ~SSH2_FILEXFER_ATTR_SIZE;
                   2019:        a.flags &= ~SSH2_FILEXFER_ATTR_UIDGID;
                   2020:        a.perm &= 01777;
1.105     djm      2021:        if (!preserve_flag)
1.89      djm      2022:                a.flags &= ~SSH2_FILEXFER_ATTR_ACMODTIME;
1.101     djm      2023:
1.89      djm      2024:        /*
1.121     djm      2025:         * sftp lacks a portable status value to match errno EEXIST,
                   2026:         * so if we get a failure back then we must check whether
1.138     dtucker  2027:         * the path already existed and is a directory.  Ensure we can
                   2028:         * write to the directory we create for the duration of the transfer.
1.89      djm      2029:         */
1.138     dtucker  2030:        saved_perm = a.perm;
                   2031:        a.perm |= (S_IWUSR|S_IXUSR);
1.121     djm      2032:        if (do_mkdir(conn, dst, &a, 0) != 0) {
                   2033:                if ((dirattrib = do_stat(conn, dst, 0)) == NULL)
1.89      djm      2034:                        return -1;
1.121     djm      2035:                if (!S_ISDIR(dirattrib->perm)) {
                   2036:                        error("\"%s\" exists but is not a directory", dst);
1.89      djm      2037:                        return -1;
1.121     djm      2038:                }
1.89      djm      2039:        }
1.138     dtucker  2040:        a.perm = saved_perm;
1.89      djm      2041:
                   2042:        if ((dirp = opendir(src)) == NULL) {
                   2043:                error("Failed to open dir \"%s\": %s", src, strerror(errno));
                   2044:                return -1;
                   2045:        }
1.101     djm      2046:
1.89      djm      2047:        while (((dp = readdir(dirp)) != NULL) && !interrupted) {
                   2048:                if (dp->d_ino == 0)
                   2049:                        continue;
1.130     djm      2050:                free(new_dst);
                   2051:                free(new_src);
1.89      djm      2052:                filename = dp->d_name;
                   2053:                new_dst = path_append(dst, filename);
                   2054:                new_src = path_append(src, filename);
                   2055:
1.90      dtucker  2056:                if (lstat(new_src, &sb) == -1) {
                   2057:                        logit("%s: lstat failed: %s", filename,
                   2058:                            strerror(errno));
                   2059:                        ret = -1;
                   2060:                } else if (S_ISDIR(sb.st_mode)) {
1.89      djm      2061:                        if (strcmp(filename, ".") == 0 ||
                   2062:                            strcmp(filename, "..") == 0)
                   2063:                                continue;
                   2064:
                   2065:                        if (upload_dir_internal(conn, new_src, new_dst,
1.115     logan    2066:                            depth + 1, preserve_flag, print_flag, resume,
1.150     djm      2067:                            fsync_flag, follow_link_flag) == -1)
1.89      djm      2068:                                ret = -1;
1.150     djm      2069:                } else if (S_ISREG(sb.st_mode) ||
                   2070:                    (follow_link_flag && S_ISLNK(sb.st_mode))) {
1.105     djm      2071:                        if (do_upload(conn, new_src, new_dst,
1.115     logan    2072:                            preserve_flag, resume, fsync_flag) == -1) {
1.89      djm      2073:                                error("Uploading of file %s to %s failed!",
                   2074:                                    new_src, new_dst);
                   2075:                                ret = -1;
                   2076:                        }
                   2077:                } else
                   2078:                        logit("%s: not a regular file\n", filename);
                   2079:        }
1.130     djm      2080:        free(new_dst);
                   2081:        free(new_src);
1.89      djm      2082:
                   2083:        do_setstat(conn, dst, &a);
                   2084:
                   2085:        (void) closedir(dirp);
                   2086:        return ret;
                   2087: }
                   2088:
                   2089: int
1.116     djm      2090: upload_dir(struct sftp_conn *conn, const char *src, const char *dst,
1.150     djm      2091:     int preserve_flag, int print_flag, int resume, int fsync_flag,
                   2092:     int follow_link_flag)
1.89      djm      2093: {
                   2094:        char *dst_canon;
                   2095:        int ret;
                   2096:
                   2097:        if ((dst_canon = do_realpath(conn, dst)) == NULL) {
1.107     djm      2098:                error("Unable to canonicalize path \"%s\"", dst);
1.89      djm      2099:                return -1;
                   2100:        }
                   2101:
1.106     djm      2102:        ret = upload_dir_internal(conn, src, dst_canon, 0, preserve_flag,
1.150     djm      2103:            print_flag, resume, fsync_flag, follow_link_flag);
1.107     djm      2104:
1.98      djm      2105:        free(dst_canon);
1.145     djm      2106:        return ret;
                   2107: }
                   2108:
                   2109: static void
                   2110: handle_dest_replies(struct sftp_conn *to, const char *to_path, int synchronous,
                   2111:     u_int *nreqsp, u_int *write_errorp)
                   2112: {
                   2113:        struct sshbuf *msg;
                   2114:        u_char type;
                   2115:        u_int id, status;
                   2116:        int r;
                   2117:        struct pollfd pfd;
                   2118:
                   2119:        if ((msg = sshbuf_new()) == NULL)
                   2120:                fatal_f("sshbuf_new failed");
                   2121:
                   2122:        /* Try to eat replies from the upload side */
                   2123:        while (*nreqsp > 0) {
                   2124:                debug3_f("%u outstanding replies", *nreqsp);
                   2125:                if (!synchronous) {
                   2126:                        /* Bail out if no data is ready to be read */
                   2127:                        pfd.fd = to->fd_in;
                   2128:                        pfd.events = POLLIN;
                   2129:                        if ((r = poll(&pfd, 1, 0)) == -1) {
                   2130:                                if (errno == EINTR)
                   2131:                                        break;
                   2132:                                fatal_f("poll: %s", strerror(errno));
                   2133:                        } else if (r == 0)
                   2134:                                break; /* fd not ready */
                   2135:                }
                   2136:                sshbuf_reset(msg);
                   2137:                get_msg(to, msg);
                   2138:
                   2139:                if ((r = sshbuf_get_u8(msg, &type)) != 0 ||
                   2140:                    (r = sshbuf_get_u32(msg, &id)) != 0)
                   2141:                        fatal_fr(r, "dest parse");
                   2142:                debug3("Received dest reply T:%u I:%u R:%u", type, id, *nreqsp);
                   2143:                if (type != SSH2_FXP_STATUS) {
                   2144:                        fatal_f("Expected SSH2_FXP_STATUS(%d) packet, got %d",
                   2145:                            SSH2_FXP_STATUS, type);
                   2146:                }
                   2147:                if ((r = sshbuf_get_u32(msg, &status)) != 0)
                   2148:                        fatal_fr(r, "parse dest status");
                   2149:                debug3("dest SSH2_FXP_STATUS %u", status);
                   2150:                if (status != SSH2_FX_OK) {
                   2151:                        /* record first error */
                   2152:                        if (*write_errorp == 0)
                   2153:                                *write_errorp = status;
                   2154:                }
                   2155:                /*
                   2156:                 * XXX this doesn't do full reply matching like do_upload and
                   2157:                 * so cannot gracefully truncate terminated uploads at a
                   2158:                 * high-water mark. ATM the only caller of this function (scp)
                   2159:                 * doesn't support transfer resumption, so this doesn't matter
                   2160:                 * a whole lot.
                   2161:                 *
                   2162:                 * To be safe, do_crossload truncates the destination file to
                   2163:                 * zero length on upload failure, since we can't trust the
                   2164:                 * server not to have reordered replies that could have
                   2165:                 * inserted holes where none existed in the source file.
                   2166:                 *
                   2167:                 * XXX we could get a more accutate progress bar if we updated
                   2168:                 * the counter based on the reply from the destination...
                   2169:                 */
                   2170:                (*nreqsp)--;
                   2171:        }
                   2172:        debug3_f("done: %u outstanding replies", *nreqsp);
1.157     dtucker  2173:        sshbuf_free(msg);
1.145     djm      2174: }
                   2175:
                   2176: int
                   2177: do_crossload(struct sftp_conn *from, struct sftp_conn *to,
                   2178:     const char *from_path, const char *to_path,
                   2179:     Attrib *a, int preserve_flag)
                   2180: {
                   2181:        struct sshbuf *msg;
1.152     djm      2182:        int write_error, read_error, r;
1.145     djm      2183:        u_int64_t offset = 0, size;
                   2184:        u_int id, buflen, num_req, max_req, status = SSH2_FX_OK;
                   2185:        u_int num_upload_req;
                   2186:        off_t progress_counter;
                   2187:        u_char *from_handle, *to_handle;
                   2188:        size_t from_handle_len, to_handle_len;
1.146     djm      2189:        struct requests requests;
1.145     djm      2190:        struct request *req;
                   2191:        u_char type;
                   2192:
                   2193:        TAILQ_INIT(&requests);
                   2194:
                   2195:        if (a == NULL && (a = do_stat(from, from_path, 0)) == NULL)
                   2196:                return -1;
                   2197:
                   2198:        if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
                   2199:            (!S_ISREG(a->perm))) {
                   2200:                error("Cannot download non-regular file: %s", from_path);
                   2201:                return(-1);
                   2202:        }
                   2203:        if (a->flags & SSH2_FILEXFER_ATTR_SIZE)
                   2204:                size = a->size;
                   2205:        else
                   2206:                size = 0;
                   2207:
                   2208:        buflen = from->download_buflen;
                   2209:        if (buflen > to->upload_buflen)
                   2210:                buflen = to->upload_buflen;
                   2211:
                   2212:        /* Send open request to read side */
                   2213:        if (send_open(from, from_path, "origin", SSH2_FXF_READ, NULL,
                   2214:            &from_handle, &from_handle_len) != 0)
                   2215:                return -1;
                   2216:
                   2217:        /* Send open request to write side */
                   2218:        a->flags &= ~SSH2_FILEXFER_ATTR_SIZE;
                   2219:        a->flags &= ~SSH2_FILEXFER_ATTR_UIDGID;
                   2220:        a->perm &= 0777;
                   2221:        if (!preserve_flag)
                   2222:                a->flags &= ~SSH2_FILEXFER_ATTR_ACMODTIME;
                   2223:        if (send_open(to, to_path, "dest",
                   2224:            SSH2_FXF_WRITE|SSH2_FXF_CREAT|SSH2_FXF_TRUNC, a,
                   2225:            &to_handle, &to_handle_len) != 0) {
                   2226:                do_close(from, from_handle, from_handle_len);
                   2227:                return -1;
                   2228:        }
                   2229:
                   2230:        /* Read from remote "from" and write to remote "to" */
                   2231:        offset = 0;
                   2232:        write_error = read_error = num_req = num_upload_req = 0;
                   2233:        max_req = 1;
                   2234:        progress_counter = 0;
                   2235:
1.153     djm      2236:        if (showprogress && size != 0) {
                   2237:                start_progress_meter(progress_meter_path(from_path),
                   2238:                    size, &progress_counter);
                   2239:        }
1.145     djm      2240:        if ((msg = sshbuf_new()) == NULL)
                   2241:                fatal_f("sshbuf_new failed");
                   2242:        while (num_req > 0 || max_req > 0) {
                   2243:                u_char *data;
                   2244:                size_t len;
                   2245:
                   2246:                /*
                   2247:                 * Simulate EOF on interrupt: stop sending new requests and
                   2248:                 * allow outstanding requests to drain gracefully
                   2249:                 */
                   2250:                if (interrupted) {
                   2251:                        if (num_req == 0) /* If we haven't started yet... */
                   2252:                                break;
                   2253:                        max_req = 0;
                   2254:                }
                   2255:
                   2256:                /* Send some more requests */
                   2257:                while (num_req < max_req) {
                   2258:                        debug3("Request range %llu -> %llu (%d/%d)",
                   2259:                            (unsigned long long)offset,
                   2260:                            (unsigned long long)offset + buflen - 1,
                   2261:                            num_req, max_req);
1.151     djm      2262:                        req = request_enqueue(&requests, from->msg_id++,
                   2263:                            buflen, offset);
1.145     djm      2264:                        offset += buflen;
                   2265:                        num_req++;
                   2266:                        send_read_request(from, req->id, req->offset,
                   2267:                            req->len, from_handle, from_handle_len);
                   2268:                }
                   2269:
                   2270:                /* Try to eat replies from the upload side (nonblocking) */
                   2271:                handle_dest_replies(to, to_path, 0,
                   2272:                    &num_upload_req, &write_error);
                   2273:
                   2274:                sshbuf_reset(msg);
                   2275:                get_msg(from, msg);
                   2276:                if ((r = sshbuf_get_u8(msg, &type)) != 0 ||
                   2277:                    (r = sshbuf_get_u32(msg, &id)) != 0)
                   2278:                        fatal_fr(r, "parse");
                   2279:                debug3("Received origin reply T:%u I:%u R:%d",
                   2280:                    type, id, max_req);
                   2281:
                   2282:                /* Find the request in our queue */
1.151     djm      2283:                if ((req = request_find(&requests, id)) == NULL)
1.145     djm      2284:                        fatal("Unexpected reply %u", id);
                   2285:
                   2286:                switch (type) {
                   2287:                case SSH2_FXP_STATUS:
                   2288:                        if ((r = sshbuf_get_u32(msg, &status)) != 0)
                   2289:                                fatal_fr(r, "parse status");
                   2290:                        if (status != SSH2_FX_EOF)
                   2291:                                read_error = 1;
                   2292:                        max_req = 0;
                   2293:                        TAILQ_REMOVE(&requests, req, tq);
                   2294:                        free(req);
                   2295:                        num_req--;
                   2296:                        break;
                   2297:                case SSH2_FXP_DATA:
                   2298:                        if ((r = sshbuf_get_string(msg, &data, &len)) != 0)
                   2299:                                fatal_fr(r, "parse data");
                   2300:                        debug3("Received data %llu -> %llu",
                   2301:                            (unsigned long long)req->offset,
                   2302:                            (unsigned long long)req->offset + len - 1);
                   2303:                        if (len > req->len)
                   2304:                                fatal("Received more data than asked for "
                   2305:                                    "%zu > %zu", len, req->len);
                   2306:
                   2307:                        /* Write this chunk out to the destination */
                   2308:                        sshbuf_reset(msg);
                   2309:                        if ((r = sshbuf_put_u8(msg, SSH2_FXP_WRITE)) != 0 ||
                   2310:                            (r = sshbuf_put_u32(msg, to->msg_id++)) != 0 ||
                   2311:                            (r = sshbuf_put_string(msg, to_handle,
                   2312:                            to_handle_len)) != 0 ||
                   2313:                            (r = sshbuf_put_u64(msg, req->offset)) != 0 ||
                   2314:                            (r = sshbuf_put_string(msg, data, len)) != 0)
                   2315:                                fatal_fr(r, "compose write");
                   2316:                        send_msg(to, msg);
                   2317:                        debug3("Sent message SSH2_FXP_WRITE I:%u O:%llu S:%zu",
                   2318:                            id, (unsigned long long)offset, len);
                   2319:                        num_upload_req++;
                   2320:                        progress_counter += len;
                   2321:                        free(data);
                   2322:
                   2323:                        if (len == req->len) {
                   2324:                                TAILQ_REMOVE(&requests, req, tq);
                   2325:                                free(req);
                   2326:                                num_req--;
                   2327:                        } else {
                   2328:                                /* Resend the request for the missing data */
                   2329:                                debug3("Short data block, re-requesting "
                   2330:                                    "%llu -> %llu (%2d)",
                   2331:                                    (unsigned long long)req->offset + len,
                   2332:                                    (unsigned long long)req->offset +
                   2333:                                    req->len - 1, num_req);
                   2334:                                req->id = from->msg_id++;
                   2335:                                req->len -= len;
                   2336:                                req->offset += len;
                   2337:                                send_read_request(from, req->id,
                   2338:                                    req->offset, req->len,
                   2339:                                    from_handle, from_handle_len);
                   2340:                                /* Reduce the request size */
                   2341:                                if (len < buflen)
                   2342:                                        buflen = MAXIMUM(MIN_READ_SIZE, len);
                   2343:                        }
                   2344:                        if (max_req > 0) { /* max_req = 0 iff EOF received */
                   2345:                                if (size > 0 && offset > size) {
                   2346:                                        /* Only one request at a time
                   2347:                                         * after the expected EOF */
                   2348:                                        debug3("Finish at %llu (%2d)",
                   2349:                                            (unsigned long long)offset,
                   2350:                                            num_req);
                   2351:                                        max_req = 1;
                   2352:                                } else if (max_req < from->num_requests) {
                   2353:                                        ++max_req;
                   2354:                                }
                   2355:                        }
                   2356:                        break;
                   2357:                default:
                   2358:                        fatal("Expected SSH2_FXP_DATA(%u) packet, got %u",
                   2359:                            SSH2_FXP_DATA, type);
                   2360:                }
                   2361:        }
                   2362:
                   2363:        if (showprogress && size)
                   2364:                stop_progress_meter();
                   2365:
                   2366:        /* Drain replies from the server (blocking) */
                   2367:        debug3_f("waiting for %u replies from destination", num_upload_req);
                   2368:        handle_dest_replies(to, to_path, 1, &num_upload_req, &write_error);
                   2369:
                   2370:        /* Sanity check */
                   2371:        if (TAILQ_FIRST(&requests) != NULL)
                   2372:                fatal("Transfer complete, but requests still in queue");
                   2373:        /* Truncate at 0 length on interrupt or error to avoid holes at dest */
                   2374:        if (read_error || write_error || interrupted) {
                   2375:                debug("truncating \"%s\" at 0", to_path);
                   2376:                do_close(to, to_handle, to_handle_len);
                   2377:                free(to_handle);
                   2378:                if (send_open(to, to_path, "dest",
                   2379:                    SSH2_FXF_WRITE|SSH2_FXF_CREAT|SSH2_FXF_TRUNC, a,
                   2380:                    &to_handle, &to_handle_len) != 0) {
                   2381:                        error("truncation failed for \"%s\"", to_path);
                   2382:                        to_handle = NULL;
                   2383:                }
                   2384:        }
                   2385:        if (read_error) {
                   2386:                error("Couldn't read from origin file \"%s\" : %s",
                   2387:                    from_path, fx2txt(status));
                   2388:                status = -1;
                   2389:                do_close(from, from_handle, from_handle_len);
                   2390:                if (to_handle != NULL)
                   2391:                        do_close(to, to_handle, to_handle_len);
                   2392:        } else if (write_error) {
                   2393:                error("Couldn't write to \"%s\": %s",
                   2394:                    to_path, fx2txt(write_error));
                   2395:                status = SSH2_FX_FAILURE;
                   2396:                do_close(from, from_handle, from_handle_len);
                   2397:                if (to_handle != NULL)
                   2398:                        do_close(to, to_handle, to_handle_len);
                   2399:        } else {
                   2400:                if (do_close(from, from_handle, from_handle_len) != 0 ||
                   2401:                    interrupted)
                   2402:                        status = -1;
                   2403:                else
                   2404:                        status = SSH2_FX_OK;
                   2405:                if (to_handle != NULL) {
                   2406:                        /* Need to resend utimes after write */
                   2407:                        if (preserve_flag)
                   2408:                                do_fsetstat(to, to_handle, to_handle_len, a);
                   2409:                        do_close(to, to_handle, to_handle_len);
                   2410:                }
                   2411:        }
                   2412:        sshbuf_free(msg);
                   2413:        free(from_handle);
                   2414:        free(to_handle);
                   2415:
                   2416:        return status == SSH2_FX_OK ? 0 : -1;
                   2417: }
                   2418:
                   2419: static int
                   2420: crossload_dir_internal(struct sftp_conn *from, struct sftp_conn *to,
                   2421:     const char *from_path, const char *to_path,
1.150     djm      2422:     int depth, Attrib *dirattrib, int preserve_flag, int print_flag,
                   2423:     int follow_link_flag)
1.145     djm      2424: {
                   2425:        int i, ret = 0;
                   2426:        SFTP_DIRENT **dir_entries;
                   2427:        char *filename, *new_from_path = NULL, *new_to_path = NULL;
                   2428:        mode_t mode = 0777;
1.149     djm      2429:        Attrib curdir;
1.145     djm      2430:
                   2431:        if (depth >= MAX_DIR_DEPTH) {
                   2432:                error("Maximum directory depth exceeded: %d levels", depth);
                   2433:                return -1;
                   2434:        }
                   2435:
                   2436:        if (dirattrib == NULL &&
                   2437:            (dirattrib = do_stat(from, from_path, 1)) == NULL) {
                   2438:                error("Unable to stat remote directory \"%s\"", from_path);
                   2439:                return -1;
                   2440:        }
                   2441:        if (!S_ISDIR(dirattrib->perm)) {
                   2442:                error("\"%s\" is not a directory", from_path);
                   2443:                return -1;
                   2444:        }
1.150     djm      2445:        if (print_flag && print_flag != SFTP_PROGRESS_ONLY)
1.145     djm      2446:                mprintf("Retrieving %s\n", from_path);
                   2447:
1.149     djm      2448:        curdir = *dirattrib; /* dirattrib will be clobbered */
                   2449:        curdir.flags &= ~SSH2_FILEXFER_ATTR_SIZE;
                   2450:        curdir.flags &= ~SSH2_FILEXFER_ATTR_UIDGID;
                   2451:        if ((curdir.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) == 0) {
                   2452:                debug("Origin did not send permissions for "
1.145     djm      2453:                    "directory \"%s\"", to_path);
1.149     djm      2454:                curdir.perm = S_IWUSR|S_IXUSR;
                   2455:                curdir.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1.145     djm      2456:        }
1.149     djm      2457:        /* We need to be able to write to the directory while we transfer it */
                   2458:        mode = curdir.perm & 01777;
                   2459:        curdir.perm = mode | (S_IWUSR|S_IXUSR);
                   2460:
                   2461:        /*
                   2462:         * sftp lacks a portable status value to match errno EEXIST,
                   2463:         * so if we get a failure back then we must check whether
                   2464:         * the path already existed and is a directory.  Ensure we can
                   2465:         * write to the directory we create for the duration of the transfer.
                   2466:         */
                   2467:        if (do_mkdir(to, to_path, &curdir, 0) != 0) {
                   2468:                if ((dirattrib = do_stat(to, to_path, 0)) == NULL)
                   2469:                        return -1;
                   2470:                if (!S_ISDIR(dirattrib->perm)) {
                   2471:                        error("\"%s\" exists but is not a directory", to_path);
                   2472:                        return -1;
                   2473:                }
                   2474:        }
                   2475:        curdir.perm = mode;
1.145     djm      2476:
                   2477:        if (do_readdir(from, from_path, &dir_entries) == -1) {
                   2478:                error("%s: Failed to get directory contents", from_path);
                   2479:                return -1;
                   2480:        }
                   2481:
                   2482:        for (i = 0; dir_entries[i] != NULL && !interrupted; i++) {
                   2483:                free(new_from_path);
                   2484:                free(new_to_path);
                   2485:
                   2486:                filename = dir_entries[i]->filename;
                   2487:                new_from_path = path_append(from_path, filename);
                   2488:                new_to_path = path_append(to_path, filename);
                   2489:
                   2490:                if (S_ISDIR(dir_entries[i]->a.perm)) {
                   2491:                        if (strcmp(filename, ".") == 0 ||
                   2492:                            strcmp(filename, "..") == 0)
                   2493:                                continue;
                   2494:                        if (crossload_dir_internal(from, to,
                   2495:                            new_from_path, new_to_path,
                   2496:                            depth + 1, &(dir_entries[i]->a), preserve_flag,
1.150     djm      2497:                            print_flag, follow_link_flag) == -1)
1.145     djm      2498:                                ret = -1;
1.150     djm      2499:                } else if (S_ISREG(dir_entries[i]->a.perm) ||
                   2500:                    (follow_link_flag && S_ISLNK(dir_entries[i]->a.perm))) {
                   2501:                        /*
                   2502:                         * If this is a symlink then don't send the link's
                   2503:                         * Attrib. do_download() will do a FXP_STAT operation
                   2504:                         * and get the link target's attributes.
                   2505:                         */
1.145     djm      2506:                        if (do_crossload(from, to, new_from_path, new_to_path,
1.150     djm      2507:                            S_ISLNK(dir_entries[i]->a.perm) ? NULL :
1.145     djm      2508:                            &(dir_entries[i]->a), preserve_flag) == -1) {
                   2509:                                error("Transfer of file %s to %s failed",
                   2510:                                    new_from_path, new_to_path);
                   2511:                                ret = -1;
                   2512:                        }
                   2513:                } else
                   2514:                        logit("%s: not a regular file\n", new_from_path);
                   2515:
                   2516:        }
                   2517:        free(new_to_path);
                   2518:        free(new_from_path);
                   2519:
1.149     djm      2520:        do_setstat(to, to_path, &curdir);
1.145     djm      2521:
                   2522:        free_sftp_dirents(dir_entries);
                   2523:
                   2524:        return ret;
                   2525: }
                   2526:
                   2527: int
                   2528: crossload_dir(struct sftp_conn *from, struct sftp_conn *to,
                   2529:     const char *from_path, const char *to_path,
1.150     djm      2530:     Attrib *dirattrib, int preserve_flag, int print_flag, int follow_link_flag)
1.145     djm      2531: {
                   2532:        char *from_path_canon;
                   2533:        int ret;
                   2534:
                   2535:        if ((from_path_canon = do_realpath(from, from_path)) == NULL) {
                   2536:                error("Unable to canonicalize path \"%s\"", from_path);
                   2537:                return -1;
                   2538:        }
                   2539:
                   2540:        ret = crossload_dir_internal(from, to, from_path_canon, to_path, 0,
1.150     djm      2541:            dirattrib, preserve_flag, print_flag, follow_link_flag);
1.145     djm      2542:        free(from_path_canon);
1.89      djm      2543:        return ret;
                   2544: }
                   2545:
                   2546: char *
1.116     djm      2547: path_append(const char *p1, const char *p2)
1.89      djm      2548: {
                   2549:        char *ret;
                   2550:        size_t len = strlen(p1) + strlen(p2) + 2;
                   2551:
                   2552:        ret = xmalloc(len);
                   2553:        strlcpy(ret, p1, len);
                   2554:        if (p1[0] != '\0' && p1[strlen(p1) - 1] != '/')
                   2555:                strlcat(ret, "/", len);
                   2556:        strlcat(ret, p2, len);
                   2557:
                   2558:        return(ret);
1.139     djm      2559: }
                   2560:
                   2561: char *
                   2562: make_absolute(char *p, const char *pwd)
                   2563: {
                   2564:        char *abs_str;
                   2565:
                   2566:        /* Derelativise */
                   2567:        if (p && !path_absolute(p)) {
                   2568:                abs_str = path_append(pwd, p);
                   2569:                free(p);
                   2570:                return(abs_str);
                   2571:        } else
                   2572:                return(p);
                   2573: }
                   2574:
                   2575: int
                   2576: remote_is_dir(struct sftp_conn *conn, const char *path)
                   2577: {
                   2578:        Attrib *a;
                   2579:
                   2580:        /* XXX: report errors? */
                   2581:        if ((a = do_stat(conn, path, 1)) == NULL)
                   2582:                return(0);
                   2583:        if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
                   2584:                return(0);
                   2585:        return(S_ISDIR(a->perm));
                   2586: }
                   2587:
                   2588:
                   2589: int
                   2590: local_is_dir(const char *path)
                   2591: {
                   2592:        struct stat sb;
                   2593:
                   2594:        /* XXX: report errors? */
                   2595:        if (stat(path, &sb) == -1)
                   2596:                return(0);
                   2597:
                   2598:        return(S_ISDIR(sb.st_mode));
                   2599: }
                   2600:
                   2601: /* Check whether path returned from glob(..., GLOB_MARK, ...) is a directory */
                   2602: int
                   2603: globpath_is_dir(const char *pathname)
                   2604: {
                   2605:        size_t l = strlen(pathname);
                   2606:
                   2607:        return l > 0 && pathname[l - 1] == '/';
1.89      djm      2608: }
                   2609: