xref: /freebsd/crypto/openssh/sftp-client.c (revision b52b9d56d4e96089873a75f9e29062eec19fabba)
1 /*
2  * Copyright (c) 2001,2002 Damien Miller.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
14  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
15  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
16  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
17  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
18  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
19  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
20  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
22  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23  */
24 
25 /* XXX: memleaks */
26 /* XXX: signed vs unsigned */
27 /* XXX: remove all logging, only return status codes */
28 /* XXX: copy between two remote sites */
29 
30 #include "includes.h"
31 RCSID("$OpenBSD: sftp-client.c,v 1.33 2002/06/23 09:30:14 deraadt Exp $");
32 
33 #include "openbsd-compat/fake-queue.h"
34 
35 #include "buffer.h"
36 #include "bufaux.h"
37 #include "getput.h"
38 #include "xmalloc.h"
39 #include "log.h"
40 #include "atomicio.h"
41 
42 #include "sftp.h"
43 #include "sftp-common.h"
44 #include "sftp-client.h"
45 
46 /* Minimum amount of data to read at at time */
47 #define MIN_READ_SIZE	512
48 
49 struct sftp_conn {
50 	int fd_in;
51 	int fd_out;
52 	u_int transfer_buflen;
53 	u_int num_requests;
54 	u_int version;
55 	u_int msg_id;
56 };
57 
58 static void
59 send_msg(int fd, Buffer *m)
60 {
61 	int mlen = buffer_len(m);
62 	int len;
63 	Buffer oqueue;
64 
65 	buffer_init(&oqueue);
66 	buffer_put_int(&oqueue, mlen);
67 	buffer_append(&oqueue, buffer_ptr(m), mlen);
68 	buffer_consume(m, mlen);
69 
70 	len = atomicio(write, fd, buffer_ptr(&oqueue), buffer_len(&oqueue));
71 	if (len <= 0)
72 		fatal("Couldn't send packet: %s", strerror(errno));
73 
74 	buffer_free(&oqueue);
75 }
76 
77 static void
78 get_msg(int fd, Buffer *m)
79 {
80 	u_int len, msg_len;
81 	unsigned char buf[4096];
82 
83 	len = atomicio(read, fd, buf, 4);
84 	if (len == 0)
85 		fatal("Connection closed");
86 	else if (len == -1)
87 		fatal("Couldn't read packet: %s", strerror(errno));
88 
89 	msg_len = GET_32BIT(buf);
90 	if (msg_len > 256 * 1024)
91 		fatal("Received message too long %u", msg_len);
92 
93 	while (msg_len) {
94 		len = atomicio(read, fd, buf, MIN(msg_len, sizeof(buf)));
95 		if (len == 0)
96 			fatal("Connection closed");
97 		else if (len == -1)
98 			fatal("Couldn't read packet: %s", strerror(errno));
99 
100 		msg_len -= len;
101 		buffer_append(m, buf, len);
102 	}
103 }
104 
105 static void
106 send_string_request(int fd, u_int id, u_int code, char *s,
107     u_int len)
108 {
109 	Buffer msg;
110 
111 	buffer_init(&msg);
112 	buffer_put_char(&msg, code);
113 	buffer_put_int(&msg, id);
114 	buffer_put_string(&msg, s, len);
115 	send_msg(fd, &msg);
116 	debug3("Sent message fd %d T:%u I:%u", fd, code, id);
117 	buffer_free(&msg);
118 }
119 
120 static void
121 send_string_attrs_request(int fd, u_int id, u_int code, char *s,
122     u_int len, Attrib *a)
123 {
124 	Buffer msg;
125 
126 	buffer_init(&msg);
127 	buffer_put_char(&msg, code);
128 	buffer_put_int(&msg, id);
129 	buffer_put_string(&msg, s, len);
130 	encode_attrib(&msg, a);
131 	send_msg(fd, &msg);
132 	debug3("Sent message fd %d T:%u I:%u", fd, code, id);
133 	buffer_free(&msg);
134 }
135 
136 static u_int
137 get_status(int fd, u_int expected_id)
138 {
139 	Buffer msg;
140 	u_int type, id, status;
141 
142 	buffer_init(&msg);
143 	get_msg(fd, &msg);
144 	type = buffer_get_char(&msg);
145 	id = buffer_get_int(&msg);
146 
147 	if (id != expected_id)
148 		fatal("ID mismatch (%u != %u)", id, expected_id);
149 	if (type != SSH2_FXP_STATUS)
150 		fatal("Expected SSH2_FXP_STATUS(%u) packet, got %u",
151 		    SSH2_FXP_STATUS, type);
152 
153 	status = buffer_get_int(&msg);
154 	buffer_free(&msg);
155 
156 	debug3("SSH2_FXP_STATUS %u", status);
157 
158 	return(status);
159 }
160 
161 static char *
162 get_handle(int fd, u_int expected_id, u_int *len)
163 {
164 	Buffer msg;
165 	u_int type, id;
166 	char *handle;
167 
168 	buffer_init(&msg);
169 	get_msg(fd, &msg);
170 	type = buffer_get_char(&msg);
171 	id = buffer_get_int(&msg);
172 
173 	if (id != expected_id)
174 		fatal("ID mismatch (%u != %u)", id, expected_id);
175 	if (type == SSH2_FXP_STATUS) {
176 		int status = buffer_get_int(&msg);
177 
178 		error("Couldn't get handle: %s", fx2txt(status));
179 		return(NULL);
180 	} else if (type != SSH2_FXP_HANDLE)
181 		fatal("Expected SSH2_FXP_HANDLE(%u) packet, got %u",
182 		    SSH2_FXP_HANDLE, type);
183 
184 	handle = buffer_get_string(&msg, len);
185 	buffer_free(&msg);
186 
187 	return(handle);
188 }
189 
190 static Attrib *
191 get_decode_stat(int fd, u_int expected_id, int quiet)
192 {
193 	Buffer msg;
194 	u_int type, id;
195 	Attrib *a;
196 
197 	buffer_init(&msg);
198 	get_msg(fd, &msg);
199 
200 	type = buffer_get_char(&msg);
201 	id = buffer_get_int(&msg);
202 
203 	debug3("Received stat reply T:%u I:%u", type, id);
204 	if (id != expected_id)
205 		fatal("ID mismatch (%u != %u)", id, expected_id);
206 	if (type == SSH2_FXP_STATUS) {
207 		int status = buffer_get_int(&msg);
208 
209 		if (quiet)
210 			debug("Couldn't stat remote file: %s", fx2txt(status));
211 		else
212 			error("Couldn't stat remote file: %s", fx2txt(status));
213 		return(NULL);
214 	} else if (type != SSH2_FXP_ATTRS) {
215 		fatal("Expected SSH2_FXP_ATTRS(%u) packet, got %u",
216 		    SSH2_FXP_ATTRS, type);
217 	}
218 	a = decode_attrib(&msg);
219 	buffer_free(&msg);
220 
221 	return(a);
222 }
223 
224 struct sftp_conn *
225 do_init(int fd_in, int fd_out, u_int transfer_buflen, u_int num_requests)
226 {
227 	u_int type;
228 	int version;
229 	Buffer msg;
230 	struct sftp_conn *ret;
231 
232 	buffer_init(&msg);
233 	buffer_put_char(&msg, SSH2_FXP_INIT);
234 	buffer_put_int(&msg, SSH2_FILEXFER_VERSION);
235 	send_msg(fd_out, &msg);
236 
237 	buffer_clear(&msg);
238 
239 	get_msg(fd_in, &msg);
240 
241 	/* Expecting a VERSION reply */
242 	if ((type = buffer_get_char(&msg)) != SSH2_FXP_VERSION) {
243 		error("Invalid packet back from SSH2_FXP_INIT (type %u)",
244 		    type);
245 		buffer_free(&msg);
246 		return(NULL);
247 	}
248 	version = buffer_get_int(&msg);
249 
250 	debug2("Remote version: %d", version);
251 
252 	/* Check for extensions */
253 	while (buffer_len(&msg) > 0) {
254 		char *name = buffer_get_string(&msg, NULL);
255 		char *value = buffer_get_string(&msg, NULL);
256 
257 		debug2("Init extension: \"%s\"", name);
258 		xfree(name);
259 		xfree(value);
260 	}
261 
262 	buffer_free(&msg);
263 
264 	ret = xmalloc(sizeof(*ret));
265 	ret->fd_in = fd_in;
266 	ret->fd_out = fd_out;
267 	ret->transfer_buflen = transfer_buflen;
268 	ret->num_requests = num_requests;
269 	ret->version = version;
270 	ret->msg_id = 1;
271 
272 	/* Some filexfer v.0 servers don't support large packets */
273 	if (version == 0)
274 		ret->transfer_buflen = MIN(ret->transfer_buflen, 20480);
275 
276 	return(ret);
277 }
278 
279 u_int
280 sftp_proto_version(struct sftp_conn *conn)
281 {
282 	return(conn->version);
283 }
284 
285 int
286 do_close(struct sftp_conn *conn, char *handle, u_int handle_len)
287 {
288 	u_int id, status;
289 	Buffer msg;
290 
291 	buffer_init(&msg);
292 
293 	id = conn->msg_id++;
294 	buffer_put_char(&msg, SSH2_FXP_CLOSE);
295 	buffer_put_int(&msg, id);
296 	buffer_put_string(&msg, handle, handle_len);
297 	send_msg(conn->fd_out, &msg);
298 	debug3("Sent message SSH2_FXP_CLOSE I:%u", id);
299 
300 	status = get_status(conn->fd_in, id);
301 	if (status != SSH2_FX_OK)
302 		error("Couldn't close file: %s", fx2txt(status));
303 
304 	buffer_free(&msg);
305 
306 	return(status);
307 }
308 
309 
310 static int
311 do_lsreaddir(struct sftp_conn *conn, char *path, int printflag,
312     SFTP_DIRENT ***dir)
313 {
314 	Buffer msg;
315 	u_int type, id, handle_len, i, expected_id, ents = 0;
316 	char *handle;
317 
318 	id = conn->msg_id++;
319 
320 	buffer_init(&msg);
321 	buffer_put_char(&msg, SSH2_FXP_OPENDIR);
322 	buffer_put_int(&msg, id);
323 	buffer_put_cstring(&msg, path);
324 	send_msg(conn->fd_out, &msg);
325 
326 	buffer_clear(&msg);
327 
328 	handle = get_handle(conn->fd_in, id, &handle_len);
329 	if (handle == NULL)
330 		return(-1);
331 
332 	if (dir) {
333 		ents = 0;
334 		*dir = xmalloc(sizeof(**dir));
335 		(*dir)[0] = NULL;
336 	}
337 
338 	for (;;) {
339 		int count;
340 
341 		id = expected_id = conn->msg_id++;
342 
343 		debug3("Sending SSH2_FXP_READDIR I:%u", id);
344 
345 		buffer_clear(&msg);
346 		buffer_put_char(&msg, SSH2_FXP_READDIR);
347 		buffer_put_int(&msg, id);
348 		buffer_put_string(&msg, handle, handle_len);
349 		send_msg(conn->fd_out, &msg);
350 
351 		buffer_clear(&msg);
352 
353 		get_msg(conn->fd_in, &msg);
354 
355 		type = buffer_get_char(&msg);
356 		id = buffer_get_int(&msg);
357 
358 		debug3("Received reply T:%u I:%u", type, id);
359 
360 		if (id != expected_id)
361 			fatal("ID mismatch (%u != %u)", id, expected_id);
362 
363 		if (type == SSH2_FXP_STATUS) {
364 			int status = buffer_get_int(&msg);
365 
366 			debug3("Received SSH2_FXP_STATUS %d", status);
367 
368 			if (status == SSH2_FX_EOF) {
369 				break;
370 			} else {
371 				error("Couldn't read directory: %s",
372 				    fx2txt(status));
373 				do_close(conn, handle, handle_len);
374 				return(status);
375 			}
376 		} else if (type != SSH2_FXP_NAME)
377 			fatal("Expected SSH2_FXP_NAME(%u) packet, got %u",
378 			    SSH2_FXP_NAME, type);
379 
380 		count = buffer_get_int(&msg);
381 		if (count == 0)
382 			break;
383 		debug3("Received %d SSH2_FXP_NAME responses", count);
384 		for (i = 0; i < count; i++) {
385 			char *filename, *longname;
386 			Attrib *a;
387 
388 			filename = buffer_get_string(&msg, NULL);
389 			longname = buffer_get_string(&msg, NULL);
390 			a = decode_attrib(&msg);
391 
392 			if (printflag)
393 				printf("%s\n", longname);
394 
395 			if (dir) {
396 				*dir = xrealloc(*dir, sizeof(**dir) *
397 				    (ents + 2));
398 				(*dir)[ents] = xmalloc(sizeof(***dir));
399 				(*dir)[ents]->filename = xstrdup(filename);
400 				(*dir)[ents]->longname = xstrdup(longname);
401 				memcpy(&(*dir)[ents]->a, a, sizeof(*a));
402 				(*dir)[++ents] = NULL;
403 			}
404 
405 			xfree(filename);
406 			xfree(longname);
407 		}
408 	}
409 
410 	buffer_free(&msg);
411 	do_close(conn, handle, handle_len);
412 	xfree(handle);
413 
414 	return(0);
415 }
416 
417 int
418 do_ls(struct sftp_conn *conn, char *path)
419 {
420 	return(do_lsreaddir(conn, path, 1, NULL));
421 }
422 
423 int
424 do_readdir(struct sftp_conn *conn, char *path, SFTP_DIRENT ***dir)
425 {
426 	return(do_lsreaddir(conn, path, 0, dir));
427 }
428 
429 void free_sftp_dirents(SFTP_DIRENT **s)
430 {
431 	int i;
432 
433 	for (i = 0; s[i]; i++) {
434 		xfree(s[i]->filename);
435 		xfree(s[i]->longname);
436 		xfree(s[i]);
437 	}
438 	xfree(s);
439 }
440 
441 int
442 do_rm(struct sftp_conn *conn, char *path)
443 {
444 	u_int status, id;
445 
446 	debug2("Sending SSH2_FXP_REMOVE \"%s\"", path);
447 
448 	id = conn->msg_id++;
449 	send_string_request(conn->fd_out, id, SSH2_FXP_REMOVE, path,
450 	    strlen(path));
451 	status = get_status(conn->fd_in, id);
452 	if (status != SSH2_FX_OK)
453 		error("Couldn't delete file: %s", fx2txt(status));
454 	return(status);
455 }
456 
457 int
458 do_mkdir(struct sftp_conn *conn, char *path, Attrib *a)
459 {
460 	u_int status, id;
461 
462 	id = conn->msg_id++;
463 	send_string_attrs_request(conn->fd_out, id, SSH2_FXP_MKDIR, path,
464 	    strlen(path), a);
465 
466 	status = get_status(conn->fd_in, id);
467 	if (status != SSH2_FX_OK)
468 		error("Couldn't create directory: %s", fx2txt(status));
469 
470 	return(status);
471 }
472 
473 int
474 do_rmdir(struct sftp_conn *conn, char *path)
475 {
476 	u_int status, id;
477 
478 	id = conn->msg_id++;
479 	send_string_request(conn->fd_out, id, SSH2_FXP_RMDIR, path,
480 	    strlen(path));
481 
482 	status = get_status(conn->fd_in, id);
483 	if (status != SSH2_FX_OK)
484 		error("Couldn't remove directory: %s", fx2txt(status));
485 
486 	return(status);
487 }
488 
489 Attrib *
490 do_stat(struct sftp_conn *conn, char *path, int quiet)
491 {
492 	u_int id;
493 
494 	id = conn->msg_id++;
495 
496 	send_string_request(conn->fd_out, id,
497 	    conn->version == 0 ? SSH2_FXP_STAT_VERSION_0 : SSH2_FXP_STAT,
498 	    path, strlen(path));
499 
500 	return(get_decode_stat(conn->fd_in, id, quiet));
501 }
502 
503 Attrib *
504 do_lstat(struct sftp_conn *conn, char *path, int quiet)
505 {
506 	u_int id;
507 
508 	if (conn->version == 0) {
509 		if (quiet)
510 			debug("Server version does not support lstat operation");
511 		else
512 			log("Server version does not support lstat operation");
513 		return(do_stat(conn, path, quiet));
514 	}
515 
516 	id = conn->msg_id++;
517 	send_string_request(conn->fd_out, id, SSH2_FXP_LSTAT, path,
518 	    strlen(path));
519 
520 	return(get_decode_stat(conn->fd_in, id, quiet));
521 }
522 
523 Attrib *
524 do_fstat(struct sftp_conn *conn, char *handle, u_int handle_len, int quiet)
525 {
526 	u_int id;
527 
528 	id = conn->msg_id++;
529 	send_string_request(conn->fd_out, id, SSH2_FXP_FSTAT, handle,
530 	    handle_len);
531 
532 	return(get_decode_stat(conn->fd_in, id, quiet));
533 }
534 
535 int
536 do_setstat(struct sftp_conn *conn, char *path, Attrib *a)
537 {
538 	u_int status, id;
539 
540 	id = conn->msg_id++;
541 	send_string_attrs_request(conn->fd_out, id, SSH2_FXP_SETSTAT, path,
542 	    strlen(path), a);
543 
544 	status = get_status(conn->fd_in, id);
545 	if (status != SSH2_FX_OK)
546 		error("Couldn't setstat on \"%s\": %s", path,
547 		    fx2txt(status));
548 
549 	return(status);
550 }
551 
552 int
553 do_fsetstat(struct sftp_conn *conn, char *handle, u_int handle_len,
554     Attrib *a)
555 {
556 	u_int status, id;
557 
558 	id = conn->msg_id++;
559 	send_string_attrs_request(conn->fd_out, id, SSH2_FXP_FSETSTAT, handle,
560 	    handle_len, a);
561 
562 	status = get_status(conn->fd_in, id);
563 	if (status != SSH2_FX_OK)
564 		error("Couldn't fsetstat: %s", fx2txt(status));
565 
566 	return(status);
567 }
568 
569 char *
570 do_realpath(struct sftp_conn *conn, char *path)
571 {
572 	Buffer msg;
573 	u_int type, expected_id, count, id;
574 	char *filename, *longname;
575 	Attrib *a;
576 
577 	expected_id = id = conn->msg_id++;
578 	send_string_request(conn->fd_out, id, SSH2_FXP_REALPATH, path,
579 	    strlen(path));
580 
581 	buffer_init(&msg);
582 
583 	get_msg(conn->fd_in, &msg);
584 	type = buffer_get_char(&msg);
585 	id = buffer_get_int(&msg);
586 
587 	if (id != expected_id)
588 		fatal("ID mismatch (%u != %u)", id, expected_id);
589 
590 	if (type == SSH2_FXP_STATUS) {
591 		u_int status = buffer_get_int(&msg);
592 
593 		error("Couldn't canonicalise: %s", fx2txt(status));
594 		return(NULL);
595 	} else if (type != SSH2_FXP_NAME)
596 		fatal("Expected SSH2_FXP_NAME(%u) packet, got %u",
597 		    SSH2_FXP_NAME, type);
598 
599 	count = buffer_get_int(&msg);
600 	if (count != 1)
601 		fatal("Got multiple names (%d) from SSH_FXP_REALPATH", count);
602 
603 	filename = buffer_get_string(&msg, NULL);
604 	longname = buffer_get_string(&msg, NULL);
605 	a = decode_attrib(&msg);
606 
607 	debug3("SSH_FXP_REALPATH %s -> %s", path, filename);
608 
609 	xfree(longname);
610 
611 	buffer_free(&msg);
612 
613 	return(filename);
614 }
615 
616 int
617 do_rename(struct sftp_conn *conn, char *oldpath, char *newpath)
618 {
619 	Buffer msg;
620 	u_int status, id;
621 
622 	buffer_init(&msg);
623 
624 	/* Send rename request */
625 	id = conn->msg_id++;
626 	buffer_put_char(&msg, SSH2_FXP_RENAME);
627 	buffer_put_int(&msg, id);
628 	buffer_put_cstring(&msg, oldpath);
629 	buffer_put_cstring(&msg, newpath);
630 	send_msg(conn->fd_out, &msg);
631 	debug3("Sent message SSH2_FXP_RENAME \"%s\" -> \"%s\"", oldpath,
632 	    newpath);
633 	buffer_free(&msg);
634 
635 	status = get_status(conn->fd_in, id);
636 	if (status != SSH2_FX_OK)
637 		error("Couldn't rename file \"%s\" to \"%s\": %s", oldpath,
638 		    newpath, fx2txt(status));
639 
640 	return(status);
641 }
642 
643 int
644 do_symlink(struct sftp_conn *conn, char *oldpath, char *newpath)
645 {
646 	Buffer msg;
647 	u_int status, id;
648 
649 	if (conn->version < 3) {
650 		error("This server does not support the symlink operation");
651 		return(SSH2_FX_OP_UNSUPPORTED);
652 	}
653 
654 	buffer_init(&msg);
655 
656 	/* Send rename request */
657 	id = conn->msg_id++;
658 	buffer_put_char(&msg, SSH2_FXP_SYMLINK);
659 	buffer_put_int(&msg, id);
660 	buffer_put_cstring(&msg, oldpath);
661 	buffer_put_cstring(&msg, newpath);
662 	send_msg(conn->fd_out, &msg);
663 	debug3("Sent message SSH2_FXP_SYMLINK \"%s\" -> \"%s\"", oldpath,
664 	    newpath);
665 	buffer_free(&msg);
666 
667 	status = get_status(conn->fd_in, id);
668 	if (status != SSH2_FX_OK)
669 		error("Couldn't rename file \"%s\" to \"%s\": %s", oldpath,
670 		    newpath, fx2txt(status));
671 
672 	return(status);
673 }
674 
675 char *
676 do_readlink(struct sftp_conn *conn, char *path)
677 {
678 	Buffer msg;
679 	u_int type, expected_id, count, id;
680 	char *filename, *longname;
681 	Attrib *a;
682 
683 	expected_id = id = conn->msg_id++;
684 	send_string_request(conn->fd_out, id, SSH2_FXP_READLINK, path,
685 	    strlen(path));
686 
687 	buffer_init(&msg);
688 
689 	get_msg(conn->fd_in, &msg);
690 	type = buffer_get_char(&msg);
691 	id = buffer_get_int(&msg);
692 
693 	if (id != expected_id)
694 		fatal("ID mismatch (%u != %u)", id, expected_id);
695 
696 	if (type == SSH2_FXP_STATUS) {
697 		u_int status = buffer_get_int(&msg);
698 
699 		error("Couldn't readlink: %s", fx2txt(status));
700 		return(NULL);
701 	} else if (type != SSH2_FXP_NAME)
702 		fatal("Expected SSH2_FXP_NAME(%u) packet, got %u",
703 		    SSH2_FXP_NAME, type);
704 
705 	count = buffer_get_int(&msg);
706 	if (count != 1)
707 		fatal("Got multiple names (%d) from SSH_FXP_READLINK", count);
708 
709 	filename = buffer_get_string(&msg, NULL);
710 	longname = buffer_get_string(&msg, NULL);
711 	a = decode_attrib(&msg);
712 
713 	debug3("SSH_FXP_READLINK %s -> %s", path, filename);
714 
715 	xfree(longname);
716 
717 	buffer_free(&msg);
718 
719 	return(filename);
720 }
721 
722 static void
723 send_read_request(int fd_out, u_int id, u_int64_t offset, u_int len,
724     char *handle, u_int handle_len)
725 {
726 	Buffer msg;
727 
728 	buffer_init(&msg);
729 	buffer_clear(&msg);
730 	buffer_put_char(&msg, SSH2_FXP_READ);
731 	buffer_put_int(&msg, id);
732 	buffer_put_string(&msg, handle, handle_len);
733 	buffer_put_int64(&msg, offset);
734 	buffer_put_int(&msg, len);
735 	send_msg(fd_out, &msg);
736 	buffer_free(&msg);
737 }
738 
739 int
740 do_download(struct sftp_conn *conn, char *remote_path, char *local_path,
741     int pflag)
742 {
743 	Attrib junk, *a;
744 	Buffer msg;
745 	char *handle;
746 	int local_fd, status, num_req, max_req, write_error;
747 	int read_error, write_errno;
748 	u_int64_t offset, size;
749 	u_int handle_len, mode, type, id, buflen;
750 	struct request {
751 		u_int id;
752 		u_int len;
753 		u_int64_t offset;
754 		TAILQ_ENTRY(request) tq;
755 	};
756 	TAILQ_HEAD(reqhead, request) requests;
757 	struct request *req;
758 
759 	TAILQ_INIT(&requests);
760 
761 	a = do_stat(conn, remote_path, 0);
762 	if (a == NULL)
763 		return(-1);
764 
765 	/* XXX: should we preserve set[ug]id? */
766 	if (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)
767 		mode = S_IWRITE | (a->perm & 0777);
768 	else
769 		mode = 0666;
770 
771 	if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
772 	    (a->perm & S_IFDIR)) {
773 		error("Cannot download a directory: %s", remote_path);
774 		return(-1);
775 	}
776 
777 	if (a->flags & SSH2_FILEXFER_ATTR_SIZE)
778 		size = a->size;
779 	else
780 		size = 0;
781 
782 	buflen = conn->transfer_buflen;
783 	buffer_init(&msg);
784 
785 	/* Send open request */
786 	id = conn->msg_id++;
787 	buffer_put_char(&msg, SSH2_FXP_OPEN);
788 	buffer_put_int(&msg, id);
789 	buffer_put_cstring(&msg, remote_path);
790 	buffer_put_int(&msg, SSH2_FXF_READ);
791 	attrib_clear(&junk); /* Send empty attributes */
792 	encode_attrib(&msg, &junk);
793 	send_msg(conn->fd_out, &msg);
794 	debug3("Sent message SSH2_FXP_OPEN I:%u P:%s", id, remote_path);
795 
796 	handle = get_handle(conn->fd_in, id, &handle_len);
797 	if (handle == NULL) {
798 		buffer_free(&msg);
799 		return(-1);
800 	}
801 
802 	local_fd = open(local_path, O_WRONLY | O_CREAT | O_TRUNC, mode);
803 	if (local_fd == -1) {
804 		error("Couldn't open local file \"%s\" for writing: %s",
805 		    local_path, strerror(errno));
806 		buffer_free(&msg);
807 		xfree(handle);
808 		return(-1);
809 	}
810 
811 	/* Read from remote and write to local */
812 	write_error = read_error = write_errno = num_req = offset = 0;
813 	max_req = 1;
814 	while (num_req > 0 || max_req > 0) {
815 		char *data;
816 		u_int len;
817 
818 		/* Send some more requests */
819 		while (num_req < max_req) {
820 			debug3("Request range %llu -> %llu (%d/%d)",
821 			    (unsigned long long)offset,
822 			    (unsigned long long)offset + buflen - 1,
823 			    num_req, max_req);
824 			req = xmalloc(sizeof(*req));
825 			req->id = conn->msg_id++;
826 			req->len = buflen;
827 			req->offset = offset;
828 			offset += buflen;
829 			num_req++;
830 			TAILQ_INSERT_TAIL(&requests, req, tq);
831 			send_read_request(conn->fd_out, req->id, req->offset,
832 			    req->len, handle, handle_len);
833 		}
834 
835 		buffer_clear(&msg);
836 		get_msg(conn->fd_in, &msg);
837 		type = buffer_get_char(&msg);
838 		id = buffer_get_int(&msg);
839 		debug3("Received reply T:%u I:%u R:%d", type, id, max_req);
840 
841 		/* Find the request in our queue */
842 		for(req = TAILQ_FIRST(&requests);
843 		    req != NULL && req->id != id;
844 		    req = TAILQ_NEXT(req, tq))
845 			;
846 		if (req == NULL)
847 			fatal("Unexpected reply %u", id);
848 
849 		switch (type) {
850 		case SSH2_FXP_STATUS:
851 			status = buffer_get_int(&msg);
852 			if (status != SSH2_FX_EOF)
853 				read_error = 1;
854 			max_req = 0;
855 			TAILQ_REMOVE(&requests, req, tq);
856 			xfree(req);
857 			num_req--;
858 			break;
859 		case SSH2_FXP_DATA:
860 			data = buffer_get_string(&msg, &len);
861 			debug3("Received data %llu -> %llu",
862 			    (unsigned long long)req->offset,
863 			    (unsigned long long)req->offset + len - 1);
864 			if (len > req->len)
865 				fatal("Received more data than asked for "
866 				      "%u > %u", len, req->len);
867 			if ((lseek(local_fd, req->offset, SEEK_SET) == -1 ||
868 			     atomicio(write, local_fd, data, len) != len) &&
869 			    !write_error) {
870 				write_errno = errno;
871 				write_error = 1;
872 				max_req = 0;
873 			}
874 			xfree(data);
875 
876 			if (len == req->len) {
877 				TAILQ_REMOVE(&requests, req, tq);
878 				xfree(req);
879 				num_req--;
880 			} else {
881 				/* Resend the request for the missing data */
882 				debug3("Short data block, re-requesting "
883 				    "%llu -> %llu (%2d)",
884 				    (unsigned long long)req->offset + len,
885 				    (unsigned long long)req->offset +
886 				    req->len - 1, num_req);
887 				req->id = conn->msg_id++;
888 				req->len -= len;
889 				req->offset += len;
890 				send_read_request(conn->fd_out, req->id,
891 				    req->offset, req->len, handle, handle_len);
892 				/* Reduce the request size */
893 				if (len < buflen)
894 					buflen = MAX(MIN_READ_SIZE, len);
895 			}
896 			if (max_req > 0) { /* max_req = 0 iff EOF received */
897 				if (size > 0 && offset > size) {
898 					/* Only one request at a time
899 					 * after the expected EOF */
900 					debug3("Finish at %llu (%2d)",
901 					    (unsigned long long)offset,
902 					    num_req);
903 					max_req = 1;
904 				}
905 				else if (max_req < conn->num_requests + 1) {
906 					++max_req;
907 				}
908 			}
909 			break;
910 		default:
911 			fatal("Expected SSH2_FXP_DATA(%u) packet, got %u",
912 			    SSH2_FXP_DATA, type);
913 		}
914 	}
915 
916 	/* Sanity check */
917 	if (TAILQ_FIRST(&requests) != NULL)
918 		fatal("Transfer complete, but requests still in queue");
919 
920 	if (read_error) {
921 		error("Couldn't read from remote file \"%s\" : %s",
922 		    remote_path, fx2txt(status));
923 		do_close(conn, handle, handle_len);
924 	} else if (write_error) {
925 		error("Couldn't write to \"%s\": %s", local_path,
926 		    strerror(write_errno));
927 		status = -1;
928 		do_close(conn, handle, handle_len);
929 	} else {
930 		status = do_close(conn, handle, handle_len);
931 
932 		/* Override umask and utimes if asked */
933 #ifdef HAVE_FCHMOD
934 		if (pflag && fchmod(local_fd, mode) == -1)
935 #else
936 		if (pflag && chmod(local_path, mode) == -1)
937 #endif /* HAVE_FCHMOD */
938 			error("Couldn't set mode on \"%s\": %s", local_path,
939 			      strerror(errno));
940 		if (pflag && (a->flags & SSH2_FILEXFER_ATTR_ACMODTIME)) {
941 			struct timeval tv[2];
942 			tv[0].tv_sec = a->atime;
943 			tv[1].tv_sec = a->mtime;
944 			tv[0].tv_usec = tv[1].tv_usec = 0;
945 			if (utimes(local_path, tv) == -1)
946 				error("Can't set times on \"%s\": %s",
947 				      local_path, strerror(errno));
948 		}
949 	}
950 	close(local_fd);
951 	buffer_free(&msg);
952 	xfree(handle);
953 
954 	return(status);
955 }
956 
957 int
958 do_upload(struct sftp_conn *conn, char *local_path, char *remote_path,
959     int pflag)
960 {
961 	int local_fd, status;
962 	u_int handle_len, id, type;
963 	u_int64_t offset;
964 	char *handle, *data;
965 	Buffer msg;
966 	struct stat sb;
967 	Attrib a;
968 	u_int32_t startid;
969 	u_int32_t ackid;
970 	struct outstanding_ack {
971 		u_int id;
972 		u_int len;
973 		u_int64_t offset;
974 		TAILQ_ENTRY(outstanding_ack) tq;
975 	};
976 	TAILQ_HEAD(ackhead, outstanding_ack) acks;
977 	struct outstanding_ack *ack;
978 
979 	TAILQ_INIT(&acks);
980 
981 	if ((local_fd = open(local_path, O_RDONLY, 0)) == -1) {
982 		error("Couldn't open local file \"%s\" for reading: %s",
983 		    local_path, strerror(errno));
984 		return(-1);
985 	}
986 	if (fstat(local_fd, &sb) == -1) {
987 		error("Couldn't fstat local file \"%s\": %s",
988 		    local_path, strerror(errno));
989 		close(local_fd);
990 		return(-1);
991 	}
992 	stat_to_attrib(&sb, &a);
993 
994 	a.flags &= ~SSH2_FILEXFER_ATTR_SIZE;
995 	a.flags &= ~SSH2_FILEXFER_ATTR_UIDGID;
996 	a.perm &= 0777;
997 	if (!pflag)
998 		a.flags &= ~SSH2_FILEXFER_ATTR_ACMODTIME;
999 
1000 	buffer_init(&msg);
1001 
1002 	/* Send open request */
1003 	id = conn->msg_id++;
1004 	buffer_put_char(&msg, SSH2_FXP_OPEN);
1005 	buffer_put_int(&msg, id);
1006 	buffer_put_cstring(&msg, remote_path);
1007 	buffer_put_int(&msg, SSH2_FXF_WRITE|SSH2_FXF_CREAT|SSH2_FXF_TRUNC);
1008 	encode_attrib(&msg, &a);
1009 	send_msg(conn->fd_out, &msg);
1010 	debug3("Sent message SSH2_FXP_OPEN I:%u P:%s", id, remote_path);
1011 
1012 	buffer_clear(&msg);
1013 
1014 	handle = get_handle(conn->fd_in, id, &handle_len);
1015 	if (handle == NULL) {
1016 		close(local_fd);
1017 		buffer_free(&msg);
1018 		return(-1);
1019 	}
1020 
1021 	startid = ackid = id + 1;
1022 	data = xmalloc(conn->transfer_buflen);
1023 
1024 	/* Read from local and write to remote */
1025 	offset = 0;
1026 	for (;;) {
1027 		int len;
1028 
1029 		/*
1030 		 * Can't use atomicio here because it returns 0 on EOF, thus losing
1031 		 * the last block of the file
1032 		 */
1033 		do
1034 			len = read(local_fd, data, conn->transfer_buflen);
1035 		while ((len == -1) && (errno == EINTR || errno == EAGAIN));
1036 
1037 		if (len == -1)
1038 			fatal("Couldn't read from \"%s\": %s", local_path,
1039 			    strerror(errno));
1040 
1041 		if (len != 0) {
1042 			ack = xmalloc(sizeof(*ack));
1043 			ack->id = ++id;
1044 			ack->offset = offset;
1045 			ack->len = len;
1046 			TAILQ_INSERT_TAIL(&acks, ack, tq);
1047 
1048 			buffer_clear(&msg);
1049 			buffer_put_char(&msg, SSH2_FXP_WRITE);
1050 			buffer_put_int(&msg, ack->id);
1051 			buffer_put_string(&msg, handle, handle_len);
1052 			buffer_put_int64(&msg, offset);
1053 			buffer_put_string(&msg, data, len);
1054 			send_msg(conn->fd_out, &msg);
1055 			debug3("Sent message SSH2_FXP_WRITE I:%u O:%llu S:%u",
1056 			       id, (unsigned long long)offset, len);
1057 		} else if (TAILQ_FIRST(&acks) == NULL)
1058 			break;
1059 
1060 		if (ack == NULL)
1061 			fatal("Unexpected ACK %u", id);
1062 
1063 		if (id == startid || len == 0 ||
1064 		    id - ackid >= conn->num_requests) {
1065 			u_int r_id;
1066 
1067 			buffer_clear(&msg);
1068 			get_msg(conn->fd_in, &msg);
1069 			type = buffer_get_char(&msg);
1070 			r_id = buffer_get_int(&msg);
1071 
1072 			if (type != SSH2_FXP_STATUS)
1073 				fatal("Expected SSH2_FXP_STATUS(%d) packet, "
1074 				    "got %d", SSH2_FXP_STATUS, type);
1075 
1076 			status = buffer_get_int(&msg);
1077 			debug3("SSH2_FXP_STATUS %d", status);
1078 
1079 			/* Find the request in our queue */
1080 			for(ack = TAILQ_FIRST(&acks);
1081 			    ack != NULL && ack->id != r_id;
1082 			    ack = TAILQ_NEXT(ack, tq))
1083 				;
1084 			if (ack == NULL)
1085 				fatal("Can't find request for ID %u", r_id);
1086 			TAILQ_REMOVE(&acks, ack, tq);
1087 
1088 			if (status != SSH2_FX_OK) {
1089 				error("Couldn't write to remote file \"%s\": %s",
1090 				      remote_path, fx2txt(status));
1091 				do_close(conn, handle, handle_len);
1092 				close(local_fd);
1093 				goto done;
1094 			}
1095 			debug3("In write loop, ack for %u %u bytes at %llu",
1096 			   ack->id, ack->len, (unsigned long long)ack->offset);
1097 			++ackid;
1098 			free(ack);
1099 		}
1100 		offset += len;
1101 	}
1102 	xfree(data);
1103 
1104 	if (close(local_fd) == -1) {
1105 		error("Couldn't close local file \"%s\": %s", local_path,
1106 		    strerror(errno));
1107 		do_close(conn, handle, handle_len);
1108 		status = -1;
1109 		goto done;
1110 	}
1111 
1112 	/* Override umask and utimes if asked */
1113 	if (pflag)
1114 		do_fsetstat(conn, handle, handle_len, &a);
1115 
1116 	status = do_close(conn, handle, handle_len);
1117 
1118 done:
1119 	xfree(handle);
1120 	buffer_free(&msg);
1121 	return(status);
1122 }
1123