- jmc@cvs.openbsd.org 2006/07/18 08:03:09
[openssh-git.git] / sftp-server.c
blob923cc8c19736e21eba78d38ba221002e96caee83
1 /* $OpenBSD: sftp-server.c,v 1.63 2006/07/17 01:31:09 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/stat.h>
22 #include <dirent.h>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <pwd.h>
26 #include <unistd.h>
28 #include "buffer.h"
29 #include "bufaux.h"
30 #include "log.h"
31 #include "xmalloc.h"
32 #include "misc.h"
33 #include "uidswap.h"
35 #include "sftp.h"
36 #include "sftp-common.h"
38 /* helper */
39 #define get_int64() buffer_get_int64(&iqueue);
40 #define get_int() buffer_get_int(&iqueue);
41 #define get_string(lenp) buffer_get_string(&iqueue, lenp);
43 /* Our verbosity */
44 LogLevel log_level = SYSLOG_LEVEL_ERROR;
46 /* Our client */
47 struct passwd *pw = NULL;
48 char *client_addr = NULL;
50 /* input and output queue */
51 Buffer iqueue;
52 Buffer oqueue;
54 /* Version of client */
55 int version;
57 /* portable attributes, etc. */
59 typedef struct Stat Stat;
61 struct Stat {
62 char *name;
63 char *long_name;
64 Attrib attrib;
67 static int
68 errno_to_portable(int unixerrno)
70 int ret = 0;
72 switch (unixerrno) {
73 case 0:
74 ret = SSH2_FX_OK;
75 break;
76 case ENOENT:
77 case ENOTDIR:
78 case EBADF:
79 case ELOOP:
80 ret = SSH2_FX_NO_SUCH_FILE;
81 break;
82 case EPERM:
83 case EACCES:
84 case EFAULT:
85 ret = SSH2_FX_PERMISSION_DENIED;
86 break;
87 case ENAMETOOLONG:
88 case EINVAL:
89 ret = SSH2_FX_BAD_MESSAGE;
90 break;
91 default:
92 ret = SSH2_FX_FAILURE;
93 break;
95 return ret;
98 static int
99 flags_from_portable(int pflags)
101 int flags = 0;
103 if ((pflags & SSH2_FXF_READ) &&
104 (pflags & SSH2_FXF_WRITE)) {
105 flags = O_RDWR;
106 } else if (pflags & SSH2_FXF_READ) {
107 flags = O_RDONLY;
108 } else if (pflags & SSH2_FXF_WRITE) {
109 flags = O_WRONLY;
111 if (pflags & SSH2_FXF_CREAT)
112 flags |= O_CREAT;
113 if (pflags & SSH2_FXF_TRUNC)
114 flags |= O_TRUNC;
115 if (pflags & SSH2_FXF_EXCL)
116 flags |= O_EXCL;
117 return flags;
120 static const char *
121 string_from_portable(int pflags)
123 static char ret[128];
125 *ret = '\0';
127 #define PAPPEND(str) { \
128 if (*ret != '\0') \
129 strlcat(ret, ",", sizeof(ret)); \
130 strlcat(ret, str, sizeof(ret)); \
133 if (pflags & SSH2_FXF_READ)
134 PAPPEND("READ")
135 if (pflags & SSH2_FXF_WRITE)
136 PAPPEND("WRITE")
137 if (pflags & SSH2_FXF_CREAT)
138 PAPPEND("CREATE")
139 if (pflags & SSH2_FXF_TRUNC)
140 PAPPEND("TRUNCATE")
141 if (pflags & SSH2_FXF_EXCL)
142 PAPPEND("EXCL")
144 return ret;
147 static Attrib *
148 get_attrib(void)
150 return decode_attrib(&iqueue);
153 /* handle handles */
155 typedef struct Handle Handle;
156 struct Handle {
157 int use;
158 DIR *dirp;
159 int fd;
160 char *name;
161 u_int64_t bytes_read, bytes_write;
164 enum {
165 HANDLE_UNUSED,
166 HANDLE_DIR,
167 HANDLE_FILE
170 Handle handles[100];
172 static void
173 handle_init(void)
175 u_int i;
177 for (i = 0; i < sizeof(handles)/sizeof(Handle); i++)
178 handles[i].use = HANDLE_UNUSED;
181 static int
182 handle_new(int use, const char *name, int fd, DIR *dirp)
184 u_int i;
186 for (i = 0; i < sizeof(handles)/sizeof(Handle); i++) {
187 if (handles[i].use == HANDLE_UNUSED) {
188 handles[i].use = use;
189 handles[i].dirp = dirp;
190 handles[i].fd = fd;
191 handles[i].name = xstrdup(name);
192 handles[i].bytes_read = handles[i].bytes_write = 0;
193 return i;
196 return -1;
199 static int
200 handle_is_ok(int i, int type)
202 return i >= 0 && (u_int)i < sizeof(handles)/sizeof(Handle) &&
203 handles[i].use == type;
206 static int
207 handle_to_string(int handle, char **stringp, int *hlenp)
209 if (stringp == NULL || hlenp == NULL)
210 return -1;
211 *stringp = xmalloc(sizeof(int32_t));
212 put_u32(*stringp, handle);
213 *hlenp = sizeof(int32_t);
214 return 0;
217 static int
218 handle_from_string(const char *handle, u_int hlen)
220 int val;
222 if (hlen != sizeof(int32_t))
223 return -1;
224 val = get_u32(handle);
225 if (handle_is_ok(val, HANDLE_FILE) ||
226 handle_is_ok(val, HANDLE_DIR))
227 return val;
228 return -1;
231 static char *
232 handle_to_name(int handle)
234 if (handle_is_ok(handle, HANDLE_DIR)||
235 handle_is_ok(handle, HANDLE_FILE))
236 return handles[handle].name;
237 return NULL;
240 static DIR *
241 handle_to_dir(int handle)
243 if (handle_is_ok(handle, HANDLE_DIR))
244 return handles[handle].dirp;
245 return NULL;
248 static int
249 handle_to_fd(int handle)
251 if (handle_is_ok(handle, HANDLE_FILE))
252 return handles[handle].fd;
253 return -1;
256 static void
257 handle_update_read(int handle, ssize_t bytes)
259 if (handle_is_ok(handle, HANDLE_FILE) && bytes > 0)
260 handles[handle].bytes_read += bytes;
263 static void
264 handle_update_write(int handle, ssize_t bytes)
266 if (handle_is_ok(handle, HANDLE_FILE) && bytes > 0)
267 handles[handle].bytes_write += bytes;
270 static u_int64_t
271 handle_bytes_read(int handle)
273 if (handle_is_ok(handle, HANDLE_FILE))
274 return (handles[handle].bytes_read);
275 return 0;
278 static u_int64_t
279 handle_bytes_write(int handle)
281 if (handle_is_ok(handle, HANDLE_FILE))
282 return (handles[handle].bytes_write);
283 return 0;
286 static int
287 handle_close(int handle)
289 int ret = -1;
291 if (handle_is_ok(handle, HANDLE_FILE)) {
292 ret = close(handles[handle].fd);
293 handles[handle].use = HANDLE_UNUSED;
294 xfree(handles[handle].name);
295 } else if (handle_is_ok(handle, HANDLE_DIR)) {
296 ret = closedir(handles[handle].dirp);
297 handles[handle].use = HANDLE_UNUSED;
298 xfree(handles[handle].name);
299 } else {
300 errno = ENOENT;
302 return ret;
305 static void
306 handle_log_close(int handle, char *emsg)
308 if (handle_is_ok(handle, HANDLE_FILE)) {
309 logit("%s%sclose \"%s\" bytes read %llu written %llu",
310 emsg == NULL ? "" : emsg, emsg == NULL ? "" : " ",
311 handle_to_name(handle),
312 handle_bytes_read(handle), handle_bytes_write(handle));
313 } else {
314 logit("%s%sclosedir \"%s\"",
315 emsg == NULL ? "" : emsg, emsg == NULL ? "" : " ",
316 handle_to_name(handle));
320 static void
321 handle_log_exit(void)
323 u_int i;
325 for (i = 0; i < sizeof(handles)/sizeof(Handle); i++)
326 if (handles[i].use != HANDLE_UNUSED)
327 handle_log_close(i, "forced");
330 static int
331 get_handle(void)
333 char *handle;
334 int val = -1;
335 u_int hlen;
337 handle = get_string(&hlen);
338 if (hlen < 256)
339 val = handle_from_string(handle, hlen);
340 xfree(handle);
341 return val;
344 /* send replies */
346 static void
347 send_msg(Buffer *m)
349 int mlen = buffer_len(m);
351 buffer_put_int(&oqueue, mlen);
352 buffer_append(&oqueue, buffer_ptr(m), mlen);
353 buffer_consume(m, mlen);
356 static const char *
357 status_to_message(u_int32_t status)
359 const char *status_messages[] = {
360 "Success", /* SSH_FX_OK */
361 "End of file", /* SSH_FX_EOF */
362 "No such file", /* SSH_FX_NO_SUCH_FILE */
363 "Permission denied", /* SSH_FX_PERMISSION_DENIED */
364 "Failure", /* SSH_FX_FAILURE */
365 "Bad message", /* SSH_FX_BAD_MESSAGE */
366 "No connection", /* SSH_FX_NO_CONNECTION */
367 "Connection lost", /* SSH_FX_CONNECTION_LOST */
368 "Operation unsupported", /* SSH_FX_OP_UNSUPPORTED */
369 "Unknown error" /* Others */
371 return (status_messages[MIN(status,SSH2_FX_MAX)]);
374 static void
375 send_status(u_int32_t id, u_int32_t status)
377 Buffer msg;
379 debug3("request %u: sent status %u", id, status);
380 if (log_level > SYSLOG_LEVEL_VERBOSE ||
381 (status != SSH2_FX_OK && status != SSH2_FX_EOF))
382 logit("sent status %s", status_to_message(status));
383 buffer_init(&msg);
384 buffer_put_char(&msg, SSH2_FXP_STATUS);
385 buffer_put_int(&msg, id);
386 buffer_put_int(&msg, status);
387 if (version >= 3) {
388 buffer_put_cstring(&msg, status_to_message(status));
389 buffer_put_cstring(&msg, "");
391 send_msg(&msg);
392 buffer_free(&msg);
394 static void
395 send_data_or_handle(char type, u_int32_t id, const char *data, int dlen)
397 Buffer msg;
399 buffer_init(&msg);
400 buffer_put_char(&msg, type);
401 buffer_put_int(&msg, id);
402 buffer_put_string(&msg, data, dlen);
403 send_msg(&msg);
404 buffer_free(&msg);
407 static void
408 send_data(u_int32_t id, const char *data, int dlen)
410 debug("request %u: sent data len %d", id, dlen);
411 send_data_or_handle(SSH2_FXP_DATA, id, data, dlen);
414 static void
415 send_handle(u_int32_t id, int handle)
417 char *string;
418 int hlen;
420 handle_to_string(handle, &string, &hlen);
421 debug("request %u: sent handle handle %d", id, handle);
422 send_data_or_handle(SSH2_FXP_HANDLE, id, string, hlen);
423 xfree(string);
426 static void
427 send_names(u_int32_t id, int count, const Stat *stats)
429 Buffer msg;
430 int i;
432 buffer_init(&msg);
433 buffer_put_char(&msg, SSH2_FXP_NAME);
434 buffer_put_int(&msg, id);
435 buffer_put_int(&msg, count);
436 debug("request %u: sent names count %d", id, count);
437 for (i = 0; i < count; i++) {
438 buffer_put_cstring(&msg, stats[i].name);
439 buffer_put_cstring(&msg, stats[i].long_name);
440 encode_attrib(&msg, &stats[i].attrib);
442 send_msg(&msg);
443 buffer_free(&msg);
446 static void
447 send_attrib(u_int32_t id, const Attrib *a)
449 Buffer msg;
451 debug("request %u: sent attrib have 0x%x", id, a->flags);
452 buffer_init(&msg);
453 buffer_put_char(&msg, SSH2_FXP_ATTRS);
454 buffer_put_int(&msg, id);
455 encode_attrib(&msg, a);
456 send_msg(&msg);
457 buffer_free(&msg);
460 /* parse incoming */
462 static void
463 process_init(void)
465 Buffer msg;
467 version = get_int();
468 verbose("received client version %d", version);
469 buffer_init(&msg);
470 buffer_put_char(&msg, SSH2_FXP_VERSION);
471 buffer_put_int(&msg, SSH2_FILEXFER_VERSION);
472 send_msg(&msg);
473 buffer_free(&msg);
476 static void
477 process_open(void)
479 u_int32_t id, pflags;
480 Attrib *a;
481 char *name;
482 int handle, fd, flags, mode, status = SSH2_FX_FAILURE;
484 id = get_int();
485 name = get_string(NULL);
486 pflags = get_int(); /* portable flags */
487 debug3("request %u: open flags %d", id, pflags);
488 a = get_attrib();
489 flags = flags_from_portable(pflags);
490 mode = (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ? a->perm : 0666;
491 logit("open \"%s\" flags %s mode 0%o",
492 name, string_from_portable(pflags), mode);
493 fd = open(name, flags, mode);
494 if (fd < 0) {
495 status = errno_to_portable(errno);
496 } else {
497 handle = handle_new(HANDLE_FILE, name, fd, NULL);
498 if (handle < 0) {
499 close(fd);
500 } else {
501 send_handle(id, handle);
502 status = SSH2_FX_OK;
505 if (status != SSH2_FX_OK)
506 send_status(id, status);
507 xfree(name);
510 static void
511 process_close(void)
513 u_int32_t id;
514 int handle, ret, status = SSH2_FX_FAILURE;
516 id = get_int();
517 handle = get_handle();
518 debug3("request %u: close handle %u", id, handle);
519 handle_log_close(handle, NULL);
520 ret = handle_close(handle);
521 status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
522 send_status(id, status);
525 static void
526 process_read(void)
528 char buf[64*1024];
529 u_int32_t id, len;
530 int handle, fd, ret, status = SSH2_FX_FAILURE;
531 u_int64_t off;
533 id = get_int();
534 handle = get_handle();
535 off = get_int64();
536 len = get_int();
538 debug("request %u: read \"%s\" (handle %d) off %llu len %d",
539 id, handle_to_name(handle), handle, (unsigned long long)off, len);
540 if (len > sizeof buf) {
541 len = sizeof buf;
542 debug2("read change len %d", len);
544 fd = handle_to_fd(handle);
545 if (fd >= 0) {
546 if (lseek(fd, off, SEEK_SET) < 0) {
547 error("process_read: seek failed");
548 status = errno_to_portable(errno);
549 } else {
550 ret = read(fd, buf, len);
551 if (ret < 0) {
552 status = errno_to_portable(errno);
553 } else if (ret == 0) {
554 status = SSH2_FX_EOF;
555 } else {
556 send_data(id, buf, ret);
557 status = SSH2_FX_OK;
558 handle_update_read(handle, ret);
562 if (status != SSH2_FX_OK)
563 send_status(id, status);
566 static void
567 process_write(void)
569 u_int32_t id;
570 u_int64_t off;
571 u_int len;
572 int handle, fd, ret, status = SSH2_FX_FAILURE;
573 char *data;
575 id = get_int();
576 handle = get_handle();
577 off = get_int64();
578 data = get_string(&len);
580 debug("request %u: write \"%s\" (handle %d) off %llu len %d",
581 id, handle_to_name(handle), handle, (unsigned long long)off, len);
582 fd = handle_to_fd(handle);
583 if (fd >= 0) {
584 if (lseek(fd, off, SEEK_SET) < 0) {
585 status = errno_to_portable(errno);
586 error("process_write: seek failed");
587 } else {
588 /* XXX ATOMICIO ? */
589 ret = write(fd, data, len);
590 if (ret < 0) {
591 error("process_write: write failed");
592 status = errno_to_portable(errno);
593 } else if ((size_t)ret == len) {
594 status = SSH2_FX_OK;
595 handle_update_write(handle, ret);
596 } else {
597 debug2("nothing at all written");
601 send_status(id, status);
602 xfree(data);
605 static void
606 process_do_stat(int do_lstat)
608 Attrib a;
609 struct stat st;
610 u_int32_t id;
611 char *name;
612 int ret, status = SSH2_FX_FAILURE;
614 id = get_int();
615 name = get_string(NULL);
616 debug3("request %u: %sstat", id, do_lstat ? "l" : "");
617 verbose("%sstat name \"%s\"", do_lstat ? "l" : "", name);
618 ret = do_lstat ? lstat(name, &st) : stat(name, &st);
619 if (ret < 0) {
620 status = errno_to_portable(errno);
621 } else {
622 stat_to_attrib(&st, &a);
623 send_attrib(id, &a);
624 status = SSH2_FX_OK;
626 if (status != SSH2_FX_OK)
627 send_status(id, status);
628 xfree(name);
631 static void
632 process_stat(void)
634 process_do_stat(0);
637 static void
638 process_lstat(void)
640 process_do_stat(1);
643 static void
644 process_fstat(void)
646 Attrib a;
647 struct stat st;
648 u_int32_t id;
649 int fd, ret, handle, status = SSH2_FX_FAILURE;
651 id = get_int();
652 handle = get_handle();
653 debug("request %u: fstat \"%s\" (handle %u)",
654 id, handle_to_name(handle), handle);
655 fd = handle_to_fd(handle);
656 if (fd >= 0) {
657 ret = fstat(fd, &st);
658 if (ret < 0) {
659 status = errno_to_portable(errno);
660 } else {
661 stat_to_attrib(&st, &a);
662 send_attrib(id, &a);
663 status = SSH2_FX_OK;
666 if (status != SSH2_FX_OK)
667 send_status(id, status);
670 static struct timeval *
671 attrib_to_tv(const Attrib *a)
673 static struct timeval tv[2];
675 tv[0].tv_sec = a->atime;
676 tv[0].tv_usec = 0;
677 tv[1].tv_sec = a->mtime;
678 tv[1].tv_usec = 0;
679 return tv;
682 static void
683 process_setstat(void)
685 Attrib *a;
686 u_int32_t id;
687 char *name;
688 int status = SSH2_FX_OK, ret;
690 id = get_int();
691 name = get_string(NULL);
692 a = get_attrib();
693 debug("request %u: setstat name \"%s\"", id, name);
694 if (a->flags & SSH2_FILEXFER_ATTR_SIZE) {
695 logit("set \"%s\" size %llu", name, a->size);
696 ret = truncate(name, a->size);
697 if (ret == -1)
698 status = errno_to_portable(errno);
700 if (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) {
701 logit("set \"%s\" mode %04o", name, a->perm);
702 ret = chmod(name, a->perm & 0777);
703 if (ret == -1)
704 status = errno_to_portable(errno);
706 if (a->flags & SSH2_FILEXFER_ATTR_ACMODTIME) {
707 char buf[64];
708 time_t t = a->mtime;
710 strftime(buf, sizeof(buf), "%Y%m%d-%H:%M:%S",
711 localtime(&t));
712 logit("set \"%s\" modtime %s", name, buf);
713 ret = utimes(name, attrib_to_tv(a));
714 if (ret == -1)
715 status = errno_to_portable(errno);
717 if (a->flags & SSH2_FILEXFER_ATTR_UIDGID) {
718 logit("set \"%s\" owner %lu group %lu", name,
719 (u_long)a->uid, (u_long)a->gid);
720 ret = chown(name, a->uid, a->gid);
721 if (ret == -1)
722 status = errno_to_portable(errno);
724 send_status(id, status);
725 xfree(name);
728 static void
729 process_fsetstat(void)
731 Attrib *a;
732 u_int32_t id;
733 int handle, fd, ret;
734 int status = SSH2_FX_OK;
736 id = get_int();
737 handle = get_handle();
738 a = get_attrib();
739 debug("request %u: fsetstat handle %d", id, handle);
740 fd = handle_to_fd(handle);
741 if (fd < 0) {
742 status = SSH2_FX_FAILURE;
743 } else {
744 char *name = handle_to_name(handle);
746 if (a->flags & SSH2_FILEXFER_ATTR_SIZE) {
747 logit("set \"%s\" size %llu", name, a->size);
748 ret = ftruncate(fd, a->size);
749 if (ret == -1)
750 status = errno_to_portable(errno);
752 if (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) {
753 logit("set \"%s\" mode %04o", name, a->perm);
754 #ifdef HAVE_FCHMOD
755 ret = fchmod(fd, a->perm & 0777);
756 #else
757 ret = chmod(name, a->perm & 0777);
758 #endif
759 if (ret == -1)
760 status = errno_to_portable(errno);
762 if (a->flags & SSH2_FILEXFER_ATTR_ACMODTIME) {
763 char buf[64];
764 time_t t = a->mtime;
766 strftime(buf, sizeof(buf), "%Y%m%d-%H:%M:%S",
767 localtime(&t));
768 logit("set \"%s\" modtime %s", name, buf);
769 #ifdef HAVE_FUTIMES
770 ret = futimes(fd, attrib_to_tv(a));
771 #else
772 ret = utimes(name, attrib_to_tv(a));
773 #endif
774 if (ret == -1)
775 status = errno_to_portable(errno);
777 if (a->flags & SSH2_FILEXFER_ATTR_UIDGID) {
778 logit("set \"%s\" owner %lu group %lu", name,
779 (u_long)a->uid, (u_long)a->gid);
780 #ifdef HAVE_FCHOWN
781 ret = fchown(fd, a->uid, a->gid);
782 #else
783 ret = chown(name, a->uid, a->gid);
784 #endif
785 if (ret == -1)
786 status = errno_to_portable(errno);
789 send_status(id, status);
792 static void
793 process_opendir(void)
795 DIR *dirp = NULL;
796 char *path;
797 int handle, status = SSH2_FX_FAILURE;
798 u_int32_t id;
800 id = get_int();
801 path = get_string(NULL);
802 debug3("request %u: opendir", id);
803 logit("opendir \"%s\"", path);
804 dirp = opendir(path);
805 if (dirp == NULL) {
806 status = errno_to_portable(errno);
807 } else {
808 handle = handle_new(HANDLE_DIR, path, 0, dirp);
809 if (handle < 0) {
810 closedir(dirp);
811 } else {
812 send_handle(id, handle);
813 status = SSH2_FX_OK;
817 if (status != SSH2_FX_OK)
818 send_status(id, status);
819 xfree(path);
822 static void
823 process_readdir(void)
825 DIR *dirp;
826 struct dirent *dp;
827 char *path;
828 int handle;
829 u_int32_t id;
831 id = get_int();
832 handle = get_handle();
833 debug("request %u: readdir \"%s\" (handle %d)", id,
834 handle_to_name(handle), handle);
835 dirp = handle_to_dir(handle);
836 path = handle_to_name(handle);
837 if (dirp == NULL || path == NULL) {
838 send_status(id, SSH2_FX_FAILURE);
839 } else {
840 struct stat st;
841 char pathname[MAXPATHLEN];
842 Stat *stats;
843 int nstats = 10, count = 0, i;
845 stats = xcalloc(nstats, sizeof(Stat));
846 while ((dp = readdir(dirp)) != NULL) {
847 if (count >= nstats) {
848 nstats *= 2;
849 stats = xrealloc(stats, nstats, sizeof(Stat));
851 /* XXX OVERFLOW ? */
852 snprintf(pathname, sizeof pathname, "%s%s%s", path,
853 strcmp(path, "/") ? "/" : "", dp->d_name);
854 if (lstat(pathname, &st) < 0)
855 continue;
856 stat_to_attrib(&st, &(stats[count].attrib));
857 stats[count].name = xstrdup(dp->d_name);
858 stats[count].long_name = ls_file(dp->d_name, &st, 0);
859 count++;
860 /* send up to 100 entries in one message */
861 /* XXX check packet size instead */
862 if (count == 100)
863 break;
865 if (count > 0) {
866 send_names(id, count, stats);
867 for (i = 0; i < count; i++) {
868 xfree(stats[i].name);
869 xfree(stats[i].long_name);
871 } else {
872 send_status(id, SSH2_FX_EOF);
874 xfree(stats);
878 static void
879 process_remove(void)
881 char *name;
882 u_int32_t id;
883 int status = SSH2_FX_FAILURE;
884 int ret;
886 id = get_int();
887 name = get_string(NULL);
888 debug3("request %u: remove", id);
889 logit("remove name \"%s\"", name);
890 ret = unlink(name);
891 status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
892 send_status(id, status);
893 xfree(name);
896 static void
897 process_mkdir(void)
899 Attrib *a;
900 u_int32_t id;
901 char *name;
902 int ret, mode, status = SSH2_FX_FAILURE;
904 id = get_int();
905 name = get_string(NULL);
906 a = get_attrib();
907 mode = (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ?
908 a->perm & 0777 : 0777;
909 debug3("request %u: mkdir", id);
910 logit("mkdir name \"%s\" mode 0%o", name, mode);
911 ret = mkdir(name, mode);
912 status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
913 send_status(id, status);
914 xfree(name);
917 static void
918 process_rmdir(void)
920 u_int32_t id;
921 char *name;
922 int ret, status;
924 id = get_int();
925 name = get_string(NULL);
926 debug3("request %u: rmdir", id);
927 logit("rmdir name \"%s\"", name);
928 ret = rmdir(name);
929 status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
930 send_status(id, status);
931 xfree(name);
934 static void
935 process_realpath(void)
937 char resolvedname[MAXPATHLEN];
938 u_int32_t id;
939 char *path;
941 id = get_int();
942 path = get_string(NULL);
943 if (path[0] == '\0') {
944 xfree(path);
945 path = xstrdup(".");
947 debug3("request %u: realpath", id);
948 verbose("realpath \"%s\"", path);
949 if (realpath(path, resolvedname) == NULL) {
950 send_status(id, errno_to_portable(errno));
951 } else {
952 Stat s;
953 attrib_clear(&s.attrib);
954 s.name = s.long_name = resolvedname;
955 send_names(id, 1, &s);
957 xfree(path);
960 static void
961 process_rename(void)
963 u_int32_t id;
964 char *oldpath, *newpath;
965 int status;
966 struct stat sb;
968 id = get_int();
969 oldpath = get_string(NULL);
970 newpath = get_string(NULL);
971 debug3("request %u: rename", id);
972 logit("rename old \"%s\" new \"%s\"", oldpath, newpath);
973 status = SSH2_FX_FAILURE;
974 if (lstat(oldpath, &sb) == -1)
975 status = errno_to_portable(errno);
976 else if (S_ISREG(sb.st_mode)) {
977 /* Race-free rename of regular files */
978 if (link(oldpath, newpath) == -1) {
979 if (errno == EOPNOTSUPP
980 #ifdef LINK_OPNOTSUPP_ERRNO
981 || errno == LINK_OPNOTSUPP_ERRNO
982 #endif
984 struct stat st;
987 * fs doesn't support links, so fall back to
988 * stat+rename. This is racy.
990 if (stat(newpath, &st) == -1) {
991 if (rename(oldpath, newpath) == -1)
992 status =
993 errno_to_portable(errno);
994 else
995 status = SSH2_FX_OK;
997 } else {
998 status = errno_to_portable(errno);
1000 } else if (unlink(oldpath) == -1) {
1001 status = errno_to_portable(errno);
1002 /* clean spare link */
1003 unlink(newpath);
1004 } else
1005 status = SSH2_FX_OK;
1006 } else if (stat(newpath, &sb) == -1) {
1007 if (rename(oldpath, newpath) == -1)
1008 status = errno_to_portable(errno);
1009 else
1010 status = SSH2_FX_OK;
1012 send_status(id, status);
1013 xfree(oldpath);
1014 xfree(newpath);
1017 static void
1018 process_readlink(void)
1020 u_int32_t id;
1021 int len;
1022 char buf[MAXPATHLEN];
1023 char *path;
1025 id = get_int();
1026 path = get_string(NULL);
1027 debug3("request %u: readlink", id);
1028 verbose("readlink \"%s\"", path);
1029 if ((len = readlink(path, buf, sizeof(buf) - 1)) == -1)
1030 send_status(id, errno_to_portable(errno));
1031 else {
1032 Stat s;
1034 buf[len] = '\0';
1035 attrib_clear(&s.attrib);
1036 s.name = s.long_name = buf;
1037 send_names(id, 1, &s);
1039 xfree(path);
1042 static void
1043 process_symlink(void)
1045 u_int32_t id;
1046 char *oldpath, *newpath;
1047 int ret, status;
1049 id = get_int();
1050 oldpath = get_string(NULL);
1051 newpath = get_string(NULL);
1052 debug3("request %u: symlink", id);
1053 logit("symlink old \"%s\" new \"%s\"", oldpath, newpath);
1054 /* this will fail if 'newpath' exists */
1055 ret = symlink(oldpath, newpath);
1056 status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK;
1057 send_status(id, status);
1058 xfree(oldpath);
1059 xfree(newpath);
1062 static void
1063 process_extended(void)
1065 u_int32_t id;
1066 char *request;
1068 id = get_int();
1069 request = get_string(NULL);
1070 send_status(id, SSH2_FX_OP_UNSUPPORTED); /* MUST */
1071 xfree(request);
1074 /* stolen from ssh-agent */
1076 static void
1077 process(void)
1079 u_int msg_len;
1080 u_int buf_len;
1081 u_int consumed;
1082 u_int type;
1083 u_char *cp;
1085 buf_len = buffer_len(&iqueue);
1086 if (buf_len < 5)
1087 return; /* Incomplete message. */
1088 cp = buffer_ptr(&iqueue);
1089 msg_len = get_u32(cp);
1090 if (msg_len > SFTP_MAX_MSG_LENGTH) {
1091 error("bad message from %s local user %s",
1092 client_addr, pw->pw_name);
1093 cleanup_exit(11);
1095 if (buf_len < msg_len + 4)
1096 return;
1097 buffer_consume(&iqueue, 4);
1098 buf_len -= 4;
1099 type = buffer_get_char(&iqueue);
1100 switch (type) {
1101 case SSH2_FXP_INIT:
1102 process_init();
1103 break;
1104 case SSH2_FXP_OPEN:
1105 process_open();
1106 break;
1107 case SSH2_FXP_CLOSE:
1108 process_close();
1109 break;
1110 case SSH2_FXP_READ:
1111 process_read();
1112 break;
1113 case SSH2_FXP_WRITE:
1114 process_write();
1115 break;
1116 case SSH2_FXP_LSTAT:
1117 process_lstat();
1118 break;
1119 case SSH2_FXP_FSTAT:
1120 process_fstat();
1121 break;
1122 case SSH2_FXP_SETSTAT:
1123 process_setstat();
1124 break;
1125 case SSH2_FXP_FSETSTAT:
1126 process_fsetstat();
1127 break;
1128 case SSH2_FXP_OPENDIR:
1129 process_opendir();
1130 break;
1131 case SSH2_FXP_READDIR:
1132 process_readdir();
1133 break;
1134 case SSH2_FXP_REMOVE:
1135 process_remove();
1136 break;
1137 case SSH2_FXP_MKDIR:
1138 process_mkdir();
1139 break;
1140 case SSH2_FXP_RMDIR:
1141 process_rmdir();
1142 break;
1143 case SSH2_FXP_REALPATH:
1144 process_realpath();
1145 break;
1146 case SSH2_FXP_STAT:
1147 process_stat();
1148 break;
1149 case SSH2_FXP_RENAME:
1150 process_rename();
1151 break;
1152 case SSH2_FXP_READLINK:
1153 process_readlink();
1154 break;
1155 case SSH2_FXP_SYMLINK:
1156 process_symlink();
1157 break;
1158 case SSH2_FXP_EXTENDED:
1159 process_extended();
1160 break;
1161 default:
1162 error("Unknown message %d", type);
1163 break;
1165 /* discard the remaining bytes from the current packet */
1166 if (buf_len < buffer_len(&iqueue))
1167 fatal("iqueue grew unexpectedly");
1168 consumed = buf_len - buffer_len(&iqueue);
1169 if (msg_len < consumed)
1170 fatal("msg_len %d < consumed %d", msg_len, consumed);
1171 if (msg_len > consumed)
1172 buffer_consume(&iqueue, msg_len - consumed);
1175 /* Cleanup handler that logs active handles upon normal exit */
1176 void
1177 cleanup_exit(int i)
1179 if (pw != NULL && client_addr != NULL) {
1180 handle_log_exit();
1181 logit("session closed for local user %s from [%s]",
1182 pw->pw_name, client_addr);
1184 _exit(i);
1187 static void
1188 usage(void)
1190 extern char *__progname;
1192 fprintf(stderr,
1193 "usage: %s [-he] [-l log_level] [-f log_facility]\n", __progname);
1194 exit(1);
1198 main(int argc, char **argv)
1200 fd_set *rset, *wset;
1201 int in, out, max, ch, skipargs = 0, log_stderr = 0;
1202 ssize_t len, olen, set_size;
1203 SyslogFacility log_facility = SYSLOG_FACILITY_AUTH;
1204 char *cp;
1206 extern char *optarg;
1207 extern char *__progname;
1209 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1210 sanitise_stdfd();
1212 __progname = ssh_get_progname(argv[0]);
1213 log_init(__progname, log_level, log_facility, log_stderr);
1215 while (!skipargs && (ch = getopt(argc, argv, "C:f:l:che")) != -1) {
1216 switch (ch) {
1217 case 'c':
1219 * Ignore all arguments if we are invoked as a
1220 * shell using "sftp-server -c command"
1222 skipargs = 1;
1223 break;
1224 case 'e':
1225 log_stderr = 1;
1226 break;
1227 case 'l':
1228 log_level = log_level_number(optarg);
1229 if (log_level == SYSLOG_LEVEL_NOT_SET)
1230 error("Invalid log level \"%s\"", optarg);
1231 break;
1232 case 'f':
1233 log_facility = log_facility_number(optarg);
1234 if (log_level == SYSLOG_FACILITY_NOT_SET)
1235 error("Invalid log facility \"%s\"", optarg);
1236 break;
1237 case 'h':
1238 default:
1239 usage();
1243 log_init(__progname, log_level, log_facility, log_stderr);
1245 if ((cp = getenv("SSH_CONNECTION")) != NULL) {
1246 client_addr = xstrdup(cp);
1247 if ((cp = strchr(client_addr, ' ')) == NULL)
1248 fatal("Malformed SSH_CONNECTION variable: \"%s\"",
1249 getenv("SSH_CONNECTION"));
1250 *cp = '\0';
1251 } else
1252 client_addr = xstrdup("UNKNOWN");
1254 if ((pw = getpwuid(getuid())) == NULL)
1255 fatal("No user found for uid %lu", (u_long)getuid());
1256 pw = pwcopy(pw);
1258 logit("session opened for local user %s from [%s]",
1259 pw->pw_name, client_addr);
1261 handle_init();
1263 in = dup(STDIN_FILENO);
1264 out = dup(STDOUT_FILENO);
1266 #ifdef HAVE_CYGWIN
1267 setmode(in, O_BINARY);
1268 setmode(out, O_BINARY);
1269 #endif
1271 max = 0;
1272 if (in > max)
1273 max = in;
1274 if (out > max)
1275 max = out;
1277 buffer_init(&iqueue);
1278 buffer_init(&oqueue);
1280 set_size = howmany(max + 1, NFDBITS) * sizeof(fd_mask);
1281 rset = (fd_set *)xmalloc(set_size);
1282 wset = (fd_set *)xmalloc(set_size);
1284 for (;;) {
1285 memset(rset, 0, set_size);
1286 memset(wset, 0, set_size);
1288 FD_SET(in, rset);
1289 olen = buffer_len(&oqueue);
1290 if (olen > 0)
1291 FD_SET(out, wset);
1293 if (select(max+1, rset, wset, NULL, NULL) < 0) {
1294 if (errno == EINTR)
1295 continue;
1296 error("select: %s", strerror(errno));
1297 cleanup_exit(2);
1300 /* copy stdin to iqueue */
1301 if (FD_ISSET(in, rset)) {
1302 char buf[4*4096];
1303 len = read(in, buf, sizeof buf);
1304 if (len == 0) {
1305 debug("read eof");
1306 cleanup_exit(0);
1307 } else if (len < 0) {
1308 error("read: %s", strerror(errno));
1309 cleanup_exit(1);
1310 } else {
1311 buffer_append(&iqueue, buf, len);
1314 /* send oqueue to stdout */
1315 if (FD_ISSET(out, wset)) {
1316 len = write(out, buffer_ptr(&oqueue), olen);
1317 if (len < 0) {
1318 error("write: %s", strerror(errno));
1319 cleanup_exit(1);
1320 } else {
1321 buffer_consume(&oqueue, len);
1324 /* process requests from client */
1325 process();