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