sdcard.c revision 75e17a8908d52e32f5de85b90b74e156265c60c6
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <stdio.h>
18#include <stdlib.h>
19#include <string.h>
20#include <unistd.h>
21#include <errno.h>
22#include <fcntl.h>
23#include <sys/mount.h>
24#include <sys/stat.h>
25#include <sys/statfs.h>
26#include <sys/uio.h>
27#include <dirent.h>
28#include <ctype.h>
29
30#include <private/android_filesystem_config.h>
31
32#include "fuse.h"
33
34/* README
35 *
36 * What is this?
37 *
38 * sdcard is a program that uses FUSE to emulate FAT-on-sdcard style
39 * directory permissions (all files are given fixed owner, group, and
40 * permissions at creation, owner, group, and permissions are not
41 * changeable, symlinks and hardlinks are not createable, etc.
42 *
43 * usage:  sdcard <path> <uid> <gid>
44 *
45 * It must be run as root, but will change to uid/gid as soon as it
46 * mounts a filesystem on /mnt/sdcard.  It will refuse to run if uid or
47 * gid are zero.
48 *
49 *
50 * Things I believe to be true:
51 *
52 * - ops that return a fuse_entry (LOOKUP, MKNOD, MKDIR, LINK, SYMLINK,
53 * CREAT) must bump that node's refcount
54 * - don't forget that FORGET can forget multiple references (req->nlookup)
55 * - if an op that returns a fuse_entry fails writing the reply to the
56 * kernel, you must rollback the refcount to reflect the reference the
57 * kernel did not actually acquire
58 *
59 */
60
61#define FUSE_TRACE 0
62
63#if FUSE_TRACE
64#define TRACE(x...) fprintf(stderr,x)
65#else
66#define TRACE(x...) do {} while (0)
67#endif
68
69#define ERROR(x...) fprintf(stderr,x)
70
71#define FUSE_UNKNOWN_INO 0xffffffff
72
73#define MOUNT_POINT "/mnt/sdcard"
74
75struct handle {
76    struct node *node;
77    int fd;
78};
79
80struct dirhandle {
81    struct node *node;
82    DIR *d;
83};
84
85struct node {
86    __u64 nid;
87    __u64 gen;
88
89    struct node *next;          /* per-dir sibling list */
90    struct node *child;         /* first contained file by this dir */
91    struct node *all;           /* global node list */
92    struct node *parent;        /* containing directory */
93
94    __u32 refcount;
95    __u32 namelen;
96
97    char *name;
98    /* If non-null, this is the real name of the file in the underlying storage.
99     * This may differ from the field "name" only by case.
100     * strlen(actual_name) will always equal strlen(name), so it is safe to use
101     * namelen for both fields.
102     */
103    char *actual_name;
104};
105
106struct fuse {
107    __u64 next_generation;
108    __u64 next_node_id;
109
110    int fd;
111
112    struct node *all;
113
114    struct node root;
115    char rootpath[1024];
116};
117
118static unsigned uid = -1;
119static unsigned gid = -1;
120
121#define PATH_BUFFER_SIZE 1024
122
123#define NO_CASE_SENSITIVE_MATCH 0
124#define CASE_SENSITIVE_MATCH 1
125
126/*
127 * Get the real-life absolute path to a node.
128 *   node: start at this node
129 *   buf: storage for returned string
130 *   name: append this string to path if set
131 */
132char *do_node_get_path(struct node *node, char *buf, const char *name, int match_case_insensitive)
133{
134    struct node *in_node = node;
135    const char *in_name = name;
136    char *out = buf + PATH_BUFFER_SIZE - 1;
137    int len;
138    out[0] = 0;
139
140    if (name) {
141        len = strlen(name);
142        goto start;
143    }
144
145    while (node) {
146        name = (node->actual_name ? node->actual_name : node->name);
147        len = node->namelen;
148        node = node->parent;
149    start:
150        if ((len + 1) > (out - buf))
151            return 0;
152        out -= len;
153        memcpy(out, name, len);
154        /* avoid double slash at beginning of path */
155        if (out[0] != '/') {
156            out --;
157            out[0] = '/';
158        }
159    }
160
161    /* If we are searching for a file within node (rather than computing node's path)
162     * and fail, then we need to look for a case insensitive match.
163     */
164    if (in_name && match_case_insensitive && access(out, F_OK) != 0) {
165        char *path, buffer[PATH_BUFFER_SIZE];
166        DIR* dir;
167        struct dirent* entry;
168        path = do_node_get_path(in_node, buffer, NULL, NO_CASE_SENSITIVE_MATCH);
169        dir = opendir(path);
170        if (!dir) {
171            ERROR("opendir %s failed: %s", path, strerror(errno));
172            return out;
173        }
174
175        while ((entry = readdir(dir))) {
176            if (!strcasecmp(entry->d_name, in_name)) {
177                /* we have a match - replace the name */
178                len = strlen(in_name);
179                memcpy(buf + PATH_BUFFER_SIZE - len - 1, entry->d_name, len);
180                break;
181            }
182        }
183        closedir(dir);
184    }
185
186   return out;
187}
188
189char *node_get_path(struct node *node, char *buf, const char *name)
190{
191    /* We look for case insensitive matches by default */
192    return do_node_get_path(node, buf, name, CASE_SENSITIVE_MATCH);
193}
194
195void attr_from_stat(struct fuse_attr *attr, struct stat *s)
196{
197    attr->ino = s->st_ino;
198    attr->size = s->st_size;
199    attr->blocks = s->st_blocks;
200    attr->atime = s->st_atime;
201    attr->mtime = s->st_mtime;
202    attr->ctime = s->st_ctime;
203    attr->atimensec = s->st_atime_nsec;
204    attr->mtimensec = s->st_mtime_nsec;
205    attr->ctimensec = s->st_ctime_nsec;
206    attr->mode = s->st_mode;
207    attr->nlink = s->st_nlink;
208
209        /* force permissions to something reasonable:
210         * world readable
211         * writable by the sdcard group
212         */
213    if (attr->mode & 0100) {
214        attr->mode = (attr->mode & (~0777)) | 0775;
215    } else {
216        attr->mode = (attr->mode & (~0777)) | 0664;
217    }
218
219        /* all files owned by root.sdcard */
220    attr->uid = 0;
221    attr->gid = AID_SDCARD_RW;
222}
223
224int node_get_attr(struct node *node, struct fuse_attr *attr)
225{
226    int res;
227    struct stat s;
228    char *path, buffer[PATH_BUFFER_SIZE];
229
230    path = node_get_path(node, buffer, 0);
231    res = lstat(path, &s);
232    if (res < 0) {
233        ERROR("lstat('%s') errno %d\n", path, errno);
234        return -1;
235    }
236
237    attr_from_stat(attr, &s);
238    attr->ino = node->nid;
239
240    return 0;
241}
242
243static void add_node_to_parent(struct node *node, struct node *parent) {
244    node->parent = parent;
245    node->next = parent->child;
246    parent->child = node;
247    parent->refcount++;
248}
249
250/* Check to see if our parent directory already has a file with a name
251 * that differs only by case.  If we find one, store it in the actual_name
252 * field so node_get_path will map it to this file in the underlying storage.
253 */
254static void node_find_actual_name(struct node *node)
255{
256    char *path, buffer[PATH_BUFFER_SIZE];
257    const char *node_name = node->name;
258    DIR* dir;
259    struct dirent* entry;
260
261    if (!node->parent) return;
262
263    path = node_get_path(node->parent, buffer, 0);
264    dir = opendir(path);
265    if (!dir) {
266        ERROR("opendir %s failed: %s", path, strerror(errno));
267        return;
268    }
269
270    while ((entry = readdir(dir))) {
271        const char *test_name = entry->d_name;
272        if (strcmp(test_name, node_name) && !strcasecmp(test_name, node_name)) {
273            /* we have a match - differs but only by case */
274            node->actual_name = strdup(test_name);
275            if (!node->actual_name) {
276                ERROR("strdup failed - out of memory\n");
277                exit(1);
278            }
279            break;
280        }
281    }
282    closedir(dir);
283}
284
285struct node *node_create(struct node *parent, const char *name, __u64 nid, __u64 gen)
286{
287    struct node *node;
288    int namelen = strlen(name);
289
290    node = calloc(1, sizeof(struct node));
291    if (node == 0) {
292        return 0;
293    }
294    node->name = malloc(namelen + 1);
295    if (node->name == 0) {
296        free(node);
297        return 0;
298    }
299
300    node->nid = nid;
301    node->gen = gen;
302    add_node_to_parent(node, parent);
303    memcpy(node->name, name, namelen + 1);
304    node->namelen = namelen;
305    node_find_actual_name(node);
306    return node;
307}
308
309static char *rename_node(struct node *node, const char *name)
310{
311    node->namelen = strlen(name);
312    char *newname = realloc(node->name, node->namelen + 1);
313    if (newname == 0)
314        return 0;
315    node->name = newname;
316    memcpy(node->name, name, node->namelen + 1);
317    node_find_actual_name(node);
318    return node->name;
319}
320
321void fuse_init(struct fuse *fuse, int fd, const char *path)
322{
323    fuse->fd = fd;
324    fuse->next_node_id = 2;
325    fuse->next_generation = 0;
326
327    fuse->all = &fuse->root;
328
329    fuse->root.nid = FUSE_ROOT_ID; /* 1 */
330    fuse->root.next = 0;
331    fuse->root.child = 0;
332    fuse->root.parent = 0;
333
334    fuse->root.all = 0;
335    fuse->root.refcount = 2;
336
337    fuse->root.name = 0;
338    rename_node(&fuse->root, path);
339}
340
341static inline void *id_to_ptr(__u64 nid)
342{
343    return (void *) nid;
344}
345
346static inline __u64 ptr_to_id(void *ptr)
347{
348    return (__u64) ptr;
349}
350
351
352struct node *lookup_by_inode(struct fuse *fuse, __u64 nid)
353{
354    if (nid == FUSE_ROOT_ID) {
355        return &fuse->root;
356    } else {
357        return id_to_ptr(nid);
358    }
359}
360
361struct node *lookup_child_by_name(struct node *node, const char *name)
362{
363    for (node = node->child; node; node = node->next) {
364        if (!strcmp(name, node->name)) {
365            return node;
366        }
367    }
368    return 0;
369}
370
371struct node *lookup_child_by_inode(struct node *node, __u64 nid)
372{
373    for (node = node->child; node; node = node->next) {
374        if (node->nid == nid) {
375            return node;
376        }
377    }
378    return 0;
379}
380
381static void dec_refcount(struct node *node) {
382    if (node->refcount > 0) {
383        node->refcount--;
384        TRACE("dec_refcount %p(%s) -> %d\n", node, node->name, node->refcount);
385    } else {
386        ERROR("Zero refcnt %p\n", node);
387    }
388 }
389
390static struct node *remove_child(struct node *parent, __u64 nid)
391{
392    struct node *prev = 0;
393    struct node *node;
394
395    for (node = parent->child; node; node = node->next) {
396        if (node->nid == nid) {
397            if (prev) {
398                prev->next = node->next;
399            } else {
400                parent->child = node->next;
401            }
402            node->next = 0;
403            node->parent = 0;
404            dec_refcount(parent);
405            return node;
406        }
407        prev = node;
408    }
409    return 0;
410}
411
412struct node *node_lookup(struct fuse *fuse, struct node *parent, const char *name,
413                         struct fuse_attr *attr)
414{
415    int res;
416    struct stat s;
417    char *path, buffer[PATH_BUFFER_SIZE];
418    struct node *node;
419
420    path = node_get_path(parent, buffer, name);
421        /* XXX error? */
422
423    res = lstat(path, &s);
424    if (res < 0)
425        return 0;
426
427    node = lookup_child_by_name(parent, name);
428    if (!node) {
429        node = node_create(parent, name, fuse->next_node_id++, fuse->next_generation++);
430        if (!node)
431            return 0;
432        node->nid = ptr_to_id(node);
433        node->all = fuse->all;
434        fuse->all = node;
435    }
436
437    attr_from_stat(attr, &s);
438    attr->ino = node->nid;
439
440    return node;
441}
442
443void node_release(struct node *node)
444{
445    TRACE("RELEASE %p (%s) rc=%d\n", node, node->name, node->refcount);
446    dec_refcount(node);
447    if (node->refcount == 0) {
448        if (node->parent->child == node) {
449            node->parent->child = node->parent->child->next;
450        } else {
451            struct node *node2;
452
453            node2 = node->parent->child;
454            while (node2->next != node)
455                node2 = node2->next;
456            node2->next = node->next;
457        }
458
459        TRACE("DESTROY %p (%s)\n", node, node->name);
460
461        node_release(node->parent);
462
463        node->parent = 0;
464        node->next = 0;
465
466            /* TODO: remove debugging - poison memory */
467        memset(node->name, 0xef, node->namelen);
468        free(node->name);
469        free(node->actual_name);
470        memset(node, 0xfc, sizeof(*node));
471        free(node);
472    }
473}
474
475void fuse_status(struct fuse *fuse, __u64 unique, int err)
476{
477    struct fuse_out_header hdr;
478    hdr.len = sizeof(hdr);
479    hdr.error = err;
480    hdr.unique = unique;
481    if (err) {
482//        ERROR("*** %d ***\n", err);
483    }
484    write(fuse->fd, &hdr, sizeof(hdr));
485}
486
487void fuse_reply(struct fuse *fuse, __u64 unique, void *data, int len)
488{
489    struct fuse_out_header hdr;
490    struct iovec vec[2];
491    int res;
492
493    hdr.len = len + sizeof(hdr);
494    hdr.error = 0;
495    hdr.unique = unique;
496
497    vec[0].iov_base = &hdr;
498    vec[0].iov_len = sizeof(hdr);
499    vec[1].iov_base = data;
500    vec[1].iov_len = len;
501
502    res = writev(fuse->fd, vec, 2);
503    if (res < 0) {
504        ERROR("*** REPLY FAILED *** %d\n", errno);
505    }
506}
507
508void lookup_entry(struct fuse *fuse, struct node *node,
509                  const char *name, __u64 unique)
510{
511    struct fuse_entry_out out;
512
513    memset(&out, 0, sizeof(out));
514
515    node = node_lookup(fuse, node, name, &out.attr);
516    if (!node) {
517        fuse_status(fuse, unique, -ENOENT);
518        return;
519    }
520
521    node->refcount++;
522//    fprintf(stderr,"ACQUIRE %p (%s) rc=%d\n", node, node->name, node->refcount);
523    out.nodeid = node->nid;
524    out.generation = node->gen;
525    out.entry_valid = 10;
526    out.attr_valid = 10;
527
528    fuse_reply(fuse, unique, &out, sizeof(out));
529}
530
531void handle_fuse_request(struct fuse *fuse, struct fuse_in_header *hdr, void *data, unsigned len)
532{
533    struct node *node;
534
535    if ((len < sizeof(*hdr)) || (hdr->len != len)) {
536        ERROR("malformed header\n");
537        return;
538    }
539
540    len -= hdr->len;
541
542    if (hdr->nodeid) {
543        node = lookup_by_inode(fuse, hdr->nodeid);
544        if (!node) {
545            fuse_status(fuse, hdr->unique, -ENOENT);
546            return;
547        }
548    } else {
549        node = 0;
550    }
551
552    switch (hdr->opcode) {
553    case FUSE_LOOKUP: { /* bytez[] -> entry_out */
554        TRACE("LOOKUP %llx %s\n", hdr->nodeid, (char*) data);
555        lookup_entry(fuse, node, (char*) data, hdr->unique);
556        return;
557    }
558    case FUSE_FORGET: {
559        struct fuse_forget_in *req = data;
560        TRACE("FORGET %llx (%s) #%lld\n", hdr->nodeid, node->name, req->nlookup);
561            /* no reply */
562        while (req->nlookup--)
563            node_release(node);
564        return;
565    }
566    case FUSE_GETATTR: { /* getattr_in -> attr_out */
567        struct fuse_getattr_in *req = data;
568        struct fuse_attr_out out;
569
570        TRACE("GETATTR flags=%x fh=%llx\n", req->getattr_flags, req->fh);
571
572        memset(&out, 0, sizeof(out));
573        node_get_attr(node, &out.attr);
574        out.attr_valid = 10;
575
576        fuse_reply(fuse, hdr->unique, &out, sizeof(out));
577        return;
578    }
579    case FUSE_SETATTR: { /* setattr_in -> attr_out */
580        struct fuse_setattr_in *req = data;
581        struct fuse_attr_out out;
582        char *path, buffer[PATH_BUFFER_SIZE];
583        int res = 0;
584
585        TRACE("SETATTR fh=%llx id=%llx valid=%x\n",
586              req->fh, hdr->nodeid, req->valid);
587
588        /* XXX: incomplete implementation -- truncate only.  chmod/chown
589         * should NEVER be implemented. */
590
591        path = node_get_path(node, buffer, 0);
592        if (req->valid & FATTR_SIZE)
593            res = truncate(path, req->size);
594
595        memset(&out, 0, sizeof(out));
596        node_get_attr(node, &out.attr);
597        out.attr_valid = 10;
598
599        if (res)
600            fuse_status(fuse, hdr->unique, -errno);
601        else
602            fuse_reply(fuse, hdr->unique, &out, sizeof(out));
603        return;
604    }
605//    case FUSE_READLINK:
606//    case FUSE_SYMLINK:
607    case FUSE_MKNOD: { /* mknod_in, bytez[] -> entry_out */
608        struct fuse_mknod_in *req = data;
609        char *path, buffer[PATH_BUFFER_SIZE];
610        char *name = ((char*) data) + sizeof(*req);
611        int res;
612
613        TRACE("MKNOD %s @ %llx\n", name, hdr->nodeid);
614        path = node_get_path(node, buffer, name);
615
616        req->mode = (req->mode & (~0777)) | 0664;
617        res = mknod(path, req->mode, req->rdev); /* XXX perm?*/
618        if (res < 0) {
619            fuse_status(fuse, hdr->unique, -errno);
620        } else {
621            lookup_entry(fuse, node, name, hdr->unique);
622        }
623        return;
624    }
625    case FUSE_MKDIR: { /* mkdir_in, bytez[] -> entry_out */
626        struct fuse_mkdir_in *req = data;
627        struct fuse_entry_out out;
628        char *path, buffer[PATH_BUFFER_SIZE];
629        char *name = ((char*) data) + sizeof(*req);
630        int res;
631
632        TRACE("MKDIR %s @ %llx 0%o\n", name, hdr->nodeid, req->mode);
633        path = node_get_path(node, buffer, name);
634
635        req->mode = (req->mode & (~0777)) | 0775;
636        res = mkdir(path, req->mode);
637        if (res < 0) {
638            fuse_status(fuse, hdr->unique, -errno);
639        } else {
640            lookup_entry(fuse, node, name, hdr->unique);
641        }
642        return;
643    }
644    case FUSE_UNLINK: { /* bytez[] -> */
645        char *path, buffer[PATH_BUFFER_SIZE];
646        int res;
647        TRACE("UNLINK %s @ %llx\n", (char*) data, hdr->nodeid);
648        path = node_get_path(node, buffer, (char*) data);
649        res = unlink(path);
650        fuse_status(fuse, hdr->unique, res ? -errno : 0);
651        return;
652    }
653    case FUSE_RMDIR: { /* bytez[] -> */
654        char *path, buffer[PATH_BUFFER_SIZE];
655        int res;
656        TRACE("RMDIR %s @ %llx\n", (char*) data, hdr->nodeid);
657        path = node_get_path(node, buffer, (char*) data);
658        res = rmdir(path);
659        fuse_status(fuse, hdr->unique, res ? -errno : 0);
660        return;
661    }
662    case FUSE_RENAME: { /* rename_in, oldname, newname ->  */
663        struct fuse_rename_in *req = data;
664        char *oldname = ((char*) data) + sizeof(*req);
665        char *newname = oldname + strlen(oldname) + 1;
666        char *oldpath, oldbuffer[PATH_BUFFER_SIZE];
667        char *newpath, newbuffer[PATH_BUFFER_SIZE];
668        struct node *target;
669        struct node *newparent;
670        int res;
671
672        TRACE("RENAME %s->%s @ %llx\n", oldname, newname, hdr->nodeid);
673
674        target = lookup_child_by_name(node, oldname);
675        if (!target) {
676            fuse_status(fuse, hdr->unique, -ENOENT);
677            return;
678        }
679        oldpath = node_get_path(node, oldbuffer, oldname);
680
681        newparent = lookup_by_inode(fuse, req->newdir);
682        if (!newparent) {
683            fuse_status(fuse, hdr->unique, -ENOENT);
684            return;
685        }
686        if (newparent == node) {
687            /* Special case for renaming a file where destination
688             * is same path differing only by case.
689             * In this case we don't want to look for a case insensitive match.
690             * This allows commands like "mv foo FOO" to work as expected.
691             */
692            newpath = do_node_get_path(newparent, newbuffer, newname, NO_CASE_SENSITIVE_MATCH);
693        } else {
694            newpath = node_get_path(newparent, newbuffer, newname);
695        }
696
697        if (!remove_child(node, target->nid)) {
698            ERROR("RENAME remove_child not found");
699            fuse_status(fuse, hdr->unique, -ENOENT);
700            return;
701        }
702        if (!rename_node(target, newname)) {
703            fuse_status(fuse, hdr->unique, -ENOMEM);
704            return;
705        }
706        add_node_to_parent(target, newparent);
707
708        res = rename(oldpath, newpath);
709        TRACE("RENAME result %d\n", res);
710
711        fuse_status(fuse, hdr->unique, res ? -errno : 0);
712        return;
713    }
714//    case FUSE_LINK:
715    case FUSE_OPEN: { /* open_in -> open_out */
716        struct fuse_open_in *req = data;
717        struct fuse_open_out out;
718        char *path, buffer[PATH_BUFFER_SIZE];
719        struct handle *h;
720
721        h = malloc(sizeof(*h));
722        if (!h) {
723            fuse_status(fuse, hdr->unique, -ENOMEM);
724            return;
725        }
726
727        path = node_get_path(node, buffer, 0);
728        TRACE("OPEN %llx '%s' 0%o fh=%p\n", hdr->nodeid, path, req->flags, h);
729        h->fd = open(path, req->flags);
730        if (h->fd < 0) {
731            ERROR("ERROR\n");
732            fuse_status(fuse, hdr->unique, errno);
733            free(h);
734            return;
735        }
736        out.fh = ptr_to_id(h);
737        out.open_flags = 0;
738        out.padding = 0;
739        fuse_reply(fuse, hdr->unique, &out, sizeof(out));
740        return;
741    }
742    case FUSE_READ: { /* read_in -> byte[] */
743        char buffer[128 * 1024];
744        struct fuse_read_in *req = data;
745        struct handle *h = id_to_ptr(req->fh);
746        int res;
747        TRACE("READ %p(%d) %u@%llu\n", h, h->fd, req->size, req->offset);
748        if (req->size > sizeof(buffer)) {
749            fuse_status(fuse, hdr->unique, -EINVAL);
750            return;
751        }
752        res = pread64(h->fd, buffer, req->size, req->offset);
753        if (res < 0) {
754            fuse_status(fuse, hdr->unique, errno);
755            return;
756        }
757        fuse_reply(fuse, hdr->unique, buffer, res);
758        return;
759    }
760    case FUSE_WRITE: { /* write_in, byte[write_in.size] -> write_out */
761        struct fuse_write_in *req = data;
762        struct fuse_write_out out;
763        struct handle *h = id_to_ptr(req->fh);
764        int res;
765        TRACE("WRITE %p(%d) %u@%llu\n", h, h->fd, req->size, req->offset);
766        res = pwrite64(h->fd, ((char*) data) + sizeof(*req), req->size, req->offset);
767        if (res < 0) {
768            fuse_status(fuse, hdr->unique, errno);
769            return;
770        }
771        out.size = res;
772        fuse_reply(fuse, hdr->unique, &out, sizeof(out));
773        goto oops;
774    }
775    case FUSE_STATFS: { /* getattr_in -> attr_out */
776        struct statfs stat;
777        struct fuse_statfs_out out;
778        int res;
779
780        TRACE("STATFS\n");
781
782        if (statfs(fuse->root.name, &stat)) {
783            fuse_status(fuse, hdr->unique, -errno);
784            return;
785        }
786
787        memset(&out, 0, sizeof(out));
788        out.st.blocks = stat.f_blocks;
789        out.st.bfree = stat.f_bfree;
790        out.st.bavail = stat.f_bavail;
791        out.st.files = stat.f_files;
792        out.st.ffree = stat.f_ffree;
793        out.st.bsize = stat.f_bsize;
794        out.st.namelen = stat.f_namelen;
795        out.st.frsize = stat.f_frsize;
796        fuse_reply(fuse, hdr->unique, &out, sizeof(out));
797        return;
798    }
799    case FUSE_RELEASE: { /* release_in -> */
800        struct fuse_release_in *req = data;
801        struct handle *h = id_to_ptr(req->fh);
802        TRACE("RELEASE %p(%d)\n", h, h->fd);
803        close(h->fd);
804        free(h);
805        fuse_status(fuse, hdr->unique, 0);
806        return;
807    }
808//    case FUSE_FSYNC:
809//    case FUSE_SETXATTR:
810//    case FUSE_GETXATTR:
811//    case FUSE_LISTXATTR:
812//    case FUSE_REMOVEXATTR:
813    case FUSE_FLUSH:
814        fuse_status(fuse, hdr->unique, 0);
815        return;
816    case FUSE_OPENDIR: { /* open_in -> open_out */
817        struct fuse_open_in *req = data;
818        struct fuse_open_out out;
819        char *path, buffer[PATH_BUFFER_SIZE];
820        struct dirhandle *h;
821
822        h = malloc(sizeof(*h));
823        if (!h) {
824            fuse_status(fuse, hdr->unique, -ENOMEM);
825            return;
826        }
827
828        path = node_get_path(node, buffer, 0);
829        TRACE("OPENDIR %llx '%s'\n", hdr->nodeid, path);
830        h->d = opendir(path);
831        if (h->d == 0) {
832            ERROR("ERROR\n");
833            fuse_status(fuse, hdr->unique, -errno);
834            free(h);
835            return;
836        }
837        out.fh = ptr_to_id(h);
838        fuse_reply(fuse, hdr->unique, &out, sizeof(out));
839        return;
840    }
841    case FUSE_READDIR: {
842        struct fuse_read_in *req = data;
843        char buffer[8192];
844        struct fuse_dirent *fde = (struct fuse_dirent*) buffer;
845        struct dirent *de;
846        struct dirhandle *h = id_to_ptr(req->fh);
847        TRACE("READDIR %p\n", h);
848        if (req->offset == 0) {
849            /* rewinddir() might have been called above us, so rewind here too */
850            TRACE("calling rewinddir()\n");
851            rewinddir(h->d);
852        }
853        de = readdir(h->d);
854        if (!de) {
855            fuse_status(fuse, hdr->unique, 0);
856            return;
857        }
858        fde->ino = FUSE_UNKNOWN_INO;
859        /* increment the offset so we can detect when rewinddir() seeks back to the beginning */
860        fde->off = req->offset + 1;
861        fde->type = de->d_type;
862        fde->namelen = strlen(de->d_name);
863        memcpy(fde->name, de->d_name, fde->namelen + 1);
864        fuse_reply(fuse, hdr->unique, fde,
865                   FUSE_DIRENT_ALIGN(sizeof(struct fuse_dirent) + fde->namelen));
866        return;
867    }
868    case FUSE_RELEASEDIR: { /* release_in -> */
869        struct fuse_release_in *req = data;
870        struct dirhandle *h = id_to_ptr(req->fh);
871        TRACE("RELEASEDIR %p\n",h);
872        closedir(h->d);
873        free(h);
874        fuse_status(fuse, hdr->unique, 0);
875        return;
876    }
877//    case FUSE_FSYNCDIR:
878    case FUSE_INIT: { /* init_in -> init_out */
879        struct fuse_init_in *req = data;
880        struct fuse_init_out out;
881
882        TRACE("INIT ver=%d.%d maxread=%d flags=%x\n",
883                req->major, req->minor, req->max_readahead, req->flags);
884
885        out.major = FUSE_KERNEL_VERSION;
886        out.minor = FUSE_KERNEL_MINOR_VERSION;
887        out.max_readahead = req->max_readahead;
888        out.flags = FUSE_ATOMIC_O_TRUNC;
889        out.max_background = 32;
890        out.congestion_threshold = 32;
891        out.max_write = 256 * 1024;
892
893        fuse_reply(fuse, hdr->unique, &out, sizeof(out));
894        return;
895    }
896    default: {
897        struct fuse_out_header h;
898        ERROR("NOTIMPL op=%d uniq=%llx nid=%llx\n",
899                hdr->opcode, hdr->unique, hdr->nodeid);
900
901        oops:
902        h.len = sizeof(h);
903        h.error = -ENOSYS;
904        h.unique = hdr->unique;
905        write(fuse->fd, &h, sizeof(h));
906        break;
907    }
908    }
909}
910
911void handle_fuse_requests(struct fuse *fuse)
912{
913    unsigned char req[256 * 1024 + 128];
914    int len;
915
916    for (;;) {
917        len = read(fuse->fd, req, 8192);
918        if (len < 0) {
919            if (errno == EINTR)
920                continue;
921            ERROR("handle_fuse_requests: errno=%d\n", errno);
922            return;
923        }
924        handle_fuse_request(fuse, (void*) req, (void*) (req + sizeof(struct fuse_in_header)), len);
925    }
926}
927
928static int usage()
929{
930    ERROR("usage: sdcard [-l -f] <path> <uid> <gid>\n\n\t-l force file names to lower case when creating new files\n\t-f fix up file system before starting (repairs bad file name case and group ownership)\n");
931    return -1;
932}
933
934int main(int argc, char **argv)
935{
936    struct fuse fuse;
937    char opts[256];
938    int fd;
939    int res;
940    const char *path = NULL;
941    int i;
942
943    for (i = 1; i < argc; i++) {
944        char* arg = argv[i];
945        if (!path)
946            path = arg;
947        else if (uid == -1)
948            uid = strtoul(arg, 0, 10);
949        else if (gid == -1)
950            gid = strtoul(arg, 0, 10);
951        else {
952            ERROR("too many arguments\n");
953            return usage();
954        }
955    }
956
957    if (!path) {
958        ERROR("no path specified\n");
959        return usage();
960    }
961    if (uid <= 0 || gid <= 0) {
962        ERROR("uid and gid must be nonzero\n");
963        return usage();
964    }
965
966        /* cleanup from previous instance, if necessary */
967    umount2(MOUNT_POINT, 2);
968
969    fd = open("/dev/fuse", O_RDWR);
970    if (fd < 0){
971        ERROR("cannot open fuse device (%d)\n", errno);
972        return -1;
973    }
974
975    sprintf(opts, "fd=%i,rootmode=40000,default_permissions,allow_other,"
976            "user_id=%d,group_id=%d", fd, uid, gid);
977
978    res = mount("/dev/fuse", MOUNT_POINT, "fuse", MS_NOSUID | MS_NODEV, opts);
979    if (res < 0) {
980        ERROR("cannot mount fuse filesystem (%d)\n", errno);
981        return -1;
982    }
983
984    if (setgid(gid) < 0) {
985        ERROR("cannot setgid!\n");
986        return -1;
987    }
988    if (setuid(uid) < 0) {
989        ERROR("cannot setuid!\n");
990        return -1;
991    }
992
993    fuse_init(&fuse, fd, path);
994
995    umask(0);
996    handle_fuse_requests(&fuse);
997
998    return 0;
999}
1000