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