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