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