- stevesk@cvs.openbsd.org 2006/08/01 23:36:12
[openssh-git.git] / sftp-server.c
blobc0839782dece03e3b9bc5f51f81d49d263bd5b61
1 /* $OpenBSD: sftp-server.c,v 1.69 2006/08/01 23:22:47 stevesk Exp $ */
2 /*
3 * Copyright (c) 2000-2004 Markus Friedl. All rights reserved.
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 #include "includes.h"
19 #include <sys/types.h>
20 #include <sys/param.h>
21 #include <sys/stat.h>
22 #ifdef HAVE_SYS_TIME_H
23 # include <sys/time.h>
24 #endif
26 #include <dirent.h>
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <pwd.h>
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <string.h>
33 #include <time.h>
34 #include <unistd.h>
36 #include "buffer.h"
37 #include "bufaux.h"
38 #include "log.h"
39 #include "xmalloc.h"
40 #include "misc.h"
41 #include "uidswap.h"
43 #include "sftp.h"
44 #include "sftp-common.h"
46 /* helper */
47 #define get_int64() buffer_get_int64(&iqueue);
48 #define get_int() buffer_get_int(&iqueue);
49 #define get_string(lenp) buffer_get_string(&iqueue, lenp);
51 /* Our verbosity */
52 LogLevel log_level = SYSLOG_LEVEL_ERROR;
54 /* Our client */
55 struct passwd *pw = NULL;
56 char *client_addr = NULL;
58 /* input and output queue */
59 Buffer iqueue;
60 Buffer oqueue;
62 /* Version of client */
63 int version;
65 /* portable attributes, etc. */
67 typedef struct Stat Stat;
69 struct Stat {
70 char *name;
71 char *long_name;
72 Attrib attrib;
75 static int
76 errno_to_portable(int unixerrno)
78 int ret = 0;
80 switch (unixerrno) {
81 case 0:
82 ret = SSH2_FX_OK;
83 break;
84 case ENOENT:
85 case ENOTDIR:
86 case EBADF:
87 case ELOOP:
88 ret = SSH2_FX_NO_SUCH_FILE;
89 break;
90 case EPERM:
91 case EACCES:
92 case EFAULT:
93 ret = SSH2_FX_PERMISSION_DENIED;
94 break;
95 case ENAMETOOLONG:
96 case EINVAL:
97 ret = SSH2_FX_BAD_MESSAGE;
98 break;
99 default:
100 ret = SSH2_FX_FAILURE;
101 break;
103 return ret;
106 static int
107 flags_from_portable(int pflags)
109 int flags = 0;
111 if ((pflags & SSH2_FXF_READ) &&
112 (pflags & SSH2_FXF_WRITE)) {
113 flags = O_RDWR;
114 } else if (pflags & SSH2_FXF_READ) {
115 flags = O_RDONLY;
116 } else if (pflags & SSH2_FXF_WRITE) {
117 flags = O_WRONLY;
119 if (pflags & SSH2_FXF_CREAT)
120 flags |= O_CREAT;
121 if (pflags & SSH2_FXF_TRUNC)
122 flags |= O_TRUNC;
123 if (pflags & SSH2_FXF_EXCL)
124 flags |= O_EXCL;
125 return flags;
128 static const char *
129 string_from_portable(int pflags)
131 static char ret[128];
133 *ret = '\0';
135 #define PAPPEND(str) { \
136 if (*ret != '\0') \
137 strlcat(ret, ",", sizeof(ret)); \
138 strlcat(ret, str, sizeof(ret)); \
141 if (pflags & SSH2_FXF_READ)
142 PAPPEND("READ")
143 if (pflags & SSH2_FXF_WRITE)
144 PAPPEND("WRITE")
145 if (pflags & SSH2_FXF_CREAT)
146 PAPPEND("CREATE")
147 if (pflags & SSH2_FXF_TRUNC)
148 PAPPEND("TRUNCATE")
149 if (pflags & SSH2_FXF_EXCL)
150 PAPPEND("EXCL")
152 return ret;
155 static Attrib *
156 get_attrib(void)
158 return decode_attrib(&iqueue);
161 /* handle handles */
163 typedef struct Handle Handle;
164 struct Handle {
165 int use;
166 DIR *dirp;
167 int fd;
168 char *name;
169 u_int64_t bytes_read, bytes_write;
172 enum {
173 HANDLE_UNUSED,
174 HANDLE_DIR,
175 HANDLE_FILE
178 Handle handles[100];
180 static void
181 handle_init(void)
183 u_int i;
185 for (i = 0; i < sizeof(handles)/sizeof(Handle); i++)
186 handles[i].use = HANDLE_UNUSED;
189 static int
190 handle_new(int use, const char *name, int fd, DIR *dirp)
192 u_int i;
194 for (i = 0; i < sizeof(handles)/sizeof(Handle); i++) {
195 if (handles[i].use == HANDLE_UNUSED) {
196 handles[i].use = use;
197 handles[i].dirp = dirp;
198 handles[i].fd = fd;
199 handles[i].name = xstrdup(name);
200 handles[i].bytes_read = handles[i].bytes_write = 0;
201 return i;
204 return -1;
207 static int
208 handle_is_ok(int i, int type)
210 return i >= 0 && (u_int)i < sizeof(handles)/sizeof(Handle) &&
211 handles[i].use == type;
214 static int
215 handle_to_string(int handle, char **stringp, int *hlenp)
217 if (stringp == NULL || hlenp == NULL)
218 return -1;
219 *stringp = xmalloc(sizeof(int32_t));
220 put_u32(*stringp, handle);
221 *hlenp = sizeof(int32_t);
222 return 0;
225 static int
226 handle_from_string(const char *handle, u_int hlen)
228 int val;
230 if (hlen != sizeof(int32_t))
231 return -1;
232 val = get_u32(handle);
233 if (handle_is_ok(val, HANDLE_FILE) ||
234 handle_is_ok(val, HANDLE_DIR))
235 return val;
236 return -1;
239 static char *
240 handle_to_name(int handle)
242 if (handle_is_ok(handle, HANDLE_DIR)||
243 handle_is_ok(handle, HANDLE_FILE))
244 return handles[handle].name;
245 return NULL;
248 static DIR *
249 handle_to_dir(int handle)
251 if (handle_is_ok(handle, HANDLE_DIR))
252 return handles[handle].dirp;
253 return NULL;
256 static int
257 handle_to_fd(int handle)
259 if (handle_is_ok(handle, HANDLE_FILE))
260 return handles[handle].fd;
261 return -1;
264 static void
265 handle_update_read(int handle, ssize_t bytes)
267 if (handle_is_ok(handle, HANDLE_FILE) && bytes > 0)
268 handles[handle].bytes_read += bytes;
271 static void
272 handle_update_write(int handle, ssize_t bytes)
274 if (handle_is_ok(handle, HANDLE_FILE) && bytes > 0)
275 handles[handle].bytes_write += bytes;
278 static u_int64_t
279 handle_bytes_read(int handle)
281 if (handle_is_ok(handle, HANDLE_FILE))
282 return (handles[handle].bytes_read);
283 return 0;
286 static u_int64_t
287 handle_bytes_write(int handle)
289 if (handle_is_ok(handle, HANDLE_FILE))
290 return (handles[handle].bytes_write);
291 return 0;
294 static int
295 handle_close(int handle)
297 int ret = -1;
299 if (handle_is_ok(handle, HANDLE_FILE)) {
300 ret = close(handles[handle].fd);
301 handles[handle].use = HANDLE_UNUSED;
302 xfree(handles[handle].name);
303 } else if (handle_is_ok(handle, HANDLE_DIR)) {
304 ret = closedir(handles[handle].dirp);
305 handles[handle].use = HANDLE_UNUSED;
306 xfree(handles[handle].name);
307 } else {
308 errno = ENOENT;
310 return ret;
313 static void
314 handle_log_close(int handle, char *emsg)
316 if (handle_is_ok(handle, HANDLE_FILE)) {
317 logit("%s%sclose \"%s\" bytes read %llu written %llu",
318 emsg == NULL ? "" : emsg, emsg == NULL ? "" : " ",
319 handle_to_name(handle),
320 handle_bytes_read(handle), handle_bytes_write(handle));
321 } else {
322 logit("%s%sclosedir \"%s\"",
323 emsg == NULL ? "" : emsg, emsg == NULL ? "" : " ",
324 handle_to_name(handle));
328 static void
329 handle_log_exit(void)
331 u_int i;
333 for (i = 0; i < sizeof(handles)/sizeof(Handle); i++)
334 if (handles[i].use != HANDLE_UNUSED)
335 handle_log_close(i, "forced");
338 static int
339 get_handle(void)
341 char *handle;
342 int val = -1;
343 u_int hlen;
345 handle = get_string(&hlen);
346 if (hlen < 256)
347 val = handle_from_string(handle, hlen);
348 xfree(handle);
349 return val;
352 /* send replies */
354 static void
355 send_msg(Buffer *m)
357 int mlen = buffer_len(m);
359 buffer_put_int(&oqueue, mlen);
360 buffer_append(&oqueue, buffer_ptr(m), mlen);
361 buffer_consume(m, mlen);
364 static const char *
365 status_to_message(u_int32_t status)
367 const char *status_messages[] = {
368 "Success", /* SSH_FX_OK */
369 "End of file", /* SSH_FX_EOF */
370 "No such file", /* SSH_FX_NO_SUCH_FILE */
371 "Permission denied", /* SSH_FX_PERMISSION_DENIED */
372 "Failure", /* SSH_FX_FAILURE */
373 "Bad message", /* SSH_FX_BAD_MESSAGE */
374 "No connection", /* SSH_FX_NO_CONNECTION */
375 "Connection lost", /* SSH_FX_CONNECTION_LOST */
376 "Operation unsupported", /* SSH_FX_OP_UNSUPPORTED */
377 "Unknown error" /* Others */
379 return (status_messages[MIN(status,SSH2_FX_MAX)]);
382 static void
383 send_status(u_int32_t id, u_int32_t status)
385 Buffer msg;
387 debug3("request %u: sent status %u", id, status);
388 if (log_level > SYSLOG_LEVEL_VERBOSE ||
389 (status != SSH2_FX_OK && status != SSH2_FX_EOF))
390 logit("sent status %s", status_to_message(status));
391 buffer_init(&msg);
392 buffer_put_char(&msg, SSH2_FXP_STATUS);
393 buffer_put_int(&msg, id);
394 buffer_put_int(&msg, status);
395 if (version >= 3) {
396 buffer_put_cstring(&msg, status_to_message(status));
397 buffer_put_cstring(&msg, "");
399 send_msg(&msg);
400 buffer_free(&msg);
402 static void
403 send_data_or_handle(char type, u_int32_t id, const char *data, int dlen)
405 Buffer msg;
407 buffer_init(&msg);
408 buffer_put_char(&msg, type);
409 buffer_put_int(&msg, id);
410 buffer_put_string(&msg, data, dlen);
411 send_msg(&msg);
412 buffer_free(&msg);
415 static void
416 send_data(u_int32_t id, const char *data, int dlen)
418 debug("request %u: sent data len %d", id, dlen);
419 send_data_or_handle(SSH2_FXP_DATA, id, data, dlen);
422 static void
423 send_handle(u_int32_t id, int handle)
425 char *string;
426 int hlen;
428 handle_to_string(handle, &string, &hlen);
429 debug("request %u: sent handle handle %d", id, handle);
430 send_data_or_handle(SSH2_FXP_HANDLE, id, string, hlen);
431 xfree(string);
434 static void
435 send_names(u_int32_t id, int count, const Stat *stats)
437 Buffer msg;
438 int i;
440 buffer_init(&msg);
441 buffer_put_char(&msg, SSH2_FXP_NAME);
442 buffer_put_int(&msg, id);
443 buffer_put_int(&msg, count);
444 debug("request %u: sent names count %d", id, count);
445 for (i = 0; i < count; i++) {
446 buffer_put_cstring(&msg, stats[i].name);
447 buffer_put_cstring(&msg, stats[i].long_name);
448 encode_attrib(&msg, &stats[i].attrib);
450 send_msg(&msg);
451 buffer_free(&msg);
454 static void
455 send_attrib(u_int32_t id, const Attrib *a)
457 Buffer msg;
459 debug("request %u: sent attrib have 0x%x", id, a->flags);
460 buffer_init(&msg);
461 buffer_put_char(&msg, SSH2_FXP_ATTRS);
462 buffer_put_int(&msg, id);
463 encode_attrib(&msg, a);
464 send_msg(&msg);
465 buffer_free(&msg);
468 /* parse incoming */
470 static void
471 process_init(void)
473 Buffer msg;
475 version = get_int();
476 verbose("received client version %d", version);
477 buffer_init(&msg);
478 buffer_put_char(&msg, SSH2_FXP_VERSION);
479 buffer_put_int(&msg, SSH2_FILEXFER_VERSION);
480 send_msg(&msg);
481 buffer_free(&msg);
484 static void
485 process_open(void)
487 u_int32_t id, pflags;
488 Attrib *a;
489 char *name;
490 int handle, fd, flags, mode, status = SSH2_FX_FAILURE;
492 id = get_int();
493 name = get_string(NULL);
494 pflags = get_int(); /* portable flags */
495 debug3("request %u: open flags %d", id, pflags);
496 a = get_attrib();
497 flags = flags_from_portable(pflags);
498 mode = (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ? a->perm : 0666;
499 logit("open \"%s\" flags %s mode 0%o",
500 name, string_from_portable(pflags), mode);
501 fd = open(name, flags, mode);
502 if (fd < 0) {
503 status = errno_to_portable(errno);
504 } else {
505 handle = handle_new(HANDLE_FILE, name, fd, NULL);
506 if (handle < 0) {
507 close(fd);
508 } else {
509 send_handle(id, handle);
510 status = SSH2_FX_OK;
513 if (status != SSH2_FX_OK)
514 send_status(id, status);
515 xfree(name);
518 static void
519 process_close(void)
521 u_int32_t id;
522 int handle, ret, status = SSH2_FX_FAILURE;
524 id = get_int();
525 handle = get_handle();
526 debug3("request %u: close handle %u", id, handle);
527 handle_log_close(handle, NULL);
528 ret = handle_close(handle);
529 status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
530 send_status(id, status);
533 static void
534 process_read(void)
536 char buf[64*1024];
537 u_int32_t id, len;
538 int handle, fd, ret, status = SSH2_FX_FAILURE;
539 u_int64_t off;
541 id = get_int();
542 handle = get_handle();
543 off = get_int64();
544 len = get_int();
546 debug("request %u: read \"%s\" (handle %d) off %llu len %d",
547 id, handle_to_name(handle), handle, (unsigned long long)off, len);
548 if (len > sizeof buf) {
549 len = sizeof buf;
550 debug2("read change len %d", len);
552 fd = handle_to_fd(handle);
553 if (fd >= 0) {
554 if (lseek(fd, off, SEEK_SET) < 0) {
555 error("process_read: seek failed");
556 status = errno_to_portable(errno);
557 } else {
558 ret = read(fd, buf, len);
559 if (ret < 0) {
560 status = errno_to_portable(errno);
561 } else if (ret == 0) {
562 status = SSH2_FX_EOF;
563 } else {
564 send_data(id, buf, ret);
565 status = SSH2_FX_OK;
566 handle_update_read(handle, ret);
570 if (status != SSH2_FX_OK)
571 send_status(id, status);
574 static void
575 process_write(void)
577 u_int32_t id;
578 u_int64_t off;
579 u_int len;
580 int handle, fd, ret, status = SSH2_FX_FAILURE;
581 char *data;
583 id = get_int();
584 handle = get_handle();
585 off = get_int64();
586 data = get_string(&len);
588 debug("request %u: write \"%s\" (handle %d) off %llu len %d",
589 id, handle_to_name(handle), handle, (unsigned long long)off, len);
590 fd = handle_to_fd(handle);
591 if (fd >= 0) {
592 if (lseek(fd, off, SEEK_SET) < 0) {
593 status = errno_to_portable(errno);
594 error("process_write: seek failed");
595 } else {
596 /* XXX ATOMICIO ? */
597 ret = write(fd, data, len);
598 if (ret < 0) {
599 error("process_write: write failed");
600 status = errno_to_portable(errno);
601 } else if ((size_t)ret == len) {
602 status = SSH2_FX_OK;
603 handle_update_write(handle, ret);
604 } else {
605 debug2("nothing at all written");
609 send_status(id, status);
610 xfree(data);
613 static void
614 process_do_stat(int do_lstat)
616 Attrib a;
617 struct stat st;
618 u_int32_t id;
619 char *name;
620 int ret, status = SSH2_FX_FAILURE;
622 id = get_int();
623 name = get_string(NULL);
624 debug3("request %u: %sstat", id, do_lstat ? "l" : "");
625 verbose("%sstat name \"%s\"", do_lstat ? "l" : "", name);
626 ret = do_lstat ? lstat(name, &st) : stat(name, &st);
627 if (ret < 0) {
628 status = errno_to_portable(errno);
629 } else {
630 stat_to_attrib(&st, &a);
631 send_attrib(id, &a);
632 status = SSH2_FX_OK;
634 if (status != SSH2_FX_OK)
635 send_status(id, status);
636 xfree(name);
639 static void
640 process_stat(void)
642 process_do_stat(0);
645 static void
646 process_lstat(void)
648 process_do_stat(1);
651 static void
652 process_fstat(void)
654 Attrib a;
655 struct stat st;
656 u_int32_t id;
657 int fd, ret, handle, status = SSH2_FX_FAILURE;
659 id = get_int();
660 handle = get_handle();
661 debug("request %u: fstat \"%s\" (handle %u)",
662 id, handle_to_name(handle), handle);
663 fd = handle_to_fd(handle);
664 if (fd >= 0) {
665 ret = fstat(fd, &st);
666 if (ret < 0) {
667 status = errno_to_portable(errno);
668 } else {
669 stat_to_attrib(&st, &a);
670 send_attrib(id, &a);
671 status = SSH2_FX_OK;
674 if (status != SSH2_FX_OK)
675 send_status(id, status);
678 static struct timeval *
679 attrib_to_tv(const Attrib *a)
681 static struct timeval tv[2];
683 tv[0].tv_sec = a->atime;
684 tv[0].tv_usec = 0;
685 tv[1].tv_sec = a->mtime;
686 tv[1].tv_usec = 0;
687 return tv;
690 static void
691 process_setstat(void)
693 Attrib *a;
694 u_int32_t id;
695 char *name;
696 int status = SSH2_FX_OK, ret;
698 id = get_int();
699 name = get_string(NULL);
700 a = get_attrib();
701 debug("request %u: setstat name \"%s\"", id, name);
702 if (a->flags & SSH2_FILEXFER_ATTR_SIZE) {
703 logit("set \"%s\" size %llu", name, a->size);
704 ret = truncate(name, a->size);
705 if (ret == -1)
706 status = errno_to_portable(errno);
708 if (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) {
709 logit("set \"%s\" mode %04o", name, a->perm);
710 ret = chmod(name, a->perm & 0777);
711 if (ret == -1)
712 status = errno_to_portable(errno);
714 if (a->flags & SSH2_FILEXFER_ATTR_ACMODTIME) {
715 char buf[64];
716 time_t t = a->mtime;
718 strftime(buf, sizeof(buf), "%Y%m%d-%H:%M:%S",
719 localtime(&t));
720 logit("set \"%s\" modtime %s", name, buf);
721 ret = utimes(name, attrib_to_tv(a));
722 if (ret == -1)
723 status = errno_to_portable(errno);
725 if (a->flags & SSH2_FILEXFER_ATTR_UIDGID) {
726 logit("set \"%s\" owner %lu group %lu", name,
727 (u_long)a->uid, (u_long)a->gid);
728 ret = chown(name, a->uid, a->gid);
729 if (ret == -1)
730 status = errno_to_portable(errno);
732 send_status(id, status);
733 xfree(name);
736 static void
737 process_fsetstat(void)
739 Attrib *a;
740 u_int32_t id;
741 int handle, fd, ret;
742 int status = SSH2_FX_OK;
744 id = get_int();
745 handle = get_handle();
746 a = get_attrib();
747 debug("request %u: fsetstat handle %d", id, handle);
748 fd = handle_to_fd(handle);
749 if (fd < 0) {
750 status = SSH2_FX_FAILURE;
751 } else {
752 char *name = handle_to_name(handle);
754 if (a->flags & SSH2_FILEXFER_ATTR_SIZE) {
755 logit("set \"%s\" size %llu", name, a->size);
756 ret = ftruncate(fd, a->size);
757 if (ret == -1)
758 status = errno_to_portable(errno);
760 if (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) {
761 logit("set \"%s\" mode %04o", name, a->perm);
762 #ifdef HAVE_FCHMOD
763 ret = fchmod(fd, a->perm & 0777);
764 #else
765 ret = chmod(name, a->perm & 0777);
766 #endif
767 if (ret == -1)
768 status = errno_to_portable(errno);
770 if (a->flags & SSH2_FILEXFER_ATTR_ACMODTIME) {
771 char buf[64];
772 time_t t = a->mtime;
774 strftime(buf, sizeof(buf), "%Y%m%d-%H:%M:%S",
775 localtime(&t));
776 logit("set \"%s\" modtime %s", name, buf);
777 #ifdef HAVE_FUTIMES
778 ret = futimes(fd, attrib_to_tv(a));
779 #else
780 ret = utimes(name, attrib_to_tv(a));
781 #endif
782 if (ret == -1)
783 status = errno_to_portable(errno);
785 if (a->flags & SSH2_FILEXFER_ATTR_UIDGID) {
786 logit("set \"%s\" owner %lu group %lu", name,
787 (u_long)a->uid, (u_long)a->gid);
788 #ifdef HAVE_FCHOWN
789 ret = fchown(fd, a->uid, a->gid);
790 #else
791 ret = chown(name, a->uid, a->gid);
792 #endif
793 if (ret == -1)
794 status = errno_to_portable(errno);
797 send_status(id, status);
800 static void
801 process_opendir(void)
803 DIR *dirp = NULL;
804 char *path;
805 int handle, status = SSH2_FX_FAILURE;
806 u_int32_t id;
808 id = get_int();
809 path = get_string(NULL);
810 debug3("request %u: opendir", id);
811 logit("opendir \"%s\"", path);
812 dirp = opendir(path);
813 if (dirp == NULL) {
814 status = errno_to_portable(errno);
815 } else {
816 handle = handle_new(HANDLE_DIR, path, 0, dirp);
817 if (handle < 0) {
818 closedir(dirp);
819 } else {
820 send_handle(id, handle);
821 status = SSH2_FX_OK;
825 if (status != SSH2_FX_OK)
826 send_status(id, status);
827 xfree(path);
830 static void
831 process_readdir(void)
833 DIR *dirp;
834 struct dirent *dp;
835 char *path;
836 int handle;
837 u_int32_t id;
839 id = get_int();
840 handle = get_handle();
841 debug("request %u: readdir \"%s\" (handle %d)", id,
842 handle_to_name(handle), handle);
843 dirp = handle_to_dir(handle);
844 path = handle_to_name(handle);
845 if (dirp == NULL || path == NULL) {
846 send_status(id, SSH2_FX_FAILURE);
847 } else {
848 struct stat st;
849 char pathname[MAXPATHLEN];
850 Stat *stats;
851 int nstats = 10, count = 0, i;
853 stats = xcalloc(nstats, sizeof(Stat));
854 while ((dp = readdir(dirp)) != NULL) {
855 if (count >= nstats) {
856 nstats *= 2;
857 stats = xrealloc(stats, nstats, sizeof(Stat));
859 /* XXX OVERFLOW ? */
860 snprintf(pathname, sizeof pathname, "%s%s%s", path,
861 strcmp(path, "/") ? "/" : "", dp->d_name);
862 if (lstat(pathname, &st) < 0)
863 continue;
864 stat_to_attrib(&st, &(stats[count].attrib));
865 stats[count].name = xstrdup(dp->d_name);
866 stats[count].long_name = ls_file(dp->d_name, &st, 0);
867 count++;
868 /* send up to 100 entries in one message */
869 /* XXX check packet size instead */
870 if (count == 100)
871 break;
873 if (count > 0) {
874 send_names(id, count, stats);
875 for (i = 0; i < count; i++) {
876 xfree(stats[i].name);
877 xfree(stats[i].long_name);
879 } else {
880 send_status(id, SSH2_FX_EOF);
882 xfree(stats);
886 static void
887 process_remove(void)
889 char *name;
890 u_int32_t id;
891 int status = SSH2_FX_FAILURE;
892 int ret;
894 id = get_int();
895 name = get_string(NULL);
896 debug3("request %u: remove", id);
897 logit("remove name \"%s\"", name);
898 ret = unlink(name);
899 status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
900 send_status(id, status);
901 xfree(name);
904 static void
905 process_mkdir(void)
907 Attrib *a;
908 u_int32_t id;
909 char *name;
910 int ret, mode, status = SSH2_FX_FAILURE;
912 id = get_int();
913 name = get_string(NULL);
914 a = get_attrib();
915 mode = (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ?
916 a->perm & 0777 : 0777;
917 debug3("request %u: mkdir", id);
918 logit("mkdir name \"%s\" mode 0%o", name, mode);
919 ret = mkdir(name, mode);
920 status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
921 send_status(id, status);
922 xfree(name);
925 static void
926 process_rmdir(void)
928 u_int32_t id;
929 char *name;
930 int ret, status;
932 id = get_int();
933 name = get_string(NULL);
934 debug3("request %u: rmdir", id);
935 logit("rmdir name \"%s\"", name);
936 ret = rmdir(name);
937 status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
938 send_status(id, status);
939 xfree(name);
942 static void
943 process_realpath(void)
945 char resolvedname[MAXPATHLEN];
946 u_int32_t id;
947 char *path;
949 id = get_int();
950 path = get_string(NULL);
951 if (path[0] == '\0') {
952 xfree(path);
953 path = xstrdup(".");
955 debug3("request %u: realpath", id);
956 verbose("realpath \"%s\"", path);
957 if (realpath(path, resolvedname) == NULL) {
958 send_status(id, errno_to_portable(errno));
959 } else {
960 Stat s;
961 attrib_clear(&s.attrib);
962 s.name = s.long_name = resolvedname;
963 send_names(id, 1, &s);
965 xfree(path);
968 static void
969 process_rename(void)
971 u_int32_t id;
972 char *oldpath, *newpath;
973 int status;
974 struct stat sb;
976 id = get_int();
977 oldpath = get_string(NULL);
978 newpath = get_string(NULL);
979 debug3("request %u: rename", id);
980 logit("rename old \"%s\" new \"%s\"", oldpath, newpath);
981 status = SSH2_FX_FAILURE;
982 if (lstat(oldpath, &sb) == -1)
983 status = errno_to_portable(errno);
984 else if (S_ISREG(sb.st_mode)) {
985 /* Race-free rename of regular files */
986 if (link(oldpath, newpath) == -1) {
987 if (errno == EOPNOTSUPP
988 #ifdef LINK_OPNOTSUPP_ERRNO
989 || errno == LINK_OPNOTSUPP_ERRNO
990 #endif
992 struct stat st;
995 * fs doesn't support links, so fall back to
996 * stat+rename. This is racy.
998 if (stat(newpath, &st) == -1) {
999 if (rename(oldpath, newpath) == -1)
1000 status =
1001 errno_to_portable(errno);
1002 else
1003 status = SSH2_FX_OK;
1005 } else {
1006 status = errno_to_portable(errno);
1008 } else if (unlink(oldpath) == -1) {
1009 status = errno_to_portable(errno);
1010 /* clean spare link */
1011 unlink(newpath);
1012 } else
1013 status = SSH2_FX_OK;
1014 } else if (stat(newpath, &sb) == -1) {
1015 if (rename(oldpath, newpath) == -1)
1016 status = errno_to_portable(errno);
1017 else
1018 status = SSH2_FX_OK;
1020 send_status(id, status);
1021 xfree(oldpath);
1022 xfree(newpath);
1025 static void
1026 process_readlink(void)
1028 u_int32_t id;
1029 int len;
1030 char buf[MAXPATHLEN];
1031 char *path;
1033 id = get_int();
1034 path = get_string(NULL);
1035 debug3("request %u: readlink", id);
1036 verbose("readlink \"%s\"", path);
1037 if ((len = readlink(path, buf, sizeof(buf) - 1)) == -1)
1038 send_status(id, errno_to_portable(errno));
1039 else {
1040 Stat s;
1042 buf[len] = '\0';
1043 attrib_clear(&s.attrib);
1044 s.name = s.long_name = buf;
1045 send_names(id, 1, &s);
1047 xfree(path);
1050 static void
1051 process_symlink(void)
1053 u_int32_t id;
1054 char *oldpath, *newpath;
1055 int ret, status;
1057 id = get_int();
1058 oldpath = get_string(NULL);
1059 newpath = get_string(NULL);
1060 debug3("request %u: symlink", id);
1061 logit("symlink old \"%s\" new \"%s\"", oldpath, newpath);
1062 /* this will fail if 'newpath' exists */
1063 ret = symlink(oldpath, newpath);
1064 status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1065 send_status(id, status);
1066 xfree(oldpath);
1067 xfree(newpath);
1070 static void
1071 process_extended(void)
1073 u_int32_t id;
1074 char *request;
1076 id = get_int();
1077 request = get_string(NULL);
1078 send_status(id, SSH2_FX_OP_UNSUPPORTED); /* MUST */
1079 xfree(request);
1082 /* stolen from ssh-agent */
1084 static void
1085 process(void)
1087 u_int msg_len;
1088 u_int buf_len;
1089 u_int consumed;
1090 u_int type;
1091 u_char *cp;
1093 buf_len = buffer_len(&iqueue);
1094 if (buf_len < 5)
1095 return; /* Incomplete message. */
1096 cp = buffer_ptr(&iqueue);
1097 msg_len = get_u32(cp);
1098 if (msg_len > SFTP_MAX_MSG_LENGTH) {
1099 error("bad message from %s local user %s",
1100 client_addr, pw->pw_name);
1101 cleanup_exit(11);
1103 if (buf_len < msg_len + 4)
1104 return;
1105 buffer_consume(&iqueue, 4);
1106 buf_len -= 4;
1107 type = buffer_get_char(&iqueue);
1108 switch (type) {
1109 case SSH2_FXP_INIT:
1110 process_init();
1111 break;
1112 case SSH2_FXP_OPEN:
1113 process_open();
1114 break;
1115 case SSH2_FXP_CLOSE:
1116 process_close();
1117 break;
1118 case SSH2_FXP_READ:
1119 process_read();
1120 break;
1121 case SSH2_FXP_WRITE:
1122 process_write();
1123 break;
1124 case SSH2_FXP_LSTAT:
1125 process_lstat();
1126 break;
1127 case SSH2_FXP_FSTAT:
1128 process_fstat();
1129 break;
1130 case SSH2_FXP_SETSTAT:
1131 process_setstat();
1132 break;
1133 case SSH2_FXP_FSETSTAT:
1134 process_fsetstat();
1135 break;
1136 case SSH2_FXP_OPENDIR:
1137 process_opendir();
1138 break;
1139 case SSH2_FXP_READDIR:
1140 process_readdir();
1141 break;
1142 case SSH2_FXP_REMOVE:
1143 process_remove();
1144 break;
1145 case SSH2_FXP_MKDIR:
1146 process_mkdir();
1147 break;
1148 case SSH2_FXP_RMDIR:
1149 process_rmdir();
1150 break;
1151 case SSH2_FXP_REALPATH:
1152 process_realpath();
1153 break;
1154 case SSH2_FXP_STAT:
1155 process_stat();
1156 break;
1157 case SSH2_FXP_RENAME:
1158 process_rename();
1159 break;
1160 case SSH2_FXP_READLINK:
1161 process_readlink();
1162 break;
1163 case SSH2_FXP_SYMLINK:
1164 process_symlink();
1165 break;
1166 case SSH2_FXP_EXTENDED:
1167 process_extended();
1168 break;
1169 default:
1170 error("Unknown message %d", type);
1171 break;
1173 /* discard the remaining bytes from the current packet */
1174 if (buf_len < buffer_len(&iqueue))
1175 fatal("iqueue grew unexpectedly");
1176 consumed = buf_len - buffer_len(&iqueue);
1177 if (msg_len < consumed)
1178 fatal("msg_len %d < consumed %d", msg_len, consumed);
1179 if (msg_len > consumed)
1180 buffer_consume(&iqueue, msg_len - consumed);
1183 /* Cleanup handler that logs active handles upon normal exit */
1184 void
1185 cleanup_exit(int i)
1187 if (pw != NULL && client_addr != NULL) {
1188 handle_log_exit();
1189 logit("session closed for local user %s from [%s]",
1190 pw->pw_name, client_addr);
1192 _exit(i);
1195 static void
1196 usage(void)
1198 extern char *__progname;
1200 fprintf(stderr,
1201 "usage: %s [-he] [-l log_level] [-f log_facility]\n", __progname);
1202 exit(1);
1206 main(int argc, char **argv)
1208 fd_set *rset, *wset;
1209 int in, out, max, ch, skipargs = 0, log_stderr = 0;
1210 ssize_t len, olen, set_size;
1211 SyslogFacility log_facility = SYSLOG_FACILITY_AUTH;
1212 char *cp;
1214 extern char *optarg;
1215 extern char *__progname;
1217 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1218 sanitise_stdfd();
1220 __progname = ssh_get_progname(argv[0]);
1221 log_init(__progname, log_level, log_facility, log_stderr);
1223 while (!skipargs && (ch = getopt(argc, argv, "C:f:l:che")) != -1) {
1224 switch (ch) {
1225 case 'c':
1227 * Ignore all arguments if we are invoked as a
1228 * shell using "sftp-server -c command"
1230 skipargs = 1;
1231 break;
1232 case 'e':
1233 log_stderr = 1;
1234 break;
1235 case 'l':
1236 log_level = log_level_number(optarg);
1237 if (log_level == SYSLOG_LEVEL_NOT_SET)
1238 error("Invalid log level \"%s\"", optarg);
1239 break;
1240 case 'f':
1241 log_facility = log_facility_number(optarg);
1242 if (log_level == SYSLOG_FACILITY_NOT_SET)
1243 error("Invalid log facility \"%s\"", optarg);
1244 break;
1245 case 'h':
1246 default:
1247 usage();
1251 log_init(__progname, log_level, log_facility, log_stderr);
1253 if ((cp = getenv("SSH_CONNECTION")) != NULL) {
1254 client_addr = xstrdup(cp);
1255 if ((cp = strchr(client_addr, ' ')) == NULL)
1256 fatal("Malformed SSH_CONNECTION variable: \"%s\"",
1257 getenv("SSH_CONNECTION"));
1258 *cp = '\0';
1259 } else
1260 client_addr = xstrdup("UNKNOWN");
1262 if ((pw = getpwuid(getuid())) == NULL)
1263 fatal("No user found for uid %lu", (u_long)getuid());
1264 pw = pwcopy(pw);
1266 logit("session opened for local user %s from [%s]",
1267 pw->pw_name, client_addr);
1269 handle_init();
1271 in = dup(STDIN_FILENO);
1272 out = dup(STDOUT_FILENO);
1274 #ifdef HAVE_CYGWIN
1275 setmode(in, O_BINARY);
1276 setmode(out, O_BINARY);
1277 #endif
1279 max = 0;
1280 if (in > max)
1281 max = in;
1282 if (out > max)
1283 max = out;
1285 buffer_init(&iqueue);
1286 buffer_init(&oqueue);
1288 set_size = howmany(max + 1, NFDBITS) * sizeof(fd_mask);
1289 rset = (fd_set *)xmalloc(set_size);
1290 wset = (fd_set *)xmalloc(set_size);
1292 for (;;) {
1293 memset(rset, 0, set_size);
1294 memset(wset, 0, set_size);
1296 FD_SET(in, rset);
1297 olen = buffer_len(&oqueue);
1298 if (olen > 0)
1299 FD_SET(out, wset);
1301 if (select(max+1, rset, wset, NULL, NULL) < 0) {
1302 if (errno == EINTR)
1303 continue;
1304 error("select: %s", strerror(errno));
1305 cleanup_exit(2);
1308 /* copy stdin to iqueue */
1309 if (FD_ISSET(in, rset)) {
1310 char buf[4*4096];
1311 len = read(in, buf, sizeof buf);
1312 if (len == 0) {
1313 debug("read eof");
1314 cleanup_exit(0);
1315 } else if (len < 0) {
1316 error("read: %s", strerror(errno));
1317 cleanup_exit(1);
1318 } else {
1319 buffer_append(&iqueue, buf, len);
1322 /* send oqueue to stdout */
1323 if (FD_ISSET(out, wset)) {
1324 len = write(out, buffer_ptr(&oqueue), olen);
1325 if (len < 0) {
1326 error("write: %s", strerror(errno));
1327 cleanup_exit(1);
1328 } else {
1329 buffer_consume(&oqueue, len);
1332 /* process requests from client */
1333 process();