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