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