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