1 /* $OpenBSD: sftp-client.c,v 1.101 2013/07/25 00:56:51 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>
52 #include "progressmeter.h"
56 #include "sftp-common.h"
57 #include "sftp-client.h"
59 extern volatile sig_atomic_t interrupted;
60 extern int showprogress;
62 /* Minimum amount of data to read at a time */
63 #define MIN_READ_SIZE 512
65 /* Maximum depth to descend in directory trees */
66 #define MAX_DIR_DEPTH 64
71 u_int transfer_buflen;
75 #define SFTP_EXT_POSIX_RENAME 0x00000001
76 #define SFTP_EXT_STATVFS 0x00000002
77 #define SFTP_EXT_FSTATVFS 0x00000004
78 #define SFTP_EXT_HARDLINK 0x00000008
81 struct bwlimit bwlimit_in, bwlimit_out;
85 get_handle(struct sftp_conn *conn, u_int expected_id, u_int *len,
86 const char *errfmt, ...) __attribute__((format(printf, 4, 5)));
90 sftpio(void *_bwlimit, size_t amount)
92 struct bwlimit *bwlimit = (struct bwlimit *)_bwlimit;
94 bandwidth_limit(bwlimit, amount);
99 send_msg(struct sftp_conn *conn, Buffer *m)
104 if (buffer_len(m) > SFTP_MAX_MSG_LENGTH)
105 fatal("Outbound message too long %u", buffer_len(m));
107 /* Send length first */
108 put_u32(mlen, buffer_len(m));
109 iov[0].iov_base = mlen;
110 iov[0].iov_len = sizeof(mlen);
111 iov[1].iov_base = buffer_ptr(m);
112 iov[1].iov_len = buffer_len(m);
114 if (atomiciov6(writev, conn->fd_out, iov, 2,
115 conn->limit_kbps > 0 ? sftpio : NULL, &conn->bwlimit_out) !=
116 buffer_len(m) + sizeof(mlen))
117 fatal("Couldn't send packet: %s", strerror(errno));
123 get_msg(struct sftp_conn *conn, Buffer *m)
127 buffer_append_space(m, 4);
128 if (atomicio6(read, conn->fd_in, buffer_ptr(m), 4,
129 conn->limit_kbps > 0 ? sftpio : NULL, &conn->bwlimit_in) != 4) {
131 fatal("Connection closed");
133 fatal("Couldn't read packet: %s", strerror(errno));
136 msg_len = buffer_get_int(m);
137 if (msg_len > SFTP_MAX_MSG_LENGTH)
138 fatal("Received message too long %u", msg_len);
140 buffer_append_space(m, msg_len);
141 if (atomicio6(read, conn->fd_in, buffer_ptr(m), msg_len,
142 conn->limit_kbps > 0 ? sftpio : NULL, &conn->bwlimit_in)
145 fatal("Connection closed");
147 fatal("Read packet: %s", strerror(errno));
152 send_string_request(struct sftp_conn *conn, u_int id, u_int code, char *s,
158 buffer_put_char(&msg, code);
159 buffer_put_int(&msg, id);
160 buffer_put_string(&msg, s, len);
161 send_msg(conn, &msg);
162 debug3("Sent message fd %d T:%u I:%u", conn->fd_out, code, id);
167 send_string_attrs_request(struct sftp_conn *conn, u_int id, u_int code,
168 char *s, u_int len, Attrib *a)
173 buffer_put_char(&msg, code);
174 buffer_put_int(&msg, id);
175 buffer_put_string(&msg, s, len);
176 encode_attrib(&msg, a);
177 send_msg(conn, &msg);
178 debug3("Sent message fd %d T:%u I:%u", conn->fd_out, code, id);
183 get_status(struct sftp_conn *conn, u_int expected_id)
186 u_int type, id, status;
190 type = buffer_get_char(&msg);
191 id = buffer_get_int(&msg);
193 if (id != expected_id)
194 fatal("ID mismatch (%u != %u)", id, expected_id);
195 if (type != SSH2_FXP_STATUS)
196 fatal("Expected SSH2_FXP_STATUS(%u) packet, got %u",
197 SSH2_FXP_STATUS, type);
199 status = buffer_get_int(&msg);
202 debug3("SSH2_FXP_STATUS %u", status);
208 get_handle(struct sftp_conn *conn, u_int expected_id, u_int *len,
209 const char *errfmt, ...)
213 char *handle, errmsg[256];
217 va_start(args, errfmt);
219 vsnprintf(errmsg, sizeof(errmsg), errfmt, args);
224 type = buffer_get_char(&msg);
225 id = buffer_get_int(&msg);
227 if (id != expected_id)
228 fatal("%s: ID mismatch (%u != %u)",
229 errfmt == NULL ? __func__ : errmsg, id, expected_id);
230 if (type == SSH2_FXP_STATUS) {
231 status = buffer_get_int(&msg);
233 error("%s: %s", errmsg, fx2txt(status));
236 } else if (type != SSH2_FXP_HANDLE)
237 fatal("%s: Expected SSH2_FXP_HANDLE(%u) packet, got %u",
238 errfmt == NULL ? __func__ : errmsg, SSH2_FXP_HANDLE, type);
240 handle = buffer_get_string(&msg, len);
247 get_decode_stat(struct sftp_conn *conn, u_int expected_id, int quiet)
256 type = buffer_get_char(&msg);
257 id = buffer_get_int(&msg);
259 debug3("Received stat reply T:%u I:%u", type, id);
260 if (id != expected_id)
261 fatal("ID mismatch (%u != %u)", id, expected_id);
262 if (type == SSH2_FXP_STATUS) {
263 int status = buffer_get_int(&msg);
266 debug("Couldn't stat remote file: %s", fx2txt(status));
268 error("Couldn't stat remote file: %s", fx2txt(status));
271 } else if (type != SSH2_FXP_ATTRS) {
272 fatal("Expected SSH2_FXP_ATTRS(%u) packet, got %u",
273 SSH2_FXP_ATTRS, type);
275 a = decode_attrib(&msg);
282 get_decode_statvfs(struct sftp_conn *conn, struct sftp_statvfs *st,
283 u_int expected_id, int quiet)
286 u_int type, id, flag;
291 type = buffer_get_char(&msg);
292 id = buffer_get_int(&msg);
294 debug3("Received statvfs reply T:%u I:%u", type, id);
295 if (id != expected_id)
296 fatal("ID mismatch (%u != %u)", id, expected_id);
297 if (type == SSH2_FXP_STATUS) {
298 int status = buffer_get_int(&msg);
301 debug("Couldn't statvfs: %s", fx2txt(status));
303 error("Couldn't statvfs: %s", fx2txt(status));
306 } else if (type != SSH2_FXP_EXTENDED_REPLY) {
307 fatal("Expected SSH2_FXP_EXTENDED_REPLY(%u) packet, got %u",
308 SSH2_FXP_EXTENDED_REPLY, type);
311 bzero(st, sizeof(*st));
312 st->f_bsize = buffer_get_int64(&msg);
313 st->f_frsize = buffer_get_int64(&msg);
314 st->f_blocks = buffer_get_int64(&msg);
315 st->f_bfree = buffer_get_int64(&msg);
316 st->f_bavail = buffer_get_int64(&msg);
317 st->f_files = buffer_get_int64(&msg);
318 st->f_ffree = buffer_get_int64(&msg);
319 st->f_favail = buffer_get_int64(&msg);
320 st->f_fsid = buffer_get_int64(&msg);
321 flag = buffer_get_int64(&msg);
322 st->f_namemax = buffer_get_int64(&msg);
324 st->f_flag = (flag & SSH2_FXE_STATVFS_ST_RDONLY) ? ST_RDONLY : 0;
325 st->f_flag |= (flag & SSH2_FXE_STATVFS_ST_NOSUID) ? ST_NOSUID : 0;
333 do_init(int fd_in, int fd_out, u_int transfer_buflen, u_int num_requests,
334 u_int64_t limit_kbps)
338 struct sftp_conn *ret;
340 ret = xmalloc(sizeof(*ret));
342 ret->fd_out = fd_out;
343 ret->transfer_buflen = transfer_buflen;
344 ret->num_requests = num_requests;
349 buffer_put_char(&msg, SSH2_FXP_INIT);
350 buffer_put_int(&msg, SSH2_FILEXFER_VERSION);
357 /* Expecting a VERSION reply */
358 if ((type = buffer_get_char(&msg)) != SSH2_FXP_VERSION) {
359 error("Invalid packet back from SSH2_FXP_INIT (type %u)",
364 ret->version = buffer_get_int(&msg);
366 debug2("Remote version: %u", ret->version);
368 /* Check for extensions */
369 while (buffer_len(&msg) > 0) {
370 char *name = buffer_get_string(&msg, NULL);
371 char *value = buffer_get_string(&msg, NULL);
374 if (strcmp(name, "posix-rename@openssh.com") == 0 &&
375 strcmp(value, "1") == 0) {
376 ret->exts |= SFTP_EXT_POSIX_RENAME;
378 } else if (strcmp(name, "statvfs@openssh.com") == 0 &&
379 strcmp(value, "2") == 0) {
380 ret->exts |= SFTP_EXT_STATVFS;
382 } else if (strcmp(name, "fstatvfs@openssh.com") == 0 &&
383 strcmp(value, "2") == 0) {
384 ret->exts |= SFTP_EXT_FSTATVFS;
386 } else if (strcmp(name, "hardlink@openssh.com") == 0 &&
387 strcmp(value, "1") == 0) {
388 ret->exts |= SFTP_EXT_HARDLINK;
392 debug2("Server supports extension \"%s\" revision %s",
395 debug2("Unrecognised server extension \"%s\"", name);
403 /* Some filexfer v.0 servers don't support large packets */
404 if (ret->version == 0)
405 ret->transfer_buflen = MIN(ret->transfer_buflen, 20480);
407 ret->limit_kbps = limit_kbps;
408 if (ret->limit_kbps > 0) {
409 bandwidth_limit_init(&ret->bwlimit_in, ret->limit_kbps,
410 ret->transfer_buflen);
411 bandwidth_limit_init(&ret->bwlimit_out, ret->limit_kbps,
412 ret->transfer_buflen);
419 sftp_proto_version(struct sftp_conn *conn)
421 return conn->version;
425 do_close(struct sftp_conn *conn, char *handle, u_int handle_len)
433 buffer_put_char(&msg, SSH2_FXP_CLOSE);
434 buffer_put_int(&msg, id);
435 buffer_put_string(&msg, handle, handle_len);
436 send_msg(conn, &msg);
437 debug3("Sent message SSH2_FXP_CLOSE I:%u", id);
439 status = get_status(conn, id);
440 if (status != SSH2_FX_OK)
441 error("Couldn't close file: %s", fx2txt(status));
450 do_lsreaddir(struct sftp_conn *conn, char *path, int printflag,
454 u_int count, type, id, handle_len, i, expected_id, ents = 0;
460 buffer_put_char(&msg, SSH2_FXP_OPENDIR);
461 buffer_put_int(&msg, id);
462 buffer_put_cstring(&msg, path);
463 send_msg(conn, &msg);
465 handle = get_handle(conn, id, &handle_len,
466 "remote readdir(\"%s\")", path);
467 if (handle == NULL) {
474 *dir = xmalloc(sizeof(**dir));
478 for (; !interrupted;) {
479 id = expected_id = conn->msg_id++;
481 debug3("Sending SSH2_FXP_READDIR I:%u", id);
484 buffer_put_char(&msg, SSH2_FXP_READDIR);
485 buffer_put_int(&msg, id);
486 buffer_put_string(&msg, handle, handle_len);
487 send_msg(conn, &msg);
493 type = buffer_get_char(&msg);
494 id = buffer_get_int(&msg);
496 debug3("Received reply T:%u I:%u", type, id);
498 if (id != expected_id)
499 fatal("ID mismatch (%u != %u)", id, expected_id);
501 if (type == SSH2_FXP_STATUS) {
502 int status = buffer_get_int(&msg);
504 debug3("Received SSH2_FXP_STATUS %d", status);
506 if (status == SSH2_FX_EOF) {
509 error("Couldn't read directory: %s",
511 do_close(conn, handle, handle_len);
516 } else if (type != SSH2_FXP_NAME)
517 fatal("Expected SSH2_FXP_NAME(%u) packet, got %u",
518 SSH2_FXP_NAME, type);
520 count = buffer_get_int(&msg);
523 debug3("Received %d SSH2_FXP_NAME responses", count);
524 for (i = 0; i < count; i++) {
525 char *filename, *longname;
528 filename = buffer_get_string(&msg, NULL);
529 longname = buffer_get_string(&msg, NULL);
530 a = decode_attrib(&msg);
533 printf("%s\n", longname);
536 * Directory entries should never contain '/'
537 * These can be used to attack recursive ops
538 * (e.g. send '../../../../etc/passwd')
540 if (strchr(filename, '/') != NULL) {
541 error("Server sent suspect path \"%s\" "
542 "during readdir of \"%s\"", filename, path);
547 *dir = xrealloc(*dir, ents + 2, sizeof(**dir));
548 (*dir)[ents] = xmalloc(sizeof(***dir));
549 (*dir)[ents]->filename = xstrdup(filename);
550 (*dir)[ents]->longname = xstrdup(longname);
551 memcpy(&(*dir)[ents]->a, a, sizeof(*a));
552 (*dir)[++ents] = NULL;
561 do_close(conn, handle, handle_len);
564 /* Don't return partial matches on interrupt */
565 if (interrupted && dir != NULL && *dir != NULL) {
566 free_sftp_dirents(*dir);
567 *dir = xmalloc(sizeof(**dir));
575 do_readdir(struct sftp_conn *conn, char *path, SFTP_DIRENT ***dir)
577 return(do_lsreaddir(conn, path, 0, dir));
580 void free_sftp_dirents(SFTP_DIRENT **s)
584 for (i = 0; s[i]; i++) {
585 free(s[i]->filename);
586 free(s[i]->longname);
593 do_rm(struct sftp_conn *conn, char *path)
597 debug2("Sending SSH2_FXP_REMOVE \"%s\"", path);
600 send_string_request(conn, id, SSH2_FXP_REMOVE, path, strlen(path));
601 status = get_status(conn, id);
602 if (status != SSH2_FX_OK)
603 error("Couldn't delete file: %s", fx2txt(status));
608 do_mkdir(struct sftp_conn *conn, char *path, Attrib *a, int printflag)
613 send_string_attrs_request(conn, id, SSH2_FXP_MKDIR, path,
616 status = get_status(conn, id);
617 if (status != SSH2_FX_OK && printflag)
618 error("Couldn't create directory: %s", fx2txt(status));
624 do_rmdir(struct sftp_conn *conn, char *path)
629 send_string_request(conn, id, SSH2_FXP_RMDIR, path,
632 status = get_status(conn, id);
633 if (status != SSH2_FX_OK)
634 error("Couldn't remove directory: %s", fx2txt(status));
640 do_stat(struct sftp_conn *conn, char *path, int quiet)
646 send_string_request(conn, id,
647 conn->version == 0 ? SSH2_FXP_STAT_VERSION_0 : SSH2_FXP_STAT,
650 return(get_decode_stat(conn, id, quiet));
654 do_lstat(struct sftp_conn *conn, char *path, int quiet)
658 if (conn->version == 0) {
660 debug("Server version does not support lstat operation");
662 logit("Server version does not support lstat operation");
663 return(do_stat(conn, path, quiet));
667 send_string_request(conn, id, SSH2_FXP_LSTAT, path,
670 return(get_decode_stat(conn, id, quiet));
675 do_fstat(struct sftp_conn *conn, char *handle, u_int handle_len, int quiet)
680 send_string_request(conn, id, SSH2_FXP_FSTAT, handle,
683 return(get_decode_stat(conn, id, quiet));
688 do_setstat(struct sftp_conn *conn, char *path, Attrib *a)
693 send_string_attrs_request(conn, id, SSH2_FXP_SETSTAT, path,
696 status = get_status(conn, id);
697 if (status != SSH2_FX_OK)
698 error("Couldn't setstat on \"%s\": %s", path,
705 do_fsetstat(struct sftp_conn *conn, char *handle, u_int handle_len,
711 send_string_attrs_request(conn, id, SSH2_FXP_FSETSTAT, handle,
714 status = get_status(conn, id);
715 if (status != SSH2_FX_OK)
716 error("Couldn't fsetstat: %s", fx2txt(status));
722 do_realpath(struct sftp_conn *conn, char *path)
725 u_int type, expected_id, count, id;
726 char *filename, *longname;
729 expected_id = id = conn->msg_id++;
730 send_string_request(conn, id, SSH2_FXP_REALPATH, path,
736 type = buffer_get_char(&msg);
737 id = buffer_get_int(&msg);
739 if (id != expected_id)
740 fatal("ID mismatch (%u != %u)", id, expected_id);
742 if (type == SSH2_FXP_STATUS) {
743 u_int status = buffer_get_int(&msg);
745 error("Couldn't canonicalise: %s", fx2txt(status));
748 } else if (type != SSH2_FXP_NAME)
749 fatal("Expected SSH2_FXP_NAME(%u) packet, got %u",
750 SSH2_FXP_NAME, type);
752 count = buffer_get_int(&msg);
754 fatal("Got multiple names (%d) from SSH_FXP_REALPATH", count);
756 filename = buffer_get_string(&msg, NULL);
757 longname = buffer_get_string(&msg, NULL);
758 a = decode_attrib(&msg);
760 debug3("SSH_FXP_REALPATH %s -> %s size %lu", path, filename,
761 (unsigned long)a->size);
771 do_rename(struct sftp_conn *conn, char *oldpath, char *newpath)
778 /* Send rename request */
780 if ((conn->exts & SFTP_EXT_POSIX_RENAME)) {
781 buffer_put_char(&msg, SSH2_FXP_EXTENDED);
782 buffer_put_int(&msg, id);
783 buffer_put_cstring(&msg, "posix-rename@openssh.com");
785 buffer_put_char(&msg, SSH2_FXP_RENAME);
786 buffer_put_int(&msg, id);
788 buffer_put_cstring(&msg, oldpath);
789 buffer_put_cstring(&msg, newpath);
790 send_msg(conn, &msg);
791 debug3("Sent message %s \"%s\" -> \"%s\"",
792 (conn->exts & SFTP_EXT_POSIX_RENAME) ? "posix-rename@openssh.com" :
793 "SSH2_FXP_RENAME", oldpath, newpath);
796 status = get_status(conn, id);
797 if (status != SSH2_FX_OK)
798 error("Couldn't rename file \"%s\" to \"%s\": %s", oldpath,
799 newpath, fx2txt(status));
805 do_hardlink(struct sftp_conn *conn, char *oldpath, char *newpath)
810 if ((conn->exts & SFTP_EXT_HARDLINK) == 0) {
811 error("Server does not support hardlink@openssh.com extension");
817 /* Send link request */
819 buffer_put_char(&msg, SSH2_FXP_EXTENDED);
820 buffer_put_int(&msg, id);
821 buffer_put_cstring(&msg, "hardlink@openssh.com");
822 buffer_put_cstring(&msg, oldpath);
823 buffer_put_cstring(&msg, newpath);
824 send_msg(conn, &msg);
825 debug3("Sent message hardlink@openssh.com \"%s\" -> \"%s\"",
829 status = get_status(conn, id);
830 if (status != SSH2_FX_OK)
831 error("Couldn't link file \"%s\" to \"%s\": %s", oldpath,
832 newpath, fx2txt(status));
838 do_symlink(struct sftp_conn *conn, char *oldpath, char *newpath)
843 if (conn->version < 3) {
844 error("This server does not support the symlink operation");
845 return(SSH2_FX_OP_UNSUPPORTED);
850 /* Send symlink request */
852 buffer_put_char(&msg, SSH2_FXP_SYMLINK);
853 buffer_put_int(&msg, id);
854 buffer_put_cstring(&msg, oldpath);
855 buffer_put_cstring(&msg, newpath);
856 send_msg(conn, &msg);
857 debug3("Sent message SSH2_FXP_SYMLINK \"%s\" -> \"%s\"", oldpath,
861 status = get_status(conn, id);
862 if (status != SSH2_FX_OK)
863 error("Couldn't symlink file \"%s\" to \"%s\": %s", oldpath,
864 newpath, fx2txt(status));
871 do_readlink(struct sftp_conn *conn, char *path)
874 u_int type, expected_id, count, id;
875 char *filename, *longname;
878 expected_id = id = conn->msg_id++;
879 send_string_request(conn, id, SSH2_FXP_READLINK, path, strlen(path));
884 type = buffer_get_char(&msg);
885 id = buffer_get_int(&msg);
887 if (id != expected_id)
888 fatal("ID mismatch (%u != %u)", id, expected_id);
890 if (type == SSH2_FXP_STATUS) {
891 u_int status = buffer_get_int(&msg);
893 error("Couldn't readlink: %s", fx2txt(status));
896 } else if (type != SSH2_FXP_NAME)
897 fatal("Expected SSH2_FXP_NAME(%u) packet, got %u",
898 SSH2_FXP_NAME, type);
900 count = buffer_get_int(&msg);
902 fatal("Got multiple names (%d) from SSH_FXP_READLINK", count);
904 filename = buffer_get_string(&msg, NULL);
905 longname = buffer_get_string(&msg, NULL);
906 a = decode_attrib(&msg);
908 debug3("SSH_FXP_READLINK %s -> %s", path, filename);
919 do_statvfs(struct sftp_conn *conn, const char *path, struct sftp_statvfs *st,
925 if ((conn->exts & SFTP_EXT_STATVFS) == 0) {
926 error("Server does not support statvfs@openssh.com extension");
934 buffer_put_char(&msg, SSH2_FXP_EXTENDED);
935 buffer_put_int(&msg, id);
936 buffer_put_cstring(&msg, "statvfs@openssh.com");
937 buffer_put_cstring(&msg, path);
938 send_msg(conn, &msg);
941 return get_decode_statvfs(conn, st, id, quiet);
946 do_fstatvfs(struct sftp_conn *conn, const char *handle, u_int handle_len,
947 struct sftp_statvfs *st, int quiet)
952 if ((conn->exts & SFTP_EXT_FSTATVFS) == 0) {
953 error("Server does not support fstatvfs@openssh.com extension");
961 buffer_put_char(&msg, SSH2_FXP_EXTENDED);
962 buffer_put_int(&msg, id);
963 buffer_put_cstring(&msg, "fstatvfs@openssh.com");
964 buffer_put_string(&msg, handle, handle_len);
965 send_msg(conn, &msg);
968 return get_decode_statvfs(conn, st, id, quiet);
973 send_read_request(struct sftp_conn *conn, u_int id, u_int64_t offset,
974 u_int len, char *handle, u_int handle_len)
980 buffer_put_char(&msg, SSH2_FXP_READ);
981 buffer_put_int(&msg, id);
982 buffer_put_string(&msg, handle, handle_len);
983 buffer_put_int64(&msg, offset);
984 buffer_put_int(&msg, len);
985 send_msg(conn, &msg);
990 do_download(struct sftp_conn *conn, char *remote_path, char *local_path,
991 Attrib *a, int pflag, int resume)
996 int local_fd = -1, status = 0, write_error;
997 int read_error, write_errno, reordered = 0;
998 u_int64_t offset = 0, size, highwater;
999 u_int handle_len, mode, type, id, buflen, num_req, max_req;
1000 off_t progress_counter;
1006 TAILQ_ENTRY(request) tq;
1008 TAILQ_HEAD(reqhead, request) requests;
1009 struct request *req;
1011 TAILQ_INIT(&requests);
1013 if (a == NULL && (a = do_stat(conn, remote_path, 0)) == NULL)
1016 /* Do not preserve set[ug]id here, as we do not preserve ownership */
1017 if (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)
1018 mode = a->perm & 0777;
1022 if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
1023 (!S_ISREG(a->perm))) {
1024 error("Cannot download non-regular file: %s", remote_path);
1028 if (a->flags & SSH2_FILEXFER_ATTR_SIZE)
1033 buflen = conn->transfer_buflen;
1036 /* Send open request */
1037 id = conn->msg_id++;
1038 buffer_put_char(&msg, SSH2_FXP_OPEN);
1039 buffer_put_int(&msg, id);
1040 buffer_put_cstring(&msg, remote_path);
1041 buffer_put_int(&msg, SSH2_FXF_READ);
1042 attrib_clear(&junk); /* Send empty attributes */
1043 encode_attrib(&msg, &junk);
1044 send_msg(conn, &msg);
1045 debug3("Sent message SSH2_FXP_OPEN I:%u P:%s", id, remote_path);
1047 handle = get_handle(conn, id, &handle_len,
1048 "remote open(\"%s\")", remote_path);
1049 if (handle == NULL) {
1054 local_fd = open(local_path, O_WRONLY | O_CREAT | (resume ? 0 : O_TRUNC),
1056 if (local_fd == -1) {
1057 error("Couldn't open local file \"%s\" for writing: %s",
1058 local_path, strerror(errno));
1061 offset = highwater = 0;
1063 if (fstat(local_fd, &st) == -1) {
1064 error("Unable to stat local file \"%s\": %s",
1065 local_path, strerror(errno));
1068 if ((size_t)st.st_size > size) {
1069 error("Unable to resume download of \"%s\": "
1070 "local file is larger than remote", local_path);
1072 do_close(conn, handle, handle_len);
1077 offset = highwater = st.st_size;
1080 /* Read from remote and write to local */
1081 write_error = read_error = write_errno = num_req = 0;
1083 progress_counter = offset;
1085 if (showprogress && size != 0)
1086 start_progress_meter(remote_path, size, &progress_counter);
1088 while (num_req > 0 || max_req > 0) {
1093 * Simulate EOF on interrupt: stop sending new requests and
1094 * allow outstanding requests to drain gracefully
1097 if (num_req == 0) /* If we haven't started yet... */
1102 /* Send some more requests */
1103 while (num_req < max_req) {
1104 debug3("Request range %llu -> %llu (%d/%d)",
1105 (unsigned long long)offset,
1106 (unsigned long long)offset + buflen - 1,
1108 req = xmalloc(sizeof(*req));
1109 req->id = conn->msg_id++;
1111 req->offset = offset;
1114 TAILQ_INSERT_TAIL(&requests, req, tq);
1115 send_read_request(conn, req->id, req->offset,
1116 req->len, handle, handle_len);
1120 get_msg(conn, &msg);
1121 type = buffer_get_char(&msg);
1122 id = buffer_get_int(&msg);
1123 debug3("Received reply T:%u I:%u R:%d", type, id, max_req);
1125 /* Find the request in our queue */
1126 for (req = TAILQ_FIRST(&requests);
1127 req != NULL && req->id != id;
1128 req = TAILQ_NEXT(req, tq))
1131 fatal("Unexpected reply %u", id);
1134 case SSH2_FXP_STATUS:
1135 status = buffer_get_int(&msg);
1136 if (status != SSH2_FX_EOF)
1139 TAILQ_REMOVE(&requests, req, tq);
1144 data = buffer_get_string(&msg, &len);
1145 debug3("Received data %llu -> %llu",
1146 (unsigned long long)req->offset,
1147 (unsigned long long)req->offset + len - 1);
1149 fatal("Received more data than asked for "
1150 "%u > %u", len, req->len);
1151 if ((lseek(local_fd, req->offset, SEEK_SET) == -1 ||
1152 atomicio(vwrite, local_fd, data, len) != len) &&
1154 write_errno = errno;
1158 else if (!reordered && req->offset <= highwater)
1159 highwater = req->offset + len;
1160 else if (!reordered && req->offset > highwater)
1162 progress_counter += len;
1165 if (len == req->len) {
1166 TAILQ_REMOVE(&requests, req, tq);
1170 /* Resend the request for the missing data */
1171 debug3("Short data block, re-requesting "
1172 "%llu -> %llu (%2d)",
1173 (unsigned long long)req->offset + len,
1174 (unsigned long long)req->offset +
1175 req->len - 1, num_req);
1176 req->id = conn->msg_id++;
1179 send_read_request(conn, req->id,
1180 req->offset, req->len, handle, handle_len);
1181 /* Reduce the request size */
1183 buflen = MAX(MIN_READ_SIZE, len);
1185 if (max_req > 0) { /* max_req = 0 iff EOF received */
1186 if (size > 0 && offset > size) {
1187 /* Only one request at a time
1188 * after the expected EOF */
1189 debug3("Finish at %llu (%2d)",
1190 (unsigned long long)offset,
1193 } else if (max_req <= conn->num_requests) {
1199 fatal("Expected SSH2_FXP_DATA(%u) packet, got %u",
1200 SSH2_FXP_DATA, type);
1204 if (showprogress && size)
1205 stop_progress_meter();
1208 if (TAILQ_FIRST(&requests) != NULL)
1209 fatal("Transfer complete, but requests still in queue");
1210 /* Truncate at highest contiguous point to avoid holes on interrupt */
1211 if (read_error || write_error || interrupted) {
1212 if (reordered && resume) {
1213 error("Unable to resume download of \"%s\": "
1214 "server reordered requests", local_path);
1216 debug("truncating at %llu", (unsigned long long)highwater);
1217 ftruncate(local_fd, highwater);
1220 error("Couldn't read from remote file \"%s\" : %s",
1221 remote_path, fx2txt(status));
1222 do_close(conn, handle, handle_len);
1223 } else if (write_error) {
1224 error("Couldn't write to \"%s\": %s", local_path,
1225 strerror(write_errno));
1227 do_close(conn, handle, handle_len);
1229 status = do_close(conn, handle, handle_len);
1232 /* Override umask and utimes if asked */
1234 if (pflag && fchmod(local_fd, mode) == -1)
1236 if (pflag && chmod(local_path, mode) == -1)
1237 #endif /* HAVE_FCHMOD */
1238 error("Couldn't set mode on \"%s\": %s", local_path,
1240 if (pflag && (a->flags & SSH2_FILEXFER_ATTR_ACMODTIME)) {
1241 struct timeval tv[2];
1242 tv[0].tv_sec = a->atime;
1243 tv[1].tv_sec = a->mtime;
1244 tv[0].tv_usec = tv[1].tv_usec = 0;
1245 if (utimes(local_path, tv) == -1)
1246 error("Can't set times on \"%s\": %s",
1247 local_path, strerror(errno));
1258 download_dir_internal(struct sftp_conn *conn, char *src, char *dst,
1259 Attrib *dirattrib, int pflag, int printflag, int depth, int resume)
1262 SFTP_DIRENT **dir_entries;
1263 char *filename, *new_src, *new_dst;
1266 if (depth >= MAX_DIR_DEPTH) {
1267 error("Maximum directory depth exceeded: %d levels", depth);
1271 if (dirattrib == NULL &&
1272 (dirattrib = do_stat(conn, src, 1)) == NULL) {
1273 error("Unable to stat remote directory \"%s\"", src);
1276 if (!S_ISDIR(dirattrib->perm)) {
1277 error("\"%s\" is not a directory", src);
1281 printf("Retrieving %s\n", src);
1283 if (dirattrib->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)
1284 mode = dirattrib->perm & 01777;
1286 debug("Server did not send permissions for "
1287 "directory \"%s\"", dst);
1290 if (mkdir(dst, mode) == -1 && errno != EEXIST) {
1291 error("mkdir %s: %s", dst, strerror(errno));
1295 if (do_readdir(conn, src, &dir_entries) == -1) {
1296 error("%s: Failed to get directory contents", src);
1300 for (i = 0; dir_entries[i] != NULL && !interrupted; i++) {
1301 filename = dir_entries[i]->filename;
1303 new_dst = path_append(dst, filename);
1304 new_src = path_append(src, filename);
1306 if (S_ISDIR(dir_entries[i]->a.perm)) {
1307 if (strcmp(filename, ".") == 0 ||
1308 strcmp(filename, "..") == 0)
1310 if (download_dir_internal(conn, new_src, new_dst,
1311 &(dir_entries[i]->a), pflag, printflag,
1312 depth + 1, resume) == -1)
1314 } else if (S_ISREG(dir_entries[i]->a.perm) ) {
1315 if (do_download(conn, new_src, new_dst,
1316 &(dir_entries[i]->a), pflag, resume) == -1) {
1317 error("Download of file %s to %s failed",
1322 logit("%s: not a regular file\n", new_src);
1329 if (dirattrib->flags & SSH2_FILEXFER_ATTR_ACMODTIME) {
1330 struct timeval tv[2];
1331 tv[0].tv_sec = dirattrib->atime;
1332 tv[1].tv_sec = dirattrib->mtime;
1333 tv[0].tv_usec = tv[1].tv_usec = 0;
1334 if (utimes(dst, tv) == -1)
1335 error("Can't set times on \"%s\": %s",
1336 dst, strerror(errno));
1338 debug("Server did not send times for directory "
1342 free_sftp_dirents(dir_entries);
1348 download_dir(struct sftp_conn *conn, char *src, char *dst,
1349 Attrib *dirattrib, int pflag, int printflag, int resume)
1354 if ((src_canon = do_realpath(conn, src)) == NULL) {
1355 error("Unable to canonicalise path \"%s\"", src);
1359 ret = download_dir_internal(conn, src_canon, dst,
1360 dirattrib, pflag, printflag, 0, resume);
1366 do_upload(struct sftp_conn *conn, char *local_path, char *remote_path,
1370 int status = SSH2_FX_OK;
1371 u_int handle_len, id, type;
1372 off_t offset, progress_counter;
1373 char *handle, *data;
1379 struct outstanding_ack {
1383 TAILQ_ENTRY(outstanding_ack) tq;
1385 TAILQ_HEAD(ackhead, outstanding_ack) acks;
1386 struct outstanding_ack *ack = NULL;
1390 if ((local_fd = open(local_path, O_RDONLY, 0)) == -1) {
1391 error("Couldn't open local file \"%s\" for reading: %s",
1392 local_path, strerror(errno));
1395 if (fstat(local_fd, &sb) == -1) {
1396 error("Couldn't fstat local file \"%s\": %s",
1397 local_path, strerror(errno));
1401 if (!S_ISREG(sb.st_mode)) {
1402 error("%s is not a regular file", local_path);
1406 stat_to_attrib(&sb, &a);
1408 a.flags &= ~SSH2_FILEXFER_ATTR_SIZE;
1409 a.flags &= ~SSH2_FILEXFER_ATTR_UIDGID;
1412 a.flags &= ~SSH2_FILEXFER_ATTR_ACMODTIME;
1416 /* Send open request */
1417 id = conn->msg_id++;
1418 buffer_put_char(&msg, SSH2_FXP_OPEN);
1419 buffer_put_int(&msg, id);
1420 buffer_put_cstring(&msg, remote_path);
1421 buffer_put_int(&msg, SSH2_FXF_WRITE|SSH2_FXF_CREAT|SSH2_FXF_TRUNC);
1422 encode_attrib(&msg, &a);
1423 send_msg(conn, &msg);
1424 debug3("Sent message SSH2_FXP_OPEN I:%u P:%s", id, remote_path);
1428 handle = get_handle(conn, id, &handle_len,
1429 "remote open(\"%s\")", remote_path);
1430 if (handle == NULL) {
1436 startid = ackid = id + 1;
1437 data = xmalloc(conn->transfer_buflen);
1439 /* Read from local and write to remote */
1440 offset = progress_counter = 0;
1442 start_progress_meter(local_path, sb.st_size,
1449 * Can't use atomicio here because it returns 0 on EOF,
1450 * thus losing the last block of the file.
1451 * Simulate an EOF on interrupt, allowing ACKs from the
1454 if (interrupted || status != SSH2_FX_OK)
1457 len = read(local_fd, data, conn->transfer_buflen);
1458 while ((len == -1) &&
1459 (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK));
1462 fatal("Couldn't read from \"%s\": %s", local_path,
1466 ack = xmalloc(sizeof(*ack));
1468 ack->offset = offset;
1470 TAILQ_INSERT_TAIL(&acks, ack, tq);
1473 buffer_put_char(&msg, SSH2_FXP_WRITE);
1474 buffer_put_int(&msg, ack->id);
1475 buffer_put_string(&msg, handle, handle_len);
1476 buffer_put_int64(&msg, offset);
1477 buffer_put_string(&msg, data, len);
1478 send_msg(conn, &msg);
1479 debug3("Sent message SSH2_FXP_WRITE I:%u O:%llu S:%u",
1480 id, (unsigned long long)offset, len);
1481 } else if (TAILQ_FIRST(&acks) == NULL)
1485 fatal("Unexpected ACK %u", id);
1487 if (id == startid || len == 0 ||
1488 id - ackid >= conn->num_requests) {
1492 get_msg(conn, &msg);
1493 type = buffer_get_char(&msg);
1494 r_id = buffer_get_int(&msg);
1496 if (type != SSH2_FXP_STATUS)
1497 fatal("Expected SSH2_FXP_STATUS(%d) packet, "
1498 "got %d", SSH2_FXP_STATUS, type);
1500 status = buffer_get_int(&msg);
1501 debug3("SSH2_FXP_STATUS %d", status);
1503 /* Find the request in our queue */
1504 for (ack = TAILQ_FIRST(&acks);
1505 ack != NULL && ack->id != r_id;
1506 ack = TAILQ_NEXT(ack, tq))
1509 fatal("Can't find request for ID %u", r_id);
1510 TAILQ_REMOVE(&acks, ack, tq);
1511 debug3("In write loop, ack for %u %u bytes at %lld",
1512 ack->id, ack->len, (long long)ack->offset);
1514 progress_counter += ack->len;
1519 fatal("%s: offset < 0", __func__);
1524 stop_progress_meter();
1527 if (status != SSH2_FX_OK) {
1528 error("Couldn't write to remote file \"%s\": %s",
1529 remote_path, fx2txt(status));
1533 if (close(local_fd) == -1) {
1534 error("Couldn't close local file \"%s\": %s", local_path,
1539 /* Override umask and utimes if asked */
1541 do_fsetstat(conn, handle, handle_len, &a);
1543 if (do_close(conn, handle, handle_len) != SSH2_FX_OK)
1551 upload_dir_internal(struct sftp_conn *conn, char *src, char *dst,
1552 int pflag, int printflag, int depth)
1554 int ret = 0, status;
1557 char *filename, *new_src, *new_dst;
1561 if (depth >= MAX_DIR_DEPTH) {
1562 error("Maximum directory depth exceeded: %d levels", depth);
1566 if (stat(src, &sb) == -1) {
1567 error("Couldn't stat directory \"%s\": %s",
1568 src, strerror(errno));
1571 if (!S_ISDIR(sb.st_mode)) {
1572 error("\"%s\" is not a directory", src);
1576 printf("Entering %s\n", src);
1579 stat_to_attrib(&sb, &a);
1580 a.flags &= ~SSH2_FILEXFER_ATTR_SIZE;
1581 a.flags &= ~SSH2_FILEXFER_ATTR_UIDGID;
1584 a.flags &= ~SSH2_FILEXFER_ATTR_ACMODTIME;
1586 status = do_mkdir(conn, dst, &a, 0);
1588 * we lack a portable status for errno EEXIST,
1589 * so if we get a SSH2_FX_FAILURE back we must check
1590 * if it was created successfully.
1592 if (status != SSH2_FX_OK) {
1593 if (status != SSH2_FX_FAILURE)
1595 if (do_stat(conn, dst, 0) == NULL)
1599 if ((dirp = opendir(src)) == NULL) {
1600 error("Failed to open dir \"%s\": %s", src, strerror(errno));
1604 while (((dp = readdir(dirp)) != NULL) && !interrupted) {
1607 filename = dp->d_name;
1608 new_dst = path_append(dst, filename);
1609 new_src = path_append(src, filename);
1611 if (lstat(new_src, &sb) == -1) {
1612 logit("%s: lstat failed: %s", filename,
1615 } else if (S_ISDIR(sb.st_mode)) {
1616 if (strcmp(filename, ".") == 0 ||
1617 strcmp(filename, "..") == 0)
1620 if (upload_dir_internal(conn, new_src, new_dst,
1621 pflag, printflag, depth + 1) == -1)
1623 } else if (S_ISREG(sb.st_mode)) {
1624 if (do_upload(conn, new_src, new_dst, pflag) == -1) {
1625 error("Uploading of file %s to %s failed!",
1630 logit("%s: not a regular file\n", filename);
1635 do_setstat(conn, dst, &a);
1637 (void) closedir(dirp);
1642 upload_dir(struct sftp_conn *conn, char *src, char *dst, int printflag,
1648 if ((dst_canon = do_realpath(conn, dst)) == NULL) {
1649 error("Unable to canonicalise path \"%s\"", dst);
1653 ret = upload_dir_internal(conn, src, dst_canon, pflag, printflag, 0);
1659 path_append(char *p1, char *p2)
1662 size_t len = strlen(p1) + strlen(p2) + 2;
1665 strlcpy(ret, p1, len);
1666 if (p1[0] != '\0' && p1[strlen(p1) - 1] != '/')
1667 strlcat(ret, "/", len);
1668 strlcat(ret, p2, len);