]> andersk Git - openssh.git/blob - sftp-server.c
- jmc@cvs.openbsd.org 2006/07/18 07:56:28
[openssh.git] / sftp-server.c
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.
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 #include "includes.h"
18
19 #include <sys/types.h>
20 #include <sys/stat.h>
21
22 #include <dirent.h>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <pwd.h>
26 #include <unistd.h>
27
28 #include "buffer.h"
29 #include "bufaux.h"
30 #include "log.h"
31 #include "xmalloc.h"
32 #include "misc.h"
33 #include "uidswap.h"
34
35 #include "sftp.h"
36 #include "sftp-common.h"
37
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);
42
43 /* Our verbosity */
44 LogLevel log_level = SYSLOG_LEVEL_ERROR;
45
46 /* Our client */
47 struct passwd *pw = NULL;
48 char *client_addr = NULL;
49
50 /* input and output queue */
51 Buffer iqueue;
52 Buffer oqueue;
53
54 /* Version of client */
55 int version;
56
57 /* portable attributes, etc. */
58
59 typedef struct Stat Stat;
60
61 struct Stat {
62         char *name;
63         char *long_name;
64         Attrib attrib;
65 };
66
67 static int
68 errno_to_portable(int unixerrno)
69 {
70         int ret = 0;
71
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;
94         }
95         return ret;
96 }
97
98 static int
99 flags_from_portable(int pflags)
100 {
101         int flags = 0;
102
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;
110         }
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;
118 }
119
120 static const char *
121 string_from_portable(int pflags)
122 {
123         static char ret[128];
124
125         *ret = '\0';
126
127 #define PAPPEND(str)    {                               \
128                 if (*ret != '\0')                       \
129                         strlcat(ret, ",", sizeof(ret)); \
130                 strlcat(ret, str, sizeof(ret));         \
131         }
132
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")
143
144         return ret;
145 }
146
147 static Attrib *
148 get_attrib(void)
149 {
150         return decode_attrib(&iqueue);
151 }
152
153 /* handle handles */
154
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;
162 };
163
164 enum {
165         HANDLE_UNUSED,
166         HANDLE_DIR,
167         HANDLE_FILE
168 };
169
170 Handle  handles[100];
171
172 static void
173 handle_init(void)
174 {
175         u_int i;
176
177         for (i = 0; i < sizeof(handles)/sizeof(Handle); i++)
178                 handles[i].use = HANDLE_UNUSED;
179 }
180
181 static int
182 handle_new(int use, const char *name, int fd, DIR *dirp)
183 {
184         u_int i;
185
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;
194                 }
195         }
196         return -1;
197 }
198
199 static int
200 handle_is_ok(int i, int type)
201 {
202         return i >= 0 && (u_int)i < sizeof(handles)/sizeof(Handle) &&
203             handles[i].use == type;
204 }
205
206 static int
207 handle_to_string(int handle, char **stringp, int *hlenp)
208 {
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;
215 }
216
217 static int
218 handle_from_string(const char *handle, u_int hlen)
219 {
220         int val;
221
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;
229 }
230
231 static char *
232 handle_to_name(int handle)
233 {
234         if (handle_is_ok(handle, HANDLE_DIR)||
235             handle_is_ok(handle, HANDLE_FILE))
236                 return handles[handle].name;
237         return NULL;
238 }
239
240 static DIR *
241 handle_to_dir(int handle)
242 {
243         if (handle_is_ok(handle, HANDLE_DIR))
244                 return handles[handle].dirp;
245         return NULL;
246 }
247
248 static int
249 handle_to_fd(int handle)
250 {
251         if (handle_is_ok(handle, HANDLE_FILE))
252                 return handles[handle].fd;
253         return -1;
254 }
255
256 static void
257 handle_update_read(int handle, ssize_t bytes)
258 {
259         if (handle_is_ok(handle, HANDLE_FILE) && bytes > 0)
260                 handles[handle].bytes_read += bytes;
261 }
262
263 static void
264 handle_update_write(int handle, ssize_t bytes)
265 {
266         if (handle_is_ok(handle, HANDLE_FILE) && bytes > 0)
267                 handles[handle].bytes_write += bytes;
268 }
269
270 static u_int64_t
271 handle_bytes_read(int handle)
272 {
273         if (handle_is_ok(handle, HANDLE_FILE))
274                 return (handles[handle].bytes_read);
275         return 0;
276 }
277
278 static u_int64_t
279 handle_bytes_write(int handle)
280 {
281         if (handle_is_ok(handle, HANDLE_FILE))
282                 return (handles[handle].bytes_write);
283         return 0;
284 }
285
286 static int
287 handle_close(int handle)
288 {
289         int ret = -1;
290
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;
301         }
302         return ret;
303 }
304
305 static void
306 handle_log_close(int handle, char *emsg)
307 {
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));
317         }
318 }
319
320 static void
321 handle_log_exit(void)
322 {
323         u_int i;
324
325         for (i = 0; i < sizeof(handles)/sizeof(Handle); i++)
326                 if (handles[i].use != HANDLE_UNUSED)
327                         handle_log_close(i, "forced");
328 }
329
330 static int
331 get_handle(void)
332 {
333         char *handle;
334         int val = -1;
335         u_int hlen;
336
337         handle = get_string(&hlen);
338         if (hlen < 256)
339                 val = handle_from_string(handle, hlen);
340         xfree(handle);
341         return val;
342 }
343
344 /* send replies */
345
346 static void
347 send_msg(Buffer *m)
348 {
349         int mlen = buffer_len(m);
350
351         buffer_put_int(&oqueue, mlen);
352         buffer_append(&oqueue, buffer_ptr(m), mlen);
353         buffer_consume(m, mlen);
354 }
355
356 static const char *
357 status_to_message(u_int32_t status)
358 {
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 */
370         };
371         return (status_messages[MIN(status,SSH2_FX_MAX)]);
372 }
373
374 static void
375 send_status(u_int32_t id, u_int32_t status)
376 {
377         Buffer msg;
378
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, "");
390         }
391         send_msg(&msg);
392         buffer_free(&msg);
393 }
394 static void
395 send_data_or_handle(char type, u_int32_t id, const char *data, int dlen)
396 {
397         Buffer msg;
398
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);
405 }
406
407 static void
408 send_data(u_int32_t id, const char *data, int dlen)
409 {
410         debug("request %u: sent data len %d", id, dlen);
411         send_data_or_handle(SSH2_FXP_DATA, id, data, dlen);
412 }
413
414 static void
415 send_handle(u_int32_t id, int handle)
416 {
417         char *string;
418         int hlen;
419
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);
424 }
425
426 static void
427 send_names(u_int32_t id, int count, const Stat *stats)
428 {
429         Buffer msg;
430         int i;
431
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);
441         }
442         send_msg(&msg);
443         buffer_free(&msg);
444 }
445
446 static void
447 send_attrib(u_int32_t id, const Attrib *a)
448 {
449         Buffer msg;
450
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);
458 }
459
460 /* parse incoming */
461
462 static void
463 process_init(void)
464 {
465         Buffer msg;
466
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);
474 }
475
476 static void
477 process_open(void)
478 {
479         u_int32_t id, pflags;
480         Attrib *a;
481         char *name;
482         int handle, fd, flags, mode, status = SSH2_FX_FAILURE;
483
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;
503                 }
504         }
505         if (status != SSH2_FX_OK)
506                 send_status(id, status);
507         xfree(name);
508 }
509
510 static void
511 process_close(void)
512 {
513         u_int32_t id;
514         int handle, ret, status = SSH2_FX_FAILURE;
515
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);
523 }
524
525 static void
526 process_read(void)
527 {
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;
532
533         id = get_int();
534         handle = get_handle();
535         off = get_int64();
536         len = get_int();
537
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);
543         }
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);
559                         }
560                 }
561         }
562         if (status != SSH2_FX_OK)
563                 send_status(id, status);
564 }
565
566 static void
567 process_write(void)
568 {
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;
574
575         id = get_int();
576         handle = get_handle();
577         off = get_int64();
578         data = get_string(&len);
579
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");
598                         }
599                 }
600         }
601         send_status(id, status);
602         xfree(data);
603 }
604
605 static void
606 process_do_stat(int do_lstat)
607 {
608         Attrib a;
609         struct stat st;
610         u_int32_t id;
611         char *name;
612         int ret, status = SSH2_FX_FAILURE;
613
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;
625         }
626         if (status != SSH2_FX_OK)
627                 send_status(id, status);
628         xfree(name);
629 }
630
631 static void
632 process_stat(void)
633 {
634         process_do_stat(0);
635 }
636
637 static void
638 process_lstat(void)
639 {
640         process_do_stat(1);
641 }
642
643 static void
644 process_fstat(void)
645 {
646         Attrib a;
647         struct stat st;
648         u_int32_t id;
649         int fd, ret, handle, status = SSH2_FX_FAILURE;
650
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;
664                 }
665         }
666         if (status != SSH2_FX_OK)
667                 send_status(id, status);
668 }
669
670 static struct timeval *
671 attrib_to_tv(const Attrib *a)
672 {
673         static struct timeval tv[2];
674
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;
680 }
681
682 static void
683 process_setstat(void)
684 {
685         Attrib *a;
686         u_int32_t id;
687         char *name;
688         int status = SSH2_FX_OK, ret;
689
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);
699         }
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);
705         }
706         if (a->flags & SSH2_FILEXFER_ATTR_ACMODTIME) {
707                 char buf[64];
708                 time_t t = a->mtime;
709
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);
716         }
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);
723         }
724         send_status(id, status);
725         xfree(name);
726 }
727
728 static void
729 process_fsetstat(void)
730 {
731         Attrib *a;
732         u_int32_t id;
733         int handle, fd, ret;
734         int status = SSH2_FX_OK;
735
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);
745
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);
751                 }
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);
761                 }
762                 if (a->flags & SSH2_FILEXFER_ATTR_ACMODTIME) {
763                         char buf[64];
764                         time_t t = a->mtime;
765
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);
776                 }
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);
787                 }
788         }
789         send_status(id, status);
790 }
791
792 static void
793 process_opendir(void)
794 {
795         DIR *dirp = NULL;
796         char *path;
797         int handle, status = SSH2_FX_FAILURE;
798         u_int32_t id;
799
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;
814                 }
815
816         }
817         if (status != SSH2_FX_OK)
818                 send_status(id, status);
819         xfree(path);
820 }
821
822 static void
823 process_readdir(void)
824 {
825         DIR *dirp;
826         struct dirent *dp;
827         char *path;
828         int handle;
829         u_int32_t id;
830
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;
844
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));
850                         }
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;
864                 }
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);
870                         }
871                 } else {
872                         send_status(id, SSH2_FX_EOF);
873                 }
874                 xfree(stats);
875         }
876 }
877
878 static void
879 process_remove(void)
880 {
881         char *name;
882         u_int32_t id;
883         int status = SSH2_FX_FAILURE;
884         int ret;
885
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);
894 }
895
896 static void
897 process_mkdir(void)
898 {
899         Attrib *a;
900         u_int32_t id;
901         char *name;
902         int ret, mode, status = SSH2_FX_FAILURE;
903
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);
915 }
916
917 static void
918 process_rmdir(void)
919 {
920         u_int32_t id;
921         char *name;
922         int ret, status;
923
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);
932 }
933
934 static void
935 process_realpath(void)
936 {
937         char resolvedname[MAXPATHLEN];
938         u_int32_t id;
939         char *path;
940
941         id = get_int();
942         path = get_string(NULL);
943         if (path[0] == '\0') {
944                 xfree(path);
945                 path = xstrdup(".");
946         }
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);
956         }
957         xfree(path);
958 }
959
960 static void
961 process_rename(void)
962 {
963         u_int32_t id;
964         char *oldpath, *newpath;
965         int status;
966         struct stat sb;
967
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
983                             ) {
984                                 struct stat st;
985
986                                 /*
987                                  * fs doesn't support links, so fall back to
988                                  * stat+rename.  This is racy.
989                                  */
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;
996                                 }
997                         } else {
998                                 status = errno_to_portable(errno);
999                         }
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;
1011         }
1012         send_status(id, status);
1013         xfree(oldpath);
1014         xfree(newpath);
1015 }
1016
1017 static void
1018 process_readlink(void)
1019 {
1020         u_int32_t id;
1021         int len;
1022         char buf[MAXPATHLEN];
1023         char *path;
1024
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;
1033
1034                 buf[len] = '\0';
1035                 attrib_clear(&s.attrib);
1036                 s.name = s.long_name = buf;
1037                 send_names(id, 1, &s);
1038         }
1039         xfree(path);
1040 }
1041
1042 static void
1043 process_symlink(void)
1044 {
1045         u_int32_t id;
1046         char *oldpath, *newpath;
1047         int ret, status;
1048
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);
1060 }
1061
1062 static void
1063 process_extended(void)
1064 {
1065         u_int32_t id;
1066         char *request;
1067
1068         id = get_int();
1069         request = get_string(NULL);
1070         send_status(id, SSH2_FX_OP_UNSUPPORTED);                /* MUST */
1071         xfree(request);
1072 }
1073
1074 /* stolen from ssh-agent */
1075
1076 static void
1077 process(void)
1078 {
1079         u_int msg_len;
1080         u_int buf_len;
1081         u_int consumed;
1082         u_int type;
1083         u_char *cp;
1084
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);
1094         }
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;
1164         }
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);
1173 }
1174
1175 /* Cleanup handler that logs active handles upon normal exit */
1176 void
1177 cleanup_exit(int i)
1178 {
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);
1183         }
1184         _exit(i);
1185 }
1186
1187 static void
1188 usage(void)
1189 {
1190         extern char *__progname;
1191
1192         fprintf(stderr,
1193             "usage: %s [-he] [-l log_level] [-f log_facility]\n", __progname);
1194         exit(1);
1195 }
1196
1197 int
1198 main(int argc, char **argv)
1199 {
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;
1205
1206         extern char *optarg;
1207         extern char *__progname;
1208
1209         /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1210         sanitise_stdfd();
1211
1212         __progname = ssh_get_progname(argv[0]);
1213         log_init(__progname, log_level, log_facility, log_stderr);
1214
1215         while (!skipargs && (ch = getopt(argc, argv, "C:f:l:che")) != -1) {
1216                 switch (ch) {
1217                 case 'c':
1218                         /*
1219                          * Ignore all arguments if we are invoked as a
1220                          * shell using "sftp-server -c command" 
1221                          */
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();
1240                 }
1241         }
1242
1243         log_init(__progname, log_level, log_facility, log_stderr);
1244
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");
1253
1254         if ((pw = getpwuid(getuid())) == NULL)
1255                 fatal("No user found for uid %lu", (u_long)getuid());
1256         pw = pwcopy(pw);
1257
1258         logit("session opened for local user %s from [%s]",
1259             pw->pw_name, client_addr);
1260
1261         handle_init();
1262
1263         in = dup(STDIN_FILENO);
1264         out = dup(STDOUT_FILENO);
1265
1266 #ifdef HAVE_CYGWIN
1267         setmode(in, O_BINARY);
1268         setmode(out, O_BINARY);
1269 #endif
1270
1271         max = 0;
1272         if (in > max)
1273                 max = in;
1274         if (out > max)
1275                 max = out;
1276
1277         buffer_init(&iqueue);
1278         buffer_init(&oqueue);
1279
1280         set_size = howmany(max + 1, NFDBITS) * sizeof(fd_mask);
1281         rset = (fd_set *)xmalloc(set_size);
1282         wset = (fd_set *)xmalloc(set_size);
1283
1284         for (;;) {
1285                 memset(rset, 0, set_size);
1286                 memset(wset, 0, set_size);
1287
1288                 FD_SET(in, rset);
1289                 olen = buffer_len(&oqueue);
1290                 if (olen > 0)
1291                         FD_SET(out, wset);
1292
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);
1298                 }
1299
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);
1312                         }
1313                 }
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);
1322                         }
1323                 }
1324                 /* process requests from client */
1325                 process();
1326         }
1327 }
This page took 0.142403 seconds and 5 git commands to generate.