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