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