1 /* $OpenBSD: sftp-client.c,v 1.89 2009/08/18 18:36:20 djm Exp $ */
3 * Copyright (c) 2001-2004 Damien Miller <djm@openbsd.org>
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.
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.
19 /* XXX: signed vs unsigned */
20 /* XXX: remove all logging, only return status codes */
21 /* XXX: copy between two remote sites */
25 #include <sys/types.h>
26 #include <sys/param.h>
27 #ifdef HAVE_SYS_STATVFS_H
28 #include <sys/statvfs.h>
30 #include "openbsd-compat/sys-queue.h"
31 #ifdef HAVE_SYS_STAT_H
32 # include <sys/stat.h>
34 #ifdef HAVE_SYS_TIME_H
35 # include <sys/time.h>
40 #ifdef DTTOIF_IN_FS_FFS_DIR_H
41 # include <fs/ffs/dir.h>
55 #include "progressmeter.h"
59 #include "sftp-common.h"
60 #include "sftp-client.h"
62 extern volatile sig_atomic_t interrupted;
63 extern int showprogress;
65 /* Minimum amount of data to read at a time */
66 #define MIN_READ_SIZE 512
68 /* Maximum depth to descend in directory trees */
69 #define MAX_DIR_DEPTH 64
74 u_int transfer_buflen;
78 #define SFTP_EXT_POSIX_RENAME 0x00000001
79 #define SFTP_EXT_STATVFS 0x00000002
80 #define SFTP_EXT_FSTATVFS 0x00000004
85 get_handle(int fd, u_int expected_id, u_int *len, const char *errfmt, ...)
86 __attribute__((format(printf, 4, 5)));
89 send_msg(int fd, Buffer *m)
94 if (buffer_len(m) > SFTP_MAX_MSG_LENGTH)
95 fatal("Outbound message too long %u", buffer_len(m));
97 /* Send length first */
98 put_u32(mlen, buffer_len(m));
99 iov[0].iov_base = mlen;
100 iov[0].iov_len = sizeof(mlen);
101 iov[1].iov_base = buffer_ptr(m);
102 iov[1].iov_len = buffer_len(m);
104 if (atomiciov(writev, fd, iov, 2) != buffer_len(m) + sizeof(mlen))
105 fatal("Couldn't send packet: %s", strerror(errno));
111 get_msg(int fd, Buffer *m)
115 buffer_append_space(m, 4);
116 if (atomicio(read, fd, buffer_ptr(m), 4) != 4) {
118 fatal("Connection closed");
120 fatal("Couldn't read packet: %s", strerror(errno));
123 msg_len = buffer_get_int(m);
124 if (msg_len > SFTP_MAX_MSG_LENGTH)
125 fatal("Received message too long %u", msg_len);
127 buffer_append_space(m, msg_len);
128 if (atomicio(read, fd, buffer_ptr(m), msg_len) != msg_len) {
130 fatal("Connection closed");
132 fatal("Read packet: %s", strerror(errno));
137 send_string_request(int fd, u_int id, u_int code, char *s,
143 buffer_put_char(&msg, code);
144 buffer_put_int(&msg, id);
145 buffer_put_string(&msg, s, len);
147 debug3("Sent message fd %d T:%u I:%u", fd, code, id);
152 send_string_attrs_request(int fd, u_int id, u_int code, char *s,
153 u_int len, Attrib *a)
158 buffer_put_char(&msg, code);
159 buffer_put_int(&msg, id);
160 buffer_put_string(&msg, s, len);
161 encode_attrib(&msg, a);
163 debug3("Sent message fd %d T:%u I:%u", fd, code, id);
168 get_status(int fd, u_int expected_id)
171 u_int type, id, status;
175 type = buffer_get_char(&msg);
176 id = buffer_get_int(&msg);
178 if (id != expected_id)
179 fatal("ID mismatch (%u != %u)", id, expected_id);
180 if (type != SSH2_FXP_STATUS)
181 fatal("Expected SSH2_FXP_STATUS(%u) packet, got %u",
182 SSH2_FXP_STATUS, type);
184 status = buffer_get_int(&msg);
187 debug3("SSH2_FXP_STATUS %u", status);
193 get_handle(int fd, u_int expected_id, u_int *len, const char *errfmt, ...)
197 char *handle, errmsg[256];
201 va_start(args, errfmt);
203 vsnprintf(errmsg, sizeof(errmsg), errfmt, args);
208 type = buffer_get_char(&msg);
209 id = buffer_get_int(&msg);
211 if (id != expected_id)
212 fatal("%s: ID mismatch (%u != %u)",
213 errfmt == NULL ? __func__ : errmsg, id, expected_id);
214 if (type == SSH2_FXP_STATUS) {
215 status = buffer_get_int(&msg);
217 error("%s: %s", errmsg, fx2txt(status));
220 } else if (type != SSH2_FXP_HANDLE)
221 fatal("%s: Expected SSH2_FXP_HANDLE(%u) packet, got %u",
222 errfmt == NULL ? __func__ : errmsg, SSH2_FXP_HANDLE, type);
224 handle = buffer_get_string(&msg, len);
231 get_decode_stat(int fd, u_int expected_id, int quiet)
240 type = buffer_get_char(&msg);
241 id = buffer_get_int(&msg);
243 debug3("Received stat reply T:%u I:%u", type, id);
244 if (id != expected_id)
245 fatal("ID mismatch (%u != %u)", id, expected_id);
246 if (type == SSH2_FXP_STATUS) {
247 int status = buffer_get_int(&msg);
250 debug("Couldn't stat remote file: %s", fx2txt(status));
252 error("Couldn't stat remote file: %s", fx2txt(status));
255 } else if (type != SSH2_FXP_ATTRS) {
256 fatal("Expected SSH2_FXP_ATTRS(%u) packet, got %u",
257 SSH2_FXP_ATTRS, type);
259 a = decode_attrib(&msg);
266 get_decode_statvfs(int fd, struct sftp_statvfs *st, u_int expected_id,
270 u_int type, id, flag;
275 type = buffer_get_char(&msg);
276 id = buffer_get_int(&msg);
278 debug3("Received statvfs reply T:%u I:%u", type, id);
279 if (id != expected_id)
280 fatal("ID mismatch (%u != %u)", id, expected_id);
281 if (type == SSH2_FXP_STATUS) {
282 int status = buffer_get_int(&msg);
285 debug("Couldn't statvfs: %s", fx2txt(status));
287 error("Couldn't statvfs: %s", fx2txt(status));
290 } else if (type != SSH2_FXP_EXTENDED_REPLY) {
291 fatal("Expected SSH2_FXP_EXTENDED_REPLY(%u) packet, got %u",
292 SSH2_FXP_EXTENDED_REPLY, type);
295 bzero(st, sizeof(*st));
296 st->f_bsize = buffer_get_int64(&msg);
297 st->f_frsize = buffer_get_int64(&msg);
298 st->f_blocks = buffer_get_int64(&msg);
299 st->f_bfree = buffer_get_int64(&msg);
300 st->f_bavail = buffer_get_int64(&msg);
301 st->f_files = buffer_get_int64(&msg);
302 st->f_ffree = buffer_get_int64(&msg);
303 st->f_favail = buffer_get_int64(&msg);
304 st->f_fsid = buffer_get_int64(&msg);
305 flag = buffer_get_int64(&msg);
306 st->f_namemax = buffer_get_int64(&msg);
308 st->f_flag = (flag & SSH2_FXE_STATVFS_ST_RDONLY) ? ST_RDONLY : 0;
309 st->f_flag |= (flag & SSH2_FXE_STATVFS_ST_NOSUID) ? ST_NOSUID : 0;
317 do_init(int fd_in, int fd_out, u_int transfer_buflen, u_int num_requests)
319 u_int type, exts = 0;
322 struct sftp_conn *ret;
325 buffer_put_char(&msg, SSH2_FXP_INIT);
326 buffer_put_int(&msg, SSH2_FILEXFER_VERSION);
327 send_msg(fd_out, &msg);
331 get_msg(fd_in, &msg);
333 /* Expecting a VERSION reply */
334 if ((type = buffer_get_char(&msg)) != SSH2_FXP_VERSION) {
335 error("Invalid packet back from SSH2_FXP_INIT (type %u)",
340 version = buffer_get_int(&msg);
342 debug2("Remote version: %d", version);
344 /* Check for extensions */
345 while (buffer_len(&msg) > 0) {
346 char *name = buffer_get_string(&msg, NULL);
347 char *value = buffer_get_string(&msg, NULL);
350 if (strcmp(name, "posix-rename@openssh.com") == 0 &&
351 strcmp(value, "1") == 0) {
352 exts |= SFTP_EXT_POSIX_RENAME;
354 } else if (strcmp(name, "statvfs@openssh.com") == 0 &&
355 strcmp(value, "2") == 0) {
356 exts |= SFTP_EXT_STATVFS;
358 } if (strcmp(name, "fstatvfs@openssh.com") == 0 &&
359 strcmp(value, "2") == 0) {
360 exts |= SFTP_EXT_FSTATVFS;
364 debug2("Server supports extension \"%s\" revision %s",
367 debug2("Unrecognised server extension \"%s\"", name);
375 ret = xmalloc(sizeof(*ret));
377 ret->fd_out = fd_out;
378 ret->transfer_buflen = transfer_buflen;
379 ret->num_requests = num_requests;
380 ret->version = version;
384 /* Some filexfer v.0 servers don't support large packets */
386 ret->transfer_buflen = MIN(ret->transfer_buflen, 20480);
392 sftp_proto_version(struct sftp_conn *conn)
394 return(conn->version);
398 do_close(struct sftp_conn *conn, char *handle, u_int handle_len)
406 buffer_put_char(&msg, SSH2_FXP_CLOSE);
407 buffer_put_int(&msg, id);
408 buffer_put_string(&msg, handle, handle_len);
409 send_msg(conn->fd_out, &msg);
410 debug3("Sent message SSH2_FXP_CLOSE I:%u", id);
412 status = get_status(conn->fd_in, id);
413 if (status != SSH2_FX_OK)
414 error("Couldn't close file: %s", fx2txt(status));
423 do_lsreaddir(struct sftp_conn *conn, char *path, int printflag,
427 u_int count, type, id, handle_len, i, expected_id, ents = 0;
433 buffer_put_char(&msg, SSH2_FXP_OPENDIR);
434 buffer_put_int(&msg, id);
435 buffer_put_cstring(&msg, path);
436 send_msg(conn->fd_out, &msg);
440 handle = get_handle(conn->fd_in, id, &handle_len,
441 "remote readdir(\"%s\")", path);
447 *dir = xmalloc(sizeof(**dir));
451 for (; !interrupted;) {
452 id = expected_id = conn->msg_id++;
454 debug3("Sending SSH2_FXP_READDIR I:%u", id);
457 buffer_put_char(&msg, SSH2_FXP_READDIR);
458 buffer_put_int(&msg, id);
459 buffer_put_string(&msg, handle, handle_len);
460 send_msg(conn->fd_out, &msg);
464 get_msg(conn->fd_in, &msg);
466 type = buffer_get_char(&msg);
467 id = buffer_get_int(&msg);
469 debug3("Received reply T:%u I:%u", type, id);
471 if (id != expected_id)
472 fatal("ID mismatch (%u != %u)", id, expected_id);
474 if (type == SSH2_FXP_STATUS) {
475 int status = buffer_get_int(&msg);
477 debug3("Received SSH2_FXP_STATUS %d", status);
479 if (status == SSH2_FX_EOF) {
482 error("Couldn't read directory: %s",
484 do_close(conn, handle, handle_len);
488 } else if (type != SSH2_FXP_NAME)
489 fatal("Expected SSH2_FXP_NAME(%u) packet, got %u",
490 SSH2_FXP_NAME, type);
492 count = buffer_get_int(&msg);
495 debug3("Received %d SSH2_FXP_NAME responses", count);
496 for (i = 0; i < count; i++) {
497 char *filename, *longname;
500 filename = buffer_get_string(&msg, NULL);
501 longname = buffer_get_string(&msg, NULL);
502 a = decode_attrib(&msg);
505 printf("%s\n", longname);
508 * Directory entries should never contain '/'
509 * These can be used to attack recursive ops
510 * (e.g. send '../../../../etc/passwd')
512 if (strchr(filename, '/') != NULL) {
513 error("Server sent suspect path \"%s\" "
514 "during readdir of \"%s\"", filename, path);
519 *dir = xrealloc(*dir, ents + 2, sizeof(**dir));
520 (*dir)[ents] = xmalloc(sizeof(***dir));
521 (*dir)[ents]->filename = xstrdup(filename);
522 (*dir)[ents]->longname = xstrdup(longname);
523 memcpy(&(*dir)[ents]->a, a, sizeof(*a));
524 (*dir)[++ents] = NULL;
533 do_close(conn, handle, handle_len);
536 /* Don't return partial matches on interrupt */
537 if (interrupted && dir != NULL && *dir != NULL) {
538 free_sftp_dirents(*dir);
539 *dir = xmalloc(sizeof(**dir));
547 do_readdir(struct sftp_conn *conn, char *path, SFTP_DIRENT ***dir)
549 return(do_lsreaddir(conn, path, 0, dir));
552 void free_sftp_dirents(SFTP_DIRENT **s)
556 for (i = 0; s[i]; i++) {
557 xfree(s[i]->filename);
558 xfree(s[i]->longname);
565 do_rm(struct sftp_conn *conn, char *path)
569 debug2("Sending SSH2_FXP_REMOVE \"%s\"", path);
572 send_string_request(conn->fd_out, id, SSH2_FXP_REMOVE, path,
574 status = get_status(conn->fd_in, id);
575 if (status != SSH2_FX_OK)
576 error("Couldn't delete file: %s", fx2txt(status));
581 do_mkdir(struct sftp_conn *conn, char *path, Attrib *a, int printflag)
586 send_string_attrs_request(conn->fd_out, id, SSH2_FXP_MKDIR, path,
589 status = get_status(conn->fd_in, id);
590 if (status != SSH2_FX_OK && printflag)
591 error("Couldn't create directory: %s", fx2txt(status));
597 do_rmdir(struct sftp_conn *conn, char *path)
602 send_string_request(conn->fd_out, id, SSH2_FXP_RMDIR, path,
605 status = get_status(conn->fd_in, id);
606 if (status != SSH2_FX_OK)
607 error("Couldn't remove directory: %s", fx2txt(status));
613 do_stat(struct sftp_conn *conn, char *path, int quiet)
619 send_string_request(conn->fd_out, id,
620 conn->version == 0 ? SSH2_FXP_STAT_VERSION_0 : SSH2_FXP_STAT,
623 return(get_decode_stat(conn->fd_in, id, quiet));
627 do_lstat(struct sftp_conn *conn, char *path, int quiet)
631 if (conn->version == 0) {
633 debug("Server version does not support lstat operation");
635 logit("Server version does not support lstat operation");
636 return(do_stat(conn, path, quiet));
640 send_string_request(conn->fd_out, id, SSH2_FXP_LSTAT, path,
643 return(get_decode_stat(conn->fd_in, id, quiet));
648 do_fstat(struct sftp_conn *conn, char *handle, u_int handle_len, int quiet)
653 send_string_request(conn->fd_out, id, SSH2_FXP_FSTAT, handle,
656 return(get_decode_stat(conn->fd_in, id, quiet));
661 do_setstat(struct sftp_conn *conn, char *path, Attrib *a)
666 send_string_attrs_request(conn->fd_out, id, SSH2_FXP_SETSTAT, path,
669 status = get_status(conn->fd_in, id);
670 if (status != SSH2_FX_OK)
671 error("Couldn't setstat on \"%s\": %s", path,
678 do_fsetstat(struct sftp_conn *conn, char *handle, u_int handle_len,
684 send_string_attrs_request(conn->fd_out, id, SSH2_FXP_FSETSTAT, handle,
687 status = get_status(conn->fd_in, id);
688 if (status != SSH2_FX_OK)
689 error("Couldn't fsetstat: %s", fx2txt(status));
695 do_realpath(struct sftp_conn *conn, char *path)
698 u_int type, expected_id, count, id;
699 char *filename, *longname;
702 expected_id = id = conn->msg_id++;
703 send_string_request(conn->fd_out, id, SSH2_FXP_REALPATH, path,
708 get_msg(conn->fd_in, &msg);
709 type = buffer_get_char(&msg);
710 id = buffer_get_int(&msg);
712 if (id != expected_id)
713 fatal("ID mismatch (%u != %u)", id, expected_id);
715 if (type == SSH2_FXP_STATUS) {
716 u_int status = buffer_get_int(&msg);
718 error("Couldn't canonicalise: %s", fx2txt(status));
720 } else if (type != SSH2_FXP_NAME)
721 fatal("Expected SSH2_FXP_NAME(%u) packet, got %u",
722 SSH2_FXP_NAME, type);
724 count = buffer_get_int(&msg);
726 fatal("Got multiple names (%d) from SSH_FXP_REALPATH", count);
728 filename = buffer_get_string(&msg, NULL);
729 longname = buffer_get_string(&msg, NULL);
730 a = decode_attrib(&msg);
732 debug3("SSH_FXP_REALPATH %s -> %s", path, filename);
742 do_rename(struct sftp_conn *conn, char *oldpath, char *newpath)
749 /* Send rename request */
751 if ((conn->exts & SFTP_EXT_POSIX_RENAME)) {
752 buffer_put_char(&msg, SSH2_FXP_EXTENDED);
753 buffer_put_int(&msg, id);
754 buffer_put_cstring(&msg, "posix-rename@openssh.com");
756 buffer_put_char(&msg, SSH2_FXP_RENAME);
757 buffer_put_int(&msg, id);
759 buffer_put_cstring(&msg, oldpath);
760 buffer_put_cstring(&msg, newpath);
761 send_msg(conn->fd_out, &msg);
762 debug3("Sent message %s \"%s\" -> \"%s\"",
763 (conn->exts & SFTP_EXT_POSIX_RENAME) ? "posix-rename@openssh.com" :
764 "SSH2_FXP_RENAME", oldpath, newpath);
767 status = get_status(conn->fd_in, id);
768 if (status != SSH2_FX_OK)
769 error("Couldn't rename file \"%s\" to \"%s\": %s", oldpath,
770 newpath, fx2txt(status));
776 do_symlink(struct sftp_conn *conn, char *oldpath, char *newpath)
781 if (conn->version < 3) {
782 error("This server does not support the symlink operation");
783 return(SSH2_FX_OP_UNSUPPORTED);
788 /* Send symlink request */
790 buffer_put_char(&msg, SSH2_FXP_SYMLINK);
791 buffer_put_int(&msg, id);
792 buffer_put_cstring(&msg, oldpath);
793 buffer_put_cstring(&msg, newpath);
794 send_msg(conn->fd_out, &msg);
795 debug3("Sent message SSH2_FXP_SYMLINK \"%s\" -> \"%s\"", oldpath,
799 status = get_status(conn->fd_in, id);
800 if (status != SSH2_FX_OK)
801 error("Couldn't symlink file \"%s\" to \"%s\": %s", oldpath,
802 newpath, fx2txt(status));
809 do_readlink(struct sftp_conn *conn, char *path)
812 u_int type, expected_id, count, id;
813 char *filename, *longname;
816 expected_id = id = conn->msg_id++;
817 send_string_request(conn->fd_out, id, SSH2_FXP_READLINK, path,
822 get_msg(conn->fd_in, &msg);
823 type = buffer_get_char(&msg);
824 id = buffer_get_int(&msg);
826 if (id != expected_id)
827 fatal("ID mismatch (%u != %u)", id, expected_id);
829 if (type == SSH2_FXP_STATUS) {
830 u_int status = buffer_get_int(&msg);
832 error("Couldn't readlink: %s", fx2txt(status));
834 } else if (type != SSH2_FXP_NAME)
835 fatal("Expected SSH2_FXP_NAME(%u) packet, got %u",
836 SSH2_FXP_NAME, type);
838 count = buffer_get_int(&msg);
840 fatal("Got multiple names (%d) from SSH_FXP_READLINK", count);
842 filename = buffer_get_string(&msg, NULL);
843 longname = buffer_get_string(&msg, NULL);
844 a = decode_attrib(&msg);
846 debug3("SSH_FXP_READLINK %s -> %s", path, filename);
857 do_statvfs(struct sftp_conn *conn, const char *path, struct sftp_statvfs *st,
863 if ((conn->exts & SFTP_EXT_STATVFS) == 0) {
864 error("Server does not support statvfs@openssh.com extension");
872 buffer_put_char(&msg, SSH2_FXP_EXTENDED);
873 buffer_put_int(&msg, id);
874 buffer_put_cstring(&msg, "statvfs@openssh.com");
875 buffer_put_cstring(&msg, path);
876 send_msg(conn->fd_out, &msg);
879 return get_decode_statvfs(conn->fd_in, st, id, quiet);
884 do_fstatvfs(struct sftp_conn *conn, const char *handle, u_int handle_len,
885 struct sftp_statvfs *st, int quiet)
890 if ((conn->exts & SFTP_EXT_FSTATVFS) == 0) {
891 error("Server does not support fstatvfs@openssh.com extension");
899 buffer_put_char(&msg, SSH2_FXP_EXTENDED);
900 buffer_put_int(&msg, id);
901 buffer_put_cstring(&msg, "fstatvfs@openssh.com");
902 buffer_put_string(&msg, handle, handle_len);
903 send_msg(conn->fd_out, &msg);
906 return get_decode_statvfs(conn->fd_in, st, id, quiet);
911 send_read_request(int fd_out, u_int id, u_int64_t offset, u_int len,
912 char *handle, u_int handle_len)
918 buffer_put_char(&msg, SSH2_FXP_READ);
919 buffer_put_int(&msg, id);
920 buffer_put_string(&msg, handle, handle_len);
921 buffer_put_int64(&msg, offset);
922 buffer_put_int(&msg, len);
923 send_msg(fd_out, &msg);
928 do_download(struct sftp_conn *conn, char *remote_path, char *local_path,
929 Attrib *a, int pflag)
934 int local_fd, status = 0, write_error;
935 int read_error, write_errno;
936 u_int64_t offset, size;
937 u_int handle_len, mode, type, id, buflen, num_req, max_req;
938 off_t progress_counter;
943 TAILQ_ENTRY(request) tq;
945 TAILQ_HEAD(reqhead, request) requests;
948 TAILQ_INIT(&requests);
950 if (a == NULL && (a = do_stat(conn, remote_path, 0)) == NULL)
953 /* Do not preserve set[ug]id here, as we do not preserve ownership */
954 if (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)
955 mode = a->perm & 0777;
959 if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
960 (!S_ISREG(a->perm))) {
961 error("Cannot download non-regular file: %s", remote_path);
965 if (a->flags & SSH2_FILEXFER_ATTR_SIZE)
970 buflen = conn->transfer_buflen;
973 /* Send open request */
975 buffer_put_char(&msg, SSH2_FXP_OPEN);
976 buffer_put_int(&msg, id);
977 buffer_put_cstring(&msg, remote_path);
978 buffer_put_int(&msg, SSH2_FXF_READ);
979 attrib_clear(&junk); /* Send empty attributes */
980 encode_attrib(&msg, &junk);
981 send_msg(conn->fd_out, &msg);
982 debug3("Sent message SSH2_FXP_OPEN I:%u P:%s", id, remote_path);
984 handle = get_handle(conn->fd_in, id, &handle_len,
985 "remote open(\"%s\")", remote_path);
986 if (handle == NULL) {
991 local_fd = open(local_path, O_WRONLY | O_CREAT | O_TRUNC,
993 if (local_fd == -1) {
994 error("Couldn't open local file \"%s\" for writing: %s",
995 local_path, strerror(errno));
996 do_close(conn, handle, handle_len);
1002 /* Read from remote and write to local */
1003 write_error = read_error = write_errno = num_req = offset = 0;
1005 progress_counter = 0;
1007 if (showprogress && size != 0)
1008 start_progress_meter(remote_path, size, &progress_counter);
1010 while (num_req > 0 || max_req > 0) {
1015 * Simulate EOF on interrupt: stop sending new requests and
1016 * allow outstanding requests to drain gracefully
1019 if (num_req == 0) /* If we haven't started yet... */
1024 /* Send some more requests */
1025 while (num_req < max_req) {
1026 debug3("Request range %llu -> %llu (%d/%d)",
1027 (unsigned long long)offset,
1028 (unsigned long long)offset + buflen - 1,
1030 req = xmalloc(sizeof(*req));
1031 req->id = conn->msg_id++;
1033 req->offset = offset;
1036 TAILQ_INSERT_TAIL(&requests, req, tq);
1037 send_read_request(conn->fd_out, req->id, req->offset,
1038 req->len, handle, handle_len);
1042 get_msg(conn->fd_in, &msg);
1043 type = buffer_get_char(&msg);
1044 id = buffer_get_int(&msg);
1045 debug3("Received reply T:%u I:%u R:%d", type, id, max_req);
1047 /* Find the request in our queue */
1048 for (req = TAILQ_FIRST(&requests);
1049 req != NULL && req->id != id;
1050 req = TAILQ_NEXT(req, tq))
1053 fatal("Unexpected reply %u", id);
1056 case SSH2_FXP_STATUS:
1057 status = buffer_get_int(&msg);
1058 if (status != SSH2_FX_EOF)
1061 TAILQ_REMOVE(&requests, req, tq);
1066 data = buffer_get_string(&msg, &len);
1067 debug3("Received data %llu -> %llu",
1068 (unsigned long long)req->offset,
1069 (unsigned long long)req->offset + len - 1);
1071 fatal("Received more data than asked for "
1072 "%u > %u", len, req->len);
1073 if ((lseek(local_fd, req->offset, SEEK_SET) == -1 ||
1074 atomicio(vwrite, local_fd, data, len) != len) &&
1076 write_errno = errno;
1080 progress_counter += len;
1083 if (len == req->len) {
1084 TAILQ_REMOVE(&requests, req, tq);
1088 /* Resend the request for the missing data */
1089 debug3("Short data block, re-requesting "
1090 "%llu -> %llu (%2d)",
1091 (unsigned long long)req->offset + len,
1092 (unsigned long long)req->offset +
1093 req->len - 1, num_req);
1094 req->id = conn->msg_id++;
1097 send_read_request(conn->fd_out, req->id,
1098 req->offset, req->len, handle, handle_len);
1099 /* Reduce the request size */
1101 buflen = MAX(MIN_READ_SIZE, len);
1103 if (max_req > 0) { /* max_req = 0 iff EOF received */
1104 if (size > 0 && offset > size) {
1105 /* Only one request at a time
1106 * after the expected EOF */
1107 debug3("Finish at %llu (%2d)",
1108 (unsigned long long)offset,
1111 } else if (max_req <= conn->num_requests) {
1117 fatal("Expected SSH2_FXP_DATA(%u) packet, got %u",
1118 SSH2_FXP_DATA, type);
1122 if (showprogress && size)
1123 stop_progress_meter();
1126 if (TAILQ_FIRST(&requests) != NULL)
1127 fatal("Transfer complete, but requests still in queue");
1130 error("Couldn't read from remote file \"%s\" : %s",
1131 remote_path, fx2txt(status));
1132 do_close(conn, handle, handle_len);
1133 } else if (write_error) {
1134 error("Couldn't write to \"%s\": %s", local_path,
1135 strerror(write_errno));
1137 do_close(conn, handle, handle_len);
1139 status = do_close(conn, handle, handle_len);
1141 /* Override umask and utimes if asked */
1143 if (pflag && fchmod(local_fd, mode) == -1)
1145 if (pflag && chmod(local_path, mode) == -1)
1146 #endif /* HAVE_FCHMOD */
1147 error("Couldn't set mode on \"%s\": %s", local_path,
1149 if (pflag && (a->flags & SSH2_FILEXFER_ATTR_ACMODTIME)) {
1150 struct timeval tv[2];
1151 tv[0].tv_sec = a->atime;
1152 tv[1].tv_sec = a->mtime;
1153 tv[0].tv_usec = tv[1].tv_usec = 0;
1154 if (utimes(local_path, tv) == -1)
1155 error("Can't set times on \"%s\": %s",
1156 local_path, strerror(errno));
1167 download_dir_internal(struct sftp_conn *conn, char *src, char *dst,
1168 Attrib *dirattrib, int pflag, int printflag, int depth)
1171 SFTP_DIRENT **dir_entries;
1172 char *filename, *new_src, *new_dst;
1175 if (depth >= MAX_DIR_DEPTH) {
1176 error("Maximum directory depth exceeded: %d levels", depth);
1180 if (dirattrib == NULL &&
1181 (dirattrib = do_stat(conn, src, 1)) == NULL) {
1182 error("Unable to stat remote directory \"%s\"", src);
1185 if (!S_ISDIR(dirattrib->perm)) {
1186 error("\"%s\" is not a directory", src);
1190 printf("Retrieving %s\n", src);
1192 if (dirattrib->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)
1193 mode = dirattrib->perm & 01777;
1195 debug("Server did not send permissions for "
1196 "directory \"%s\"", dst);
1199 if (mkdir(dst, mode) == -1 && errno != EEXIST) {
1200 error("mkdir %s: %s", dst, strerror(errno));
1204 if (do_readdir(conn, src, &dir_entries) == -1) {
1205 error("%s: Failed to get directory contents", src);
1209 for (i = 0; dir_entries[i] != NULL && !interrupted; i++) {
1210 filename = dir_entries[i]->filename;
1212 new_dst = path_append(dst, filename);
1213 new_src = path_append(src, filename);
1215 if (S_ISDIR(dir_entries[i]->a.perm)) {
1216 if (strcmp(filename, ".") == 0 ||
1217 strcmp(filename, "..") == 0)
1219 if (download_dir_internal(conn, new_src, new_dst,
1220 &(dir_entries[i]->a), pflag, printflag,
1223 } else if (S_ISREG(dir_entries[i]->a.perm) ) {
1224 if (do_download(conn, new_src, new_dst,
1225 &(dir_entries[i]->a), pflag) == -1) {
1226 error("Download of file %s to %s failed",
1231 logit("%s: not a regular file\n", new_src);
1238 if (dirattrib->flags & SSH2_FILEXFER_ATTR_ACMODTIME) {
1239 struct timeval tv[2];
1240 tv[0].tv_sec = dirattrib->atime;
1241 tv[1].tv_sec = dirattrib->mtime;
1242 tv[0].tv_usec = tv[1].tv_usec = 0;
1243 if (utimes(dst, tv) == -1)
1244 error("Can't set times on \"%s\": %s",
1245 dst, strerror(errno));
1247 debug("Server did not send times for directory "
1251 free_sftp_dirents(dir_entries);
1257 download_dir(struct sftp_conn *conn, char *src, char *dst,
1258 Attrib *dirattrib, int pflag, int printflag)
1263 if ((src_canon = do_realpath(conn, src)) == NULL) {
1264 error("Unable to canonicalise path \"%s\"", src);
1268 ret = download_dir_internal(conn, src_canon, dst,
1269 dirattrib, pflag, printflag, 0);
1275 do_upload(struct sftp_conn *conn, char *local_path, char *remote_path,
1279 int status = SSH2_FX_OK;
1280 u_int handle_len, id, type;
1282 char *handle, *data;
1288 struct outstanding_ack {
1292 TAILQ_ENTRY(outstanding_ack) tq;
1294 TAILQ_HEAD(ackhead, outstanding_ack) acks;
1295 struct outstanding_ack *ack = NULL;
1299 if ((local_fd = open(local_path, O_RDONLY, 0)) == -1) {
1300 error("Couldn't open local file \"%s\" for reading: %s",
1301 local_path, strerror(errno));
1304 if (fstat(local_fd, &sb) == -1) {
1305 error("Couldn't fstat local file \"%s\": %s",
1306 local_path, strerror(errno));
1310 if (!S_ISREG(sb.st_mode)) {
1311 error("%s is not a regular file", local_path);
1315 stat_to_attrib(&sb, &a);
1317 a.flags &= ~SSH2_FILEXFER_ATTR_SIZE;
1318 a.flags &= ~SSH2_FILEXFER_ATTR_UIDGID;
1321 a.flags &= ~SSH2_FILEXFER_ATTR_ACMODTIME;
1325 /* Send open request */
1326 id = conn->msg_id++;
1327 buffer_put_char(&msg, SSH2_FXP_OPEN);
1328 buffer_put_int(&msg, id);
1329 buffer_put_cstring(&msg, remote_path);
1330 buffer_put_int(&msg, SSH2_FXF_WRITE|SSH2_FXF_CREAT|SSH2_FXF_TRUNC);
1331 encode_attrib(&msg, &a);
1332 send_msg(conn->fd_out, &msg);
1333 debug3("Sent message SSH2_FXP_OPEN I:%u P:%s", id, remote_path);
1337 handle = get_handle(conn->fd_in, id, &handle_len,
1338 "remote open(\"%s\")", remote_path);
1339 if (handle == NULL) {
1345 startid = ackid = id + 1;
1346 data = xmalloc(conn->transfer_buflen);
1348 /* Read from local and write to remote */
1351 start_progress_meter(local_path, sb.st_size, &offset);
1357 * Can't use atomicio here because it returns 0 on EOF,
1358 * thus losing the last block of the file.
1359 * Simulate an EOF on interrupt, allowing ACKs from the
1362 if (interrupted || status != SSH2_FX_OK)
1365 len = read(local_fd, data, conn->transfer_buflen);
1366 while ((len == -1) &&
1367 (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK));
1370 fatal("Couldn't read from \"%s\": %s", local_path,
1374 ack = xmalloc(sizeof(*ack));
1376 ack->offset = offset;
1378 TAILQ_INSERT_TAIL(&acks, ack, tq);
1381 buffer_put_char(&msg, SSH2_FXP_WRITE);
1382 buffer_put_int(&msg, ack->id);
1383 buffer_put_string(&msg, handle, handle_len);
1384 buffer_put_int64(&msg, offset);
1385 buffer_put_string(&msg, data, len);
1386 send_msg(conn->fd_out, &msg);
1387 debug3("Sent message SSH2_FXP_WRITE I:%u O:%llu S:%u",
1388 id, (unsigned long long)offset, len);
1389 } else if (TAILQ_FIRST(&acks) == NULL)
1393 fatal("Unexpected ACK %u", id);
1395 if (id == startid || len == 0 ||
1396 id - ackid >= conn->num_requests) {
1400 get_msg(conn->fd_in, &msg);
1401 type = buffer_get_char(&msg);
1402 r_id = buffer_get_int(&msg);
1404 if (type != SSH2_FXP_STATUS)
1405 fatal("Expected SSH2_FXP_STATUS(%d) packet, "
1406 "got %d", SSH2_FXP_STATUS, type);
1408 status = buffer_get_int(&msg);
1409 debug3("SSH2_FXP_STATUS %d", status);
1411 /* Find the request in our queue */
1412 for (ack = TAILQ_FIRST(&acks);
1413 ack != NULL && ack->id != r_id;
1414 ack = TAILQ_NEXT(ack, tq))
1417 fatal("Can't find request for ID %u", r_id);
1418 TAILQ_REMOVE(&acks, ack, tq);
1419 debug3("In write loop, ack for %u %u bytes at %lld",
1420 ack->id, ack->len, (long long)ack->offset);
1426 fatal("%s: offset < 0", __func__);
1431 stop_progress_meter();
1434 if (status != SSH2_FX_OK) {
1435 error("Couldn't write to remote file \"%s\": %s",
1436 remote_path, fx2txt(status));
1440 if (close(local_fd) == -1) {
1441 error("Couldn't close local file \"%s\": %s", local_path,
1446 /* Override umask and utimes if asked */
1448 do_fsetstat(conn, handle, handle_len, &a);
1450 if (do_close(conn, handle, handle_len) != SSH2_FX_OK)
1458 upload_dir_internal(struct sftp_conn *conn, char *src, char *dst,
1459 int pflag, int printflag, int depth)
1461 int ret = 0, status;
1464 char *filename, *new_src, *new_dst;
1468 if (depth >= MAX_DIR_DEPTH) {
1469 error("Maximum directory depth exceeded: %d levels", depth);
1473 if (stat(src, &sb) == -1) {
1474 error("Couldn't stat directory \"%s\": %s",
1475 src, strerror(errno));
1478 if (!S_ISDIR(sb.st_mode)) {
1479 error("\"%s\" is not a directory", src);
1483 printf("Entering %s\n", src);
1486 stat_to_attrib(&sb, &a);
1487 a.flags &= ~SSH2_FILEXFER_ATTR_SIZE;
1488 a.flags &= ~SSH2_FILEXFER_ATTR_UIDGID;
1491 a.flags &= ~SSH2_FILEXFER_ATTR_ACMODTIME;
1493 status = do_mkdir(conn, dst, &a, 0);
1495 * we lack a portable status for errno EEXIST,
1496 * so if we get a SSH2_FX_FAILURE back we must check
1497 * if it was created successfully.
1499 if (status != SSH2_FX_OK) {
1500 if (status != SSH2_FX_FAILURE)
1502 if (do_stat(conn, dst, 0) == NULL)
1506 if ((dirp = opendir(src)) == NULL) {
1507 error("Failed to open dir \"%s\": %s", src, strerror(errno));
1511 while (((dp = readdir(dirp)) != NULL) && !interrupted) {
1514 filename = dp->d_name;
1515 new_dst = path_append(dst, filename);
1516 new_src = path_append(src, filename);
1518 if (S_ISDIR(DTTOIF(dp->d_type))) {
1519 if (strcmp(filename, ".") == 0 ||
1520 strcmp(filename, "..") == 0)
1523 if (upload_dir_internal(conn, new_src, new_dst,
1524 pflag, depth + 1, printflag) == -1)
1526 } else if (S_ISREG(DTTOIF(dp->d_type)) ) {
1527 if (do_upload(conn, new_src, new_dst, pflag) == -1) {
1528 error("Uploading of file %s to %s failed!",
1533 logit("%s: not a regular file\n", filename);
1538 do_setstat(conn, dst, &a);
1540 (void) closedir(dirp);
1545 upload_dir(struct sftp_conn *conn, char *src, char *dst, int printflag,
1551 if ((dst_canon = do_realpath(conn, dst)) == NULL) {
1552 error("Unable to canonicalise path \"%s\"", dst);
1556 ret = upload_dir_internal(conn, src, dst_canon, pflag, printflag, 0);
1562 path_append(char *p1, char *p2)
1565 size_t len = strlen(p1) + strlen(p2) + 2;
1568 strlcpy(ret, p1, len);
1569 if (p1[0] != '\0' && p1[strlen(p1) - 1] != '/')
1570 strlcat(ret, "/", len);
1571 strlcat(ret, p2, len);