1 /*	$NetBSD: sftp-server.c,v 1.12 2015/07/03 01:00:00 christos Exp $	*/
2 /* $OpenBSD: sftp-server.c,v 1.106 2015/04/24 01:36:01 deraadt 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.12 2015/07/03 01:00:00 christos Exp $");
21 #include <sys/param.h>	/* MIN */
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <sys/time.h>
25 #include <sys/mount.h>
26 #include <sys/statvfs.h>
27 
28 #include <dirent.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <string.h>
34 #include <pwd.h>
35 #include <time.h>
36 #include <unistd.h>
37 #include <stdarg.h>
38 
39 #include "xmalloc.h"
40 #include "sshbuf.h"
41 #include "ssherr.h"
42 #include "log.h"
43 #include "misc.h"
44 #include "match.h"
45 #include "uidswap.h"
46 
47 #include "sftp.h"
48 #include "sftp-common.h"
49 
50 /* Our verbosity */
51 static LogLevel log_level = SYSLOG_LEVEL_ERROR;
52 
53 /* Our client */
54 static struct passwd *pw = NULL;
55 static char *client_addr = NULL;
56 
57 /* input and output queue */
58 struct sshbuf *iqueue;
59 struct sshbuf *oqueue;
60 
61 /* Version of client */
62 static u_int version;
63 
64 /* SSH2_FXP_INIT received */
65 static int init_done;
66 
67 /* Disable writes */
68 static int readonly;
69 
70 /* Requests that are allowed/denied */
71 static char *request_whitelist, *request_blacklist;
72 
73 /* portable attributes, etc. */
74 typedef struct Stat Stat;
75 
76 struct Stat {
77 	char *name;
78 	char *long_name;
79 	Attrib attrib;
80 };
81 
82 /* Packet handlers */
83 static void process_open(u_int32_t id);
84 static void process_close(u_int32_t id);
85 static void process_read(u_int32_t id);
86 static void process_write(u_int32_t id);
87 static void process_stat(u_int32_t id);
88 static void process_lstat(u_int32_t id);
89 static void process_fstat(u_int32_t id);
90 static void process_setstat(u_int32_t id);
91 static void process_fsetstat(u_int32_t id);
92 static void process_opendir(u_int32_t id);
93 static void process_readdir(u_int32_t id);
94 static void process_remove(u_int32_t id);
95 static void process_mkdir(u_int32_t id);
96 static void process_rmdir(u_int32_t id);
97 static void process_realpath(u_int32_t id);
98 static void process_rename(u_int32_t id);
99 static void process_readlink(u_int32_t id);
100 static void process_symlink(u_int32_t id);
101 static void process_extended_posix_rename(u_int32_t id);
102 static void process_extended_statvfs(u_int32_t id);
103 static void process_extended_fstatvfs(u_int32_t id);
104 static void process_extended_hardlink(u_int32_t id);
105 static void process_extended_fsync(u_int32_t id);
106 static void process_extended(u_int32_t id);
107 
108 struct sftp_handler {
109 	const char *name;	/* user-visible name for fine-grained perms */
110 	const char *ext_name;	/* extended request name */
111 	u_int type;		/* packet type, for non extended packets */
112 	void (*handler)(u_int32_t);
113 	int does_write;		/* if nonzero, banned for readonly mode */
114 };
115 
116 struct sftp_handler handlers[] = {
117 	/* NB. SSH2_FXP_OPEN does the readonly check in the handler itself */
118 	{ "open", NULL, SSH2_FXP_OPEN, process_open, 0 },
119 	{ "close", NULL, SSH2_FXP_CLOSE, process_close, 0 },
120 	{ "read", NULL, SSH2_FXP_READ, process_read, 0 },
121 	{ "write", NULL, SSH2_FXP_WRITE, process_write, 1 },
122 	{ "lstat", NULL, SSH2_FXP_LSTAT, process_lstat, 0 },
123 	{ "fstat", NULL, SSH2_FXP_FSTAT, process_fstat, 0 },
124 	{ "setstat", NULL, SSH2_FXP_SETSTAT, process_setstat, 1 },
125 	{ "fsetstat", NULL, SSH2_FXP_FSETSTAT, process_fsetstat, 1 },
126 	{ "opendir", NULL, SSH2_FXP_OPENDIR, process_opendir, 0 },
127 	{ "readdir", NULL, SSH2_FXP_READDIR, process_readdir, 0 },
128 	{ "remove", NULL, SSH2_FXP_REMOVE, process_remove, 1 },
129 	{ "mkdir", NULL, SSH2_FXP_MKDIR, process_mkdir, 1 },
130 	{ "rmdir", NULL, SSH2_FXP_RMDIR, process_rmdir, 1 },
131 	{ "realpath", NULL, SSH2_FXP_REALPATH, process_realpath, 0 },
132 	{ "stat", NULL, SSH2_FXP_STAT, process_stat, 0 },
133 	{ "rename", NULL, SSH2_FXP_RENAME, process_rename, 1 },
134 	{ "readlink", NULL, SSH2_FXP_READLINK, process_readlink, 0 },
135 	{ "symlink", NULL, SSH2_FXP_SYMLINK, process_symlink, 1 },
136 	{ NULL, NULL, 0, NULL, 0 }
137 };
138 
139 /* SSH2_FXP_EXTENDED submessages */
140 struct sftp_handler extended_handlers[] = {
141 	{ "posix-rename", "posix-rename@openssh.com", 0,
142 	   process_extended_posix_rename, 1 },
143 	{ "statvfs", "statvfs@openssh.com", 0, process_extended_statvfs, 0 },
144 	{ "fstatvfs", "fstatvfs@openssh.com", 0, process_extended_fstatvfs, 0 },
145 	{ "hardlink", "hardlink@openssh.com", 0, process_extended_hardlink, 1 },
146 	{ "fsync", "fsync@openssh.com", 0, process_extended_fsync, 1 },
147 	{ NULL, NULL, 0, NULL, 0 }
148 };
149 
150 static int
151 request_permitted(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_blacklist != NULL &&
160 	    ((result = match_list(h->name, request_blacklist, NULL))) != NULL) {
161 		free(result);
162 		verbose("Refusing blacklisted %s request", h->name);
163 		return 0;
164 	}
165 	if (request_whitelist != NULL &&
166 	    ((result = match_list(h->name, request_whitelist, NULL))) != NULL) {
167 		free(result);
168 		debug2("Permitting whitelisted %s request", h->name);
169 		return 1;
170 	}
171 	if (request_whitelist != NULL) {
172 		verbose("Refusing non-whitelisted %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 Handle *handles = NULL;
285 u_int num_handles = 0;
286 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, const 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("%s: buffer error: %s", __func__, ssh_err(r));
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[MIN(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("%s: sshbuf_new failed", __func__);
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("%s: buffer error: %s", __func__, ssh_err(r));
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("%s: buffer error: %s", __func__, ssh_err(r));
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("%s: sshbuf_new failed", __func__);
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("%s: buffer error: %s", __func__, ssh_err(r));
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("%s: sshbuf_new failed", __func__);
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("%s: buffer error: %s", __func__, ssh_err(r));
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("%s: buffer error: %s", __func__, ssh_err(r));
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("%s: sshbuf_new failed", __func__);
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("%s: buffer error: %s", __func__, ssh_err(r));
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("%s: sshbuf_new failed", __func__);
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("%s: buffer error: %s", __func__, ssh_err(r));
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("%s: buffer error: %s", __func__, ssh_err(r));
646 	verbose("received client version %u", version);
647 	if ((msg = sshbuf_new()) == NULL)
648 		fatal("%s: sshbuf_new failed", __func__);
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 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
667 	send_msg(msg);
668 	sshbuf_free(msg);
669 }
670 
671 static void
672 process_open(u_int32_t id)
673 {
674 	u_int32_t pflags;
675 	Attrib a;
676 	char *name;
677 	int r, handle, fd, flags, mode, status = SSH2_FX_FAILURE;
678 
679 	if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 ||
680 	    (r = sshbuf_get_u32(iqueue, &pflags)) != 0 || /* portable flags */
681 	    (r = decode_attrib(iqueue, &a)) != 0)
682 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
683 
684 	debug3("request %u: open flags %d", id, pflags);
685 	flags = flags_from_portable(pflags);
686 	mode = (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ? a.perm : 0666;
687 	logit("open \"%s\" flags %s mode 0%o",
688 	    name, string_from_portable(pflags), mode);
689 	if (readonly &&
690 	    ((flags & O_ACCMODE) == O_WRONLY ||
691 	    (flags & O_ACCMODE) == O_RDWR)) {
692 		verbose("Refusing open request in read-only mode");
693 		status = SSH2_FX_PERMISSION_DENIED;
694 	} else {
695 		fd = open(name, flags, mode);
696 		if (fd < 0) {
697 			status = errno_to_portable(errno);
698 		} else {
699 			handle = handle_new(HANDLE_FILE, name, fd, flags, NULL);
700 			if (handle < 0) {
701 				close(fd);
702 			} else {
703 				send_handle(id, handle);
704 				status = SSH2_FX_OK;
705 			}
706 		}
707 	}
708 	if (status != SSH2_FX_OK)
709 		send_status(id, status);
710 	free(name);
711 }
712 
713 static void
714 process_close(u_int32_t id)
715 {
716 	int r, handle, ret, status = SSH2_FX_FAILURE;
717 
718 	if ((r = get_handle(iqueue, &handle)) != 0)
719 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
720 
721 	debug3("request %u: close handle %u", id, handle);
722 	handle_log_close(handle, NULL);
723 	ret = handle_close(handle);
724 	status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
725 	send_status(id, status);
726 }
727 
728 static void
729 process_read(u_int32_t id)
730 {
731 	u_char buf[64*1024];
732 	u_int32_t len;
733 	int r, handle, fd, ret, status = SSH2_FX_FAILURE;
734 	u_int64_t off;
735 
736 	if ((r = get_handle(iqueue, &handle)) != 0 ||
737 	    (r = sshbuf_get_u64(iqueue, &off)) != 0 ||
738 	    (r = sshbuf_get_u32(iqueue, &len)) != 0)
739 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
740 
741 	debug("request %u: read \"%s\" (handle %d) off %llu len %d",
742 	    id, handle_to_name(handle), handle, (unsigned long long)off, len);
743 	if (len > sizeof buf) {
744 		len = sizeof buf;
745 		debug2("read change len %d", len);
746 	}
747 	fd = handle_to_fd(handle);
748 	if (fd >= 0) {
749 		if (lseek(fd, off, SEEK_SET) < 0) {
750 			error("process_read: seek failed");
751 			status = errno_to_portable(errno);
752 		} else {
753 			ret = read(fd, buf, len);
754 			if (ret < 0) {
755 				status = errno_to_portable(errno);
756 			} else if (ret == 0) {
757 				status = SSH2_FX_EOF;
758 			} else {
759 				send_data(id, buf, ret);
760 				status = SSH2_FX_OK;
761 				handle_update_read(handle, ret);
762 			}
763 		}
764 	}
765 	if (status != SSH2_FX_OK)
766 		send_status(id, status);
767 }
768 
769 static void
770 process_write(u_int32_t id)
771 {
772 	u_int64_t off;
773 	size_t len;
774 	int r, handle, fd, ret, status;
775 	u_char *data;
776 
777 	if ((r = get_handle(iqueue, &handle)) != 0 ||
778 	    (r = sshbuf_get_u64(iqueue, &off)) != 0 ||
779 	    (r = sshbuf_get_string(iqueue, &data, &len)) != 0)
780 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
781 
782 	debug("request %u: write \"%s\" (handle %d) off %llu len %zu",
783 	    id, handle_to_name(handle), handle, (unsigned long long)off, len);
784 	fd = handle_to_fd(handle);
785 
786 	if (fd < 0)
787 		status = SSH2_FX_FAILURE;
788 	else {
789 		if (!(handle_to_flags(handle) & O_APPEND) &&
790 				lseek(fd, off, SEEK_SET) < 0) {
791 			status = errno_to_portable(errno);
792 			error("process_write: seek failed");
793 		} else {
794 /* XXX ATOMICIO ? */
795 			ret = write(fd, data, len);
796 			if (ret < 0) {
797 				error("process_write: write failed");
798 				status = errno_to_portable(errno);
799 			} else if ((size_t)ret == len) {
800 				status = SSH2_FX_OK;
801 				handle_update_write(handle, ret);
802 			} else {
803 				debug2("nothing at all written");
804 				status = SSH2_FX_FAILURE;
805 			}
806 		}
807 	}
808 	send_status(id, status);
809 	free(data);
810 }
811 
812 static void
813 process_do_stat(u_int32_t id, int do_lstat)
814 {
815 	Attrib a;
816 	struct stat st;
817 	char *name;
818 	int r, status = SSH2_FX_FAILURE;
819 
820 	if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0)
821 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
822 
823 	debug3("request %u: %sstat", id, do_lstat ? "l" : "");
824 	verbose("%sstat name \"%s\"", do_lstat ? "l" : "", name);
825 	r = do_lstat ? lstat(name, &st) : stat(name, &st);
826 	if (r < 0) {
827 		status = errno_to_portable(errno);
828 	} else {
829 		stat_to_attrib(&st, &a);
830 		send_attrib(id, &a);
831 		status = SSH2_FX_OK;
832 	}
833 	if (status != SSH2_FX_OK)
834 		send_status(id, status);
835 	free(name);
836 }
837 
838 static void
839 process_stat(u_int32_t id)
840 {
841 	process_do_stat(id, 0);
842 }
843 
844 static void
845 process_lstat(u_int32_t id)
846 {
847 	process_do_stat(id, 1);
848 }
849 
850 static void
851 process_fstat(u_int32_t id)
852 {
853 	Attrib a;
854 	struct stat st;
855 	int fd, r, handle, status = SSH2_FX_FAILURE;
856 
857 	if ((r = get_handle(iqueue, &handle)) != 0)
858 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
859 	debug("request %u: fstat \"%s\" (handle %u)",
860 	    id, handle_to_name(handle), handle);
861 	fd = handle_to_fd(handle);
862 	if (fd >= 0) {
863 		r = fstat(fd, &st);
864 		if (r < 0) {
865 			status = errno_to_portable(errno);
866 		} else {
867 			stat_to_attrib(&st, &a);
868 			send_attrib(id, &a);
869 			status = SSH2_FX_OK;
870 		}
871 	}
872 	if (status != SSH2_FX_OK)
873 		send_status(id, status);
874 }
875 
876 static struct timeval *
877 attrib_to_tv(const Attrib *a)
878 {
879 	static struct timeval tv[2];
880 
881 	tv[0].tv_sec = a->atime;
882 	tv[0].tv_usec = 0;
883 	tv[1].tv_sec = a->mtime;
884 	tv[1].tv_usec = 0;
885 	return tv;
886 }
887 
888 static void
889 process_setstat(u_int32_t id)
890 {
891 	Attrib a;
892 	char *name;
893 	int r, status = SSH2_FX_OK;
894 
895 	if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 ||
896 	    (r = decode_attrib(iqueue, &a)) != 0)
897 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
898 
899 	debug("request %u: setstat name \"%s\"", id, name);
900 	if (a.flags & SSH2_FILEXFER_ATTR_SIZE) {
901 		logit("set \"%s\" size %llu",
902 		    name, (unsigned long long)a.size);
903 		r = truncate(name, a.size);
904 		if (r == -1)
905 			status = errno_to_portable(errno);
906 	}
907 	if (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) {
908 		logit("set \"%s\" mode %04o", name, a.perm);
909 		r = chmod(name, a.perm & 07777);
910 		if (r == -1)
911 			status = errno_to_portable(errno);
912 	}
913 	if (a.flags & SSH2_FILEXFER_ATTR_ACMODTIME) {
914 		char buf[64];
915 		time_t t = a.mtime;
916 
917 		strftime(buf, sizeof(buf), "%Y%m%d-%H:%M:%S",
918 		    localtime(&t));
919 		logit("set \"%s\" modtime %s", name, buf);
920 		r = utimes(name, attrib_to_tv(&a));
921 		if (r == -1)
922 			status = errno_to_portable(errno);
923 	}
924 	if (a.flags & SSH2_FILEXFER_ATTR_UIDGID) {
925 		logit("set \"%s\" owner %lu group %lu", name,
926 		    (u_long)a.uid, (u_long)a.gid);
927 		r = chown(name, a.uid, a.gid);
928 		if (r == -1)
929 			status = errno_to_portable(errno);
930 	}
931 	send_status(id, status);
932 	free(name);
933 }
934 
935 static void
936 process_fsetstat(u_int32_t id)
937 {
938 	Attrib a;
939 	int handle, fd, r;
940 	int status = SSH2_FX_OK;
941 
942 	if ((r = get_handle(iqueue, &handle)) != 0 ||
943 	    (r = decode_attrib(iqueue, &a)) != 0)
944 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
945 
946 	debug("request %u: fsetstat handle %d", id, handle);
947 	fd = handle_to_fd(handle);
948 	if (fd < 0)
949 		status = SSH2_FX_FAILURE;
950 	else {
951 		char *name = handle_to_name(handle);
952 
953 		if (a.flags & SSH2_FILEXFER_ATTR_SIZE) {
954 			logit("set \"%s\" size %llu",
955 			    name, (unsigned long long)a.size);
956 			r = ftruncate(fd, a.size);
957 			if (r == -1)
958 				status = errno_to_portable(errno);
959 		}
960 		if (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) {
961 			logit("set \"%s\" mode %04o", name, a.perm);
962 			r = fchmod(fd, a.perm & 07777);
963 			if (r == -1)
964 				status = errno_to_portable(errno);
965 		}
966 		if (a.flags & SSH2_FILEXFER_ATTR_ACMODTIME) {
967 			char buf[64];
968 			time_t t = a.mtime;
969 
970 			strftime(buf, sizeof(buf), "%Y%m%d-%H:%M:%S",
971 			    localtime(&t));
972 			logit("set \"%s\" modtime %s", name, buf);
973 			r = futimes(fd, attrib_to_tv(&a));
974 			if (r == -1)
975 				status = errno_to_portable(errno);
976 		}
977 		if (a.flags & SSH2_FILEXFER_ATTR_UIDGID) {
978 			logit("set \"%s\" owner %lu group %lu", name,
979 			    (u_long)a.uid, (u_long)a.gid);
980 			r = fchown(fd, a.uid, a.gid);
981 			if (r == -1)
982 				status = errno_to_portable(errno);
983 		}
984 	}
985 	send_status(id, status);
986 }
987 
988 static void
989 process_opendir(u_int32_t id)
990 {
991 	DIR *dirp = NULL;
992 	char *path;
993 	int r, handle, status = SSH2_FX_FAILURE;
994 
995 	if ((r = sshbuf_get_cstring(iqueue, &path, NULL)) != 0)
996 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
997 
998 	debug3("request %u: opendir", id);
999 	logit("opendir \"%s\"", path);
1000 	dirp = opendir(path);
1001 	if (dirp == NULL) {
1002 		status = errno_to_portable(errno);
1003 	} else {
1004 		handle = handle_new(HANDLE_DIR, path, 0, 0, dirp);
1005 		if (handle < 0) {
1006 			closedir(dirp);
1007 		} else {
1008 			send_handle(id, handle);
1009 			status = SSH2_FX_OK;
1010 		}
1011 
1012 	}
1013 	if (status != SSH2_FX_OK)
1014 		send_status(id, status);
1015 	free(path);
1016 }
1017 
1018 static void
1019 process_readdir(u_int32_t id)
1020 {
1021 	DIR *dirp;
1022 	struct dirent *dp;
1023 	char *path;
1024 	int r, handle;
1025 
1026 	if ((r = get_handle(iqueue, &handle)) != 0)
1027 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1028 
1029 	debug("request %u: readdir \"%s\" (handle %d)", id,
1030 	    handle_to_name(handle), handle);
1031 	dirp = handle_to_dir(handle);
1032 	path = handle_to_name(handle);
1033 	if (dirp == NULL || path == NULL) {
1034 		send_status(id, SSH2_FX_FAILURE);
1035 	} else {
1036 		struct stat st;
1037 		char pathname[PATH_MAX];
1038 		Stat *stats;
1039 		int nstats = 10, count = 0, i;
1040 
1041 		stats = xcalloc(nstats, sizeof(Stat));
1042 		while ((dp = readdir(dirp)) != NULL) {
1043 			if (count >= nstats) {
1044 				nstats *= 2;
1045 				stats = xreallocarray(stats, nstats, sizeof(Stat));
1046 			}
1047 /* XXX OVERFLOW ? */
1048 			snprintf(pathname, sizeof pathname, "%s%s%s", path,
1049 			    strcmp(path, "/") ? "/" : "", dp->d_name);
1050 			if (lstat(pathname, &st) < 0)
1051 				continue;
1052 			stat_to_attrib(&st, &(stats[count].attrib));
1053 			stats[count].name = xstrdup(dp->d_name);
1054 			stats[count].long_name = ls_file(dp->d_name, &st, 0, 0);
1055 			count++;
1056 			/* send up to 100 entries in one message */
1057 			/* XXX check packet size instead */
1058 			if (count == 100)
1059 				break;
1060 		}
1061 		if (count > 0) {
1062 			send_names(id, count, stats);
1063 			for (i = 0; i < count; i++) {
1064 				free(stats[i].name);
1065 				free(stats[i].long_name);
1066 			}
1067 		} else {
1068 			send_status(id, SSH2_FX_EOF);
1069 		}
1070 		free(stats);
1071 	}
1072 }
1073 
1074 static void
1075 process_remove(u_int32_t id)
1076 {
1077 	char *name;
1078 	int r, status = SSH2_FX_FAILURE;
1079 
1080 	if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0)
1081 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1082 
1083 	debug3("request %u: remove", id);
1084 	logit("remove name \"%s\"", name);
1085 	r = unlink(name);
1086 	status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1087 	send_status(id, status);
1088 	free(name);
1089 }
1090 
1091 static void
1092 process_mkdir(u_int32_t id)
1093 {
1094 	Attrib a;
1095 	char *name;
1096 	int r, mode, status = SSH2_FX_FAILURE;
1097 
1098 	if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 ||
1099 	    (r = decode_attrib(iqueue, &a)) != 0)
1100 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1101 
1102 	mode = (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ?
1103 	    a.perm & 07777 : 0777;
1104 	debug3("request %u: mkdir", id);
1105 	logit("mkdir name \"%s\" mode 0%o", name, mode);
1106 	r = mkdir(name, mode);
1107 	status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1108 	send_status(id, status);
1109 	free(name);
1110 }
1111 
1112 static void
1113 process_rmdir(u_int32_t id)
1114 {
1115 	char *name;
1116 	int r, status;
1117 
1118 	if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0)
1119 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1120 
1121 	debug3("request %u: rmdir", id);
1122 	logit("rmdir name \"%s\"", name);
1123 	r = rmdir(name);
1124 	status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1125 	send_status(id, status);
1126 	free(name);
1127 }
1128 
1129 static void
1130 process_realpath(u_int32_t id)
1131 {
1132 	char resolvedname[PATH_MAX];
1133 	char *path;
1134 	int r;
1135 
1136 	if ((r = sshbuf_get_cstring(iqueue, &path, NULL)) != 0)
1137 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1138 
1139 	if (path[0] == '\0') {
1140 		free(path);
1141 		path = xstrdup(".");
1142 	}
1143 	debug3("request %u: realpath", id);
1144 	verbose("realpath \"%s\"", path);
1145 	if (realpath(path, resolvedname) == NULL) {
1146 		send_status(id, errno_to_portable(errno));
1147 	} else {
1148 		Stat s;
1149 		attrib_clear(&s.attrib);
1150 		s.name = s.long_name = resolvedname;
1151 		send_names(id, 1, &s);
1152 	}
1153 	free(path);
1154 }
1155 
1156 static void
1157 process_rename(u_int32_t id)
1158 {
1159 	char *oldpath, *newpath;
1160 	int r, status;
1161 	struct stat sb;
1162 
1163 	if ((r = sshbuf_get_cstring(iqueue, &oldpath, NULL)) != 0 ||
1164 	    (r = sshbuf_get_cstring(iqueue, &newpath, NULL)) != 0)
1165 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1166 
1167 	debug3("request %u: rename", id);
1168 	logit("rename old \"%s\" new \"%s\"", oldpath, newpath);
1169 	status = SSH2_FX_FAILURE;
1170 	if (lstat(oldpath, &sb) == -1)
1171 		status = errno_to_portable(errno);
1172 	else if (S_ISREG(sb.st_mode)) {
1173 		/* Race-free rename of regular files */
1174 		if (link(oldpath, newpath) == -1) {
1175 			if (errno == EOPNOTSUPP) {
1176 				struct stat st;
1177 
1178 				/*
1179 				 * fs doesn't support links, so fall back to
1180 				 * stat+rename.  This is racy.
1181 				 */
1182 				if (stat(newpath, &st) == -1) {
1183 					if (rename(oldpath, newpath) == -1)
1184 						status =
1185 						    errno_to_portable(errno);
1186 					else
1187 						status = SSH2_FX_OK;
1188 				}
1189 			} else {
1190 				status = errno_to_portable(errno);
1191 			}
1192 		} else if (unlink(oldpath) == -1) {
1193 			status = errno_to_portable(errno);
1194 			/* clean spare link */
1195 			unlink(newpath);
1196 		} else
1197 			status = SSH2_FX_OK;
1198 	} else if (stat(newpath, &sb) == -1) {
1199 		if (rename(oldpath, newpath) == -1)
1200 			status = errno_to_portable(errno);
1201 		else
1202 			status = SSH2_FX_OK;
1203 	}
1204 	send_status(id, status);
1205 	free(oldpath);
1206 	free(newpath);
1207 }
1208 
1209 static void
1210 process_readlink(u_int32_t id)
1211 {
1212 	int r, len;
1213 	char buf[PATH_MAX];
1214 	char *path;
1215 
1216 	if ((r = sshbuf_get_cstring(iqueue, &path, NULL)) != 0)
1217 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1218 
1219 	debug3("request %u: readlink", id);
1220 	verbose("readlink \"%s\"", path);
1221 	if ((len = readlink(path, buf, sizeof(buf) - 1)) == -1)
1222 		send_status(id, errno_to_portable(errno));
1223 	else {
1224 		Stat s;
1225 
1226 		buf[len] = '\0';
1227 		attrib_clear(&s.attrib);
1228 		s.name = s.long_name = buf;
1229 		send_names(id, 1, &s);
1230 	}
1231 	free(path);
1232 }
1233 
1234 static void
1235 process_symlink(u_int32_t id)
1236 {
1237 	char *oldpath, *newpath;
1238 	int r, status;
1239 
1240 	if ((r = sshbuf_get_cstring(iqueue, &oldpath, NULL)) != 0 ||
1241 	    (r = sshbuf_get_cstring(iqueue, &newpath, NULL)) != 0)
1242 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1243 
1244 	debug3("request %u: symlink", id);
1245 	logit("symlink old \"%s\" new \"%s\"", oldpath, newpath);
1246 	/* this will fail if 'newpath' exists */
1247 	r = symlink(oldpath, newpath);
1248 	status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1249 	send_status(id, status);
1250 	free(oldpath);
1251 	free(newpath);
1252 }
1253 
1254 static void
1255 process_extended_posix_rename(u_int32_t id)
1256 {
1257 	char *oldpath, *newpath;
1258 	int r, status;
1259 
1260 	if ((r = sshbuf_get_cstring(iqueue, &oldpath, NULL)) != 0 ||
1261 	    (r = sshbuf_get_cstring(iqueue, &newpath, NULL)) != 0)
1262 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1263 
1264 	debug3("request %u: posix-rename", id);
1265 	logit("posix-rename old \"%s\" new \"%s\"", oldpath, newpath);
1266 	r = rename(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_statvfs(u_int32_t id)
1275 {
1276 	char *path;
1277 	struct statvfs st;
1278 	int r;
1279 
1280 	if ((r = sshbuf_get_cstring(iqueue, &path, NULL)) != 0)
1281 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1282 	debug3("request %u: statvfs", id);
1283 	logit("statvfs \"%s\"", path);
1284 
1285 	if (statvfs(path, &st) != 0)
1286 		send_status(id, errno_to_portable(errno));
1287 	else
1288 		send_statvfs(id, &st);
1289         free(path);
1290 }
1291 
1292 static void
1293 process_extended_fstatvfs(u_int32_t id)
1294 {
1295 	int r, handle, fd;
1296 	struct statvfs st;
1297 
1298 	if ((r = get_handle(iqueue, &handle)) != 0)
1299 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1300 	debug("request %u: fstatvfs \"%s\" (handle %u)",
1301 	    id, handle_to_name(handle), handle);
1302 	if ((fd = handle_to_fd(handle)) < 0) {
1303 		send_status(id, SSH2_FX_FAILURE);
1304 		return;
1305 	}
1306 	if (fstatvfs(fd, &st) != 0)
1307 		send_status(id, errno_to_portable(errno));
1308 	else
1309 		send_statvfs(id, &st);
1310 }
1311 
1312 static void
1313 process_extended_hardlink(u_int32_t id)
1314 {
1315 	char *oldpath, *newpath;
1316 	int r, status;
1317 
1318 	if ((r = sshbuf_get_cstring(iqueue, &oldpath, NULL)) != 0 ||
1319 	    (r = sshbuf_get_cstring(iqueue, &newpath, NULL)) != 0)
1320 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1321 
1322 	debug3("request %u: hardlink", id);
1323 	logit("hardlink old \"%s\" new \"%s\"", oldpath, newpath);
1324 	r = link(oldpath, newpath);
1325 	status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1326 	send_status(id, status);
1327 	free(oldpath);
1328 	free(newpath);
1329 }
1330 
1331 static void
1332 process_extended_fsync(u_int32_t id)
1333 {
1334 	int handle, fd, r, status = SSH2_FX_OP_UNSUPPORTED;
1335 
1336 	if ((r = get_handle(iqueue, &handle)) != 0)
1337 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1338 	debug3("request %u: fsync (handle %u)", id, handle);
1339 	verbose("fsync \"%s\"", handle_to_name(handle));
1340 	if ((fd = handle_to_fd(handle)) < 0)
1341 		status = SSH2_FX_NO_SUCH_FILE;
1342 	else if (handle_is_ok(handle, HANDLE_FILE)) {
1343 		r = fsync(fd);
1344 		status = (r == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1345 	}
1346 	send_status(id, status);
1347 }
1348 
1349 static void
1350 process_extended(u_int32_t id)
1351 {
1352 	char *request;
1353 	int i, r;
1354 
1355 	if ((r = sshbuf_get_cstring(iqueue, &request, NULL)) != 0)
1356 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1357 	for (i = 0; extended_handlers[i].handler != NULL; i++) {
1358 		if (strcmp(request, extended_handlers[i].ext_name) == 0) {
1359 			if (!request_permitted(&extended_handlers[i]))
1360 				send_status(id, SSH2_FX_PERMISSION_DENIED);
1361 			else
1362 				extended_handlers[i].handler(id);
1363 			break;
1364 		}
1365 	}
1366 	if (extended_handlers[i].handler == NULL) {
1367 		error("Unknown extended request \"%.100s\"", request);
1368 		send_status(id, SSH2_FX_OP_UNSUPPORTED);	/* MUST */
1369 	}
1370 	free(request);
1371 }
1372 
1373 /* stolen from ssh-agent */
1374 
1375 static void
1376 process(void)
1377 {
1378 	u_int msg_len;
1379 	u_int buf_len;
1380 	u_int consumed;
1381 	u_char type;
1382 	const u_char *cp;
1383 	int i, r;
1384 	u_int32_t id;
1385 
1386 	buf_len = sshbuf_len(iqueue);
1387 	if (buf_len < 5)
1388 		return;		/* Incomplete message. */
1389 	cp = sshbuf_ptr(iqueue);
1390 	msg_len = get_u32(cp);
1391 	if (msg_len > SFTP_MAX_MSG_LENGTH) {
1392 		error("bad message from %s local user %s",
1393 		    client_addr, pw->pw_name);
1394 		sftp_server_cleanup_exit(11);
1395 	}
1396 	if (buf_len < msg_len + 4)
1397 		return;
1398 	if ((r = sshbuf_consume(iqueue, 4)) != 0)
1399 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1400 	buf_len -= 4;
1401 	if ((r = sshbuf_get_u8(iqueue, &type)) != 0)
1402 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1403 
1404 	switch (type) {
1405 	case SSH2_FXP_INIT:
1406 		process_init();
1407 		init_done = 1;
1408 		break;
1409 	case SSH2_FXP_EXTENDED:
1410 		if (!init_done)
1411 			fatal("Received extended request before init");
1412 		if ((r = sshbuf_get_u32(iqueue, &id)) != 0)
1413 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
1414 		process_extended(id);
1415 		break;
1416 	default:
1417 		if (!init_done)
1418 			fatal("Received %u request before init", type);
1419 		if ((r = sshbuf_get_u32(iqueue, &id)) != 0)
1420 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
1421 		for (i = 0; handlers[i].handler != NULL; i++) {
1422 			if (type == handlers[i].type) {
1423 				if (!request_permitted(&handlers[i])) {
1424 					send_status(id,
1425 					    SSH2_FX_PERMISSION_DENIED);
1426 				} else {
1427 					handlers[i].handler(id);
1428 				}
1429 				break;
1430 			}
1431 		}
1432 		if (handlers[i].handler == NULL)
1433 			error("Unknown message %u", type);
1434 	}
1435 	/* discard the remaining bytes from the current packet */
1436 	if (buf_len < sshbuf_len(iqueue)) {
1437 		error("iqueue grew unexpectedly");
1438 		sftp_server_cleanup_exit(255);
1439 	}
1440 	consumed = buf_len - sshbuf_len(iqueue);
1441 	if (msg_len < consumed) {
1442 		error("msg_len %u < consumed %u", msg_len, consumed);
1443 		sftp_server_cleanup_exit(255);
1444 	}
1445 	if (msg_len > consumed &&
1446 	    (r = sshbuf_consume(iqueue, msg_len - consumed)) != 0)
1447 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1448 }
1449 
1450 /* Cleanup handler that logs active handles upon normal exit */
1451 void
1452 sftp_server_cleanup_exit(int i)
1453 {
1454 	if (pw != NULL && client_addr != NULL) {
1455 		handle_log_exit();
1456 		logit("session closed for local user %s from [%s]",
1457 		    pw->pw_name, client_addr);
1458 	}
1459 	_exit(i);
1460 }
1461 
1462 __dead static void
1463 sftp_server_usage(void)
1464 {
1465 	extern char *__progname;
1466 
1467 	fprintf(stderr,
1468 	    "usage: %s [-ehR] [-d start_directory] [-f log_facility] "
1469 	    "[-l log_level]\n\t[-P blacklisted_requests] "
1470 	    "[-p whitelisted_requests] [-u umask]\n"
1471 	    "       %s -Q protocol_feature\n",
1472 	    __progname, __progname);
1473 	exit(1);
1474 }
1475 
1476 int
1477 sftp_server_main(int argc, char **argv, struct passwd *user_pw)
1478 {
1479 	fd_set *rset, *wset;
1480 	int i, r, in, out, max, ch, skipargs = 0, log_stderr = 0;
1481 	ssize_t len, olen, set_size;
1482 	SyslogFacility log_facility = SYSLOG_FACILITY_AUTH;
1483 	char *cp, *homedir = NULL, buf[4*4096];
1484 	long mask;
1485 
1486 	extern char *optarg;
1487 	extern char *__progname;
1488 
1489 	log_init(__progname, log_level, log_facility, log_stderr);
1490 
1491 	pw = pwcopy(user_pw);
1492 
1493 	while (!skipargs && (ch = getopt(argc, argv,
1494 	    "d:f:l:P:p:Q:u:cehR")) != -1) {
1495 		switch (ch) {
1496 		case 'Q':
1497 			if (strcasecmp(optarg, "requests") != 0) {
1498 				fprintf(stderr, "Invalid query type\n");
1499 				exit(1);
1500 			}
1501 			for (i = 0; handlers[i].handler != NULL; i++)
1502 				printf("%s\n", handlers[i].name);
1503 			for (i = 0; extended_handlers[i].handler != NULL; i++)
1504 				printf("%s\n", extended_handlers[i].name);
1505 			exit(0);
1506 			break;
1507 		case 'R':
1508 			readonly = 1;
1509 			break;
1510 		case 'c':
1511 			/*
1512 			 * Ignore all arguments if we are invoked as a
1513 			 * shell using "sftp-server -c command"
1514 			 */
1515 			skipargs = 1;
1516 			break;
1517 		case 'e':
1518 			log_stderr = 1;
1519 			break;
1520 		case 'l':
1521 			log_level = log_level_number(optarg);
1522 			if (log_level == SYSLOG_LEVEL_NOT_SET)
1523 				error("Invalid log level \"%s\"", optarg);
1524 			break;
1525 		case 'f':
1526 			log_facility = log_facility_number(optarg);
1527 			if (log_facility == SYSLOG_FACILITY_NOT_SET)
1528 				error("Invalid log facility \"%s\"", optarg);
1529 			break;
1530 		case 'd':
1531 			cp = tilde_expand_filename(optarg, user_pw->pw_uid);
1532 			homedir = percent_expand(cp, "d", user_pw->pw_dir,
1533 			    "u", user_pw->pw_name, (char *)NULL);
1534 			free(cp);
1535 			break;
1536 		case 'p':
1537 			if (request_whitelist != NULL)
1538 				fatal("Permitted requests already set");
1539 			request_whitelist = xstrdup(optarg);
1540 			break;
1541 		case 'P':
1542 			if (request_blacklist != NULL)
1543 				fatal("Refused requests already set");
1544 			request_blacklist = xstrdup(optarg);
1545 			break;
1546 		case 'u':
1547 			errno = 0;
1548 			mask = strtol(optarg, &cp, 8);
1549 			if (mask < 0 || mask > 0777 || *cp != '\0' ||
1550 			    cp == optarg || (mask == 0 && errno != 0))
1551 				fatal("Invalid umask \"%s\"", optarg);
1552 			(void)umask((mode_t)mask);
1553 			break;
1554 		case 'h':
1555 		default:
1556 			sftp_server_usage();
1557 		}
1558 	}
1559 
1560 	log_init(__progname, log_level, log_facility, log_stderr);
1561 
1562 	if ((cp = getenv("SSH_CONNECTION")) != NULL) {
1563 		client_addr = xstrdup(cp);
1564 		if ((cp = strchr(client_addr, ' ')) == NULL) {
1565 			error("Malformed SSH_CONNECTION variable: \"%s\"",
1566 			    getenv("SSH_CONNECTION"));
1567 			sftp_server_cleanup_exit(255);
1568 		}
1569 		*cp = '\0';
1570 	} else
1571 		client_addr = xstrdup("UNKNOWN");
1572 
1573 	logit("session opened for local user %s from [%s]",
1574 	    pw->pw_name, client_addr);
1575 
1576 	in = STDIN_FILENO;
1577 	out = STDOUT_FILENO;
1578 
1579 	max = 0;
1580 	if (in > max)
1581 		max = in;
1582 	if (out > max)
1583 		max = out;
1584 
1585 	if ((iqueue = sshbuf_new()) == NULL)
1586 		fatal("%s: sshbuf_new failed", __func__);
1587 	if ((oqueue = sshbuf_new()) == NULL)
1588 		fatal("%s: sshbuf_new failed", __func__);
1589 
1590 	set_size = howmany(max + 1, NFDBITS) * sizeof(fd_mask);
1591 	rset = (fd_set *)xmalloc(set_size);
1592 	wset = (fd_set *)xmalloc(set_size);
1593 
1594 	if (homedir != NULL) {
1595 		if (chdir(homedir) != 0) {
1596 			error("chdir to \"%s\" failed: %s", homedir,
1597 			    strerror(errno));
1598 		}
1599 	}
1600 
1601 	for (;;) {
1602 		memset(rset, 0, set_size);
1603 		memset(wset, 0, set_size);
1604 
1605 		/*
1606 		 * Ensure that we can read a full buffer and handle
1607 		 * the worst-case length packet it can generate,
1608 		 * otherwise apply backpressure by stopping reads.
1609 		 */
1610 		if ((r = sshbuf_check_reserve(iqueue, sizeof(buf))) == 0 &&
1611 		    (r = sshbuf_check_reserve(oqueue,
1612 		    SFTP_MAX_MSG_LENGTH)) == 0)
1613 			FD_SET(in, rset);
1614 		else if (r != SSH_ERR_NO_BUFFER_SPACE)
1615 			fatal("%s: sshbuf_check_reserve failed: %s",
1616 			    __func__, ssh_err(r));
1617 
1618 		olen = sshbuf_len(oqueue);
1619 		if (olen > 0)
1620 			FD_SET(out, wset);
1621 
1622 		if (select(max+1, rset, wset, NULL, NULL) < 0) {
1623 			if (errno == EINTR)
1624 				continue;
1625 			error("select: %s", strerror(errno));
1626 			sftp_server_cleanup_exit(2);
1627 		}
1628 
1629 		/* copy stdin to iqueue */
1630 		if (FD_ISSET(in, rset)) {
1631 			len = read(in, buf, sizeof buf);
1632 			if (len == 0) {
1633 				debug("read eof");
1634 				sftp_server_cleanup_exit(0);
1635 			} else if (len < 0) {
1636 				error("read: %s", strerror(errno));
1637 				sftp_server_cleanup_exit(1);
1638 			} else if ((r = sshbuf_put(iqueue, buf, len)) != 0) {
1639 				fatal("%s: buffer error: %s",
1640 				    __func__, ssh_err(r));
1641 			}
1642 		}
1643 		/* send oqueue to stdout */
1644 		if (FD_ISSET(out, wset)) {
1645 			len = write(out, sshbuf_ptr(oqueue), olen);
1646 			if (len < 0) {
1647 				error("write: %s", strerror(errno));
1648 				sftp_server_cleanup_exit(1);
1649 			} else if ((r = sshbuf_consume(oqueue, len)) != 0) {
1650 				fatal("%s: buffer error: %s",
1651 				    __func__, ssh_err(r));
1652 			}
1653 		}
1654 
1655 		/*
1656 		 * Process requests from client if we can fit the results
1657 		 * into the output buffer, otherwise stop processing input
1658 		 * and let the output queue drain.
1659 		 */
1660 		r = sshbuf_check_reserve(oqueue, SFTP_MAX_MSG_LENGTH);
1661 		if (r == 0)
1662 			process();
1663 		else if (r != SSH_ERR_NO_BUFFER_SPACE)
1664 			fatal("%s: sshbuf_check_reserve: %s",
1665 			    __func__, ssh_err(r));
1666 	}
1667 }
1668