xref: /openbsd-src/usr.bin/ssh/sftp-client.c (revision d4c5fc9dc00f5a9cadd8c2de4e52d85d3c1c6003)
1 /* $OpenBSD: sftp-client.c,v 1.129 2018/05/25 04:25:46 djm Exp $ */
2 /*
3  * Copyright (c) 2001-2004 Damien Miller <djm@openbsd.org>
4  *
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.
8  *
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.
16  */
17 
18 /* XXX: memleaks */
19 /* XXX: signed vs unsigned */
20 /* XXX: remove all logging, only return status codes */
21 /* XXX: copy between two remote sites */
22 
23 #include <sys/types.h>
24 #include <sys/poll.h>
25 #include <sys/queue.h>
26 #include <sys/stat.h>
27 #include <sys/time.h>
28 #include <sys/statvfs.h>
29 #include <sys/uio.h>
30 
31 #include <dirent.h>
32 #include <errno.h>
33 #include <fcntl.h>
34 #include <signal.h>
35 #include <stdarg.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <unistd.h>
40 
41 #include "xmalloc.h"
42 #include "ssherr.h"
43 #include "sshbuf.h"
44 #include "log.h"
45 #include "atomicio.h"
46 #include "progressmeter.h"
47 #include "misc.h"
48 #include "utf8.h"
49 
50 #include "sftp.h"
51 #include "sftp-common.h"
52 #include "sftp-client.h"
53 
54 extern volatile sig_atomic_t interrupted;
55 extern int showprogress;
56 
57 /* Minimum amount of data to read at a time */
58 #define MIN_READ_SIZE	512
59 
60 /* Maximum depth to descend in directory trees */
61 #define MAX_DIR_DEPTH 64
62 
63 struct sftp_conn {
64 	int fd_in;
65 	int fd_out;
66 	u_int transfer_buflen;
67 	u_int num_requests;
68 	u_int version;
69 	u_int msg_id;
70 #define SFTP_EXT_POSIX_RENAME	0x00000001
71 #define SFTP_EXT_STATVFS	0x00000002
72 #define SFTP_EXT_FSTATVFS	0x00000004
73 #define SFTP_EXT_HARDLINK	0x00000008
74 #define SFTP_EXT_FSYNC		0x00000010
75 	u_int exts;
76 	u_int64_t limit_kbps;
77 	struct bwlimit bwlimit_in, bwlimit_out;
78 };
79 
80 static u_char *
81 get_handle(struct sftp_conn *conn, u_int expected_id, size_t *len,
82     const char *errfmt, ...) __attribute__((format(printf, 4, 5)));
83 
84 /* ARGSUSED */
85 static int
86 sftpio(void *_bwlimit, size_t amount)
87 {
88 	struct bwlimit *bwlimit = (struct bwlimit *)_bwlimit;
89 
90 	bandwidth_limit(bwlimit, amount);
91 	return 0;
92 }
93 
94 static void
95 send_msg(struct sftp_conn *conn, struct sshbuf *m)
96 {
97 	u_char mlen[4];
98 	struct iovec iov[2];
99 
100 	if (sshbuf_len(m) > SFTP_MAX_MSG_LENGTH)
101 		fatal("Outbound message too long %zu", sshbuf_len(m));
102 
103 	/* Send length first */
104 	put_u32(mlen, sshbuf_len(m));
105 	iov[0].iov_base = mlen;
106 	iov[0].iov_len = sizeof(mlen);
107 	iov[1].iov_base = (u_char *)sshbuf_ptr(m);
108 	iov[1].iov_len = sshbuf_len(m);
109 
110 	if (atomiciov6(writev, conn->fd_out, iov, 2,
111 	    conn->limit_kbps > 0 ? sftpio : NULL, &conn->bwlimit_out) !=
112 	    sshbuf_len(m) + sizeof(mlen))
113 		fatal("Couldn't send packet: %s", strerror(errno));
114 
115 	sshbuf_reset(m);
116 }
117 
118 static void
119 get_msg_extended(struct sftp_conn *conn, struct sshbuf *m, int initial)
120 {
121 	u_int msg_len;
122 	u_char *p;
123 	int r;
124 
125 	if ((r = sshbuf_reserve(m, 4, &p)) != 0)
126 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
127 	if (atomicio6(read, conn->fd_in, p, 4,
128 	    conn->limit_kbps > 0 ? sftpio : NULL, &conn->bwlimit_in) != 4) {
129 		if (errno == EPIPE || errno == ECONNRESET)
130 			fatal("Connection closed");
131 		else
132 			fatal("Couldn't read packet: %s", strerror(errno));
133 	}
134 
135 	if ((r = sshbuf_get_u32(m, &msg_len)) != 0)
136 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
137 	if (msg_len > SFTP_MAX_MSG_LENGTH) {
138 		do_log2(initial ? SYSLOG_LEVEL_ERROR : SYSLOG_LEVEL_FATAL,
139 		    "Received message too long %u", msg_len);
140 		fatal("Ensure the remote shell produces no output "
141 		    "for non-interactive sessions.");
142 	}
143 
144 	if ((r = sshbuf_reserve(m, msg_len, &p)) != 0)
145 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
146 	if (atomicio6(read, conn->fd_in, p, msg_len,
147 	    conn->limit_kbps > 0 ? sftpio : NULL, &conn->bwlimit_in)
148 	    != msg_len) {
149 		if (errno == EPIPE)
150 			fatal("Connection closed");
151 		else
152 			fatal("Read packet: %s", strerror(errno));
153 	}
154 }
155 
156 static void
157 get_msg(struct sftp_conn *conn, struct sshbuf *m)
158 {
159 	get_msg_extended(conn, m, 0);
160 }
161 
162 static void
163 send_string_request(struct sftp_conn *conn, u_int id, u_int code, const char *s,
164     u_int len)
165 {
166 	struct sshbuf *msg;
167 	int r;
168 
169 	if ((msg = sshbuf_new()) == NULL)
170 		fatal("%s: sshbuf_new failed", __func__);
171 	if ((r = sshbuf_put_u8(msg, code)) != 0 ||
172 	    (r = sshbuf_put_u32(msg, id)) != 0 ||
173 	    (r = sshbuf_put_string(msg, s, len)) != 0)
174 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
175 	send_msg(conn, msg);
176 	debug3("Sent message fd %d T:%u I:%u", conn->fd_out, code, id);
177 	sshbuf_free(msg);
178 }
179 
180 static void
181 send_string_attrs_request(struct sftp_conn *conn, u_int id, u_int code,
182     const void *s, u_int len, Attrib *a)
183 {
184 	struct sshbuf *msg;
185 	int r;
186 
187 	if ((msg = sshbuf_new()) == NULL)
188 		fatal("%s: sshbuf_new failed", __func__);
189 	if ((r = sshbuf_put_u8(msg, code)) != 0 ||
190 	    (r = sshbuf_put_u32(msg, id)) != 0 ||
191 	    (r = sshbuf_put_string(msg, s, len)) != 0 ||
192 	    (r = encode_attrib(msg, a)) != 0)
193 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
194 	send_msg(conn, msg);
195 	debug3("Sent message fd %d T:%u I:%u", conn->fd_out, code, id);
196 	sshbuf_free(msg);
197 }
198 
199 static u_int
200 get_status(struct sftp_conn *conn, u_int expected_id)
201 {
202 	struct sshbuf *msg;
203 	u_char type;
204 	u_int id, status;
205 	int r;
206 
207 	if ((msg = sshbuf_new()) == NULL)
208 		fatal("%s: sshbuf_new failed", __func__);
209 	get_msg(conn, msg);
210 	if ((r = sshbuf_get_u8(msg, &type)) != 0 ||
211 	    (r = sshbuf_get_u32(msg, &id)) != 0)
212 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
213 
214 	if (id != expected_id)
215 		fatal("ID mismatch (%u != %u)", id, expected_id);
216 	if (type != SSH2_FXP_STATUS)
217 		fatal("Expected SSH2_FXP_STATUS(%u) packet, got %u",
218 		    SSH2_FXP_STATUS, type);
219 
220 	if ((r = sshbuf_get_u32(msg, &status)) != 0)
221 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
222 	sshbuf_free(msg);
223 
224 	debug3("SSH2_FXP_STATUS %u", status);
225 
226 	return status;
227 }
228 
229 static u_char *
230 get_handle(struct sftp_conn *conn, u_int expected_id, size_t *len,
231     const char *errfmt, ...)
232 {
233 	struct sshbuf *msg;
234 	u_int id, status;
235 	u_char type;
236 	u_char *handle;
237 	char errmsg[256];
238 	va_list args;
239 	int r;
240 
241 	va_start(args, errfmt);
242 	if (errfmt != NULL)
243 		vsnprintf(errmsg, sizeof(errmsg), errfmt, args);
244 	va_end(args);
245 
246 	if ((msg = sshbuf_new()) == NULL)
247 		fatal("%s: sshbuf_new failed", __func__);
248 	get_msg(conn, msg);
249 	if ((r = sshbuf_get_u8(msg, &type)) != 0 ||
250 	    (r = sshbuf_get_u32(msg, &id)) != 0)
251 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
252 
253 	if (id != expected_id)
254 		fatal("%s: ID mismatch (%u != %u)",
255 		    errfmt == NULL ? __func__ : errmsg, id, expected_id);
256 	if (type == SSH2_FXP_STATUS) {
257 		if ((r = sshbuf_get_u32(msg, &status)) != 0)
258 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
259 		if (errfmt != NULL)
260 			error("%s: %s", errmsg, fx2txt(status));
261 		sshbuf_free(msg);
262 		return(NULL);
263 	} else if (type != SSH2_FXP_HANDLE)
264 		fatal("%s: Expected SSH2_FXP_HANDLE(%u) packet, got %u",
265 		    errfmt == NULL ? __func__ : errmsg, SSH2_FXP_HANDLE, type);
266 
267 	if ((r = sshbuf_get_string(msg, &handle, len)) != 0)
268 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
269 	sshbuf_free(msg);
270 
271 	return handle;
272 }
273 
274 static Attrib *
275 get_decode_stat(struct sftp_conn *conn, u_int expected_id, int quiet)
276 {
277 	struct sshbuf *msg;
278 	u_int id;
279 	u_char type;
280 	int r;
281 	static Attrib a;
282 
283 	if ((msg = sshbuf_new()) == NULL)
284 		fatal("%s: sshbuf_new failed", __func__);
285 	get_msg(conn, msg);
286 
287 	if ((r = sshbuf_get_u8(msg, &type)) != 0 ||
288 	    (r = sshbuf_get_u32(msg, &id)) != 0)
289 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
290 
291 	debug3("Received stat reply T:%u I:%u", type, id);
292 	if (id != expected_id)
293 		fatal("ID mismatch (%u != %u)", id, expected_id);
294 	if (type == SSH2_FXP_STATUS) {
295 		u_int status;
296 
297 		if ((r = sshbuf_get_u32(msg, &status)) != 0)
298 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
299 		if (quiet)
300 			debug("Couldn't stat remote file: %s", fx2txt(status));
301 		else
302 			error("Couldn't stat remote file: %s", fx2txt(status));
303 		sshbuf_free(msg);
304 		return(NULL);
305 	} else if (type != SSH2_FXP_ATTRS) {
306 		fatal("Expected SSH2_FXP_ATTRS(%u) packet, got %u",
307 		    SSH2_FXP_ATTRS, type);
308 	}
309 	if ((r = decode_attrib(msg, &a)) != 0) {
310 		error("%s: couldn't decode attrib: %s", __func__, ssh_err(r));
311 		sshbuf_free(msg);
312 		return NULL;
313 	}
314 	sshbuf_free(msg);
315 
316 	return &a;
317 }
318 
319 static int
320 get_decode_statvfs(struct sftp_conn *conn, struct sftp_statvfs *st,
321     u_int expected_id, int quiet)
322 {
323 	struct sshbuf *msg;
324 	u_char type;
325 	u_int id;
326 	u_int64_t flag;
327 	int r;
328 
329 	if ((msg = sshbuf_new()) == NULL)
330 		fatal("%s: sshbuf_new failed", __func__);
331 	get_msg(conn, msg);
332 
333 	if ((r = sshbuf_get_u8(msg, &type)) != 0 ||
334 	    (r = sshbuf_get_u32(msg, &id)) != 0)
335 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
336 
337 	debug3("Received statvfs reply T:%u I:%u", type, id);
338 	if (id != expected_id)
339 		fatal("ID mismatch (%u != %u)", id, expected_id);
340 	if (type == SSH2_FXP_STATUS) {
341 		u_int status;
342 
343 		if ((r = sshbuf_get_u32(msg, &status)) != 0)
344 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
345 		if (quiet)
346 			debug("Couldn't statvfs: %s", fx2txt(status));
347 		else
348 			error("Couldn't statvfs: %s", fx2txt(status));
349 		sshbuf_free(msg);
350 		return -1;
351 	} else if (type != SSH2_FXP_EXTENDED_REPLY) {
352 		fatal("Expected SSH2_FXP_EXTENDED_REPLY(%u) packet, got %u",
353 		    SSH2_FXP_EXTENDED_REPLY, type);
354 	}
355 
356 	memset(st, 0, sizeof(*st));
357 	if ((r = sshbuf_get_u64(msg, &st->f_bsize)) != 0 ||
358 	    (r = sshbuf_get_u64(msg, &st->f_frsize)) != 0 ||
359 	    (r = sshbuf_get_u64(msg, &st->f_blocks)) != 0 ||
360 	    (r = sshbuf_get_u64(msg, &st->f_bfree)) != 0 ||
361 	    (r = sshbuf_get_u64(msg, &st->f_bavail)) != 0 ||
362 	    (r = sshbuf_get_u64(msg, &st->f_files)) != 0 ||
363 	    (r = sshbuf_get_u64(msg, &st->f_ffree)) != 0 ||
364 	    (r = sshbuf_get_u64(msg, &st->f_favail)) != 0 ||
365 	    (r = sshbuf_get_u64(msg, &st->f_fsid)) != 0 ||
366 	    (r = sshbuf_get_u64(msg, &flag)) != 0 ||
367 	    (r = sshbuf_get_u64(msg, &st->f_namemax)) != 0)
368 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
369 
370 	st->f_flag = (flag & SSH2_FXE_STATVFS_ST_RDONLY) ? ST_RDONLY : 0;
371 	st->f_flag |= (flag & SSH2_FXE_STATVFS_ST_NOSUID) ? ST_NOSUID : 0;
372 
373 	sshbuf_free(msg);
374 
375 	return 0;
376 }
377 
378 struct sftp_conn *
379 do_init(int fd_in, int fd_out, u_int transfer_buflen, u_int num_requests,
380     u_int64_t limit_kbps)
381 {
382 	u_char type;
383 	struct sshbuf *msg;
384 	struct sftp_conn *ret;
385 	int r;
386 
387 	ret = xcalloc(1, sizeof(*ret));
388 	ret->msg_id = 1;
389 	ret->fd_in = fd_in;
390 	ret->fd_out = fd_out;
391 	ret->transfer_buflen = transfer_buflen;
392 	ret->num_requests = num_requests;
393 	ret->exts = 0;
394 	ret->limit_kbps = 0;
395 
396 	if ((msg = sshbuf_new()) == NULL)
397 		fatal("%s: sshbuf_new failed", __func__);
398 	if ((r = sshbuf_put_u8(msg, SSH2_FXP_INIT)) != 0 ||
399 	    (r = sshbuf_put_u32(msg, SSH2_FILEXFER_VERSION)) != 0)
400 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
401 	send_msg(ret, msg);
402 
403 	sshbuf_reset(msg);
404 
405 	get_msg_extended(ret, msg, 1);
406 
407 	/* Expecting a VERSION reply */
408 	if ((r = sshbuf_get_u8(msg, &type)) != 0)
409 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
410 	if (type != SSH2_FXP_VERSION) {
411 		error("Invalid packet back from SSH2_FXP_INIT (type %u)",
412 		    type);
413 		sshbuf_free(msg);
414 		free(ret);
415 		return(NULL);
416 	}
417 	if ((r = sshbuf_get_u32(msg, &ret->version)) != 0)
418 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
419 
420 	debug2("Remote version: %u", ret->version);
421 
422 	/* Check for extensions */
423 	while (sshbuf_len(msg) > 0) {
424 		char *name;
425 		u_char *value;
426 		size_t vlen;
427 		int known = 0;
428 
429 		if ((r = sshbuf_get_cstring(msg, &name, NULL)) != 0 ||
430 		    (r = sshbuf_get_string(msg, &value, &vlen)) != 0)
431 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
432 		if (strcmp(name, "posix-rename@openssh.com") == 0 &&
433 		    strcmp((char *)value, "1") == 0) {
434 			ret->exts |= SFTP_EXT_POSIX_RENAME;
435 			known = 1;
436 		} else if (strcmp(name, "statvfs@openssh.com") == 0 &&
437 		    strcmp((char *)value, "2") == 0) {
438 			ret->exts |= SFTP_EXT_STATVFS;
439 			known = 1;
440 		} else if (strcmp(name, "fstatvfs@openssh.com") == 0 &&
441 		    strcmp((char *)value, "2") == 0) {
442 			ret->exts |= SFTP_EXT_FSTATVFS;
443 			known = 1;
444 		} else if (strcmp(name, "hardlink@openssh.com") == 0 &&
445 		    strcmp((char *)value, "1") == 0) {
446 			ret->exts |= SFTP_EXT_HARDLINK;
447 			known = 1;
448 		} else if (strcmp(name, "fsync@openssh.com") == 0 &&
449 		    strcmp((char *)value, "1") == 0) {
450 			ret->exts |= SFTP_EXT_FSYNC;
451 			known = 1;
452 		}
453 		if (known) {
454 			debug2("Server supports extension \"%s\" revision %s",
455 			    name, value);
456 		} else {
457 			debug2("Unrecognised server extension \"%s\"", name);
458 		}
459 		free(name);
460 		free(value);
461 	}
462 
463 	sshbuf_free(msg);
464 
465 	/* Some filexfer v.0 servers don't support large packets */
466 	if (ret->version == 0)
467 		ret->transfer_buflen = MINIMUM(ret->transfer_buflen, 20480);
468 
469 	ret->limit_kbps = limit_kbps;
470 	if (ret->limit_kbps > 0) {
471 		bandwidth_limit_init(&ret->bwlimit_in, ret->limit_kbps,
472 		    ret->transfer_buflen);
473 		bandwidth_limit_init(&ret->bwlimit_out, ret->limit_kbps,
474 		    ret->transfer_buflen);
475 	}
476 
477 	return ret;
478 }
479 
480 u_int
481 sftp_proto_version(struct sftp_conn *conn)
482 {
483 	return conn->version;
484 }
485 
486 int
487 do_close(struct sftp_conn *conn, const u_char *handle, u_int handle_len)
488 {
489 	u_int id, status;
490 	struct sshbuf *msg;
491 	int r;
492 
493 	if ((msg = sshbuf_new()) == NULL)
494 		fatal("%s: sshbuf_new failed", __func__);
495 
496 	id = conn->msg_id++;
497 	if ((r = sshbuf_put_u8(msg, SSH2_FXP_CLOSE)) != 0 ||
498 	    (r = sshbuf_put_u32(msg, id)) != 0 ||
499 	    (r = sshbuf_put_string(msg, handle, handle_len)) != 0)
500 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
501 	send_msg(conn, msg);
502 	debug3("Sent message SSH2_FXP_CLOSE I:%u", id);
503 
504 	status = get_status(conn, id);
505 	if (status != SSH2_FX_OK)
506 		error("Couldn't close file: %s", fx2txt(status));
507 
508 	sshbuf_free(msg);
509 
510 	return status == SSH2_FX_OK ? 0 : -1;
511 }
512 
513 
514 static int
515 do_lsreaddir(struct sftp_conn *conn, const char *path, int print_flag,
516     SFTP_DIRENT ***dir)
517 {
518 	struct sshbuf *msg;
519 	u_int count, id, i, expected_id, ents = 0;
520 	size_t handle_len;
521 	u_char type, *handle;
522 	int status = SSH2_FX_FAILURE;
523 	int r;
524 
525 	if (dir)
526 		*dir = NULL;
527 
528 	id = conn->msg_id++;
529 
530 	if ((msg = sshbuf_new()) == NULL)
531 		fatal("%s: sshbuf_new failed", __func__);
532 	if ((r = sshbuf_put_u8(msg, SSH2_FXP_OPENDIR)) != 0 ||
533 	    (r = sshbuf_put_u32(msg, id)) != 0 ||
534 	    (r = sshbuf_put_cstring(msg, path)) != 0)
535 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
536 	send_msg(conn, msg);
537 
538 	handle = get_handle(conn, id, &handle_len,
539 	    "remote readdir(\"%s\")", path);
540 	if (handle == NULL) {
541 		sshbuf_free(msg);
542 		return -1;
543 	}
544 
545 	if (dir) {
546 		ents = 0;
547 		*dir = xcalloc(1, sizeof(**dir));
548 		(*dir)[0] = NULL;
549 	}
550 
551 	for (; !interrupted;) {
552 		id = expected_id = conn->msg_id++;
553 
554 		debug3("Sending SSH2_FXP_READDIR I:%u", id);
555 
556 		sshbuf_reset(msg);
557 		if ((r = sshbuf_put_u8(msg, SSH2_FXP_READDIR)) != 0 ||
558 		    (r = sshbuf_put_u32(msg, id)) != 0 ||
559 		    (r = sshbuf_put_string(msg, handle, handle_len)) != 0)
560 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
561 		send_msg(conn, msg);
562 
563 		sshbuf_reset(msg);
564 
565 		get_msg(conn, msg);
566 
567 		if ((r = sshbuf_get_u8(msg, &type)) != 0 ||
568 		    (r = sshbuf_get_u32(msg, &id)) != 0)
569 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
570 
571 		debug3("Received reply T:%u I:%u", type, id);
572 
573 		if (id != expected_id)
574 			fatal("ID mismatch (%u != %u)", id, expected_id);
575 
576 		if (type == SSH2_FXP_STATUS) {
577 			u_int rstatus;
578 
579 			if ((r = sshbuf_get_u32(msg, &rstatus)) != 0)
580 				fatal("%s: buffer error: %s",
581 				    __func__, ssh_err(r));
582 			debug3("Received SSH2_FXP_STATUS %d", rstatus);
583 			if (rstatus == SSH2_FX_EOF)
584 				break;
585 			error("Couldn't read directory: %s", fx2txt(rstatus));
586 			goto out;
587 		} else if (type != SSH2_FXP_NAME)
588 			fatal("Expected SSH2_FXP_NAME(%u) packet, got %u",
589 			    SSH2_FXP_NAME, type);
590 
591 		if ((r = sshbuf_get_u32(msg, &count)) != 0)
592 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
593 		if (count > SSHBUF_SIZE_MAX)
594 			fatal("%s: nonsensical number of entries", __func__);
595 		if (count == 0)
596 			break;
597 		debug3("Received %d SSH2_FXP_NAME responses", count);
598 		for (i = 0; i < count; i++) {
599 			char *filename, *longname;
600 			Attrib a;
601 
602 			if ((r = sshbuf_get_cstring(msg, &filename,
603 			    NULL)) != 0 ||
604 			    (r = sshbuf_get_cstring(msg, &longname,
605 			    NULL)) != 0)
606 				fatal("%s: buffer error: %s",
607 				    __func__, ssh_err(r));
608 			if ((r = decode_attrib(msg, &a)) != 0) {
609 				error("%s: couldn't decode attrib: %s",
610 				    __func__, ssh_err(r));
611 				free(filename);
612 				free(longname);
613 				sshbuf_free(msg);
614 				return -1;
615 			}
616 
617 			if (print_flag)
618 				mprintf("%s\n", longname);
619 
620 			/*
621 			 * Directory entries should never contain '/'
622 			 * These can be used to attack recursive ops
623 			 * (e.g. send '../../../../etc/passwd')
624 			 */
625 			if (strchr(filename, '/') != NULL) {
626 				error("Server sent suspect path \"%s\" "
627 				    "during readdir of \"%s\"", filename, path);
628 			} else if (dir) {
629 				*dir = xreallocarray(*dir, ents + 2, sizeof(**dir));
630 				(*dir)[ents] = xcalloc(1, sizeof(***dir));
631 				(*dir)[ents]->filename = xstrdup(filename);
632 				(*dir)[ents]->longname = xstrdup(longname);
633 				memcpy(&(*dir)[ents]->a, &a, sizeof(a));
634 				(*dir)[++ents] = NULL;
635 			}
636 			free(filename);
637 			free(longname);
638 		}
639 	}
640 	status = 0;
641 
642  out:
643 	sshbuf_free(msg);
644 	do_close(conn, handle, handle_len);
645 	free(handle);
646 
647 	if (status != 0 && dir != NULL) {
648 		/* Don't return results on error */
649 		free_sftp_dirents(*dir);
650 		*dir = NULL;
651 	} else if (interrupted && dir != NULL && *dir != NULL) {
652 		/* Don't return partial matches on interrupt */
653 		free_sftp_dirents(*dir);
654 		*dir = xcalloc(1, sizeof(**dir));
655 		**dir = NULL;
656 	}
657 
658 	return status == SSH2_FX_OK ? 0 : -1;
659 }
660 
661 int
662 do_readdir(struct sftp_conn *conn, const char *path, SFTP_DIRENT ***dir)
663 {
664 	return(do_lsreaddir(conn, path, 0, dir));
665 }
666 
667 void free_sftp_dirents(SFTP_DIRENT **s)
668 {
669 	int i;
670 
671 	if (s == NULL)
672 		return;
673 	for (i = 0; s[i]; i++) {
674 		free(s[i]->filename);
675 		free(s[i]->longname);
676 		free(s[i]);
677 	}
678 	free(s);
679 }
680 
681 int
682 do_rm(struct sftp_conn *conn, const char *path)
683 {
684 	u_int status, id;
685 
686 	debug2("Sending SSH2_FXP_REMOVE \"%s\"", path);
687 
688 	id = conn->msg_id++;
689 	send_string_request(conn, id, SSH2_FXP_REMOVE, path, strlen(path));
690 	status = get_status(conn, id);
691 	if (status != SSH2_FX_OK)
692 		error("Couldn't delete file: %s", fx2txt(status));
693 	return status == SSH2_FX_OK ? 0 : -1;
694 }
695 
696 int
697 do_mkdir(struct sftp_conn *conn, const char *path, Attrib *a, int print_flag)
698 {
699 	u_int status, id;
700 
701 	id = conn->msg_id++;
702 	send_string_attrs_request(conn, id, SSH2_FXP_MKDIR, path,
703 	    strlen(path), a);
704 
705 	status = get_status(conn, id);
706 	if (status != SSH2_FX_OK && print_flag)
707 		error("Couldn't create directory: %s", fx2txt(status));
708 
709 	return status == SSH2_FX_OK ? 0 : -1;
710 }
711 
712 int
713 do_rmdir(struct sftp_conn *conn, const char *path)
714 {
715 	u_int status, id;
716 
717 	id = conn->msg_id++;
718 	send_string_request(conn, id, SSH2_FXP_RMDIR, path,
719 	    strlen(path));
720 
721 	status = get_status(conn, id);
722 	if (status != SSH2_FX_OK)
723 		error("Couldn't remove directory: %s", fx2txt(status));
724 
725 	return status == SSH2_FX_OK ? 0 : -1;
726 }
727 
728 Attrib *
729 do_stat(struct sftp_conn *conn, const char *path, int quiet)
730 {
731 	u_int id;
732 
733 	id = conn->msg_id++;
734 
735 	send_string_request(conn, id,
736 	    conn->version == 0 ? SSH2_FXP_STAT_VERSION_0 : SSH2_FXP_STAT,
737 	    path, strlen(path));
738 
739 	return(get_decode_stat(conn, id, quiet));
740 }
741 
742 Attrib *
743 do_lstat(struct sftp_conn *conn, const char *path, int quiet)
744 {
745 	u_int id;
746 
747 	if (conn->version == 0) {
748 		if (quiet)
749 			debug("Server version does not support lstat operation");
750 		else
751 			logit("Server version does not support lstat operation");
752 		return(do_stat(conn, path, quiet));
753 	}
754 
755 	id = conn->msg_id++;
756 	send_string_request(conn, id, SSH2_FXP_LSTAT, path,
757 	    strlen(path));
758 
759 	return(get_decode_stat(conn, id, quiet));
760 }
761 
762 #ifdef notyet
763 Attrib *
764 do_fstat(struct sftp_conn *conn, const u_char *handle, u_int handle_len,
765     int quiet)
766 {
767 	u_int id;
768 
769 	id = conn->msg_id++;
770 	send_string_request(conn, id, SSH2_FXP_FSTAT, handle,
771 	    handle_len);
772 
773 	return(get_decode_stat(conn, id, quiet));
774 }
775 #endif
776 
777 int
778 do_setstat(struct sftp_conn *conn, const char *path, Attrib *a)
779 {
780 	u_int status, id;
781 
782 	id = conn->msg_id++;
783 	send_string_attrs_request(conn, id, SSH2_FXP_SETSTAT, path,
784 	    strlen(path), a);
785 
786 	status = get_status(conn, id);
787 	if (status != SSH2_FX_OK)
788 		error("Couldn't setstat on \"%s\": %s", path,
789 		    fx2txt(status));
790 
791 	return status == SSH2_FX_OK ? 0 : -1;
792 }
793 
794 int
795 do_fsetstat(struct sftp_conn *conn, const u_char *handle, u_int handle_len,
796     Attrib *a)
797 {
798 	u_int status, id;
799 
800 	id = conn->msg_id++;
801 	send_string_attrs_request(conn, id, SSH2_FXP_FSETSTAT, handle,
802 	    handle_len, a);
803 
804 	status = get_status(conn, id);
805 	if (status != SSH2_FX_OK)
806 		error("Couldn't fsetstat: %s", fx2txt(status));
807 
808 	return status == SSH2_FX_OK ? 0 : -1;
809 }
810 
811 char *
812 do_realpath(struct sftp_conn *conn, const char *path)
813 {
814 	struct sshbuf *msg;
815 	u_int expected_id, count, id;
816 	char *filename, *longname;
817 	Attrib a;
818 	u_char type;
819 	int r;
820 
821 	expected_id = id = conn->msg_id++;
822 	send_string_request(conn, id, SSH2_FXP_REALPATH, path,
823 	    strlen(path));
824 
825 	if ((msg = sshbuf_new()) == NULL)
826 		fatal("%s: sshbuf_new failed", __func__);
827 
828 	get_msg(conn, msg);
829 	if ((r = sshbuf_get_u8(msg, &type)) != 0 ||
830 	    (r = sshbuf_get_u32(msg, &id)) != 0)
831 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
832 
833 	if (id != expected_id)
834 		fatal("ID mismatch (%u != %u)", id, expected_id);
835 
836 	if (type == SSH2_FXP_STATUS) {
837 		u_int status;
838 
839 		if ((r = sshbuf_get_u32(msg, &status)) != 0)
840 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
841 		error("Couldn't canonicalize: %s", fx2txt(status));
842 		sshbuf_free(msg);
843 		return NULL;
844 	} else if (type != SSH2_FXP_NAME)
845 		fatal("Expected SSH2_FXP_NAME(%u) packet, got %u",
846 		    SSH2_FXP_NAME, type);
847 
848 	if ((r = sshbuf_get_u32(msg, &count)) != 0)
849 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
850 	if (count != 1)
851 		fatal("Got multiple names (%d) from SSH_FXP_REALPATH", count);
852 
853 	if ((r = sshbuf_get_cstring(msg, &filename, NULL)) != 0 ||
854 	    (r = sshbuf_get_cstring(msg, &longname, NULL)) != 0 ||
855 	    (r = decode_attrib(msg, &a)) != 0)
856 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
857 
858 	debug3("SSH_FXP_REALPATH %s -> %s size %lu", path, filename,
859 	    (unsigned long)a.size);
860 
861 	free(longname);
862 
863 	sshbuf_free(msg);
864 
865 	return(filename);
866 }
867 
868 int
869 do_rename(struct sftp_conn *conn, const char *oldpath, const char *newpath,
870     int force_legacy)
871 {
872 	struct sshbuf *msg;
873 	u_int status, id;
874 	int r, use_ext = (conn->exts & SFTP_EXT_POSIX_RENAME) && !force_legacy;
875 
876 	if ((msg = sshbuf_new()) == NULL)
877 		fatal("%s: sshbuf_new failed", __func__);
878 
879 	/* Send rename request */
880 	id = conn->msg_id++;
881 	if (use_ext) {
882 		if ((r = sshbuf_put_u8(msg, SSH2_FXP_EXTENDED)) != 0 ||
883 		    (r = sshbuf_put_u32(msg, id)) != 0 ||
884 		    (r = sshbuf_put_cstring(msg,
885 		    "posix-rename@openssh.com")) != 0)
886 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
887 	} else {
888 		if ((r = sshbuf_put_u8(msg, SSH2_FXP_RENAME)) != 0 ||
889 		    (r = sshbuf_put_u32(msg, id)) != 0)
890 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
891 	}
892 	if ((r = sshbuf_put_cstring(msg, oldpath)) != 0 ||
893 	    (r = sshbuf_put_cstring(msg, newpath)) != 0)
894 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
895 	send_msg(conn, msg);
896 	debug3("Sent message %s \"%s\" -> \"%s\"",
897 	    use_ext ? "posix-rename@openssh.com" :
898 	    "SSH2_FXP_RENAME", oldpath, newpath);
899 	sshbuf_free(msg);
900 
901 	status = get_status(conn, id);
902 	if (status != SSH2_FX_OK)
903 		error("Couldn't rename file \"%s\" to \"%s\": %s", oldpath,
904 		    newpath, fx2txt(status));
905 
906 	return status == SSH2_FX_OK ? 0 : -1;
907 }
908 
909 int
910 do_hardlink(struct sftp_conn *conn, const char *oldpath, const char *newpath)
911 {
912 	struct sshbuf *msg;
913 	u_int status, id;
914 	int r;
915 
916 	if ((conn->exts & SFTP_EXT_HARDLINK) == 0) {
917 		error("Server does not support hardlink@openssh.com extension");
918 		return -1;
919 	}
920 
921 	if ((msg = sshbuf_new()) == NULL)
922 		fatal("%s: sshbuf_new failed", __func__);
923 
924 	/* Send link request */
925 	id = conn->msg_id++;
926 	if ((r = sshbuf_put_u8(msg, SSH2_FXP_EXTENDED)) != 0 ||
927 	    (r = sshbuf_put_u32(msg, id)) != 0 ||
928 	    (r = sshbuf_put_cstring(msg, "hardlink@openssh.com")) != 0 ||
929 	    (r = sshbuf_put_cstring(msg, oldpath)) != 0 ||
930 	    (r = sshbuf_put_cstring(msg, newpath)) != 0)
931 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
932 	send_msg(conn, msg);
933 	debug3("Sent message hardlink@openssh.com \"%s\" -> \"%s\"",
934 	       oldpath, newpath);
935 	sshbuf_free(msg);
936 
937 	status = get_status(conn, id);
938 	if (status != SSH2_FX_OK)
939 		error("Couldn't link file \"%s\" to \"%s\": %s", oldpath,
940 		    newpath, fx2txt(status));
941 
942 	return status == SSH2_FX_OK ? 0 : -1;
943 }
944 
945 int
946 do_symlink(struct sftp_conn *conn, const char *oldpath, const char *newpath)
947 {
948 	struct sshbuf *msg;
949 	u_int status, id;
950 	int r;
951 
952 	if (conn->version < 3) {
953 		error("This server does not support the symlink operation");
954 		return(SSH2_FX_OP_UNSUPPORTED);
955 	}
956 
957 	if ((msg = sshbuf_new()) == NULL)
958 		fatal("%s: sshbuf_new failed", __func__);
959 
960 	/* Send symlink request */
961 	id = conn->msg_id++;
962 	if ((r = sshbuf_put_u8(msg, SSH2_FXP_SYMLINK)) != 0 ||
963 	    (r = sshbuf_put_u32(msg, id)) != 0 ||
964 	    (r = sshbuf_put_cstring(msg, oldpath)) != 0 ||
965 	    (r = sshbuf_put_cstring(msg, newpath)) != 0)
966 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
967 	send_msg(conn, msg);
968 	debug3("Sent message SSH2_FXP_SYMLINK \"%s\" -> \"%s\"", oldpath,
969 	    newpath);
970 	sshbuf_free(msg);
971 
972 	status = get_status(conn, id);
973 	if (status != SSH2_FX_OK)
974 		error("Couldn't symlink file \"%s\" to \"%s\": %s", oldpath,
975 		    newpath, fx2txt(status));
976 
977 	return status == SSH2_FX_OK ? 0 : -1;
978 }
979 
980 int
981 do_fsync(struct sftp_conn *conn, u_char *handle, u_int handle_len)
982 {
983 	struct sshbuf *msg;
984 	u_int status, id;
985 	int r;
986 
987 	/* Silently return if the extension is not supported */
988 	if ((conn->exts & SFTP_EXT_FSYNC) == 0)
989 		return -1;
990 
991 	/* Send fsync request */
992 	if ((msg = sshbuf_new()) == NULL)
993 		fatal("%s: sshbuf_new failed", __func__);
994 	id = conn->msg_id++;
995 	if ((r = sshbuf_put_u8(msg, SSH2_FXP_EXTENDED)) != 0 ||
996 	    (r = sshbuf_put_u32(msg, id)) != 0 ||
997 	    (r = sshbuf_put_cstring(msg, "fsync@openssh.com")) != 0 ||
998 	    (r = sshbuf_put_string(msg, handle, handle_len)) != 0)
999 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1000 	send_msg(conn, msg);
1001 	debug3("Sent message fsync@openssh.com I:%u", id);
1002 	sshbuf_free(msg);
1003 
1004 	status = get_status(conn, id);
1005 	if (status != SSH2_FX_OK)
1006 		error("Couldn't sync file: %s", fx2txt(status));
1007 
1008 	return status == SSH2_FX_OK ? 0 : -1;
1009 }
1010 
1011 #ifdef notyet
1012 char *
1013 do_readlink(struct sftp_conn *conn, const char *path)
1014 {
1015 	struct sshbuf *msg;
1016 	u_int expected_id, count, id;
1017 	char *filename, *longname;
1018 	Attrib a;
1019 	u_char type;
1020 	int r;
1021 
1022 	expected_id = id = conn->msg_id++;
1023 	send_string_request(conn, id, SSH2_FXP_READLINK, path, strlen(path));
1024 
1025 	if ((msg = sshbuf_new()) == NULL)
1026 		fatal("%s: sshbuf_new failed", __func__);
1027 
1028 	get_msg(conn, msg);
1029 	if ((r = sshbuf_get_u8(msg, &type)) != 0 ||
1030 	    (r = sshbuf_get_u32(msg, &id)) != 0)
1031 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1032 
1033 	if (id != expected_id)
1034 		fatal("ID mismatch (%u != %u)", id, expected_id);
1035 
1036 	if (type == SSH2_FXP_STATUS) {
1037 		u_int status;
1038 
1039 		if ((r = sshbuf_get_u32(msg, &status)) != 0)
1040 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
1041 		error("Couldn't readlink: %s", fx2txt(status));
1042 		sshbuf_free(msg);
1043 		return(NULL);
1044 	} else if (type != SSH2_FXP_NAME)
1045 		fatal("Expected SSH2_FXP_NAME(%u) packet, got %u",
1046 		    SSH2_FXP_NAME, type);
1047 
1048 	if ((r = sshbuf_get_u32(msg, &count)) != 0)
1049 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1050 	if (count != 1)
1051 		fatal("Got multiple names (%d) from SSH_FXP_READLINK", count);
1052 
1053 	if ((r = sshbuf_get_cstring(msg, &filename, NULL)) != 0 ||
1054 	    (r = sshbuf_get_cstring(msg, &longname, NULL)) != 0 ||
1055 	    (r = decode_attrib(msg, &a)) != 0)
1056 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1057 
1058 	debug3("SSH_FXP_READLINK %s -> %s", path, filename);
1059 
1060 	free(longname);
1061 
1062 	sshbuf_free(msg);
1063 
1064 	return filename;
1065 }
1066 #endif
1067 
1068 int
1069 do_statvfs(struct sftp_conn *conn, const char *path, struct sftp_statvfs *st,
1070     int quiet)
1071 {
1072 	struct sshbuf *msg;
1073 	u_int id;
1074 	int r;
1075 
1076 	if ((conn->exts & SFTP_EXT_STATVFS) == 0) {
1077 		error("Server does not support statvfs@openssh.com extension");
1078 		return -1;
1079 	}
1080 
1081 	id = conn->msg_id++;
1082 
1083 	if ((msg = sshbuf_new()) == NULL)
1084 		fatal("%s: sshbuf_new failed", __func__);
1085 	sshbuf_reset(msg);
1086 	if ((r = sshbuf_put_u8(msg, SSH2_FXP_EXTENDED)) != 0 ||
1087 	    (r = sshbuf_put_u32(msg, id)) != 0 ||
1088 	    (r = sshbuf_put_cstring(msg, "statvfs@openssh.com")) != 0 ||
1089 	    (r = sshbuf_put_cstring(msg, path)) != 0)
1090 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1091 	send_msg(conn, msg);
1092 	sshbuf_free(msg);
1093 
1094 	return get_decode_statvfs(conn, st, id, quiet);
1095 }
1096 
1097 #ifdef notyet
1098 int
1099 do_fstatvfs(struct sftp_conn *conn, const u_char *handle, u_int handle_len,
1100     struct sftp_statvfs *st, int quiet)
1101 {
1102 	struct sshbuf *msg;
1103 	u_int id;
1104 
1105 	if ((conn->exts & SFTP_EXT_FSTATVFS) == 0) {
1106 		error("Server does not support fstatvfs@openssh.com extension");
1107 		return -1;
1108 	}
1109 
1110 	id = conn->msg_id++;
1111 
1112 	if ((msg = sshbuf_new()) == NULL)
1113 		fatal("%s: sshbuf_new failed", __func__);
1114 	sshbuf_reset(msg);
1115 	if ((r = sshbuf_put_u8(msg, SSH2_FXP_EXTENDED)) != 0 ||
1116 	    (r = sshbuf_put_u32(msg, id)) != 0 ||
1117 	    (r = sshbuf_put_cstring(msg, "fstatvfs@openssh.com")) != 0 ||
1118 	    (r = sshbuf_put_string(msg, handle, handle_len)) != 0)
1119 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1120 	send_msg(conn, msg);
1121 	sshbuf_free(msg);
1122 
1123 	return get_decode_statvfs(conn, st, id, quiet);
1124 }
1125 #endif
1126 
1127 static void
1128 send_read_request(struct sftp_conn *conn, u_int id, u_int64_t offset,
1129     u_int len, const u_char *handle, u_int handle_len)
1130 {
1131 	struct sshbuf *msg;
1132 	int r;
1133 
1134 	if ((msg = sshbuf_new()) == NULL)
1135 		fatal("%s: sshbuf_new failed", __func__);
1136 	sshbuf_reset(msg);
1137 	if ((r = sshbuf_put_u8(msg, SSH2_FXP_READ)) != 0 ||
1138 	    (r = sshbuf_put_u32(msg, id)) != 0 ||
1139 	    (r = sshbuf_put_string(msg, handle, handle_len)) != 0 ||
1140 	    (r = sshbuf_put_u64(msg, offset)) != 0 ||
1141 	    (r = sshbuf_put_u32(msg, len)) != 0)
1142 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1143 	send_msg(conn, msg);
1144 	sshbuf_free(msg);
1145 }
1146 
1147 int
1148 do_download(struct sftp_conn *conn, const char *remote_path,
1149     const char *local_path, Attrib *a, int preserve_flag, int resume_flag,
1150     int fsync_flag)
1151 {
1152 	Attrib junk;
1153 	struct sshbuf *msg;
1154 	u_char *handle;
1155 	int local_fd = -1, write_error;
1156 	int read_error, write_errno, reordered = 0, r;
1157 	u_int64_t offset = 0, size, highwater;
1158 	u_int mode, id, buflen, num_req, max_req, status = SSH2_FX_OK;
1159 	off_t progress_counter;
1160 	size_t handle_len;
1161 	struct stat st;
1162 	struct request {
1163 		u_int id;
1164 		size_t len;
1165 		u_int64_t offset;
1166 		TAILQ_ENTRY(request) tq;
1167 	};
1168 	TAILQ_HEAD(reqhead, request) requests;
1169 	struct request *req;
1170 	u_char type;
1171 
1172 	TAILQ_INIT(&requests);
1173 
1174 	if (a == NULL && (a = do_stat(conn, remote_path, 0)) == NULL)
1175 		return -1;
1176 
1177 	/* Do not preserve set[ug]id here, as we do not preserve ownership */
1178 	if (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)
1179 		mode = a->perm & 0777;
1180 	else
1181 		mode = 0666;
1182 
1183 	if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
1184 	    (!S_ISREG(a->perm))) {
1185 		error("Cannot download non-regular file: %s", remote_path);
1186 		return(-1);
1187 	}
1188 
1189 	if (a->flags & SSH2_FILEXFER_ATTR_SIZE)
1190 		size = a->size;
1191 	else
1192 		size = 0;
1193 
1194 	buflen = conn->transfer_buflen;
1195 	if ((msg = sshbuf_new()) == NULL)
1196 		fatal("%s: sshbuf_new failed", __func__);
1197 
1198 	attrib_clear(&junk); /* Send empty attributes */
1199 
1200 	/* Send open request */
1201 	id = conn->msg_id++;
1202 	if ((r = sshbuf_put_u8(msg, SSH2_FXP_OPEN)) != 0 ||
1203 	    (r = sshbuf_put_u32(msg, id)) != 0 ||
1204 	    (r = sshbuf_put_cstring(msg, remote_path)) != 0 ||
1205 	    (r = sshbuf_put_u32(msg, SSH2_FXF_READ)) != 0 ||
1206 	    (r = encode_attrib(msg, &junk)) != 0)
1207 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1208 	send_msg(conn, msg);
1209 	debug3("Sent message SSH2_FXP_OPEN I:%u P:%s", id, remote_path);
1210 
1211 	handle = get_handle(conn, id, &handle_len,
1212 	    "remote open(\"%s\")", remote_path);
1213 	if (handle == NULL) {
1214 		sshbuf_free(msg);
1215 		return(-1);
1216 	}
1217 
1218 	local_fd = open(local_path,
1219 	    O_WRONLY | O_CREAT | (resume_flag ? 0 : O_TRUNC), mode | S_IWUSR);
1220 	if (local_fd == -1) {
1221 		error("Couldn't open local file \"%s\" for writing: %s",
1222 		    local_path, strerror(errno));
1223 		goto fail;
1224 	}
1225 	offset = highwater = 0;
1226 	if (resume_flag) {
1227 		if (fstat(local_fd, &st) == -1) {
1228 			error("Unable to stat local file \"%s\": %s",
1229 			    local_path, strerror(errno));
1230 			goto fail;
1231 		}
1232 		if (st.st_size < 0) {
1233 			error("\"%s\" has negative size", local_path);
1234 			goto fail;
1235 		}
1236 		if ((u_int64_t)st.st_size > size) {
1237 			error("Unable to resume download of \"%s\": "
1238 			    "local file is larger than remote", local_path);
1239  fail:
1240 			do_close(conn, handle, handle_len);
1241 			sshbuf_free(msg);
1242 			free(handle);
1243 			if (local_fd != -1)
1244 				close(local_fd);
1245 			return -1;
1246 		}
1247 		offset = highwater = st.st_size;
1248 	}
1249 
1250 	/* Read from remote and write to local */
1251 	write_error = read_error = write_errno = num_req = 0;
1252 	max_req = 1;
1253 	progress_counter = offset;
1254 
1255 	if (showprogress && size != 0)
1256 		start_progress_meter(remote_path, size, &progress_counter);
1257 
1258 	while (num_req > 0 || max_req > 0) {
1259 		u_char *data;
1260 		size_t len;
1261 
1262 		/*
1263 		 * Simulate EOF on interrupt: stop sending new requests and
1264 		 * allow outstanding requests to drain gracefully
1265 		 */
1266 		if (interrupted) {
1267 			if (num_req == 0) /* If we haven't started yet... */
1268 				break;
1269 			max_req = 0;
1270 		}
1271 
1272 		/* Send some more requests */
1273 		while (num_req < max_req) {
1274 			debug3("Request range %llu -> %llu (%d/%d)",
1275 			    (unsigned long long)offset,
1276 			    (unsigned long long)offset + buflen - 1,
1277 			    num_req, max_req);
1278 			req = xcalloc(1, sizeof(*req));
1279 			req->id = conn->msg_id++;
1280 			req->len = buflen;
1281 			req->offset = offset;
1282 			offset += buflen;
1283 			num_req++;
1284 			TAILQ_INSERT_TAIL(&requests, req, tq);
1285 			send_read_request(conn, req->id, req->offset,
1286 			    req->len, handle, handle_len);
1287 		}
1288 
1289 		sshbuf_reset(msg);
1290 		get_msg(conn, msg);
1291 		if ((r = sshbuf_get_u8(msg, &type)) != 0 ||
1292 		    (r = sshbuf_get_u32(msg, &id)) != 0)
1293 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
1294 		debug3("Received reply T:%u I:%u R:%d", type, id, max_req);
1295 
1296 		/* Find the request in our queue */
1297 		for (req = TAILQ_FIRST(&requests);
1298 		    req != NULL && req->id != id;
1299 		    req = TAILQ_NEXT(req, tq))
1300 			;
1301 		if (req == NULL)
1302 			fatal("Unexpected reply %u", id);
1303 
1304 		switch (type) {
1305 		case SSH2_FXP_STATUS:
1306 			if ((r = sshbuf_get_u32(msg, &status)) != 0)
1307 				fatal("%s: buffer error: %s",
1308 				    __func__, ssh_err(r));
1309 			if (status != SSH2_FX_EOF)
1310 				read_error = 1;
1311 			max_req = 0;
1312 			TAILQ_REMOVE(&requests, req, tq);
1313 			free(req);
1314 			num_req--;
1315 			break;
1316 		case SSH2_FXP_DATA:
1317 			if ((r = sshbuf_get_string(msg, &data, &len)) != 0)
1318 				fatal("%s: buffer error: %s",
1319 				    __func__, ssh_err(r));
1320 			debug3("Received data %llu -> %llu",
1321 			    (unsigned long long)req->offset,
1322 			    (unsigned long long)req->offset + len - 1);
1323 			if (len > req->len)
1324 				fatal("Received more data than asked for "
1325 				    "%zu > %zu", len, req->len);
1326 			if ((lseek(local_fd, req->offset, SEEK_SET) == -1 ||
1327 			    atomicio(vwrite, local_fd, data, len) != len) &&
1328 			    !write_error) {
1329 				write_errno = errno;
1330 				write_error = 1;
1331 				max_req = 0;
1332 			}
1333 			else if (!reordered && req->offset <= highwater)
1334 				highwater = req->offset + len;
1335 			else if (!reordered && req->offset > highwater)
1336 				reordered = 1;
1337 			progress_counter += len;
1338 			free(data);
1339 
1340 			if (len == req->len) {
1341 				TAILQ_REMOVE(&requests, req, tq);
1342 				free(req);
1343 				num_req--;
1344 			} else {
1345 				/* Resend the request for the missing data */
1346 				debug3("Short data block, re-requesting "
1347 				    "%llu -> %llu (%2d)",
1348 				    (unsigned long long)req->offset + len,
1349 				    (unsigned long long)req->offset +
1350 				    req->len - 1, num_req);
1351 				req->id = conn->msg_id++;
1352 				req->len -= len;
1353 				req->offset += len;
1354 				send_read_request(conn, req->id,
1355 				    req->offset, req->len, handle, handle_len);
1356 				/* Reduce the request size */
1357 				if (len < buflen)
1358 					buflen = MAXIMUM(MIN_READ_SIZE, len);
1359 			}
1360 			if (max_req > 0) { /* max_req = 0 iff EOF received */
1361 				if (size > 0 && offset > size) {
1362 					/* Only one request at a time
1363 					 * after the expected EOF */
1364 					debug3("Finish at %llu (%2d)",
1365 					    (unsigned long long)offset,
1366 					    num_req);
1367 					max_req = 1;
1368 				} else if (max_req <= conn->num_requests) {
1369 					++max_req;
1370 				}
1371 			}
1372 			break;
1373 		default:
1374 			fatal("Expected SSH2_FXP_DATA(%u) packet, got %u",
1375 			    SSH2_FXP_DATA, type);
1376 		}
1377 	}
1378 
1379 	if (showprogress && size)
1380 		stop_progress_meter();
1381 
1382 	/* Sanity check */
1383 	if (TAILQ_FIRST(&requests) != NULL)
1384 		fatal("Transfer complete, but requests still in queue");
1385 	/* Truncate at highest contiguous point to avoid holes on interrupt */
1386 	if (read_error || write_error || interrupted) {
1387 		if (reordered && resume_flag) {
1388 			error("Unable to resume download of \"%s\": "
1389 			    "server reordered requests", local_path);
1390 		}
1391 		debug("truncating at %llu", (unsigned long long)highwater);
1392 		if (ftruncate(local_fd, highwater) == -1)
1393 			error("ftruncate \"%s\": %s", local_path,
1394 			    strerror(errno));
1395 	}
1396 	if (read_error) {
1397 		error("Couldn't read from remote file \"%s\" : %s",
1398 		    remote_path, fx2txt(status));
1399 		status = -1;
1400 		do_close(conn, handle, handle_len);
1401 	} else if (write_error) {
1402 		error("Couldn't write to \"%s\": %s", local_path,
1403 		    strerror(write_errno));
1404 		status = SSH2_FX_FAILURE;
1405 		do_close(conn, handle, handle_len);
1406 	} else {
1407 		if (do_close(conn, handle, handle_len) != 0 || interrupted)
1408 			status = SSH2_FX_FAILURE;
1409 		else
1410 			status = SSH2_FX_OK;
1411 		/* Override umask and utimes if asked */
1412 		if (preserve_flag && fchmod(local_fd, mode) == -1)
1413 			error("Couldn't set mode on \"%s\": %s", local_path,
1414 			    strerror(errno));
1415 		if (preserve_flag &&
1416 		    (a->flags & SSH2_FILEXFER_ATTR_ACMODTIME)) {
1417 			struct timeval tv[2];
1418 			tv[0].tv_sec = a->atime;
1419 			tv[1].tv_sec = a->mtime;
1420 			tv[0].tv_usec = tv[1].tv_usec = 0;
1421 			if (utimes(local_path, tv) == -1)
1422 				error("Can't set times on \"%s\": %s",
1423 				    local_path, strerror(errno));
1424 		}
1425 		if (fsync_flag) {
1426 			debug("syncing \"%s\"", local_path);
1427 			if (fsync(local_fd) == -1)
1428 				error("Couldn't sync file \"%s\": %s",
1429 				    local_path, strerror(errno));
1430 		}
1431 	}
1432 	close(local_fd);
1433 	sshbuf_free(msg);
1434 	free(handle);
1435 
1436 	return status == SSH2_FX_OK ? 0 : -1;
1437 }
1438 
1439 static int
1440 download_dir_internal(struct sftp_conn *conn, const char *src, const char *dst,
1441     int depth, Attrib *dirattrib, int preserve_flag, int print_flag,
1442     int resume_flag, int fsync_flag)
1443 {
1444 	int i, ret = 0;
1445 	SFTP_DIRENT **dir_entries;
1446 	char *filename, *new_src, *new_dst;
1447 	mode_t mode = 0777;
1448 
1449 	if (depth >= MAX_DIR_DEPTH) {
1450 		error("Maximum directory depth exceeded: %d levels", depth);
1451 		return -1;
1452 	}
1453 
1454 	if (dirattrib == NULL &&
1455 	    (dirattrib = do_stat(conn, src, 1)) == NULL) {
1456 		error("Unable to stat remote directory \"%s\"", src);
1457 		return -1;
1458 	}
1459 	if (!S_ISDIR(dirattrib->perm)) {
1460 		error("\"%s\" is not a directory", src);
1461 		return -1;
1462 	}
1463 	if (print_flag)
1464 		mprintf("Retrieving %s\n", src);
1465 
1466 	if (dirattrib->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)
1467 		mode = dirattrib->perm & 01777;
1468 	else {
1469 		debug("Server did not send permissions for "
1470 		    "directory \"%s\"", dst);
1471 	}
1472 
1473 	if (mkdir(dst, mode) == -1 && errno != EEXIST) {
1474 		error("mkdir %s: %s", dst, strerror(errno));
1475 		return -1;
1476 	}
1477 
1478 	if (do_readdir(conn, src, &dir_entries) == -1) {
1479 		error("%s: Failed to get directory contents", src);
1480 		return -1;
1481 	}
1482 
1483 	for (i = 0; dir_entries[i] != NULL && !interrupted; i++) {
1484 		filename = dir_entries[i]->filename;
1485 
1486 		new_dst = path_append(dst, filename);
1487 		new_src = path_append(src, filename);
1488 
1489 		if (S_ISDIR(dir_entries[i]->a.perm)) {
1490 			if (strcmp(filename, ".") == 0 ||
1491 			    strcmp(filename, "..") == 0)
1492 				continue;
1493 			if (download_dir_internal(conn, new_src, new_dst,
1494 			    depth + 1, &(dir_entries[i]->a), preserve_flag,
1495 			    print_flag, resume_flag, fsync_flag) == -1)
1496 				ret = -1;
1497 		} else if (S_ISREG(dir_entries[i]->a.perm) ) {
1498 			if (do_download(conn, new_src, new_dst,
1499 			    &(dir_entries[i]->a), preserve_flag,
1500 			    resume_flag, fsync_flag) == -1) {
1501 				error("Download of file %s to %s failed",
1502 				    new_src, new_dst);
1503 				ret = -1;
1504 			}
1505 		} else
1506 			logit("%s: not a regular file\n", new_src);
1507 
1508 		free(new_dst);
1509 		free(new_src);
1510 	}
1511 
1512 	if (preserve_flag) {
1513 		if (dirattrib->flags & SSH2_FILEXFER_ATTR_ACMODTIME) {
1514 			struct timeval tv[2];
1515 			tv[0].tv_sec = dirattrib->atime;
1516 			tv[1].tv_sec = dirattrib->mtime;
1517 			tv[0].tv_usec = tv[1].tv_usec = 0;
1518 			if (utimes(dst, tv) == -1)
1519 				error("Can't set times on \"%s\": %s",
1520 				    dst, strerror(errno));
1521 		} else
1522 			debug("Server did not send times for directory "
1523 			    "\"%s\"", dst);
1524 	}
1525 
1526 	free_sftp_dirents(dir_entries);
1527 
1528 	return ret;
1529 }
1530 
1531 int
1532 download_dir(struct sftp_conn *conn, const char *src, const char *dst,
1533     Attrib *dirattrib, int preserve_flag, int print_flag, int resume_flag,
1534     int fsync_flag)
1535 {
1536 	char *src_canon;
1537 	int ret;
1538 
1539 	if ((src_canon = do_realpath(conn, src)) == NULL) {
1540 		error("Unable to canonicalize path \"%s\"", src);
1541 		return -1;
1542 	}
1543 
1544 	ret = download_dir_internal(conn, src_canon, dst, 0,
1545 	    dirattrib, preserve_flag, print_flag, resume_flag, fsync_flag);
1546 	free(src_canon);
1547 	return ret;
1548 }
1549 
1550 int
1551 do_upload(struct sftp_conn *conn, const char *local_path,
1552     const char *remote_path, int preserve_flag, int resume, int fsync_flag)
1553 {
1554 	int r, local_fd;
1555 	u_int status = SSH2_FX_OK;
1556 	u_int id;
1557 	u_char type;
1558 	off_t offset, progress_counter;
1559 	u_char *handle, *data;
1560 	struct sshbuf *msg;
1561 	struct stat sb;
1562 	Attrib a, *c = NULL;
1563 	u_int32_t startid;
1564 	u_int32_t ackid;
1565 	struct outstanding_ack {
1566 		u_int id;
1567 		u_int len;
1568 		off_t offset;
1569 		TAILQ_ENTRY(outstanding_ack) tq;
1570 	};
1571 	TAILQ_HEAD(ackhead, outstanding_ack) acks;
1572 	struct outstanding_ack *ack = NULL;
1573 	size_t handle_len;
1574 
1575 	TAILQ_INIT(&acks);
1576 
1577 	if ((local_fd = open(local_path, O_RDONLY, 0)) == -1) {
1578 		error("Couldn't open local file \"%s\" for reading: %s",
1579 		    local_path, strerror(errno));
1580 		return(-1);
1581 	}
1582 	if (fstat(local_fd, &sb) == -1) {
1583 		error("Couldn't fstat local file \"%s\": %s",
1584 		    local_path, strerror(errno));
1585 		close(local_fd);
1586 		return(-1);
1587 	}
1588 	if (!S_ISREG(sb.st_mode)) {
1589 		error("%s is not a regular file", local_path);
1590 		close(local_fd);
1591 		return(-1);
1592 	}
1593 	stat_to_attrib(&sb, &a);
1594 
1595 	a.flags &= ~SSH2_FILEXFER_ATTR_SIZE;
1596 	a.flags &= ~SSH2_FILEXFER_ATTR_UIDGID;
1597 	a.perm &= 0777;
1598 	if (!preserve_flag)
1599 		a.flags &= ~SSH2_FILEXFER_ATTR_ACMODTIME;
1600 
1601 	if (resume) {
1602 		/* Get remote file size if it exists */
1603 		if ((c = do_stat(conn, remote_path, 0)) == NULL) {
1604 			close(local_fd);
1605 			return -1;
1606 		}
1607 
1608 		if ((off_t)c->size >= sb.st_size) {
1609 			error("destination file bigger or same size as "
1610 			      "source file");
1611 			close(local_fd);
1612 			return -1;
1613 		}
1614 
1615 		if (lseek(local_fd, (off_t)c->size, SEEK_SET) == -1) {
1616 			close(local_fd);
1617 			return -1;
1618 		}
1619 	}
1620 
1621 	if ((msg = sshbuf_new()) == NULL)
1622 		fatal("%s: sshbuf_new failed", __func__);
1623 
1624 	/* Send open request */
1625 	id = conn->msg_id++;
1626 	if ((r = sshbuf_put_u8(msg, SSH2_FXP_OPEN)) != 0 ||
1627 	    (r = sshbuf_put_u32(msg, id)) != 0 ||
1628 	    (r = sshbuf_put_cstring(msg, remote_path)) != 0 ||
1629 	    (r = sshbuf_put_u32(msg, SSH2_FXF_WRITE|SSH2_FXF_CREAT|
1630 	    (resume ? SSH2_FXF_APPEND : SSH2_FXF_TRUNC))) != 0 ||
1631 	    (r = encode_attrib(msg, &a)) != 0)
1632 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1633 	send_msg(conn, msg);
1634 	debug3("Sent message SSH2_FXP_OPEN I:%u P:%s", id, remote_path);
1635 
1636 	sshbuf_reset(msg);
1637 
1638 	handle = get_handle(conn, id, &handle_len,
1639 	    "remote open(\"%s\")", remote_path);
1640 	if (handle == NULL) {
1641 		close(local_fd);
1642 		sshbuf_free(msg);
1643 		return -1;
1644 	}
1645 
1646 	startid = ackid = id + 1;
1647 	data = xmalloc(conn->transfer_buflen);
1648 
1649 	/* Read from local and write to remote */
1650 	offset = progress_counter = (resume ? c->size : 0);
1651 	if (showprogress)
1652 		start_progress_meter(local_path, sb.st_size,
1653 		    &progress_counter);
1654 
1655 	for (;;) {
1656 		int len;
1657 
1658 		/*
1659 		 * Can't use atomicio here because it returns 0 on EOF,
1660 		 * thus losing the last block of the file.
1661 		 * Simulate an EOF on interrupt, allowing ACKs from the
1662 		 * server to drain.
1663 		 */
1664 		if (interrupted || status != SSH2_FX_OK)
1665 			len = 0;
1666 		else do
1667 			len = read(local_fd, data, conn->transfer_buflen);
1668 		while ((len == -1) && (errno == EINTR || errno == EAGAIN));
1669 
1670 		if (len == -1)
1671 			fatal("Couldn't read from \"%s\": %s", local_path,
1672 			    strerror(errno));
1673 
1674 		if (len != 0) {
1675 			ack = xcalloc(1, sizeof(*ack));
1676 			ack->id = ++id;
1677 			ack->offset = offset;
1678 			ack->len = len;
1679 			TAILQ_INSERT_TAIL(&acks, ack, tq);
1680 
1681 			sshbuf_reset(msg);
1682 			if ((r = sshbuf_put_u8(msg, SSH2_FXP_WRITE)) != 0 ||
1683 			    (r = sshbuf_put_u32(msg, ack->id)) != 0 ||
1684 			    (r = sshbuf_put_string(msg, handle,
1685 			    handle_len)) != 0 ||
1686 			    (r = sshbuf_put_u64(msg, offset)) != 0 ||
1687 			    (r = sshbuf_put_string(msg, data, len)) != 0)
1688 				fatal("%s: buffer error: %s",
1689 				    __func__, ssh_err(r));
1690 			send_msg(conn, msg);
1691 			debug3("Sent message SSH2_FXP_WRITE I:%u O:%llu S:%u",
1692 			    id, (unsigned long long)offset, len);
1693 		} else if (TAILQ_FIRST(&acks) == NULL)
1694 			break;
1695 
1696 		if (ack == NULL)
1697 			fatal("Unexpected ACK %u", id);
1698 
1699 		if (id == startid || len == 0 ||
1700 		    id - ackid >= conn->num_requests) {
1701 			u_int rid;
1702 
1703 			sshbuf_reset(msg);
1704 			get_msg(conn, msg);
1705 			if ((r = sshbuf_get_u8(msg, &type)) != 0 ||
1706 			    (r = sshbuf_get_u32(msg, &rid)) != 0)
1707 				fatal("%s: buffer error: %s",
1708 				    __func__, ssh_err(r));
1709 
1710 			if (type != SSH2_FXP_STATUS)
1711 				fatal("Expected SSH2_FXP_STATUS(%d) packet, "
1712 				    "got %d", SSH2_FXP_STATUS, type);
1713 
1714 			if ((r = sshbuf_get_u32(msg, &status)) != 0)
1715 				fatal("%s: buffer error: %s",
1716 				    __func__, ssh_err(r));
1717 			debug3("SSH2_FXP_STATUS %u", status);
1718 
1719 			/* Find the request in our queue */
1720 			for (ack = TAILQ_FIRST(&acks);
1721 			    ack != NULL && ack->id != rid;
1722 			    ack = TAILQ_NEXT(ack, tq))
1723 				;
1724 			if (ack == NULL)
1725 				fatal("Can't find request for ID %u", rid);
1726 			TAILQ_REMOVE(&acks, ack, tq);
1727 			debug3("In write loop, ack for %u %u bytes at %lld",
1728 			    ack->id, ack->len, (long long)ack->offset);
1729 			++ackid;
1730 			progress_counter += ack->len;
1731 			free(ack);
1732 		}
1733 		offset += len;
1734 		if (offset < 0)
1735 			fatal("%s: offset < 0", __func__);
1736 	}
1737 	sshbuf_free(msg);
1738 
1739 	if (showprogress)
1740 		stop_progress_meter();
1741 	free(data);
1742 
1743 	if (status != SSH2_FX_OK) {
1744 		error("Couldn't write to remote file \"%s\": %s",
1745 		    remote_path, fx2txt(status));
1746 		status = SSH2_FX_FAILURE;
1747 	}
1748 
1749 	if (close(local_fd) == -1) {
1750 		error("Couldn't close local file \"%s\": %s", local_path,
1751 		    strerror(errno));
1752 		status = SSH2_FX_FAILURE;
1753 	}
1754 
1755 	/* Override umask and utimes if asked */
1756 	if (preserve_flag)
1757 		do_fsetstat(conn, handle, handle_len, &a);
1758 
1759 	if (fsync_flag)
1760 		(void)do_fsync(conn, handle, handle_len);
1761 
1762 	if (do_close(conn, handle, handle_len) != 0)
1763 		status = SSH2_FX_FAILURE;
1764 
1765 	free(handle);
1766 
1767 	return status == SSH2_FX_OK ? 0 : -1;
1768 }
1769 
1770 static int
1771 upload_dir_internal(struct sftp_conn *conn, const char *src, const char *dst,
1772     int depth, int preserve_flag, int print_flag, int resume, int fsync_flag)
1773 {
1774 	int ret = 0;
1775 	DIR *dirp;
1776 	struct dirent *dp;
1777 	char *filename, *new_src, *new_dst;
1778 	struct stat sb;
1779 	Attrib a, *dirattrib;
1780 
1781 	if (depth >= MAX_DIR_DEPTH) {
1782 		error("Maximum directory depth exceeded: %d levels", depth);
1783 		return -1;
1784 	}
1785 
1786 	if (stat(src, &sb) == -1) {
1787 		error("Couldn't stat directory \"%s\": %s",
1788 		    src, strerror(errno));
1789 		return -1;
1790 	}
1791 	if (!S_ISDIR(sb.st_mode)) {
1792 		error("\"%s\" is not a directory", src);
1793 		return -1;
1794 	}
1795 	if (print_flag)
1796 		mprintf("Entering %s\n", src);
1797 
1798 	attrib_clear(&a);
1799 	stat_to_attrib(&sb, &a);
1800 	a.flags &= ~SSH2_FILEXFER_ATTR_SIZE;
1801 	a.flags &= ~SSH2_FILEXFER_ATTR_UIDGID;
1802 	a.perm &= 01777;
1803 	if (!preserve_flag)
1804 		a.flags &= ~SSH2_FILEXFER_ATTR_ACMODTIME;
1805 
1806 	/*
1807 	 * sftp lacks a portable status value to match errno EEXIST,
1808 	 * so if we get a failure back then we must check whether
1809 	 * the path already existed and is a directory.
1810 	 */
1811 	if (do_mkdir(conn, dst, &a, 0) != 0) {
1812 		if ((dirattrib = do_stat(conn, dst, 0)) == NULL)
1813 			return -1;
1814 		if (!S_ISDIR(dirattrib->perm)) {
1815 			error("\"%s\" exists but is not a directory", dst);
1816 			return -1;
1817 		}
1818 	}
1819 
1820 	if ((dirp = opendir(src)) == NULL) {
1821 		error("Failed to open dir \"%s\": %s", src, strerror(errno));
1822 		return -1;
1823 	}
1824 
1825 	while (((dp = readdir(dirp)) != NULL) && !interrupted) {
1826 		if (dp->d_ino == 0)
1827 			continue;
1828 		filename = dp->d_name;
1829 		new_dst = path_append(dst, filename);
1830 		new_src = path_append(src, filename);
1831 
1832 		if (lstat(new_src, &sb) == -1) {
1833 			logit("%s: lstat failed: %s", filename,
1834 			    strerror(errno));
1835 			ret = -1;
1836 		} else if (S_ISDIR(sb.st_mode)) {
1837 			if (strcmp(filename, ".") == 0 ||
1838 			    strcmp(filename, "..") == 0)
1839 				continue;
1840 
1841 			if (upload_dir_internal(conn, new_src, new_dst,
1842 			    depth + 1, preserve_flag, print_flag, resume,
1843 			    fsync_flag) == -1)
1844 				ret = -1;
1845 		} else if (S_ISREG(sb.st_mode)) {
1846 			if (do_upload(conn, new_src, new_dst,
1847 			    preserve_flag, resume, fsync_flag) == -1) {
1848 				error("Uploading of file %s to %s failed!",
1849 				    new_src, new_dst);
1850 				ret = -1;
1851 			}
1852 		} else
1853 			logit("%s: not a regular file\n", filename);
1854 		free(new_dst);
1855 		free(new_src);
1856 	}
1857 
1858 	do_setstat(conn, dst, &a);
1859 
1860 	(void) closedir(dirp);
1861 	return ret;
1862 }
1863 
1864 int
1865 upload_dir(struct sftp_conn *conn, const char *src, const char *dst,
1866     int preserve_flag, int print_flag, int resume, int fsync_flag)
1867 {
1868 	char *dst_canon;
1869 	int ret;
1870 
1871 	if ((dst_canon = do_realpath(conn, dst)) == NULL) {
1872 		error("Unable to canonicalize path \"%s\"", dst);
1873 		return -1;
1874 	}
1875 
1876 	ret = upload_dir_internal(conn, src, dst_canon, 0, preserve_flag,
1877 	    print_flag, resume, fsync_flag);
1878 
1879 	free(dst_canon);
1880 	return ret;
1881 }
1882 
1883 char *
1884 path_append(const char *p1, const char *p2)
1885 {
1886 	char *ret;
1887 	size_t len = strlen(p1) + strlen(p2) + 2;
1888 
1889 	ret = xmalloc(len);
1890 	strlcpy(ret, p1, len);
1891 	if (p1[0] != '\0' && p1[strlen(p1) - 1] != '/')
1892 		strlcat(ret, "/", len);
1893 	strlcat(ret, p2, len);
1894 
1895 	return(ret);
1896 }
1897 
1898