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