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