xref: /netbsd-src/crypto/external/bsd/openssh/dist/sftp-server.c (revision 6a493d6bc668897c91594964a732d38505b70cbb)
1 /*	$NetBSD: sftp-server.c,v 1.9 2013/11/08 19:18:25 christos Exp $	*/
2 /* $OpenBSD: sftp-server.c,v 1.97 2013/05/17 00:13:14 djm Exp $ */
3 /*
4  * Copyright (c) 2000-2004 Markus Friedl.  All rights reserved.
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 #include "includes.h"
20 __RCSID("$NetBSD: sftp-server.c,v 1.9 2013/11/08 19:18:25 christos Exp $");
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <sys/time.h>
24 #include <sys/param.h>
25 #include <sys/mount.h>
26 #include <sys/statvfs.h>
27 
28 #include <dirent.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <string.h>
34 #include <pwd.h>
35 #include <time.h>
36 #include <unistd.h>
37 #include <stdarg.h>
38 
39 #include "xmalloc.h"
40 #include "buffer.h"
41 #include "log.h"
42 #include "misc.h"
43 #include "uidswap.h"
44 
45 #include "sftp.h"
46 #include "sftp-common.h"
47 
48 /* helper */
49 #define get_int64()			buffer_get_int64(&iqueue);
50 #define get_int()			buffer_get_int(&iqueue);
51 #define get_string(lenp)		buffer_get_string(&iqueue, lenp);
52 
53 /* Our verbosity */
54 LogLevel log_level = SYSLOG_LEVEL_ERROR;
55 
56 /* Our client */
57 struct passwd *pw = NULL;
58 char *client_addr = NULL;
59 
60 /* input and output queue */
61 Buffer iqueue;
62 Buffer oqueue;
63 
64 /* Version of client */
65 u_int version;
66 
67 /* Disable writes */
68 int readonly;
69 
70 /* portable attributes, etc. */
71 
72 typedef struct Stat Stat;
73 
74 struct Stat {
75 	char *name;
76 	char *long_name;
77 	Attrib attrib;
78 };
79 
80 static int
81 errno_to_portable(int unixerrno)
82 {
83 	int ret = 0;
84 
85 	switch (unixerrno) {
86 	case 0:
87 		ret = SSH2_FX_OK;
88 		break;
89 	case ENOENT:
90 	case ENOTDIR:
91 	case EBADF:
92 	case ELOOP:
93 		ret = SSH2_FX_NO_SUCH_FILE;
94 		break;
95 	case EPERM:
96 	case EACCES:
97 	case EFAULT:
98 		ret = SSH2_FX_PERMISSION_DENIED;
99 		break;
100 	case ENAMETOOLONG:
101 	case EINVAL:
102 		ret = SSH2_FX_BAD_MESSAGE;
103 		break;
104 	case ENOSYS:
105 		ret = SSH2_FX_OP_UNSUPPORTED;
106 		break;
107 	default:
108 		ret = SSH2_FX_FAILURE;
109 		break;
110 	}
111 	return ret;
112 }
113 
114 static int
115 flags_from_portable(int pflags)
116 {
117 	int flags = 0;
118 
119 	if ((pflags & SSH2_FXF_READ) &&
120 	    (pflags & SSH2_FXF_WRITE)) {
121 		flags = O_RDWR;
122 	} else if (pflags & SSH2_FXF_READ) {
123 		flags = O_RDONLY;
124 	} else if (pflags & SSH2_FXF_WRITE) {
125 		flags = O_WRONLY;
126 	}
127 	if (pflags & SSH2_FXF_CREAT)
128 		flags |= O_CREAT;
129 	if (pflags & SSH2_FXF_TRUNC)
130 		flags |= O_TRUNC;
131 	if (pflags & SSH2_FXF_EXCL)
132 		flags |= O_EXCL;
133 	return flags;
134 }
135 
136 static const char *
137 string_from_portable(int pflags)
138 {
139 	static char ret[128];
140 
141 	*ret = '\0';
142 
143 #define PAPPEND(str)	{				\
144 		if (*ret != '\0')			\
145 			strlcat(ret, ",", sizeof(ret));	\
146 		strlcat(ret, str, sizeof(ret));		\
147 	}
148 
149 	if (pflags & SSH2_FXF_READ)
150 		PAPPEND("READ")
151 	if (pflags & SSH2_FXF_WRITE)
152 		PAPPEND("WRITE")
153 	if (pflags & SSH2_FXF_CREAT)
154 		PAPPEND("CREATE")
155 	if (pflags & SSH2_FXF_TRUNC)
156 		PAPPEND("TRUNCATE")
157 	if (pflags & SSH2_FXF_EXCL)
158 		PAPPEND("EXCL")
159 
160 	return ret;
161 }
162 
163 static Attrib *
164 get_attrib(void)
165 {
166 	return decode_attrib(&iqueue);
167 }
168 
169 /* handle handles */
170 
171 typedef struct Handle Handle;
172 struct Handle {
173 	int use;
174 	DIR *dirp;
175 	int fd;
176 	char *name;
177 	u_int64_t bytes_read, bytes_write;
178 	int next_unused;
179 };
180 
181 enum {
182 	HANDLE_UNUSED,
183 	HANDLE_DIR,
184 	HANDLE_FILE
185 };
186 
187 Handle *handles = NULL;
188 u_int num_handles = 0;
189 int first_unused_handle = -1;
190 
191 static void handle_unused(int i)
192 {
193 	handles[i].use = HANDLE_UNUSED;
194 	handles[i].next_unused = first_unused_handle;
195 	first_unused_handle = i;
196 }
197 
198 static int
199 handle_new(int use, const char *name, int fd, DIR *dirp)
200 {
201 	int i;
202 
203 	if (first_unused_handle == -1) {
204 		if (num_handles + 1 <= num_handles)
205 			return -1;
206 		num_handles++;
207 		handles = xrealloc(handles, num_handles, sizeof(Handle));
208 		handle_unused(num_handles - 1);
209 	}
210 
211 	i = first_unused_handle;
212 	first_unused_handle = handles[i].next_unused;
213 
214 	handles[i].use = use;
215 	handles[i].dirp = dirp;
216 	handles[i].fd = fd;
217 	handles[i].name = xstrdup(name);
218 	handles[i].bytes_read = handles[i].bytes_write = 0;
219 
220 	return i;
221 }
222 
223 static int
224 handle_is_ok(int i, int type)
225 {
226 	return i >= 0 && (u_int)i < num_handles && handles[i].use == type;
227 }
228 
229 static int
230 handle_to_string(int handle, char **stringp, int *hlenp)
231 {
232 	if (stringp == NULL || hlenp == NULL)
233 		return -1;
234 	*stringp = xmalloc(sizeof(int32_t));
235 	put_u32(*stringp, handle);
236 	*hlenp = sizeof(int32_t);
237 	return 0;
238 }
239 
240 static int
241 handle_from_string(const char *handle, u_int hlen)
242 {
243 	int val;
244 
245 	if (hlen != sizeof(int32_t))
246 		return -1;
247 	val = get_u32(handle);
248 	if (handle_is_ok(val, HANDLE_FILE) ||
249 	    handle_is_ok(val, HANDLE_DIR))
250 		return val;
251 	return -1;
252 }
253 
254 static char *
255 handle_to_name(int handle)
256 {
257 	if (handle_is_ok(handle, HANDLE_DIR)||
258 	    handle_is_ok(handle, HANDLE_FILE))
259 		return handles[handle].name;
260 	return NULL;
261 }
262 
263 static DIR *
264 handle_to_dir(int handle)
265 {
266 	if (handle_is_ok(handle, HANDLE_DIR))
267 		return handles[handle].dirp;
268 	return NULL;
269 }
270 
271 static int
272 handle_to_fd(int handle)
273 {
274 	if (handle_is_ok(handle, HANDLE_FILE))
275 		return handles[handle].fd;
276 	return -1;
277 }
278 
279 static void
280 handle_update_read(int handle, ssize_t bytes)
281 {
282 	if (handle_is_ok(handle, HANDLE_FILE) && bytes > 0)
283 		handles[handle].bytes_read += bytes;
284 }
285 
286 static void
287 handle_update_write(int handle, ssize_t bytes)
288 {
289 	if (handle_is_ok(handle, HANDLE_FILE) && bytes > 0)
290 		handles[handle].bytes_write += bytes;
291 }
292 
293 static u_int64_t
294 handle_bytes_read(int handle)
295 {
296 	if (handle_is_ok(handle, HANDLE_FILE))
297 		return (handles[handle].bytes_read);
298 	return 0;
299 }
300 
301 static u_int64_t
302 handle_bytes_write(int handle)
303 {
304 	if (handle_is_ok(handle, HANDLE_FILE))
305 		return (handles[handle].bytes_write);
306 	return 0;
307 }
308 
309 static int
310 handle_close(int handle)
311 {
312 	int ret = -1;
313 
314 	if (handle_is_ok(handle, HANDLE_FILE)) {
315 		ret = close(handles[handle].fd);
316 		free(handles[handle].name);
317 		handle_unused(handle);
318 	} else if (handle_is_ok(handle, HANDLE_DIR)) {
319 		ret = closedir(handles[handle].dirp);
320 		free(handles[handle].name);
321 		handle_unused(handle);
322 	} else {
323 		errno = ENOENT;
324 	}
325 	return ret;
326 }
327 
328 static void
329 handle_log_close(int handle, const char *emsg)
330 {
331 	if (handle_is_ok(handle, HANDLE_FILE)) {
332 		logit("%s%sclose \"%s\" bytes read %llu written %llu",
333 		    emsg == NULL ? "" : emsg, emsg == NULL ? "" : " ",
334 		    handle_to_name(handle),
335 		    (unsigned long long)handle_bytes_read(handle),
336 		    (unsigned long long)handle_bytes_write(handle));
337 	} else {
338 		logit("%s%sclosedir \"%s\"",
339 		    emsg == NULL ? "" : emsg, emsg == NULL ? "" : " ",
340 		    handle_to_name(handle));
341 	}
342 }
343 
344 static void
345 handle_log_exit(void)
346 {
347 	u_int i;
348 
349 	for (i = 0; i < num_handles; i++)
350 		if (handles[i].use != HANDLE_UNUSED)
351 			handle_log_close(i, "forced");
352 }
353 
354 static int
355 get_handle(void)
356 {
357 	char *handle;
358 	int val = -1;
359 	u_int hlen;
360 
361 	handle = get_string(&hlen);
362 	if (hlen < 256)
363 		val = handle_from_string(handle, hlen);
364 	free(handle);
365 	return val;
366 }
367 
368 /* send replies */
369 
370 static void
371 send_msg(Buffer *m)
372 {
373 	int mlen = buffer_len(m);
374 
375 	buffer_put_int(&oqueue, mlen);
376 	buffer_append(&oqueue, buffer_ptr(m), mlen);
377 	buffer_consume(m, mlen);
378 }
379 
380 static const char *
381 status_to_message(u_int32_t status)
382 {
383 	const char *status_messages[] = {
384 		"Success",			/* SSH_FX_OK */
385 		"End of file",			/* SSH_FX_EOF */
386 		"No such file",			/* SSH_FX_NO_SUCH_FILE */
387 		"Permission denied",		/* SSH_FX_PERMISSION_DENIED */
388 		"Failure",			/* SSH_FX_FAILURE */
389 		"Bad message",			/* SSH_FX_BAD_MESSAGE */
390 		"No connection",		/* SSH_FX_NO_CONNECTION */
391 		"Connection lost",		/* SSH_FX_CONNECTION_LOST */
392 		"Operation unsupported",	/* SSH_FX_OP_UNSUPPORTED */
393 		"Unknown error"			/* Others */
394 	};
395 	return (status_messages[MIN(status,SSH2_FX_MAX)]);
396 }
397 
398 static void
399 send_status(u_int32_t id, u_int32_t status)
400 {
401 	Buffer msg;
402 
403 	debug3("request %u: sent status %u", id, status);
404 	if (log_level > SYSLOG_LEVEL_VERBOSE ||
405 	    (status != SSH2_FX_OK && status != SSH2_FX_EOF))
406 		logit("sent status %s", status_to_message(status));
407 	buffer_init(&msg);
408 	buffer_put_char(&msg, SSH2_FXP_STATUS);
409 	buffer_put_int(&msg, id);
410 	buffer_put_int(&msg, status);
411 	if (version >= 3) {
412 		buffer_put_cstring(&msg, status_to_message(status));
413 		buffer_put_cstring(&msg, "");
414 	}
415 	send_msg(&msg);
416 	buffer_free(&msg);
417 }
418 static void
419 send_data_or_handle(char type, u_int32_t id, const char *data, int dlen)
420 {
421 	Buffer msg;
422 
423 	buffer_init(&msg);
424 	buffer_put_char(&msg, type);
425 	buffer_put_int(&msg, id);
426 	buffer_put_string(&msg, data, dlen);
427 	send_msg(&msg);
428 	buffer_free(&msg);
429 }
430 
431 static void
432 send_data(u_int32_t id, const char *data, int dlen)
433 {
434 	debug("request %u: sent data len %d", id, dlen);
435 	send_data_or_handle(SSH2_FXP_DATA, id, data, dlen);
436 }
437 
438 static void
439 send_handle(u_int32_t id, int handle)
440 {
441 	char *string;
442 	int hlen;
443 
444 	handle_to_string(handle, &string, &hlen);
445 	debug("request %u: sent handle handle %d", id, handle);
446 	send_data_or_handle(SSH2_FXP_HANDLE, id, string, hlen);
447 	free(string);
448 }
449 
450 static void
451 send_names(u_int32_t id, int count, const Stat *stats)
452 {
453 	Buffer msg;
454 	int i;
455 
456 	buffer_init(&msg);
457 	buffer_put_char(&msg, SSH2_FXP_NAME);
458 	buffer_put_int(&msg, id);
459 	buffer_put_int(&msg, count);
460 	debug("request %u: sent names count %d", id, count);
461 	for (i = 0; i < count; i++) {
462 		buffer_put_cstring(&msg, stats[i].name);
463 		buffer_put_cstring(&msg, stats[i].long_name);
464 		encode_attrib(&msg, &stats[i].attrib);
465 	}
466 	send_msg(&msg);
467 	buffer_free(&msg);
468 }
469 
470 static void
471 send_attrib(u_int32_t id, const Attrib *a)
472 {
473 	Buffer msg;
474 
475 	debug("request %u: sent attrib have 0x%x", id, a->flags);
476 	buffer_init(&msg);
477 	buffer_put_char(&msg, SSH2_FXP_ATTRS);
478 	buffer_put_int(&msg, id);
479 	encode_attrib(&msg, a);
480 	send_msg(&msg);
481 	buffer_free(&msg);
482 }
483 
484 static void
485 send_statvfs(u_int32_t id, struct statvfs *st)
486 {
487 	Buffer msg;
488 	u_int64_t flag;
489 
490 	flag = (st->f_flag & ST_RDONLY) ? SSH2_FXE_STATVFS_ST_RDONLY : 0;
491 	flag |= (st->f_flag & ST_NOSUID) ? SSH2_FXE_STATVFS_ST_NOSUID : 0;
492 
493 	buffer_init(&msg);
494 	buffer_put_char(&msg, SSH2_FXP_EXTENDED_REPLY);
495 	buffer_put_int(&msg, id);
496 	buffer_put_int64(&msg, st->f_bsize);
497 	buffer_put_int64(&msg, st->f_frsize);
498 	buffer_put_int64(&msg, st->f_blocks);
499 	buffer_put_int64(&msg, st->f_bfree);
500 	buffer_put_int64(&msg, st->f_bavail);
501 	buffer_put_int64(&msg, st->f_files);
502 	buffer_put_int64(&msg, st->f_ffree);
503 	buffer_put_int64(&msg, st->f_favail);
504 	buffer_put_int64(&msg, st->f_fsid);
505 	buffer_put_int64(&msg, flag);
506 	buffer_put_int64(&msg, st->f_namemax);
507 	send_msg(&msg);
508 	buffer_free(&msg);
509 }
510 
511 /* parse incoming */
512 
513 static void
514 process_init(void)
515 {
516 	Buffer msg;
517 
518 	version = get_int();
519 	verbose("received client version %u", version);
520 	buffer_init(&msg);
521 	buffer_put_char(&msg, SSH2_FXP_VERSION);
522 	buffer_put_int(&msg, SSH2_FILEXFER_VERSION);
523 	/* POSIX rename extension */
524 	buffer_put_cstring(&msg, "posix-rename@openssh.com");
525 	buffer_put_cstring(&msg, "1"); /* version */
526 	/* statvfs extension */
527 	buffer_put_cstring(&msg, "statvfs@openssh.com");
528 	buffer_put_cstring(&msg, "2"); /* version */
529 	/* fstatvfs extension */
530 	buffer_put_cstring(&msg, "fstatvfs@openssh.com");
531 	buffer_put_cstring(&msg, "2"); /* version */
532 	/* hardlink extension */
533 	buffer_put_cstring(&msg, "hardlink@openssh.com");
534 	buffer_put_cstring(&msg, "1"); /* version */
535 	send_msg(&msg);
536 	buffer_free(&msg);
537 }
538 
539 static void
540 process_open(void)
541 {
542 	u_int32_t id, pflags;
543 	Attrib *a;
544 	char *name;
545 	int handle, fd, flags, mode, status = SSH2_FX_FAILURE;
546 
547 	id = get_int();
548 	name = get_string(NULL);
549 	pflags = get_int();		/* portable flags */
550 	debug3("request %u: open flags %d", id, pflags);
551 	a = get_attrib();
552 	flags = flags_from_portable(pflags);
553 	mode = (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ? a->perm : 0666;
554 	logit("open \"%s\" flags %s mode 0%o",
555 	    name, string_from_portable(pflags), mode);
556 	if (readonly &&
557 	    ((flags & O_ACCMODE) == O_WRONLY || (flags & O_ACCMODE) == O_RDWR))
558 		status = SSH2_FX_PERMISSION_DENIED;
559 	else {
560 		fd = open(name, flags, mode);
561 		if (fd < 0) {
562 			status = errno_to_portable(errno);
563 		} else {
564 			handle = handle_new(HANDLE_FILE, name, fd, NULL);
565 			if (handle < 0) {
566 				close(fd);
567 			} else {
568 				send_handle(id, handle);
569 				status = SSH2_FX_OK;
570 			}
571 		}
572 	}
573 	if (status != SSH2_FX_OK)
574 		send_status(id, status);
575 	free(name);
576 }
577 
578 static void
579 process_close(void)
580 {
581 	u_int32_t id;
582 	int handle, ret, status = SSH2_FX_FAILURE;
583 
584 	id = get_int();
585 	handle = get_handle();
586 	debug3("request %u: close handle %u", id, handle);
587 	handle_log_close(handle, NULL);
588 	ret = handle_close(handle);
589 	status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
590 	send_status(id, status);
591 }
592 
593 static void
594 process_read(void)
595 {
596 	char buf[64*1024];
597 	u_int32_t id, len;
598 	int handle, fd, ret, status = SSH2_FX_FAILURE;
599 	u_int64_t off;
600 
601 	id = get_int();
602 	handle = get_handle();
603 	off = get_int64();
604 	len = get_int();
605 
606 	debug("request %u: read \"%s\" (handle %d) off %llu len %d",
607 	    id, handle_to_name(handle), handle, (unsigned long long)off, len);
608 	if (len > sizeof buf) {
609 		len = sizeof buf;
610 		debug2("read change len %d", len);
611 	}
612 	fd = handle_to_fd(handle);
613 	if (fd >= 0) {
614 		if (lseek(fd, off, SEEK_SET) < 0) {
615 			error("process_read: seek failed");
616 			status = errno_to_portable(errno);
617 		} else {
618 			ret = read(fd, buf, len);
619 			if (ret < 0) {
620 				status = errno_to_portable(errno);
621 			} else if (ret == 0) {
622 				status = SSH2_FX_EOF;
623 			} else {
624 				send_data(id, buf, ret);
625 				status = SSH2_FX_OK;
626 				handle_update_read(handle, ret);
627 			}
628 		}
629 	}
630 	if (status != SSH2_FX_OK)
631 		send_status(id, status);
632 }
633 
634 static void
635 process_write(void)
636 {
637 	u_int32_t id;
638 	u_int64_t off;
639 	u_int len;
640 	int handle, fd, ret, status;
641 	char *data;
642 
643 	id = get_int();
644 	handle = get_handle();
645 	off = get_int64();
646 	data = get_string(&len);
647 
648 	debug("request %u: write \"%s\" (handle %d) off %llu len %d",
649 	    id, handle_to_name(handle), handle, (unsigned long long)off, len);
650 	fd = handle_to_fd(handle);
651 
652 	if (fd < 0)
653 		status = SSH2_FX_FAILURE;
654 	else if (readonly)
655 		status = SSH2_FX_PERMISSION_DENIED;
656 	else {
657 		if (lseek(fd, off, SEEK_SET) < 0) {
658 			status = errno_to_portable(errno);
659 			error("process_write: seek failed");
660 		} else {
661 /* XXX ATOMICIO ? */
662 			ret = write(fd, data, len);
663 			if (ret < 0) {
664 				error("process_write: write failed");
665 				status = errno_to_portable(errno);
666 			} else if ((size_t)ret == len) {
667 				status = SSH2_FX_OK;
668 				handle_update_write(handle, ret);
669 			} else {
670 				debug2("nothing at all written");
671 				status = SSH2_FX_FAILURE;
672 			}
673 		}
674 	}
675 	send_status(id, status);
676 	free(data);
677 }
678 
679 static void
680 process_do_stat(int do_lstat)
681 {
682 	Attrib a;
683 	struct stat st;
684 	u_int32_t id;
685 	char *name;
686 	int ret, status = SSH2_FX_FAILURE;
687 
688 	id = get_int();
689 	name = get_string(NULL);
690 	debug3("request %u: %sstat", id, do_lstat ? "l" : "");
691 	verbose("%sstat name \"%s\"", do_lstat ? "l" : "", name);
692 	ret = do_lstat ? lstat(name, &st) : stat(name, &st);
693 	if (ret < 0) {
694 		status = errno_to_portable(errno);
695 	} else {
696 		stat_to_attrib(&st, &a);
697 		send_attrib(id, &a);
698 		status = SSH2_FX_OK;
699 	}
700 	if (status != SSH2_FX_OK)
701 		send_status(id, status);
702 	free(name);
703 }
704 
705 static void
706 process_stat(void)
707 {
708 	process_do_stat(0);
709 }
710 
711 static void
712 process_lstat(void)
713 {
714 	process_do_stat(1);
715 }
716 
717 static void
718 process_fstat(void)
719 {
720 	Attrib a;
721 	struct stat st;
722 	u_int32_t id;
723 	int fd, ret, handle, status = SSH2_FX_FAILURE;
724 
725 	id = get_int();
726 	handle = get_handle();
727 	debug("request %u: fstat \"%s\" (handle %u)",
728 	    id, handle_to_name(handle), handle);
729 	fd = handle_to_fd(handle);
730 	if (fd >= 0) {
731 		ret = fstat(fd, &st);
732 		if (ret < 0) {
733 			status = errno_to_portable(errno);
734 		} else {
735 			stat_to_attrib(&st, &a);
736 			send_attrib(id, &a);
737 			status = SSH2_FX_OK;
738 		}
739 	}
740 	if (status != SSH2_FX_OK)
741 		send_status(id, status);
742 }
743 
744 static struct timeval *
745 attrib_to_tv(const Attrib *a)
746 {
747 	static struct timeval tv[2];
748 
749 	tv[0].tv_sec = a->atime;
750 	tv[0].tv_usec = 0;
751 	tv[1].tv_sec = a->mtime;
752 	tv[1].tv_usec = 0;
753 	return tv;
754 }
755 
756 static void
757 process_setstat(void)
758 {
759 	Attrib *a;
760 	u_int32_t id;
761 	char *name;
762 	int status = SSH2_FX_OK, ret;
763 
764 	id = get_int();
765 	name = get_string(NULL);
766 	a = get_attrib();
767 	debug("request %u: setstat name \"%s\"", id, name);
768 	if (readonly) {
769 		status = SSH2_FX_PERMISSION_DENIED;
770 		a->flags = 0;
771 	}
772 	if (a->flags & SSH2_FILEXFER_ATTR_SIZE) {
773 		logit("set \"%s\" size %llu",
774 		    name, (unsigned long long)a->size);
775 		ret = truncate(name, a->size);
776 		if (ret == -1)
777 			status = errno_to_portable(errno);
778 	}
779 	if (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) {
780 		logit("set \"%s\" mode %04o", name, a->perm);
781 		ret = chmod(name, a->perm & 07777);
782 		if (ret == -1)
783 			status = errno_to_portable(errno);
784 	}
785 	if (a->flags & SSH2_FILEXFER_ATTR_ACMODTIME) {
786 		char buf[64];
787 		time_t t = a->mtime;
788 
789 		strftime(buf, sizeof(buf), "%Y%m%d-%H:%M:%S",
790 		    localtime(&t));
791 		logit("set \"%s\" modtime %s", name, buf);
792 		ret = utimes(name, attrib_to_tv(a));
793 		if (ret == -1)
794 			status = errno_to_portable(errno);
795 	}
796 	if (a->flags & SSH2_FILEXFER_ATTR_UIDGID) {
797 		logit("set \"%s\" owner %lu group %lu", name,
798 		    (u_long)a->uid, (u_long)a->gid);
799 		ret = chown(name, a->uid, a->gid);
800 		if (ret == -1)
801 			status = errno_to_portable(errno);
802 	}
803 	send_status(id, status);
804 	free(name);
805 }
806 
807 static void
808 process_fsetstat(void)
809 {
810 	Attrib *a;
811 	u_int32_t id;
812 	int handle, fd, ret;
813 	int status = SSH2_FX_OK;
814 
815 	id = get_int();
816 	handle = get_handle();
817 	a = get_attrib();
818 	debug("request %u: fsetstat handle %d", id, handle);
819 	fd = handle_to_fd(handle);
820 	if (fd < 0)
821 		status = SSH2_FX_FAILURE;
822 	else if (readonly)
823 		status = SSH2_FX_PERMISSION_DENIED;
824 	else {
825 		char *name = handle_to_name(handle);
826 
827 		if (a->flags & SSH2_FILEXFER_ATTR_SIZE) {
828 			logit("set \"%s\" size %llu",
829 			    name, (unsigned long long)a->size);
830 			ret = ftruncate(fd, a->size);
831 			if (ret == -1)
832 				status = errno_to_portable(errno);
833 		}
834 		if (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) {
835 			logit("set \"%s\" mode %04o", name, a->perm);
836 			ret = fchmod(fd, a->perm & 07777);
837 			if (ret == -1)
838 				status = errno_to_portable(errno);
839 		}
840 		if (a->flags & SSH2_FILEXFER_ATTR_ACMODTIME) {
841 			char buf[64];
842 			time_t t = a->mtime;
843 
844 			strftime(buf, sizeof(buf), "%Y%m%d-%H:%M:%S",
845 			    localtime(&t));
846 			logit("set \"%s\" modtime %s", name, buf);
847 			ret = futimes(fd, attrib_to_tv(a));
848 			if (ret == -1)
849 				status = errno_to_portable(errno);
850 		}
851 		if (a->flags & SSH2_FILEXFER_ATTR_UIDGID) {
852 			logit("set \"%s\" owner %lu group %lu", name,
853 			    (u_long)a->uid, (u_long)a->gid);
854 			ret = fchown(fd, a->uid, a->gid);
855 			if (ret == -1)
856 				status = errno_to_portable(errno);
857 		}
858 	}
859 	send_status(id, status);
860 }
861 
862 static void
863 process_opendir(void)
864 {
865 	DIR *dirp = NULL;
866 	char *path;
867 	int handle, status = SSH2_FX_FAILURE;
868 	u_int32_t id;
869 
870 	id = get_int();
871 	path = get_string(NULL);
872 	debug3("request %u: opendir", id);
873 	logit("opendir \"%s\"", path);
874 	dirp = opendir(path);
875 	if (dirp == NULL) {
876 		status = errno_to_portable(errno);
877 	} else {
878 		handle = handle_new(HANDLE_DIR, path, 0, dirp);
879 		if (handle < 0) {
880 			closedir(dirp);
881 		} else {
882 			send_handle(id, handle);
883 			status = SSH2_FX_OK;
884 		}
885 
886 	}
887 	if (status != SSH2_FX_OK)
888 		send_status(id, status);
889 	free(path);
890 }
891 
892 static void
893 process_readdir(void)
894 {
895 	DIR *dirp;
896 	struct dirent *dp;
897 	char *path;
898 	int handle;
899 	u_int32_t id;
900 
901 	id = get_int();
902 	handle = get_handle();
903 	debug("request %u: readdir \"%s\" (handle %d)", id,
904 	    handle_to_name(handle), handle);
905 	dirp = handle_to_dir(handle);
906 	path = handle_to_name(handle);
907 	if (dirp == NULL || path == NULL) {
908 		send_status(id, SSH2_FX_FAILURE);
909 	} else {
910 		struct stat st;
911 		char pathname[MAXPATHLEN];
912 		Stat *stats;
913 		int nstats = 10, count = 0, i;
914 
915 		stats = xcalloc(nstats, sizeof(Stat));
916 		while ((dp = readdir(dirp)) != NULL) {
917 			if (count >= nstats) {
918 				nstats *= 2;
919 				stats = xrealloc(stats, nstats, sizeof(Stat));
920 			}
921 /* XXX OVERFLOW ? */
922 			snprintf(pathname, sizeof pathname, "%s%s%s", path,
923 			    strcmp(path, "/") ? "/" : "", dp->d_name);
924 			if (lstat(pathname, &st) < 0)
925 				continue;
926 			stat_to_attrib(&st, &(stats[count].attrib));
927 			stats[count].name = xstrdup(dp->d_name);
928 			stats[count].long_name = ls_file(dp->d_name, &st, 0, 0);
929 			count++;
930 			/* send up to 100 entries in one message */
931 			/* XXX check packet size instead */
932 			if (count == 100)
933 				break;
934 		}
935 		if (count > 0) {
936 			send_names(id, count, stats);
937 			for (i = 0; i < count; i++) {
938 				free(stats[i].name);
939 				free(stats[i].long_name);
940 			}
941 		} else {
942 			send_status(id, SSH2_FX_EOF);
943 		}
944 		free(stats);
945 	}
946 }
947 
948 static void
949 process_remove(void)
950 {
951 	char *name;
952 	u_int32_t id;
953 	int status = SSH2_FX_FAILURE;
954 	int ret;
955 
956 	id = get_int();
957 	name = get_string(NULL);
958 	debug3("request %u: remove", id);
959 	logit("remove name \"%s\"", name);
960 	if (readonly)
961 		status = SSH2_FX_PERMISSION_DENIED;
962 	else {
963 		ret = unlink(name);
964 		status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
965 	}
966 	send_status(id, status);
967 	free(name);
968 }
969 
970 static void
971 process_mkdir(void)
972 {
973 	Attrib *a;
974 	u_int32_t id;
975 	char *name;
976 	int ret, mode, status = SSH2_FX_FAILURE;
977 
978 	id = get_int();
979 	name = get_string(NULL);
980 	a = get_attrib();
981 	mode = (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ?
982 	    a->perm & 07777 : 0777;
983 	debug3("request %u: mkdir", id);
984 	logit("mkdir name \"%s\" mode 0%o", name, mode);
985 	if (readonly)
986 		status = SSH2_FX_PERMISSION_DENIED;
987 	else {
988 		ret = mkdir(name, mode);
989 		status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
990 	}
991 	send_status(id, status);
992 	free(name);
993 }
994 
995 static void
996 process_rmdir(void)
997 {
998 	u_int32_t id;
999 	char *name;
1000 	int ret, status;
1001 
1002 	id = get_int();
1003 	name = get_string(NULL);
1004 	debug3("request %u: rmdir", id);
1005 	logit("rmdir name \"%s\"", name);
1006 	if (readonly)
1007 		status = SSH2_FX_PERMISSION_DENIED;
1008 	else {
1009 		ret = rmdir(name);
1010 		status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1011 	}
1012 	send_status(id, status);
1013 	free(name);
1014 }
1015 
1016 static void
1017 process_realpath(void)
1018 {
1019 	char resolvedname[MAXPATHLEN];
1020 	u_int32_t id;
1021 	char *path;
1022 
1023 	id = get_int();
1024 	path = get_string(NULL);
1025 	if (path[0] == '\0') {
1026 		free(path);
1027 		path = xstrdup(".");
1028 	}
1029 	debug3("request %u: realpath", id);
1030 	verbose("realpath \"%s\"", path);
1031 	if (realpath(path, resolvedname) == NULL) {
1032 		send_status(id, errno_to_portable(errno));
1033 	} else {
1034 		Stat s;
1035 		attrib_clear(&s.attrib);
1036 		s.name = s.long_name = resolvedname;
1037 		send_names(id, 1, &s);
1038 	}
1039 	free(path);
1040 }
1041 
1042 static void
1043 process_rename(void)
1044 {
1045 	u_int32_t id;
1046 	char *oldpath, *newpath;
1047 	int status;
1048 	struct stat sb;
1049 
1050 	id = get_int();
1051 	oldpath = get_string(NULL);
1052 	newpath = get_string(NULL);
1053 	debug3("request %u: rename", id);
1054 	logit("rename old \"%s\" new \"%s\"", oldpath, newpath);
1055 	status = SSH2_FX_FAILURE;
1056 	if (readonly)
1057 		status = SSH2_FX_PERMISSION_DENIED;
1058 	else if (lstat(oldpath, &sb) == -1)
1059 		status = errno_to_portable(errno);
1060 	else if (S_ISREG(sb.st_mode)) {
1061 		/* Race-free rename of regular files */
1062 		if (link(oldpath, newpath) == -1) {
1063 			if (errno == EOPNOTSUPP) {
1064 				struct stat st;
1065 
1066 				/*
1067 				 * fs doesn't support links, so fall back to
1068 				 * stat+rename.  This is racy.
1069 				 */
1070 				if (stat(newpath, &st) == -1) {
1071 					if (rename(oldpath, newpath) == -1)
1072 						status =
1073 						    errno_to_portable(errno);
1074 					else
1075 						status = SSH2_FX_OK;
1076 				}
1077 			} else {
1078 				status = errno_to_portable(errno);
1079 			}
1080 		} else if (unlink(oldpath) == -1) {
1081 			status = errno_to_portable(errno);
1082 			/* clean spare link */
1083 			unlink(newpath);
1084 		} else
1085 			status = SSH2_FX_OK;
1086 	} else if (stat(newpath, &sb) == -1) {
1087 		if (rename(oldpath, newpath) == -1)
1088 			status = errno_to_portable(errno);
1089 		else
1090 			status = SSH2_FX_OK;
1091 	}
1092 	send_status(id, status);
1093 	free(oldpath);
1094 	free(newpath);
1095 }
1096 
1097 static void
1098 process_readlink(void)
1099 {
1100 	u_int32_t id;
1101 	int len;
1102 	char buf[MAXPATHLEN];
1103 	char *path;
1104 
1105 	id = get_int();
1106 	path = get_string(NULL);
1107 	debug3("request %u: readlink", id);
1108 	verbose("readlink \"%s\"", path);
1109 	if ((len = readlink(path, buf, sizeof(buf) - 1)) == -1)
1110 		send_status(id, errno_to_portable(errno));
1111 	else {
1112 		Stat s;
1113 
1114 		buf[len] = '\0';
1115 		attrib_clear(&s.attrib);
1116 		s.name = s.long_name = buf;
1117 		send_names(id, 1, &s);
1118 	}
1119 	free(path);
1120 }
1121 
1122 static void
1123 process_symlink(void)
1124 {
1125 	u_int32_t id;
1126 	char *oldpath, *newpath;
1127 	int ret, status;
1128 
1129 	id = get_int();
1130 	oldpath = get_string(NULL);
1131 	newpath = get_string(NULL);
1132 	debug3("request %u: symlink", id);
1133 	logit("symlink old \"%s\" new \"%s\"", oldpath, newpath);
1134 	/* this will fail if 'newpath' exists */
1135 	if (readonly)
1136 		status = SSH2_FX_PERMISSION_DENIED;
1137 	else {
1138 		ret = symlink(oldpath, newpath);
1139 		status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1140 	}
1141 	send_status(id, status);
1142 	free(oldpath);
1143 	free(newpath);
1144 }
1145 
1146 static void
1147 process_extended_posix_rename(u_int32_t id)
1148 {
1149 	char *oldpath, *newpath;
1150 	int ret, status;
1151 
1152 	oldpath = get_string(NULL);
1153 	newpath = get_string(NULL);
1154 	debug3("request %u: posix-rename", id);
1155 	logit("posix-rename old \"%s\" new \"%s\"", oldpath, newpath);
1156 	if (readonly)
1157 		status = SSH2_FX_PERMISSION_DENIED;
1158 	else {
1159 		ret = rename(oldpath, newpath);
1160 		status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1161 	}
1162 	send_status(id, status);
1163 	free(oldpath);
1164 	free(newpath);
1165 }
1166 
1167 static void
1168 process_extended_statvfs(u_int32_t id)
1169 {
1170 	char *path;
1171 	struct statvfs st;
1172 
1173 	path = get_string(NULL);
1174 	debug3("request %u: statfs", id);
1175 	logit("statfs \"%s\"", path);
1176 
1177 	if (statvfs(path, &st) != 0)
1178 		send_status(id, errno_to_portable(errno));
1179 	else
1180 		send_statvfs(id, &st);
1181         free(path);
1182 }
1183 
1184 static void
1185 process_extended_fstatvfs(u_int32_t id)
1186 {
1187 	int handle, fd;
1188 	struct statvfs st;
1189 
1190 	handle = get_handle();
1191 	debug("request %u: fstatvfs \"%s\" (handle %u)",
1192 	    id, handle_to_name(handle), handle);
1193 	if ((fd = handle_to_fd(handle)) < 0) {
1194 		send_status(id, SSH2_FX_FAILURE);
1195 		return;
1196 	}
1197 	if (fstatvfs(fd, &st) != 0)
1198 		send_status(id, errno_to_portable(errno));
1199 	else
1200 		send_statvfs(id, &st);
1201 }
1202 
1203 static void
1204 process_extended_hardlink(u_int32_t id)
1205 {
1206 	char *oldpath, *newpath;
1207 	int ret, status;
1208 
1209 	oldpath = get_string(NULL);
1210 	newpath = get_string(NULL);
1211 	debug3("request %u: hardlink", id);
1212 	logit("hardlink old \"%s\" new \"%s\"", oldpath, newpath);
1213 	if (readonly)
1214 		status = SSH2_FX_PERMISSION_DENIED;
1215 	else {
1216 		ret = link(oldpath, newpath);
1217 		status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1218 	}
1219 	send_status(id, status);
1220 	free(oldpath);
1221 	free(newpath);
1222 }
1223 
1224 static void
1225 process_extended(void)
1226 {
1227 	u_int32_t id;
1228 	char *request;
1229 
1230 	id = get_int();
1231 	request = get_string(NULL);
1232 	if (strcmp(request, "posix-rename@openssh.com") == 0)
1233 		process_extended_posix_rename(id);
1234 	else if (strcmp(request, "statvfs@openssh.com") == 0)
1235 		process_extended_statvfs(id);
1236 	else if (strcmp(request, "fstatvfs@openssh.com") == 0)
1237 		process_extended_fstatvfs(id);
1238 	else if (strcmp(request, "hardlink@openssh.com") == 0)
1239 		process_extended_hardlink(id);
1240 	else
1241 		send_status(id, SSH2_FX_OP_UNSUPPORTED);	/* MUST */
1242 	free(request);
1243 }
1244 
1245 /* stolen from ssh-agent */
1246 
1247 static void
1248 process(void)
1249 {
1250 	u_int msg_len;
1251 	u_int buf_len;
1252 	u_int consumed;
1253 	u_int type;
1254 	u_char *cp;
1255 
1256 	buf_len = buffer_len(&iqueue);
1257 	if (buf_len < 5)
1258 		return;		/* Incomplete message. */
1259 	cp = buffer_ptr(&iqueue);
1260 	msg_len = get_u32(cp);
1261 	if (msg_len > SFTP_MAX_MSG_LENGTH) {
1262 		error("bad message from %s local user %s",
1263 		    client_addr, pw->pw_name);
1264 		sftp_server_cleanup_exit(11);
1265 	}
1266 	if (buf_len < msg_len + 4)
1267 		return;
1268 	buffer_consume(&iqueue, 4);
1269 	buf_len -= 4;
1270 	type = buffer_get_char(&iqueue);
1271 	switch (type) {
1272 	case SSH2_FXP_INIT:
1273 		process_init();
1274 		break;
1275 	case SSH2_FXP_OPEN:
1276 		process_open();
1277 		break;
1278 	case SSH2_FXP_CLOSE:
1279 		process_close();
1280 		break;
1281 	case SSH2_FXP_READ:
1282 		process_read();
1283 		break;
1284 	case SSH2_FXP_WRITE:
1285 		process_write();
1286 		break;
1287 	case SSH2_FXP_LSTAT:
1288 		process_lstat();
1289 		break;
1290 	case SSH2_FXP_FSTAT:
1291 		process_fstat();
1292 		break;
1293 	case SSH2_FXP_SETSTAT:
1294 		process_setstat();
1295 		break;
1296 	case SSH2_FXP_FSETSTAT:
1297 		process_fsetstat();
1298 		break;
1299 	case SSH2_FXP_OPENDIR:
1300 		process_opendir();
1301 		break;
1302 	case SSH2_FXP_READDIR:
1303 		process_readdir();
1304 		break;
1305 	case SSH2_FXP_REMOVE:
1306 		process_remove();
1307 		break;
1308 	case SSH2_FXP_MKDIR:
1309 		process_mkdir();
1310 		break;
1311 	case SSH2_FXP_RMDIR:
1312 		process_rmdir();
1313 		break;
1314 	case SSH2_FXP_REALPATH:
1315 		process_realpath();
1316 		break;
1317 	case SSH2_FXP_STAT:
1318 		process_stat();
1319 		break;
1320 	case SSH2_FXP_RENAME:
1321 		process_rename();
1322 		break;
1323 	case SSH2_FXP_READLINK:
1324 		process_readlink();
1325 		break;
1326 	case SSH2_FXP_SYMLINK:
1327 		process_symlink();
1328 		break;
1329 	case SSH2_FXP_EXTENDED:
1330 		process_extended();
1331 		break;
1332 	default:
1333 		error("Unknown message %d", type);
1334 		break;
1335 	}
1336 	/* discard the remaining bytes from the current packet */
1337 	if (buf_len < buffer_len(&iqueue)) {
1338 		error("iqueue grew unexpectedly");
1339 		sftp_server_cleanup_exit(255);
1340 	}
1341 	consumed = buf_len - buffer_len(&iqueue);
1342 	if (msg_len < consumed) {
1343 		error("msg_len %d < consumed %d", msg_len, consumed);
1344 		sftp_server_cleanup_exit(255);
1345 	}
1346 	if (msg_len > consumed)
1347 		buffer_consume(&iqueue, msg_len - consumed);
1348 }
1349 
1350 /* Cleanup handler that logs active handles upon normal exit */
1351 void
1352 sftp_server_cleanup_exit(int i)
1353 {
1354 	if (pw != NULL && client_addr != NULL) {
1355 		handle_log_exit();
1356 		logit("session closed for local user %s from [%s]",
1357 		    pw->pw_name, client_addr);
1358 	}
1359 	_exit(i);
1360 }
1361 
1362 __dead static void
1363 sftp_server_usage(void)
1364 {
1365 	extern char *__progname;
1366 
1367 	fprintf(stderr,
1368 	    "usage: %s [-ehR] [-d start_directory] [-f log_facility] "
1369 	    "[-l log_level]\n\t[-u umask]\n",
1370 	    __progname);
1371 	exit(1);
1372 }
1373 
1374 int
1375 sftp_server_main(int argc, char **argv, struct passwd *user_pw)
1376 {
1377 	fd_set *rset, *wset;
1378 	int in, out, max, ch, skipargs = 0, log_stderr = 0;
1379 	ssize_t len, olen, set_size;
1380 	SyslogFacility log_facility = SYSLOG_FACILITY_AUTH;
1381 	char *cp, *homedir = NULL, buf[4*4096];
1382 	long mask;
1383 
1384 	extern char *optarg;
1385 	extern char *__progname;
1386 
1387 	log_init(__progname, log_level, log_facility, log_stderr);
1388 
1389 	pw = pwcopy(user_pw);
1390 
1391 	while (!skipargs && (ch = getopt(argc, argv, "d:f:l:u:cehR")) != -1) {
1392 		switch (ch) {
1393 		case 'R':
1394 			readonly = 1;
1395 			break;
1396 		case 'c':
1397 			/*
1398 			 * Ignore all arguments if we are invoked as a
1399 			 * shell using "sftp-server -c command"
1400 			 */
1401 			skipargs = 1;
1402 			break;
1403 		case 'e':
1404 			log_stderr = 1;
1405 			break;
1406 		case 'l':
1407 			log_level = log_level_number(optarg);
1408 			if (log_level == SYSLOG_LEVEL_NOT_SET)
1409 				error("Invalid log level \"%s\"", optarg);
1410 			break;
1411 		case 'f':
1412 			log_facility = log_facility_number(optarg);
1413 			if (log_facility == SYSLOG_FACILITY_NOT_SET)
1414 				error("Invalid log facility \"%s\"", optarg);
1415 			break;
1416 		case 'd':
1417 			cp = tilde_expand_filename(optarg, user_pw->pw_uid);
1418 			homedir = percent_expand(cp, "d", user_pw->pw_dir,
1419 			    "u", user_pw->pw_name, (char *)NULL);
1420 			free(cp);
1421 			break;
1422 		case 'u':
1423 			errno = 0;
1424 			mask = strtol(optarg, &cp, 8);
1425 			if (mask < 0 || mask > 0777 || *cp != '\0' ||
1426 			    cp == optarg || (mask == 0 && errno != 0))
1427 				fatal("Invalid umask \"%s\"", optarg);
1428 			(void)umask((mode_t)mask);
1429 			break;
1430 		case 'h':
1431 		default:
1432 			sftp_server_usage();
1433 		}
1434 	}
1435 
1436 	log_init(__progname, log_level, log_facility, log_stderr);
1437 
1438 	if ((cp = getenv("SSH_CONNECTION")) != NULL) {
1439 		client_addr = xstrdup(cp);
1440 		if ((cp = strchr(client_addr, ' ')) == NULL) {
1441 			error("Malformed SSH_CONNECTION variable: \"%s\"",
1442 			    getenv("SSH_CONNECTION"));
1443 			sftp_server_cleanup_exit(255);
1444 		}
1445 		*cp = '\0';
1446 	} else
1447 		client_addr = xstrdup("UNKNOWN");
1448 
1449 	logit("session opened for local user %s from [%s]",
1450 	    pw->pw_name, client_addr);
1451 
1452 	in = STDIN_FILENO;
1453 	out = STDOUT_FILENO;
1454 
1455 	max = 0;
1456 	if (in > max)
1457 		max = in;
1458 	if (out > max)
1459 		max = out;
1460 
1461 	buffer_init(&iqueue);
1462 	buffer_init(&oqueue);
1463 
1464 	set_size = howmany(max + 1, NFDBITS) * sizeof(fd_mask);
1465 	rset = (fd_set *)xmalloc(set_size);
1466 	wset = (fd_set *)xmalloc(set_size);
1467 
1468 	if (homedir != NULL) {
1469 		if (chdir(homedir) != 0) {
1470 			error("chdir to \"%s\" failed: %s", homedir,
1471 			    strerror(errno));
1472 		}
1473 	}
1474 
1475 	for (;;) {
1476 		memset(rset, 0, set_size);
1477 		memset(wset, 0, set_size);
1478 
1479 		/*
1480 		 * Ensure that we can read a full buffer and handle
1481 		 * the worst-case length packet it can generate,
1482 		 * otherwise apply backpressure by stopping reads.
1483 		 */
1484 		if (buffer_check_alloc(&iqueue, sizeof(buf)) &&
1485 		    buffer_check_alloc(&oqueue, SFTP_MAX_MSG_LENGTH))
1486 			FD_SET(in, rset);
1487 
1488 		olen = buffer_len(&oqueue);
1489 		if (olen > 0)
1490 			FD_SET(out, wset);
1491 
1492 		if (select(max+1, rset, wset, NULL, NULL) < 0) {
1493 			if (errno == EINTR)
1494 				continue;
1495 			error("select: %s", strerror(errno));
1496 			sftp_server_cleanup_exit(2);
1497 		}
1498 
1499 		/* copy stdin to iqueue */
1500 		if (FD_ISSET(in, rset)) {
1501 			len = read(in, buf, sizeof buf);
1502 			if (len == 0) {
1503 				debug("read eof");
1504 				sftp_server_cleanup_exit(0);
1505 			} else if (len < 0) {
1506 				error("read: %s", strerror(errno));
1507 				sftp_server_cleanup_exit(1);
1508 			} else {
1509 				buffer_append(&iqueue, buf, len);
1510 			}
1511 		}
1512 		/* send oqueue to stdout */
1513 		if (FD_ISSET(out, wset)) {
1514 			len = write(out, buffer_ptr(&oqueue), olen);
1515 			if (len < 0) {
1516 				error("write: %s", strerror(errno));
1517 				sftp_server_cleanup_exit(1);
1518 			} else {
1519 				buffer_consume(&oqueue, len);
1520 			}
1521 		}
1522 
1523 		/*
1524 		 * Process requests from client if we can fit the results
1525 		 * into the output buffer, otherwise stop processing input
1526 		 * and let the output queue drain.
1527 		 */
1528 		if (buffer_check_alloc(&oqueue, SFTP_MAX_MSG_LENGTH))
1529 			process();
1530 	}
1531 }
1532