xref: /openbsd-src/usr.bin/ssh/sftp-server.c (revision c1a45aed656e7d5627c30c92421893a76f370ccb)
1 /* $OpenBSD: sftp-server.c,v 1.140 2022/03/31 03:05:49 djm Exp $ */
2 /*
3  * Copyright (c) 2000-2004 Markus Friedl.  All rights reserved.
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 
18 #include <sys/types.h>
19 #include <sys/resource.h>
20 #include <sys/stat.h>
21 #include <sys/time.h>
22 #include <sys/mount.h>
23 #include <sys/statvfs.h>
24 
25 #include <dirent.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <poll.h>
29 #include <stdlib.h>
30 #include <stdio.h>
31 #include <string.h>
32 #include <pwd.h>
33 #include <time.h>
34 #include <unistd.h>
35 #include <stdarg.h>
36 
37 #include "atomicio.h"
38 #include "xmalloc.h"
39 #include "sshbuf.h"
40 #include "ssherr.h"
41 #include "log.h"
42 #include "misc.h"
43 #include "match.h"
44 #include "uidswap.h"
45 
46 #include "sftp.h"
47 #include "sftp-common.h"
48 
49 char *sftp_realpath(const char *, char *); /* sftp-realpath.c */
50 
51 /* Maximum data read that we are willing to accept */
52 #define SFTP_MAX_READ_LENGTH (SFTP_MAX_MSG_LENGTH - 1024)
53 
54 /* Our verbosity */
55 static LogLevel log_level = SYSLOG_LEVEL_ERROR;
56 
57 /* Our client */
58 static struct passwd *pw = NULL;
59 static char *client_addr = NULL;
60 
61 /* input and output queue */
62 struct sshbuf *iqueue;
63 struct sshbuf *oqueue;
64 
65 /* Version of client */
66 static u_int version;
67 
68 /* SSH2_FXP_INIT received */
69 static int init_done;
70 
71 /* Disable writes */
72 static int readonly;
73 
74 /* Requests that are allowed/denied */
75 static char *request_allowlist, *request_denylist;
76 
77 /* portable attributes, etc. */
78 typedef struct Stat Stat;
79 
80 struct Stat {
81 	char *name;
82 	char *long_name;
83 	Attrib attrib;
84 };
85 
86 /* Packet handlers */
87 static void process_open(u_int32_t id);
88 static void process_close(u_int32_t id);
89 static void process_read(u_int32_t id);
90 static void process_write(u_int32_t id);
91 static void process_stat(u_int32_t id);
92 static void process_lstat(u_int32_t id);
93 static void process_fstat(u_int32_t id);
94 static void process_setstat(u_int32_t id);
95 static void process_fsetstat(u_int32_t id);
96 static void process_opendir(u_int32_t id);
97 static void process_readdir(u_int32_t id);
98 static void process_remove(u_int32_t id);
99 static void process_mkdir(u_int32_t id);
100 static void process_rmdir(u_int32_t id);
101 static void process_realpath(u_int32_t id);
102 static void process_rename(u_int32_t id);
103 static void process_readlink(u_int32_t id);
104 static void process_symlink(u_int32_t id);
105 static void process_extended_posix_rename(u_int32_t id);
106 static void process_extended_statvfs(u_int32_t id);
107 static void process_extended_fstatvfs(u_int32_t id);
108 static void process_extended_hardlink(u_int32_t id);
109 static void process_extended_fsync(u_int32_t id);
110 static void process_extended_lsetstat(u_int32_t id);
111 static void process_extended_limits(u_int32_t id);
112 static void process_extended_expand(u_int32_t id);
113 static void process_extended_copy_data(u_int32_t id);
114 static void process_extended(u_int32_t id);
115 
116 struct sftp_handler {
117 	const char *name;	/* user-visible name for fine-grained perms */
118 	const char *ext_name;	/* extended request name */
119 	u_int type;		/* packet type, for non extended packets */
120 	void (*handler)(u_int32_t);
121 	int does_write;		/* if nonzero, banned for readonly mode */
122 };
123 
124 static const struct sftp_handler handlers[] = {
125 	/* NB. SSH2_FXP_OPEN does the readonly check in the handler itself */
126 	{ "open", NULL, SSH2_FXP_OPEN, process_open, 0 },
127 	{ "close", NULL, SSH2_FXP_CLOSE, process_close, 0 },
128 	{ "read", NULL, SSH2_FXP_READ, process_read, 0 },
129 	{ "write", NULL, SSH2_FXP_WRITE, process_write, 1 },
130 	{ "lstat", NULL, SSH2_FXP_LSTAT, process_lstat, 0 },
131 	{ "fstat", NULL, SSH2_FXP_FSTAT, process_fstat, 0 },
132 	{ "setstat", NULL, SSH2_FXP_SETSTAT, process_setstat, 1 },
133 	{ "fsetstat", NULL, SSH2_FXP_FSETSTAT, process_fsetstat, 1 },
134 	{ "opendir", NULL, SSH2_FXP_OPENDIR, process_opendir, 0 },
135 	{ "readdir", NULL, SSH2_FXP_READDIR, process_readdir, 0 },
136 	{ "remove", NULL, SSH2_FXP_REMOVE, process_remove, 1 },
137 	{ "mkdir", NULL, SSH2_FXP_MKDIR, process_mkdir, 1 },
138 	{ "rmdir", NULL, SSH2_FXP_RMDIR, process_rmdir, 1 },
139 	{ "realpath", NULL, SSH2_FXP_REALPATH, process_realpath, 0 },
140 	{ "stat", NULL, SSH2_FXP_STAT, process_stat, 0 },
141 	{ "rename", NULL, SSH2_FXP_RENAME, process_rename, 1 },
142 	{ "readlink", NULL, SSH2_FXP_READLINK, process_readlink, 0 },
143 	{ "symlink", NULL, SSH2_FXP_SYMLINK, process_symlink, 1 },
144 	{ NULL, NULL, 0, NULL, 0 }
145 };
146 
147 /* SSH2_FXP_EXTENDED submessages */
148 static const struct sftp_handler extended_handlers[] = {
149 	{ "posix-rename", "posix-rename@openssh.com", 0,
150 	    process_extended_posix_rename, 1 },
151 	{ "statvfs", "statvfs@openssh.com", 0, process_extended_statvfs, 0 },
152 	{ "fstatvfs", "fstatvfs@openssh.com", 0, process_extended_fstatvfs, 0 },
153 	{ "hardlink", "hardlink@openssh.com", 0, process_extended_hardlink, 1 },
154 	{ "fsync", "fsync@openssh.com", 0, process_extended_fsync, 1 },
155 	{ "lsetstat", "lsetstat@openssh.com", 0, process_extended_lsetstat, 1 },
156 	{ "limits", "limits@openssh.com", 0, process_extended_limits, 0 },
157 	{ "expand-path", "expand-path@openssh.com", 0,
158 	    process_extended_expand, 0 },
159 	{ "copy-data", "copy-data", 0, process_extended_copy_data, 1 },
160 	{ NULL, NULL, 0, NULL, 0 }
161 };
162 
163 static const struct sftp_handler *
164 extended_handler_byname(const char *name)
165 {
166 	int i;
167 
168 	for (i = 0; extended_handlers[i].handler != NULL; i++) {
169 		if (strcmp(name, extended_handlers[i].ext_name) == 0)
170 			return &extended_handlers[i];
171 	}
172 	return NULL;
173 }
174 
175 static int
176 request_permitted(const struct sftp_handler *h)
177 {
178 	char *result;
179 
180 	if (readonly && h->does_write) {
181 		verbose("Refusing %s request in read-only mode", h->name);
182 		return 0;
183 	}
184 	if (request_denylist != NULL &&
185 	    ((result = match_list(h->name, request_denylist, NULL))) != NULL) {
186 		free(result);
187 		verbose("Refusing denylisted %s request", h->name);
188 		return 0;
189 	}
190 	if (request_allowlist != NULL &&
191 	    ((result = match_list(h->name, request_allowlist, NULL))) != NULL) {
192 		free(result);
193 		debug2("Permitting allowlisted %s request", h->name);
194 		return 1;
195 	}
196 	if (request_allowlist != NULL) {
197 		verbose("Refusing non-allowlisted %s request", h->name);
198 		return 0;
199 	}
200 	return 1;
201 }
202 
203 static int
204 errno_to_portable(int unixerrno)
205 {
206 	int ret = 0;
207 
208 	switch (unixerrno) {
209 	case 0:
210 		ret = SSH2_FX_OK;
211 		break;
212 	case ENOENT:
213 	case ENOTDIR:
214 	case EBADF:
215 	case ELOOP:
216 		ret = SSH2_FX_NO_SUCH_FILE;
217 		break;
218 	case EPERM:
219 	case EACCES:
220 	case EFAULT:
221 		ret = SSH2_FX_PERMISSION_DENIED;
222 		break;
223 	case ENAMETOOLONG:
224 	case EINVAL:
225 		ret = SSH2_FX_BAD_MESSAGE;
226 		break;
227 	case ENOSYS:
228 		ret = SSH2_FX_OP_UNSUPPORTED;
229 		break;
230 	default:
231 		ret = SSH2_FX_FAILURE;
232 		break;
233 	}
234 	return ret;
235 }
236 
237 static int
238 flags_from_portable(int pflags)
239 {
240 	int flags = 0;
241 
242 	if ((pflags & SSH2_FXF_READ) &&
243 	    (pflags & SSH2_FXF_WRITE)) {
244 		flags = O_RDWR;
245 	} else if (pflags & SSH2_FXF_READ) {
246 		flags = O_RDONLY;
247 	} else if (pflags & SSH2_FXF_WRITE) {
248 		flags = O_WRONLY;
249 	}
250 	if (pflags & SSH2_FXF_APPEND)
251 		flags |= O_APPEND;
252 	if (pflags & SSH2_FXF_CREAT)
253 		flags |= O_CREAT;
254 	if (pflags & SSH2_FXF_TRUNC)
255 		flags |= O_TRUNC;
256 	if (pflags & SSH2_FXF_EXCL)
257 		flags |= O_EXCL;
258 	return flags;
259 }
260 
261 static const char *
262 string_from_portable(int pflags)
263 {
264 	static char ret[128];
265 
266 	*ret = '\0';
267 
268 #define PAPPEND(str)	{				\
269 		if (*ret != '\0')			\
270 			strlcat(ret, ",", sizeof(ret));	\
271 		strlcat(ret, str, sizeof(ret));		\
272 	}
273 
274 	if (pflags & SSH2_FXF_READ)
275 		PAPPEND("READ")
276 	if (pflags & SSH2_FXF_WRITE)
277 		PAPPEND("WRITE")
278 	if (pflags & SSH2_FXF_APPEND)
279 		PAPPEND("APPEND")
280 	if (pflags & SSH2_FXF_CREAT)
281 		PAPPEND("CREATE")
282 	if (pflags & SSH2_FXF_TRUNC)
283 		PAPPEND("TRUNCATE")
284 	if (pflags & SSH2_FXF_EXCL)
285 		PAPPEND("EXCL")
286 
287 	return ret;
288 }
289 
290 /* handle handles */
291 
292 typedef struct Handle Handle;
293 struct Handle {
294 	int use;
295 	DIR *dirp;
296 	int fd;
297 	int flags;
298 	char *name;
299 	u_int64_t bytes_read, bytes_write;
300 	int next_unused;
301 };
302 
303 enum {
304 	HANDLE_UNUSED,
305 	HANDLE_DIR,
306 	HANDLE_FILE
307 };
308 
309 static Handle *handles = NULL;
310 static u_int num_handles = 0;
311 static int first_unused_handle = -1;
312 
313 static void handle_unused(int i)
314 {
315 	handles[i].use = HANDLE_UNUSED;
316 	handles[i].next_unused = first_unused_handle;
317 	first_unused_handle = i;
318 }
319 
320 static int
321 handle_new(int use, const char *name, int fd, int flags, DIR *dirp)
322 {
323 	int i;
324 
325 	if (first_unused_handle == -1) {
326 		if (num_handles + 1 <= num_handles)
327 			return -1;
328 		num_handles++;
329 		handles = xreallocarray(handles, num_handles, sizeof(Handle));
330 		handle_unused(num_handles - 1);
331 	}
332 
333 	i = first_unused_handle;
334 	first_unused_handle = handles[i].next_unused;
335 
336 	handles[i].use = use;
337 	handles[i].dirp = dirp;
338 	handles[i].fd = fd;
339 	handles[i].flags = flags;
340 	handles[i].name = xstrdup(name);
341 	handles[i].bytes_read = handles[i].bytes_write = 0;
342 
343 	return i;
344 }
345 
346 static int
347 handle_is_ok(int i, int type)
348 {
349 	return i >= 0 && (u_int)i < num_handles && handles[i].use == type;
350 }
351 
352 static int
353 handle_to_string(int handle, u_char **stringp, int *hlenp)
354 {
355 	if (stringp == NULL || hlenp == NULL)
356 		return -1;
357 	*stringp = xmalloc(sizeof(int32_t));
358 	put_u32(*stringp, handle);
359 	*hlenp = sizeof(int32_t);
360 	return 0;
361 }
362 
363 static int
364 handle_from_string(const u_char *handle, u_int hlen)
365 {
366 	int val;
367 
368 	if (hlen != sizeof(int32_t))
369 		return -1;
370 	val = get_u32(handle);
371 	if (handle_is_ok(val, HANDLE_FILE) ||
372 	    handle_is_ok(val, HANDLE_DIR))
373 		return val;
374 	return -1;
375 }
376 
377 static char *
378 handle_to_name(int handle)
379 {
380 	if (handle_is_ok(handle, HANDLE_DIR)||
381 	    handle_is_ok(handle, HANDLE_FILE))
382 		return handles[handle].name;
383 	return NULL;
384 }
385 
386 static DIR *
387 handle_to_dir(int handle)
388 {
389 	if (handle_is_ok(handle, HANDLE_DIR))
390 		return handles[handle].dirp;
391 	return NULL;
392 }
393 
394 static int
395 handle_to_fd(int handle)
396 {
397 	if (handle_is_ok(handle, HANDLE_FILE))
398 		return handles[handle].fd;
399 	return -1;
400 }
401 
402 static int
403 handle_to_flags(int handle)
404 {
405 	if (handle_is_ok(handle, HANDLE_FILE))
406 		return handles[handle].flags;
407 	return 0;
408 }
409 
410 static void
411 handle_update_read(int handle, ssize_t bytes)
412 {
413 	if (handle_is_ok(handle, HANDLE_FILE) && bytes > 0)
414 		handles[handle].bytes_read += bytes;
415 }
416 
417 static void
418 handle_update_write(int handle, ssize_t bytes)
419 {
420 	if (handle_is_ok(handle, HANDLE_FILE) && bytes > 0)
421 		handles[handle].bytes_write += bytes;
422 }
423 
424 static u_int64_t
425 handle_bytes_read(int handle)
426 {
427 	if (handle_is_ok(handle, HANDLE_FILE))
428 		return (handles[handle].bytes_read);
429 	return 0;
430 }
431 
432 static u_int64_t
433 handle_bytes_write(int handle)
434 {
435 	if (handle_is_ok(handle, HANDLE_FILE))
436 		return (handles[handle].bytes_write);
437 	return 0;
438 }
439 
440 static int
441 handle_close(int handle)
442 {
443 	int ret = -1;
444 
445 	if (handle_is_ok(handle, HANDLE_FILE)) {
446 		ret = close(handles[handle].fd);
447 		free(handles[handle].name);
448 		handle_unused(handle);
449 	} else if (handle_is_ok(handle, HANDLE_DIR)) {
450 		ret = closedir(handles[handle].dirp);
451 		free(handles[handle].name);
452 		handle_unused(handle);
453 	} else {
454 		errno = ENOENT;
455 	}
456 	return ret;
457 }
458 
459 static void
460 handle_log_close(int handle, char *emsg)
461 {
462 	if (handle_is_ok(handle, HANDLE_FILE)) {
463 		logit("%s%sclose \"%s\" bytes read %llu written %llu",
464 		    emsg == NULL ? "" : emsg, emsg == NULL ? "" : " ",
465 		    handle_to_name(handle),
466 		    (unsigned long long)handle_bytes_read(handle),
467 		    (unsigned long long)handle_bytes_write(handle));
468 	} else {
469 		logit("%s%sclosedir \"%s\"",
470 		    emsg == NULL ? "" : emsg, emsg == NULL ? "" : " ",
471 		    handle_to_name(handle));
472 	}
473 }
474 
475 static void
476 handle_log_exit(void)
477 {
478 	u_int i;
479 
480 	for (i = 0; i < num_handles; i++)
481 		if (handles[i].use != HANDLE_UNUSED)
482 			handle_log_close(i, "forced");
483 }
484 
485 static int
486 get_handle(struct sshbuf *queue, int *hp)
487 {
488 	u_char *handle;
489 	int r;
490 	size_t hlen;
491 
492 	*hp = -1;
493 	if ((r = sshbuf_get_string(queue, &handle, &hlen)) != 0)
494 		return r;
495 	if (hlen < 256)
496 		*hp = handle_from_string(handle, hlen);
497 	free(handle);
498 	return 0;
499 }
500 
501 /* send replies */
502 
503 static void
504 send_msg(struct sshbuf *m)
505 {
506 	int r;
507 
508 	if ((r = sshbuf_put_stringb(oqueue, m)) != 0)
509 		fatal_fr(r, "enqueue");
510 	sshbuf_reset(m);
511 }
512 
513 static const char *
514 status_to_message(u_int32_t status)
515 {
516 	static const char * const status_messages[] = {
517 		"Success",			/* SSH_FX_OK */
518 		"End of file",			/* SSH_FX_EOF */
519 		"No such file",			/* SSH_FX_NO_SUCH_FILE */
520 		"Permission denied",		/* SSH_FX_PERMISSION_DENIED */
521 		"Failure",			/* SSH_FX_FAILURE */
522 		"Bad message",			/* SSH_FX_BAD_MESSAGE */
523 		"No connection",		/* SSH_FX_NO_CONNECTION */
524 		"Connection lost",		/* SSH_FX_CONNECTION_LOST */
525 		"Operation unsupported",	/* SSH_FX_OP_UNSUPPORTED */
526 		"Unknown error"			/* Others */
527 	};
528 	return (status_messages[MINIMUM(status,SSH2_FX_MAX)]);
529 }
530 
531 static void
532 send_status_errmsg(u_int32_t id, u_int32_t status, const char *errmsg)
533 {
534 	struct sshbuf *msg;
535 	int r;
536 
537 	debug3("request %u: sent status %u", id, status);
538 	if (log_level > SYSLOG_LEVEL_VERBOSE ||
539 	    (status != SSH2_FX_OK && status != SSH2_FX_EOF))
540 		logit("sent status %s", status_to_message(status));
541 	if ((msg = sshbuf_new()) == NULL)
542 		fatal_f("sshbuf_new failed");
543 	if ((r = sshbuf_put_u8(msg, SSH2_FXP_STATUS)) != 0 ||
544 	    (r = sshbuf_put_u32(msg, id)) != 0 ||
545 	    (r = sshbuf_put_u32(msg, status)) != 0)
546 		fatal_fr(r, "compose");
547 	if (version >= 3) {
548 		if ((r = sshbuf_put_cstring(msg, errmsg == NULL ?
549 		    status_to_message(status) : errmsg)) != 0 ||
550 		    (r = sshbuf_put_cstring(msg, "")) != 0)
551 			fatal_fr(r, "compose message");
552 	}
553 	send_msg(msg);
554 	sshbuf_free(msg);
555 }
556 
557 static void
558 send_status(u_int32_t id, u_int32_t status)
559 {
560 	send_status_errmsg(id, status, NULL);
561 }
562 
563 static void
564 send_data_or_handle(char type, u_int32_t id, const u_char *data, int dlen)
565 {
566 	struct sshbuf *msg;
567 	int r;
568 
569 	if ((msg = sshbuf_new()) == NULL)
570 		fatal_f("sshbuf_new failed");
571 	if ((r = sshbuf_put_u8(msg, type)) != 0 ||
572 	    (r = sshbuf_put_u32(msg, id)) != 0 ||
573 	    (r = sshbuf_put_string(msg, data, dlen)) != 0)
574 		fatal_fr(r, "compose");
575 	send_msg(msg);
576 	sshbuf_free(msg);
577 }
578 
579 static void
580 send_data(u_int32_t id, const u_char *data, int dlen)
581 {
582 	debug("request %u: sent data len %d", id, dlen);
583 	send_data_or_handle(SSH2_FXP_DATA, id, data, dlen);
584 }
585 
586 static void
587 send_handle(u_int32_t id, int handle)
588 {
589 	u_char *string;
590 	int hlen;
591 
592 	handle_to_string(handle, &string, &hlen);
593 	debug("request %u: sent handle handle %d", id, handle);
594 	send_data_or_handle(SSH2_FXP_HANDLE, id, string, hlen);
595 	free(string);
596 }
597 
598 static void
599 send_names(u_int32_t id, int count, const Stat *stats)
600 {
601 	struct sshbuf *msg;
602 	int i, r;
603 
604 	if ((msg = sshbuf_new()) == NULL)
605 		fatal_f("sshbuf_new failed");
606 	if ((r = sshbuf_put_u8(msg, SSH2_FXP_NAME)) != 0 ||
607 	    (r = sshbuf_put_u32(msg, id)) != 0 ||
608 	    (r = sshbuf_put_u32(msg, count)) != 0)
609 		fatal_fr(r, "compose");
610 	debug("request %u: sent names count %d", id, count);
611 	for (i = 0; i < count; i++) {
612 		if ((r = sshbuf_put_cstring(msg, stats[i].name)) != 0 ||
613 		    (r = sshbuf_put_cstring(msg, stats[i].long_name)) != 0 ||
614 		    (r = encode_attrib(msg, &stats[i].attrib)) != 0)
615 			fatal_fr(r, "compose filenames/attrib");
616 	}
617 	send_msg(msg);
618 	sshbuf_free(msg);
619 }
620 
621 static void
622 send_attrib(u_int32_t id, const Attrib *a)
623 {
624 	struct sshbuf *msg;
625 	int r;
626 
627 	debug("request %u: sent attrib have 0x%x", id, a->flags);
628 	if ((msg = sshbuf_new()) == NULL)
629 		fatal_f("sshbuf_new failed");
630 	if ((r = sshbuf_put_u8(msg, SSH2_FXP_ATTRS)) != 0 ||
631 	    (r = sshbuf_put_u32(msg, id)) != 0 ||
632 	    (r = encode_attrib(msg, a)) != 0)
633 		fatal_fr(r, "compose");
634 	send_msg(msg);
635 	sshbuf_free(msg);
636 }
637 
638 static void
639 send_statvfs(u_int32_t id, struct statvfs *st)
640 {
641 	struct sshbuf *msg;
642 	u_int64_t flag;
643 	int r;
644 
645 	flag = (st->f_flag & ST_RDONLY) ? SSH2_FXE_STATVFS_ST_RDONLY : 0;
646 	flag |= (st->f_flag & ST_NOSUID) ? SSH2_FXE_STATVFS_ST_NOSUID : 0;
647 
648 	if ((msg = sshbuf_new()) == NULL)
649 		fatal_f("sshbuf_new failed");
650 	if ((r = sshbuf_put_u8(msg, SSH2_FXP_EXTENDED_REPLY)) != 0 ||
651 	    (r = sshbuf_put_u32(msg, id)) != 0 ||
652 	    (r = sshbuf_put_u64(msg, st->f_bsize)) != 0 ||
653 	    (r = sshbuf_put_u64(msg, st->f_frsize)) != 0 ||
654 	    (r = sshbuf_put_u64(msg, st->f_blocks)) != 0 ||
655 	    (r = sshbuf_put_u64(msg, st->f_bfree)) != 0 ||
656 	    (r = sshbuf_put_u64(msg, st->f_bavail)) != 0 ||
657 	    (r = sshbuf_put_u64(msg, st->f_files)) != 0 ||
658 	    (r = sshbuf_put_u64(msg, st->f_ffree)) != 0 ||
659 	    (r = sshbuf_put_u64(msg, st->f_favail)) != 0 ||
660 	    (r = sshbuf_put_u64(msg, st->f_fsid)) != 0 ||
661 	    (r = sshbuf_put_u64(msg, flag)) != 0 ||
662 	    (r = sshbuf_put_u64(msg, st->f_namemax)) != 0)
663 		fatal_fr(r, "compose");
664 	send_msg(msg);
665 	sshbuf_free(msg);
666 }
667 
668 /*
669  * Prepare SSH2_FXP_VERSION extension advertisement for a single extension.
670  * The extension is checked for permission prior to advertisement.
671  */
672 static int
673 compose_extension(struct sshbuf *msg, const char *name, const char *ver)
674 {
675 	int r;
676 	const struct sftp_handler *exthnd;
677 
678 	if ((exthnd = extended_handler_byname(name)) == NULL)
679 		fatal_f("internal error: no handler for %s", name);
680 	if (!request_permitted(exthnd)) {
681 		debug2_f("refusing to advertise disallowed extension %s", name);
682 		return 0;
683 	}
684 	if ((r = sshbuf_put_cstring(msg, name)) != 0 ||
685 	    (r = sshbuf_put_cstring(msg, ver)) != 0)
686 		fatal_fr(r, "compose %s", name);
687 	return 0;
688 }
689 
690 /* parse incoming */
691 
692 static void
693 process_init(void)
694 {
695 	struct sshbuf *msg;
696 	int r;
697 
698 	if ((r = sshbuf_get_u32(iqueue, &version)) != 0)
699 		fatal_fr(r, "parse");
700 	verbose("received client version %u", version);
701 	if ((msg = sshbuf_new()) == NULL)
702 		fatal_f("sshbuf_new failed");
703 	if ((r = sshbuf_put_u8(msg, SSH2_FXP_VERSION)) != 0 ||
704 	    (r = sshbuf_put_u32(msg, SSH2_FILEXFER_VERSION)) != 0)
705 		fatal_fr(r, "compose");
706 
707 	 /* extension advertisements */
708 	compose_extension(msg, "posix-rename@openssh.com", "1");
709 	compose_extension(msg, "statvfs@openssh.com", "2");
710 	compose_extension(msg, "fstatvfs@openssh.com", "2");
711 	compose_extension(msg, "hardlink@openssh.com", "1");
712 	compose_extension(msg, "fsync@openssh.com", "1");
713 	compose_extension(msg, "lsetstat@openssh.com", "1");
714 	compose_extension(msg, "limits@openssh.com", "1");
715 	compose_extension(msg, "expand-path@openssh.com", "1");
716 	compose_extension(msg, "copy-data", "1");
717 
718 	send_msg(msg);
719 	sshbuf_free(msg);
720 }
721 
722 static void
723 process_open(u_int32_t id)
724 {
725 	u_int32_t pflags;
726 	Attrib a;
727 	char *name;
728 	int r, handle, fd, flags, mode, status = SSH2_FX_FAILURE;
729 
730 	if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 ||
731 	    (r = sshbuf_get_u32(iqueue, &pflags)) != 0 || /* portable flags */
732 	    (r = decode_attrib(iqueue, &a)) != 0)
733 		fatal_fr(r, "parse");
734 
735 	debug3("request %u: open flags %d", id, pflags);
736 	flags = flags_from_portable(pflags);
737 	mode = (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ? a.perm : 0666;
738 	logit("open \"%s\" flags %s mode 0%o",
739 	    name, string_from_portable(pflags), mode);
740 	if (readonly &&
741 	    ((flags & O_ACCMODE) != O_RDONLY ||
742 	    (flags & (O_CREAT|O_TRUNC)) != 0)) {
743 		verbose("Refusing open request in read-only mode");
744 		status = SSH2_FX_PERMISSION_DENIED;
745 	} else {
746 		fd = open(name, flags, mode);
747 		if (fd == -1) {
748 			status = errno_to_portable(errno);
749 		} else {
750 			handle = handle_new(HANDLE_FILE, name, fd, flags, NULL);
751 			if (handle < 0) {
752 				close(fd);
753 			} else {
754 				send_handle(id, handle);
755 				status = SSH2_FX_OK;
756 			}
757 		}
758 	}
759 	if (status != SSH2_FX_OK)
760 		send_status(id, status);
761 	free(name);
762 }
763 
764 static void
765 process_close(u_int32_t id)
766 {
767 	int r, handle, ret, status = SSH2_FX_FAILURE;
768 
769 	if ((r = get_handle(iqueue, &handle)) != 0)
770 		fatal_fr(r, "parse");
771 
772 	debug3("request %u: close handle %u", id, handle);
773 	handle_log_close(handle, NULL);
774 	ret = handle_close(handle);
775 	status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
776 	send_status(id, status);
777 }
778 
779 static void
780 process_read(u_int32_t id)
781 {
782 	static u_char *buf;
783 	static size_t buflen;
784 	u_int32_t len;
785 	int r, handle, fd, ret, status = SSH2_FX_FAILURE;
786 	u_int64_t off;
787 
788 	if ((r = get_handle(iqueue, &handle)) != 0 ||
789 	    (r = sshbuf_get_u64(iqueue, &off)) != 0 ||
790 	    (r = sshbuf_get_u32(iqueue, &len)) != 0)
791 		fatal_fr(r, "parse");
792 
793 	debug("request %u: read \"%s\" (handle %d) off %llu len %u",
794 	    id, handle_to_name(handle), handle, (unsigned long long)off, len);
795 	if ((fd = handle_to_fd(handle)) == -1)
796 		goto out;
797 	if (len > SFTP_MAX_READ_LENGTH) {
798 		debug2("read change len %u to %u", len, SFTP_MAX_READ_LENGTH);
799 		len = SFTP_MAX_READ_LENGTH;
800 	}
801 	if (len > buflen) {
802 		debug3_f("allocate %zu => %u", buflen, len);
803 		if ((buf = realloc(NULL, len)) == NULL)
804 			fatal_f("realloc failed");
805 		buflen = len;
806 	}
807 	if (lseek(fd, off, SEEK_SET) == -1) {
808 		status = errno_to_portable(errno);
809 		error_f("seek \"%.100s\": %s", handle_to_name(handle),
810 		    strerror(errno));
811 		goto out;
812 	}
813 	if (len == 0) {
814 		/* weird, but not strictly disallowed */
815 		ret = 0;
816 	} else if ((ret = read(fd, buf, len)) == -1) {
817 		status = errno_to_portable(errno);
818 		error_f("read \"%.100s\": %s", handle_to_name(handle),
819 		    strerror(errno));
820 		goto out;
821 	} else if (ret == 0) {
822 		status = SSH2_FX_EOF;
823 		goto out;
824 	}
825 	send_data(id, buf, ret);
826 	handle_update_read(handle, ret);
827 	/* success */
828 	status = SSH2_FX_OK;
829  out:
830 	if (status != SSH2_FX_OK)
831 		send_status(id, status);
832 }
833 
834 static void
835 process_write(u_int32_t id)
836 {
837 	u_int64_t off;
838 	size_t len;
839 	int r, handle, fd, ret, status;
840 	u_char *data;
841 
842 	if ((r = get_handle(iqueue, &handle)) != 0 ||
843 	    (r = sshbuf_get_u64(iqueue, &off)) != 0 ||
844 	    (r = sshbuf_get_string(iqueue, &data, &len)) != 0)
845 		fatal_fr(r, "parse");
846 
847 	debug("request %u: write \"%s\" (handle %d) off %llu len %zu",
848 	    id, handle_to_name(handle), handle, (unsigned long long)off, len);
849 	fd = handle_to_fd(handle);
850 
851 	if (fd < 0)
852 		status = SSH2_FX_FAILURE;
853 	else {
854 		if (!(handle_to_flags(handle) & O_APPEND) &&
855 		    lseek(fd, off, SEEK_SET) == -1) {
856 			status = errno_to_portable(errno);
857 			error_f("seek \"%.100s\": %s", handle_to_name(handle),
858 			    strerror(errno));
859 		} else {
860 /* XXX ATOMICIO ? */
861 			ret = write(fd, data, len);
862 			if (ret == -1) {
863 				status = errno_to_portable(errno);
864 				error_f("write \"%.100s\": %s",
865 				    handle_to_name(handle), strerror(errno));
866 			} else if ((size_t)ret == len) {
867 				status = SSH2_FX_OK;
868 				handle_update_write(handle, ret);
869 			} else {
870 				debug2_f("nothing at all written");
871 				status = SSH2_FX_FAILURE;
872 			}
873 		}
874 	}
875 	send_status(id, status);
876 	free(data);
877 }
878 
879 static void
880 process_do_stat(u_int32_t id, int do_lstat)
881 {
882 	Attrib a;
883 	struct stat st;
884 	char *name;
885 	int r, status = SSH2_FX_FAILURE;
886 
887 	if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0)
888 		fatal_fr(r, "parse");
889 
890 	debug3("request %u: %sstat", id, do_lstat ? "l" : "");
891 	verbose("%sstat name \"%s\"", do_lstat ? "l" : "", name);
892 	r = do_lstat ? lstat(name, &st) : stat(name, &st);
893 	if (r == -1) {
894 		status = errno_to_portable(errno);
895 	} else {
896 		stat_to_attrib(&st, &a);
897 		send_attrib(id, &a);
898 		status = SSH2_FX_OK;
899 	}
900 	if (status != SSH2_FX_OK)
901 		send_status(id, status);
902 	free(name);
903 }
904 
905 static void
906 process_stat(u_int32_t id)
907 {
908 	process_do_stat(id, 0);
909 }
910 
911 static void
912 process_lstat(u_int32_t id)
913 {
914 	process_do_stat(id, 1);
915 }
916 
917 static void
918 process_fstat(u_int32_t id)
919 {
920 	Attrib a;
921 	struct stat st;
922 	int fd, r, handle, status = SSH2_FX_FAILURE;
923 
924 	if ((r = get_handle(iqueue, &handle)) != 0)
925 		fatal_fr(r, "parse");
926 	debug("request %u: fstat \"%s\" (handle %u)",
927 	    id, handle_to_name(handle), handle);
928 	fd = handle_to_fd(handle);
929 	if (fd >= 0) {
930 		r = fstat(fd, &st);
931 		if (r == -1) {
932 			status = errno_to_portable(errno);
933 		} else {
934 			stat_to_attrib(&st, &a);
935 			send_attrib(id, &a);
936 			status = SSH2_FX_OK;
937 		}
938 	}
939 	if (status != SSH2_FX_OK)
940 		send_status(id, status);
941 }
942 
943 static struct timeval *
944 attrib_to_tv(const Attrib *a)
945 {
946 	static struct timeval tv[2];
947 
948 	tv[0].tv_sec = a->atime;
949 	tv[0].tv_usec = 0;
950 	tv[1].tv_sec = a->mtime;
951 	tv[1].tv_usec = 0;
952 	return tv;
953 }
954 
955 static struct timespec *
956 attrib_to_ts(const Attrib *a)
957 {
958 	static struct timespec ts[2];
959 
960 	ts[0].tv_sec = a->atime;
961 	ts[0].tv_nsec = 0;
962 	ts[1].tv_sec = a->mtime;
963 	ts[1].tv_nsec = 0;
964 	return ts;
965 }
966 
967 static void
968 process_setstat(u_int32_t id)
969 {
970 	Attrib a;
971 	char *name;
972 	int r, status = SSH2_FX_OK;
973 
974 	if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 ||
975 	    (r = decode_attrib(iqueue, &a)) != 0)
976 		fatal_fr(r, "parse");
977 
978 	debug("request %u: setstat name \"%s\"", id, name);
979 	if (a.flags & SSH2_FILEXFER_ATTR_SIZE) {
980 		logit("set \"%s\" size %llu",
981 		    name, (unsigned long long)a.size);
982 		r = truncate(name, a.size);
983 		if (r == -1)
984 			status = errno_to_portable(errno);
985 	}
986 	if (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) {
987 		logit("set \"%s\" mode %04o", name, a.perm);
988 		r = chmod(name, a.perm & 07777);
989 		if (r == -1)
990 			status = errno_to_portable(errno);
991 	}
992 	if (a.flags & SSH2_FILEXFER_ATTR_ACMODTIME) {
993 		char buf[64];
994 		time_t t = a.mtime;
995 
996 		strftime(buf, sizeof(buf), "%Y%m%d-%H:%M:%S",
997 		    localtime(&t));
998 		logit("set \"%s\" modtime %s", name, buf);
999 		r = utimes(name, attrib_to_tv(&a));
1000 		if (r == -1)
1001 			status = errno_to_portable(errno);
1002 	}
1003 	if (a.flags & SSH2_FILEXFER_ATTR_UIDGID) {
1004 		logit("set \"%s\" owner %lu group %lu", name,
1005 		    (u_long)a.uid, (u_long)a.gid);
1006 		r = chown(name, a.uid, a.gid);
1007 		if (r == -1)
1008 			status = errno_to_portable(errno);
1009 	}
1010 	send_status(id, status);
1011 	free(name);
1012 }
1013 
1014 static void
1015 process_fsetstat(u_int32_t id)
1016 {
1017 	Attrib a;
1018 	int handle, fd, r;
1019 	int status = SSH2_FX_OK;
1020 
1021 	if ((r = get_handle(iqueue, &handle)) != 0 ||
1022 	    (r = decode_attrib(iqueue, &a)) != 0)
1023 		fatal_fr(r, "parse");
1024 
1025 	debug("request %u: fsetstat handle %d", id, handle);
1026 	fd = handle_to_fd(handle);
1027 	if (fd < 0)
1028 		status = SSH2_FX_FAILURE;
1029 	else {
1030 		char *name = handle_to_name(handle);
1031 
1032 		if (a.flags & SSH2_FILEXFER_ATTR_SIZE) {
1033 			logit("set \"%s\" size %llu",
1034 			    name, (unsigned long long)a.size);
1035 			r = ftruncate(fd, a.size);
1036 			if (r == -1)
1037 				status = errno_to_portable(errno);
1038 		}
1039 		if (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) {
1040 			logit("set \"%s\" mode %04o", name, a.perm);
1041 			r = fchmod(fd, a.perm & 07777);
1042 			if (r == -1)
1043 				status = errno_to_portable(errno);
1044 		}
1045 		if (a.flags & SSH2_FILEXFER_ATTR_ACMODTIME) {
1046 			char buf[64];
1047 			time_t t = a.mtime;
1048 
1049 			strftime(buf, sizeof(buf), "%Y%m%d-%H:%M:%S",
1050 			    localtime(&t));
1051 			logit("set \"%s\" modtime %s", name, buf);
1052 			r = futimes(fd, attrib_to_tv(&a));
1053 			if (r == -1)
1054 				status = errno_to_portable(errno);
1055 		}
1056 		if (a.flags & SSH2_FILEXFER_ATTR_UIDGID) {
1057 			logit("set \"%s\" owner %lu group %lu", name,
1058 			    (u_long)a.uid, (u_long)a.gid);
1059 			r = fchown(fd, a.uid, a.gid);
1060 			if (r == -1)
1061 				status = errno_to_portable(errno);
1062 		}
1063 	}
1064 	send_status(id, status);
1065 }
1066 
1067 static void
1068 process_opendir(u_int32_t id)
1069 {
1070 	DIR *dirp = NULL;
1071 	char *path;
1072 	int r, handle, status = SSH2_FX_FAILURE;
1073 
1074 	if ((r = sshbuf_get_cstring(iqueue, &path, NULL)) != 0)
1075 		fatal_fr(r, "parse");
1076 
1077 	debug3("request %u: opendir", id);
1078 	logit("opendir \"%s\"", path);
1079 	dirp = opendir(path);
1080 	if (dirp == NULL) {
1081 		status = errno_to_portable(errno);
1082 	} else {
1083 		handle = handle_new(HANDLE_DIR, path, 0, 0, dirp);
1084 		if (handle < 0) {
1085 			closedir(dirp);
1086 		} else {
1087 			send_handle(id, handle);
1088 			status = SSH2_FX_OK;
1089 		}
1090 
1091 	}
1092 	if (status != SSH2_FX_OK)
1093 		send_status(id, status);
1094 	free(path);
1095 }
1096 
1097 static void
1098 process_readdir(u_int32_t id)
1099 {
1100 	DIR *dirp;
1101 	struct dirent *dp;
1102 	char *path;
1103 	int r, handle;
1104 
1105 	if ((r = get_handle(iqueue, &handle)) != 0)
1106 		fatal_fr(r, "parse");
1107 
1108 	debug("request %u: readdir \"%s\" (handle %d)", id,
1109 	    handle_to_name(handle), handle);
1110 	dirp = handle_to_dir(handle);
1111 	path = handle_to_name(handle);
1112 	if (dirp == NULL || path == NULL) {
1113 		send_status(id, SSH2_FX_FAILURE);
1114 	} else {
1115 		struct stat st;
1116 		char pathname[PATH_MAX];
1117 		Stat *stats;
1118 		int nstats = 10, count = 0, i;
1119 
1120 		stats = xcalloc(nstats, sizeof(Stat));
1121 		while ((dp = readdir(dirp)) != NULL) {
1122 			if (count >= nstats) {
1123 				nstats *= 2;
1124 				stats = xreallocarray(stats, nstats, sizeof(Stat));
1125 			}
1126 /* XXX OVERFLOW ? */
1127 			snprintf(pathname, sizeof pathname, "%s%s%s", path,
1128 			    strcmp(path, "/") ? "/" : "", dp->d_name);
1129 			if (lstat(pathname, &st) == -1)
1130 				continue;
1131 			stat_to_attrib(&st, &(stats[count].attrib));
1132 			stats[count].name = xstrdup(dp->d_name);
1133 			stats[count].long_name = ls_file(dp->d_name, &st, 0, 0);
1134 			count++;
1135 			/* send up to 100 entries in one message */
1136 			/* XXX check packet size instead */
1137 			if (count == 100)
1138 				break;
1139 		}
1140 		if (count > 0) {
1141 			send_names(id, count, stats);
1142 			for (i = 0; i < count; i++) {
1143 				free(stats[i].name);
1144 				free(stats[i].long_name);
1145 			}
1146 		} else {
1147 			send_status(id, SSH2_FX_EOF);
1148 		}
1149 		free(stats);
1150 	}
1151 }
1152 
1153 static void
1154 process_remove(u_int32_t id)
1155 {
1156 	char *name;
1157 	int r, status = SSH2_FX_FAILURE;
1158 
1159 	if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0)
1160 		fatal_fr(r, "parse");
1161 
1162 	debug3("request %u: remove", id);
1163 	logit("remove name \"%s\"", name);
1164 	r = unlink(name);
1165 	status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1166 	send_status(id, status);
1167 	free(name);
1168 }
1169 
1170 static void
1171 process_mkdir(u_int32_t id)
1172 {
1173 	Attrib a;
1174 	char *name;
1175 	int r, mode, status = SSH2_FX_FAILURE;
1176 
1177 	if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 ||
1178 	    (r = decode_attrib(iqueue, &a)) != 0)
1179 		fatal_fr(r, "parse");
1180 
1181 	mode = (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ?
1182 	    a.perm & 07777 : 0777;
1183 	debug3("request %u: mkdir", id);
1184 	logit("mkdir name \"%s\" mode 0%o", name, mode);
1185 	r = mkdir(name, mode);
1186 	status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1187 	send_status(id, status);
1188 	free(name);
1189 }
1190 
1191 static void
1192 process_rmdir(u_int32_t id)
1193 {
1194 	char *name;
1195 	int r, status;
1196 
1197 	if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0)
1198 		fatal_fr(r, "parse");
1199 
1200 	debug3("request %u: rmdir", id);
1201 	logit("rmdir name \"%s\"", name);
1202 	r = rmdir(name);
1203 	status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1204 	send_status(id, status);
1205 	free(name);
1206 }
1207 
1208 static void
1209 process_realpath(u_int32_t id)
1210 {
1211 	char resolvedname[PATH_MAX];
1212 	char *path;
1213 	int r;
1214 
1215 	if ((r = sshbuf_get_cstring(iqueue, &path, NULL)) != 0)
1216 		fatal_fr(r, "parse");
1217 
1218 	if (path[0] == '\0') {
1219 		free(path);
1220 		path = xstrdup(".");
1221 	}
1222 	debug3("request %u: realpath", id);
1223 	verbose("realpath \"%s\"", path);
1224 	if (sftp_realpath(path, resolvedname) == NULL) {
1225 		send_status(id, errno_to_portable(errno));
1226 	} else {
1227 		Stat s;
1228 		attrib_clear(&s.attrib);
1229 		s.name = s.long_name = resolvedname;
1230 		send_names(id, 1, &s);
1231 	}
1232 	free(path);
1233 }
1234 
1235 static void
1236 process_rename(u_int32_t id)
1237 {
1238 	char *oldpath, *newpath;
1239 	int r, status;
1240 	struct stat sb;
1241 
1242 	if ((r = sshbuf_get_cstring(iqueue, &oldpath, NULL)) != 0 ||
1243 	    (r = sshbuf_get_cstring(iqueue, &newpath, NULL)) != 0)
1244 		fatal_fr(r, "parse");
1245 
1246 	debug3("request %u: rename", id);
1247 	logit("rename old \"%s\" new \"%s\"", oldpath, newpath);
1248 	status = SSH2_FX_FAILURE;
1249 	if (lstat(oldpath, &sb) == -1)
1250 		status = errno_to_portable(errno);
1251 	else if (S_ISREG(sb.st_mode)) {
1252 		/* Race-free rename of regular files */
1253 		if (link(oldpath, newpath) == -1) {
1254 			if (errno == EOPNOTSUPP) {
1255 				struct stat st;
1256 
1257 				/*
1258 				 * fs doesn't support links, so fall back to
1259 				 * stat+rename.  This is racy.
1260 				 */
1261 				if (stat(newpath, &st) == -1) {
1262 					if (rename(oldpath, newpath) == -1)
1263 						status =
1264 						    errno_to_portable(errno);
1265 					else
1266 						status = SSH2_FX_OK;
1267 				}
1268 			} else {
1269 				status = errno_to_portable(errno);
1270 			}
1271 		} else if (unlink(oldpath) == -1) {
1272 			status = errno_to_portable(errno);
1273 			/* clean spare link */
1274 			unlink(newpath);
1275 		} else
1276 			status = SSH2_FX_OK;
1277 	} else if (stat(newpath, &sb) == -1) {
1278 		if (rename(oldpath, newpath) == -1)
1279 			status = errno_to_portable(errno);
1280 		else
1281 			status = SSH2_FX_OK;
1282 	}
1283 	send_status(id, status);
1284 	free(oldpath);
1285 	free(newpath);
1286 }
1287 
1288 static void
1289 process_readlink(u_int32_t id)
1290 {
1291 	int r, len;
1292 	char buf[PATH_MAX];
1293 	char *path;
1294 
1295 	if ((r = sshbuf_get_cstring(iqueue, &path, NULL)) != 0)
1296 		fatal_fr(r, "parse");
1297 
1298 	debug3("request %u: readlink", id);
1299 	verbose("readlink \"%s\"", path);
1300 	if ((len = readlink(path, buf, sizeof(buf) - 1)) == -1)
1301 		send_status(id, errno_to_portable(errno));
1302 	else {
1303 		Stat s;
1304 
1305 		buf[len] = '\0';
1306 		attrib_clear(&s.attrib);
1307 		s.name = s.long_name = buf;
1308 		send_names(id, 1, &s);
1309 	}
1310 	free(path);
1311 }
1312 
1313 static void
1314 process_symlink(u_int32_t id)
1315 {
1316 	char *oldpath, *newpath;
1317 	int r, status;
1318 
1319 	if ((r = sshbuf_get_cstring(iqueue, &oldpath, NULL)) != 0 ||
1320 	    (r = sshbuf_get_cstring(iqueue, &newpath, NULL)) != 0)
1321 		fatal_fr(r, "parse");
1322 
1323 	debug3("request %u: symlink", id);
1324 	logit("symlink old \"%s\" new \"%s\"", oldpath, newpath);
1325 	/* this will fail if 'newpath' exists */
1326 	r = symlink(oldpath, newpath);
1327 	status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1328 	send_status(id, status);
1329 	free(oldpath);
1330 	free(newpath);
1331 }
1332 
1333 static void
1334 process_extended_posix_rename(u_int32_t id)
1335 {
1336 	char *oldpath, *newpath;
1337 	int r, status;
1338 
1339 	if ((r = sshbuf_get_cstring(iqueue, &oldpath, NULL)) != 0 ||
1340 	    (r = sshbuf_get_cstring(iqueue, &newpath, NULL)) != 0)
1341 		fatal_fr(r, "parse");
1342 
1343 	debug3("request %u: posix-rename", id);
1344 	logit("posix-rename old \"%s\" new \"%s\"", oldpath, newpath);
1345 	r = rename(oldpath, newpath);
1346 	status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1347 	send_status(id, status);
1348 	free(oldpath);
1349 	free(newpath);
1350 }
1351 
1352 static void
1353 process_extended_statvfs(u_int32_t id)
1354 {
1355 	char *path;
1356 	struct statvfs st;
1357 	int r;
1358 
1359 	if ((r = sshbuf_get_cstring(iqueue, &path, NULL)) != 0)
1360 		fatal_fr(r, "parse");
1361 	debug3("request %u: statvfs", id);
1362 	logit("statvfs \"%s\"", path);
1363 
1364 	if (statvfs(path, &st) != 0)
1365 		send_status(id, errno_to_portable(errno));
1366 	else
1367 		send_statvfs(id, &st);
1368 	free(path);
1369 }
1370 
1371 static void
1372 process_extended_fstatvfs(u_int32_t id)
1373 {
1374 	int r, handle, fd;
1375 	struct statvfs st;
1376 
1377 	if ((r = get_handle(iqueue, &handle)) != 0)
1378 		fatal_fr(r, "parse");
1379 	debug("request %u: fstatvfs \"%s\" (handle %u)",
1380 	    id, handle_to_name(handle), handle);
1381 	if ((fd = handle_to_fd(handle)) < 0) {
1382 		send_status(id, SSH2_FX_FAILURE);
1383 		return;
1384 	}
1385 	if (fstatvfs(fd, &st) != 0)
1386 		send_status(id, errno_to_portable(errno));
1387 	else
1388 		send_statvfs(id, &st);
1389 }
1390 
1391 static void
1392 process_extended_hardlink(u_int32_t id)
1393 {
1394 	char *oldpath, *newpath;
1395 	int r, status;
1396 
1397 	if ((r = sshbuf_get_cstring(iqueue, &oldpath, NULL)) != 0 ||
1398 	    (r = sshbuf_get_cstring(iqueue, &newpath, NULL)) != 0)
1399 		fatal_fr(r, "parse");
1400 
1401 	debug3("request %u: hardlink", id);
1402 	logit("hardlink old \"%s\" new \"%s\"", oldpath, newpath);
1403 	r = link(oldpath, newpath);
1404 	status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1405 	send_status(id, status);
1406 	free(oldpath);
1407 	free(newpath);
1408 }
1409 
1410 static void
1411 process_extended_fsync(u_int32_t id)
1412 {
1413 	int handle, fd, r, status = SSH2_FX_OP_UNSUPPORTED;
1414 
1415 	if ((r = get_handle(iqueue, &handle)) != 0)
1416 		fatal_fr(r, "parse");
1417 	debug3("request %u: fsync (handle %u)", id, handle);
1418 	verbose("fsync \"%s\"", handle_to_name(handle));
1419 	if ((fd = handle_to_fd(handle)) < 0)
1420 		status = SSH2_FX_NO_SUCH_FILE;
1421 	else if (handle_is_ok(handle, HANDLE_FILE)) {
1422 		r = fsync(fd);
1423 		status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1424 	}
1425 	send_status(id, status);
1426 }
1427 
1428 static void
1429 process_extended_lsetstat(u_int32_t id)
1430 {
1431 	Attrib a;
1432 	char *name;
1433 	int r, status = SSH2_FX_OK;
1434 
1435 	if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 ||
1436 	    (r = decode_attrib(iqueue, &a)) != 0)
1437 		fatal_fr(r, "parse");
1438 
1439 	debug("request %u: lsetstat name \"%s\"", id, name);
1440 	if (a.flags & SSH2_FILEXFER_ATTR_SIZE) {
1441 		/* nonsensical for links */
1442 		status = SSH2_FX_BAD_MESSAGE;
1443 		goto out;
1444 	}
1445 	if (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) {
1446 		logit("set \"%s\" mode %04o", name, a.perm);
1447 		r = fchmodat(AT_FDCWD, name,
1448 		    a.perm & 07777, AT_SYMLINK_NOFOLLOW);
1449 		if (r == -1)
1450 			status = errno_to_portable(errno);
1451 	}
1452 	if (a.flags & SSH2_FILEXFER_ATTR_ACMODTIME) {
1453 		char buf[64];
1454 		time_t t = a.mtime;
1455 
1456 		strftime(buf, sizeof(buf), "%Y%m%d-%H:%M:%S",
1457 		    localtime(&t));
1458 		logit("set \"%s\" modtime %s", name, buf);
1459 		r = utimensat(AT_FDCWD, name,
1460 		    attrib_to_ts(&a), AT_SYMLINK_NOFOLLOW);
1461 		if (r == -1)
1462 			status = errno_to_portable(errno);
1463 	}
1464 	if (a.flags & SSH2_FILEXFER_ATTR_UIDGID) {
1465 		logit("set \"%s\" owner %lu group %lu", name,
1466 		    (u_long)a.uid, (u_long)a.gid);
1467 		r = fchownat(AT_FDCWD, name, a.uid, a.gid,
1468 		    AT_SYMLINK_NOFOLLOW);
1469 		if (r == -1)
1470 			status = errno_to_portable(errno);
1471 	}
1472  out:
1473 	send_status(id, status);
1474 	free(name);
1475 }
1476 
1477 static void
1478 process_extended_limits(u_int32_t id)
1479 {
1480 	struct sshbuf *msg;
1481 	int r;
1482 	uint64_t nfiles = 0;
1483 	struct rlimit rlim;
1484 
1485 	debug("request %u: limits", id);
1486 
1487 	if (getrlimit(RLIMIT_NOFILE, &rlim) != -1 && rlim.rlim_cur > 5)
1488 		nfiles = rlim.rlim_cur - 5; /* stdio(3) + syslog + spare */
1489 
1490 	if ((msg = sshbuf_new()) == NULL)
1491 		fatal_f("sshbuf_new failed");
1492 	if ((r = sshbuf_put_u8(msg, SSH2_FXP_EXTENDED_REPLY)) != 0 ||
1493 	    (r = sshbuf_put_u32(msg, id)) != 0 ||
1494 	    /* max-packet-length */
1495 	    (r = sshbuf_put_u64(msg, SFTP_MAX_MSG_LENGTH)) != 0 ||
1496 	    /* max-read-length */
1497 	    (r = sshbuf_put_u64(msg, SFTP_MAX_READ_LENGTH)) != 0 ||
1498 	    /* max-write-length */
1499 	    (r = sshbuf_put_u64(msg, SFTP_MAX_MSG_LENGTH - 1024)) != 0 ||
1500 	    /* max-open-handles */
1501 	    (r = sshbuf_put_u64(msg, nfiles)) != 0)
1502 		fatal_fr(r, "compose");
1503 	send_msg(msg);
1504 	sshbuf_free(msg);
1505 }
1506 
1507 static void
1508 process_extended_expand(u_int32_t id)
1509 {
1510 	char cwd[PATH_MAX], resolvedname[PATH_MAX];
1511 	char *path, *npath;
1512 	int r;
1513 	Stat s;
1514 
1515 	if ((r = sshbuf_get_cstring(iqueue, &path, NULL)) != 0)
1516 		fatal_fr(r, "parse");
1517 	if (getcwd(cwd, sizeof(cwd)) == NULL) {
1518 		send_status(id, errno_to_portable(errno));
1519 		goto out;
1520 	}
1521 
1522 	debug3("request %u: expand, original \"%s\"", id, path);
1523 	if (path[0] == '\0') {
1524 		/* empty path */
1525 		free(path);
1526 		path = xstrdup(".");
1527 	} else if (*path == '~') {
1528 		/* ~ expand path */
1529 		/* Special-case for "~" and "~/" to respect homedir flag */
1530 		if (strcmp(path, "~") == 0) {
1531 			free(path);
1532 			path = xstrdup(cwd);
1533 		} else if (strncmp(path, "~/", 2) == 0) {
1534 			npath = xstrdup(path + 2);
1535 			free(path);
1536 			xasprintf(&path, "%s/%s", cwd, npath);
1537 			free(npath);
1538 		} else {
1539 			/* ~user expansions */
1540 			if (tilde_expand(path, pw->pw_uid, &npath) != 0) {
1541 				send_status_errmsg(id,
1542 				    errno_to_portable(ENOENT), "no such user");
1543 				goto out;
1544 			}
1545 			free(path);
1546 			path = npath;
1547 		}
1548 	} else if (*path != '/') {
1549 		/* relative path */
1550 		xasprintf(&npath, "%s/%s", cwd, path);
1551 		free(path);
1552 		path = npath;
1553 	}
1554 	verbose("expand \"%s\"", path);
1555 	if (sftp_realpath(path, resolvedname) == NULL) {
1556 		send_status(id, errno_to_portable(errno));
1557 		goto out;
1558 	}
1559 	attrib_clear(&s.attrib);
1560 	s.name = s.long_name = resolvedname;
1561 	send_names(id, 1, &s);
1562  out:
1563 	free(path);
1564 }
1565 
1566 static void
1567 process_extended_copy_data(u_int32_t id)
1568 {
1569 	u_char buf[64*1024];
1570 	int read_handle, read_fd, write_handle, write_fd;
1571 	u_int64_t len, read_off, read_len, write_off;
1572 	int r, copy_until_eof, status = SSH2_FX_OP_UNSUPPORTED;
1573 	size_t ret;
1574 
1575 	if ((r = get_handle(iqueue, &read_handle)) != 0 ||
1576 	    (r = sshbuf_get_u64(iqueue, &read_off)) != 0 ||
1577 	    (r = sshbuf_get_u64(iqueue, &read_len)) != 0 ||
1578 	    (r = get_handle(iqueue, &write_handle)) != 0 ||
1579 	    (r = sshbuf_get_u64(iqueue, &write_off)) != 0)
1580 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1581 
1582 	debug("request %u: copy-data from \"%s\" (handle %d) off %llu len %llu "
1583 	    "to \"%s\" (handle %d) off %llu",
1584 	    id, handle_to_name(read_handle), read_handle,
1585 	    (unsigned long long)read_off, (unsigned long long)read_len,
1586 	    handle_to_name(write_handle), write_handle,
1587 	    (unsigned long long)write_off);
1588 
1589 	/* For read length of 0, we read until EOF. */
1590 	if (read_len == 0) {
1591 		read_len = (u_int64_t)-1 - read_off;
1592 		copy_until_eof = 1;
1593 	} else
1594 		copy_until_eof = 0;
1595 
1596 	read_fd = handle_to_fd(read_handle);
1597 	write_fd = handle_to_fd(write_handle);
1598 
1599 	/* Disallow reading & writing to the same handle or same path or dirs */
1600 	if (read_handle == write_handle || read_fd < 0 || write_fd < 0 ||
1601 	    !strcmp(handle_to_name(read_handle), handle_to_name(write_handle))) {
1602 		status = SSH2_FX_FAILURE;
1603 		goto out;
1604 	}
1605 
1606 	if (lseek(read_fd, read_off, SEEK_SET) < 0) {
1607 		status = errno_to_portable(errno);
1608 		error("%s: read_seek failed", __func__);
1609 		goto out;
1610 	}
1611 
1612 	if ((handle_to_flags(write_handle) & O_APPEND) == 0 &&
1613 	    lseek(write_fd, write_off, SEEK_SET) < 0) {
1614 		status = errno_to_portable(errno);
1615 		error("%s: write_seek failed", __func__);
1616 		goto out;
1617 	}
1618 
1619 	/* Process the request in chunks. */
1620 	while (read_len > 0 || copy_until_eof) {
1621 		len = MINIMUM(sizeof(buf), read_len);
1622 		read_len -= len;
1623 
1624 		ret = atomicio(read, read_fd, buf, len);
1625 		if (ret == 0 && errno == EPIPE) {
1626 			status = copy_until_eof ? SSH2_FX_OK : SSH2_FX_EOF;
1627 			break;
1628 		} else if (ret == 0) {
1629 			status = errno_to_portable(errno);
1630 			error("%s: read failed: %s", __func__, strerror(errno));
1631 			break;
1632 		}
1633 		len = ret;
1634 		handle_update_read(read_handle, len);
1635 
1636 		ret = atomicio(vwrite, write_fd, buf, len);
1637 		if (ret != len) {
1638 			status = errno_to_portable(errno);
1639 			error("%s: write failed: %llu != %llu: %s", __func__,
1640 			    (unsigned long long)ret, (unsigned long long)len,
1641 			    strerror(errno));
1642 			break;
1643 		}
1644 		handle_update_write(write_handle, len);
1645 	}
1646 
1647 	if (read_len == 0)
1648 		status = SSH2_FX_OK;
1649 
1650  out:
1651 	send_status(id, status);
1652 }
1653 
1654 static void
1655 process_extended(u_int32_t id)
1656 {
1657 	char *request;
1658 	int r;
1659 	const struct sftp_handler *exthand;
1660 
1661 	if ((r = sshbuf_get_cstring(iqueue, &request, NULL)) != 0)
1662 		fatal_fr(r, "parse");
1663 	if ((exthand = extended_handler_byname(request)) == NULL) {
1664 		error("Unknown extended request \"%.100s\"", request);
1665 		send_status(id, SSH2_FX_OP_UNSUPPORTED);	/* MUST */
1666 	} else {
1667 		if (!request_permitted(exthand))
1668 			send_status(id, SSH2_FX_PERMISSION_DENIED);
1669 		else
1670 			exthand->handler(id);
1671 	}
1672 	free(request);
1673 }
1674 
1675 /* stolen from ssh-agent */
1676 
1677 static void
1678 process(void)
1679 {
1680 	u_int msg_len;
1681 	u_int buf_len;
1682 	u_int consumed;
1683 	u_char type;
1684 	const u_char *cp;
1685 	int i, r;
1686 	u_int32_t id;
1687 
1688 	buf_len = sshbuf_len(iqueue);
1689 	if (buf_len < 5)
1690 		return;		/* Incomplete message. */
1691 	cp = sshbuf_ptr(iqueue);
1692 	msg_len = get_u32(cp);
1693 	if (msg_len > SFTP_MAX_MSG_LENGTH) {
1694 		error("bad message from %s local user %s",
1695 		    client_addr, pw->pw_name);
1696 		sftp_server_cleanup_exit(11);
1697 	}
1698 	if (buf_len < msg_len + 4)
1699 		return;
1700 	if ((r = sshbuf_consume(iqueue, 4)) != 0)
1701 		fatal_fr(r, "consume");
1702 	buf_len -= 4;
1703 	if ((r = sshbuf_get_u8(iqueue, &type)) != 0)
1704 		fatal_fr(r, "parse type");
1705 
1706 	switch (type) {
1707 	case SSH2_FXP_INIT:
1708 		process_init();
1709 		init_done = 1;
1710 		break;
1711 	case SSH2_FXP_EXTENDED:
1712 		if (!init_done)
1713 			fatal("Received extended request before init");
1714 		if ((r = sshbuf_get_u32(iqueue, &id)) != 0)
1715 			fatal_fr(r, "parse extended ID");
1716 		process_extended(id);
1717 		break;
1718 	default:
1719 		if (!init_done)
1720 			fatal("Received %u request before init", type);
1721 		if ((r = sshbuf_get_u32(iqueue, &id)) != 0)
1722 			fatal_fr(r, "parse ID");
1723 		for (i = 0; handlers[i].handler != NULL; i++) {
1724 			if (type == handlers[i].type) {
1725 				if (!request_permitted(&handlers[i])) {
1726 					send_status(id,
1727 					    SSH2_FX_PERMISSION_DENIED);
1728 				} else {
1729 					handlers[i].handler(id);
1730 				}
1731 				break;
1732 			}
1733 		}
1734 		if (handlers[i].handler == NULL)
1735 			error("Unknown message %u", type);
1736 	}
1737 	/* discard the remaining bytes from the current packet */
1738 	if (buf_len < sshbuf_len(iqueue)) {
1739 		error("iqueue grew unexpectedly");
1740 		sftp_server_cleanup_exit(255);
1741 	}
1742 	consumed = buf_len - sshbuf_len(iqueue);
1743 	if (msg_len < consumed) {
1744 		error("msg_len %u < consumed %u", msg_len, consumed);
1745 		sftp_server_cleanup_exit(255);
1746 	}
1747 	if (msg_len > consumed &&
1748 	    (r = sshbuf_consume(iqueue, msg_len - consumed)) != 0)
1749 		fatal_fr(r, "consume");
1750 }
1751 
1752 /* Cleanup handler that logs active handles upon normal exit */
1753 void
1754 sftp_server_cleanup_exit(int i)
1755 {
1756 	if (pw != NULL && client_addr != NULL) {
1757 		handle_log_exit();
1758 		logit("session closed for local user %s from [%s]",
1759 		    pw->pw_name, client_addr);
1760 	}
1761 	_exit(i);
1762 }
1763 
1764 static void
1765 sftp_server_usage(void)
1766 {
1767 	extern char *__progname;
1768 
1769 	fprintf(stderr,
1770 	    "usage: %s [-ehR] [-d start_directory] [-f log_facility] "
1771 	    "[-l log_level]\n\t[-P denied_requests] "
1772 	    "[-p allowed_requests] [-u umask]\n"
1773 	    "       %s -Q protocol_feature\n",
1774 	    __progname, __progname);
1775 	exit(1);
1776 }
1777 
1778 int
1779 sftp_server_main(int argc, char **argv, struct passwd *user_pw)
1780 {
1781 	int i, r, in, out, ch, skipargs = 0, log_stderr = 0;
1782 	ssize_t len, olen;
1783 	SyslogFacility log_facility = SYSLOG_FACILITY_AUTH;
1784 	char *cp, *homedir = NULL, uidstr[32], buf[4*4096];
1785 	long mask;
1786 
1787 	extern char *optarg;
1788 	extern char *__progname;
1789 
1790 	log_init(__progname, log_level, log_facility, log_stderr);
1791 
1792 	pw = pwcopy(user_pw);
1793 
1794 	while (!skipargs && (ch = getopt(argc, argv,
1795 	    "d:f:l:P:p:Q:u:cehR")) != -1) {
1796 		switch (ch) {
1797 		case 'Q':
1798 			if (strcasecmp(optarg, "requests") != 0) {
1799 				fprintf(stderr, "Invalid query type\n");
1800 				exit(1);
1801 			}
1802 			for (i = 0; handlers[i].handler != NULL; i++)
1803 				printf("%s\n", handlers[i].name);
1804 			for (i = 0; extended_handlers[i].handler != NULL; i++)
1805 				printf("%s\n", extended_handlers[i].name);
1806 			exit(0);
1807 			break;
1808 		case 'R':
1809 			readonly = 1;
1810 			break;
1811 		case 'c':
1812 			/*
1813 			 * Ignore all arguments if we are invoked as a
1814 			 * shell using "sftp-server -c command"
1815 			 */
1816 			skipargs = 1;
1817 			break;
1818 		case 'e':
1819 			log_stderr = 1;
1820 			break;
1821 		case 'l':
1822 			log_level = log_level_number(optarg);
1823 			if (log_level == SYSLOG_LEVEL_NOT_SET)
1824 				error("Invalid log level \"%s\"", optarg);
1825 			break;
1826 		case 'f':
1827 			log_facility = log_facility_number(optarg);
1828 			if (log_facility == SYSLOG_FACILITY_NOT_SET)
1829 				error("Invalid log facility \"%s\"", optarg);
1830 			break;
1831 		case 'd':
1832 			cp = tilde_expand_filename(optarg, user_pw->pw_uid);
1833 			snprintf(uidstr, sizeof(uidstr), "%llu",
1834 			    (unsigned long long)pw->pw_uid);
1835 			homedir = percent_expand(cp, "d", user_pw->pw_dir,
1836 			    "u", user_pw->pw_name, "U", uidstr, (char *)NULL);
1837 			free(cp);
1838 			break;
1839 		case 'p':
1840 			if (request_allowlist != NULL)
1841 				fatal("Permitted requests already set");
1842 			request_allowlist = xstrdup(optarg);
1843 			break;
1844 		case 'P':
1845 			if (request_denylist != NULL)
1846 				fatal("Refused requests already set");
1847 			request_denylist = xstrdup(optarg);
1848 			break;
1849 		case 'u':
1850 			errno = 0;
1851 			mask = strtol(optarg, &cp, 8);
1852 			if (mask < 0 || mask > 0777 || *cp != '\0' ||
1853 			    cp == optarg || (mask == 0 && errno != 0))
1854 				fatal("Invalid umask \"%s\"", optarg);
1855 			(void)umask((mode_t)mask);
1856 			break;
1857 		case 'h':
1858 		default:
1859 			sftp_server_usage();
1860 		}
1861 	}
1862 
1863 	log_init(__progname, log_level, log_facility, log_stderr);
1864 
1865 	if ((cp = getenv("SSH_CONNECTION")) != NULL) {
1866 		client_addr = xstrdup(cp);
1867 		if ((cp = strchr(client_addr, ' ')) == NULL) {
1868 			error("Malformed SSH_CONNECTION variable: \"%s\"",
1869 			    getenv("SSH_CONNECTION"));
1870 			sftp_server_cleanup_exit(255);
1871 		}
1872 		*cp = '\0';
1873 	} else
1874 		client_addr = xstrdup("UNKNOWN");
1875 
1876 	logit("session opened for local user %s from [%s]",
1877 	    pw->pw_name, client_addr);
1878 
1879 	in = STDIN_FILENO;
1880 	out = STDOUT_FILENO;
1881 
1882 	if ((iqueue = sshbuf_new()) == NULL)
1883 		fatal_f("sshbuf_new failed");
1884 	if ((oqueue = sshbuf_new()) == NULL)
1885 		fatal_f("sshbuf_new failed");
1886 
1887 	if (homedir != NULL) {
1888 		if (chdir(homedir) != 0) {
1889 			error("chdir to \"%s\" failed: %s", homedir,
1890 			    strerror(errno));
1891 		}
1892 	}
1893 
1894 	for (;;) {
1895 		struct pollfd pfd[2];
1896 
1897 		memset(pfd, 0, sizeof pfd);
1898 		pfd[0].fd = pfd[1].fd = -1;
1899 
1900 		/*
1901 		 * Ensure that we can read a full buffer and handle
1902 		 * the worst-case length packet it can generate,
1903 		 * otherwise apply backpressure by stopping reads.
1904 		 */
1905 		if ((r = sshbuf_check_reserve(iqueue, sizeof(buf))) == 0 &&
1906 		    (r = sshbuf_check_reserve(oqueue,
1907 		    SFTP_MAX_MSG_LENGTH)) == 0) {
1908 			pfd[0].fd = in;
1909 			pfd[0].events = POLLIN;
1910 		}
1911 		else if (r != SSH_ERR_NO_BUFFER_SPACE)
1912 			fatal_fr(r, "reserve");
1913 
1914 		olen = sshbuf_len(oqueue);
1915 		if (olen > 0) {
1916 			pfd[1].fd = out;
1917 			pfd[1].events = POLLOUT;
1918 		}
1919 
1920 		if (poll(pfd, 2, -1) == -1) {
1921 			if (errno == EINTR)
1922 				continue;
1923 			error("poll: %s", strerror(errno));
1924 			sftp_server_cleanup_exit(2);
1925 		}
1926 
1927 		/* copy stdin to iqueue */
1928 		if (pfd[0].revents & (POLLIN|POLLHUP)) {
1929 			len = read(in, buf, sizeof buf);
1930 			if (len == 0) {
1931 				debug("read eof");
1932 				sftp_server_cleanup_exit(0);
1933 			} else if (len == -1) {
1934 				if (errno != EAGAIN && errno != EINTR) {
1935 					error("read: %s", strerror(errno));
1936 					sftp_server_cleanup_exit(1);
1937 				}
1938 			} else if ((r = sshbuf_put(iqueue, buf, len)) != 0)
1939 				fatal_fr(r, "sshbuf_put");
1940 		}
1941 		/* send oqueue to stdout */
1942 		if (pfd[1].revents & (POLLOUT|POLLHUP)) {
1943 			len = write(out, sshbuf_ptr(oqueue), olen);
1944 			if (len == 0 || (len == -1 && errno == EPIPE)) {
1945 				debug("write eof");
1946 				sftp_server_cleanup_exit(0);
1947 			} else if (len == -1) {
1948 				sftp_server_cleanup_exit(1);
1949 				if (errno != EAGAIN && errno != EINTR) {
1950 					error("write: %s", strerror(errno));
1951 					sftp_server_cleanup_exit(1);
1952 				}
1953 			} else if ((r = sshbuf_consume(oqueue, len)) != 0)
1954 				fatal_fr(r, "consume");
1955 		}
1956 
1957 		/*
1958 		 * Process requests from client if we can fit the results
1959 		 * into the output buffer, otherwise stop processing input
1960 		 * and let the output queue drain.
1961 		 */
1962 		r = sshbuf_check_reserve(oqueue, SFTP_MAX_MSG_LENGTH);
1963 		if (r == 0)
1964 			process();
1965 		else if (r != SSH_ERR_NO_BUFFER_SPACE)
1966 			fatal_fr(r, "reserve");
1967 	}
1968 }
1969