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 <limits.h>
29#include <ctype.h>
30#include <pthread.h>
31
32#include <private/android_filesystem_config.h>
33
34#include "fuse.h"
35
36/* README
37 *
38 * What is this?
39 *
40 * sdcard is a program that uses FUSE to emulate FAT-on-sdcard style
41 * directory permissions (all files are given fixed owner, group, and
42 * permissions at creation, owner, group, and permissions are not
43 * changeable, symlinks and hardlinks are not createable, etc.
44 *
45 * See usage() for command line options.
46 *
47 * It must be run as root, but will drop to requested UID/GID as soon as it
48 * mounts a filesystem.  It will refuse to run if requested UID/GID are zero.
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#define FUSE_TRACE 0
61
62#if FUSE_TRACE
63#define TRACE(x...) fprintf(stderr,x)
64#else
65#define TRACE(x...) do {} while (0)
66#endif
67
68#define ERROR(x...) fprintf(stderr,x)
69
70#define FUSE_UNKNOWN_INO 0xffffffff
71
72/* Maximum number of bytes to write in one request. */
73#define MAX_WRITE (256 * 1024)
74
75/* Maximum number of bytes to read in one request. */
76#define MAX_READ (128 * 1024)
77
78/* Largest possible request.
79 * The request size is bounded by the maximum size of a FUSE_WRITE request because it has
80 * the largest possible data payload. */
81#define MAX_REQUEST_SIZE (sizeof(struct fuse_in_header) + sizeof(struct fuse_write_in) + MAX_WRITE)
82
83/* Default number of threads. */
84#define DEFAULT_NUM_THREADS 2
85
86/* Pseudo-error constant used to indicate that no fuse status is needed
87 * or that a reply has already been written. */
88#define NO_STATUS 1
89
90struct handle {
91    int fd;
92};
93
94struct dirhandle {
95    DIR *d;
96};
97
98struct node {
99    __u32 refcount;
100    __u64 nid;
101    __u64 gen;
102
103    struct node *next;          /* per-dir sibling list */
104    struct node *child;         /* first contained file by this dir */
105    struct node *parent;        /* containing directory */
106
107    size_t namelen;
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
117/* Global data structure shared by all fuse handlers. */
118struct fuse {
119    pthread_mutex_t lock;
120
121    __u64 next_generation;
122    int fd;
123    struct node root;
124    char rootpath[PATH_MAX];
125};
126
127/* Private data used by a single fuse handler. */
128struct fuse_handler {
129    struct fuse* fuse;
130    int token;
131
132    /* To save memory, we never use the contents of the request buffer and the read
133     * buffer at the same time.  This allows us to share the underlying storage. */
134    union {
135        __u8 request_buffer[MAX_REQUEST_SIZE];
136        __u8 read_buffer[MAX_READ];
137    };
138};
139
140static inline void *id_to_ptr(__u64 nid)
141{
142    return (void *) (uintptr_t) nid;
143}
144
145static inline __u64 ptr_to_id(void *ptr)
146{
147    return (__u64) (uintptr_t) ptr;
148}
149
150static void acquire_node_locked(struct node* node)
151{
152    node->refcount++;
153    TRACE("ACQUIRE %p (%s) rc=%d\n", node, node->name, node->refcount);
154}
155
156static void remove_node_from_parent_locked(struct node* node);
157
158static void release_node_locked(struct node* node)
159{
160    TRACE("RELEASE %p (%s) rc=%d\n", node, node->name, node->refcount);
161    if (node->refcount > 0) {
162        node->refcount--;
163        if (!node->refcount) {
164            TRACE("DESTROY %p (%s)\n", node, node->name);
165            remove_node_from_parent_locked(node);
166
167                /* TODO: remove debugging - poison memory */
168            memset(node->name, 0xef, node->namelen);
169            free(node->name);
170            free(node->actual_name);
171            memset(node, 0xfc, sizeof(*node));
172            free(node);
173        }
174    } else {
175        ERROR("Zero refcnt %p\n", node);
176    }
177}
178
179static void add_node_to_parent_locked(struct node *node, struct node *parent) {
180    node->parent = parent;
181    node->next = parent->child;
182    parent->child = node;
183    acquire_node_locked(parent);
184}
185
186static void remove_node_from_parent_locked(struct node* node)
187{
188    if (node->parent) {
189        if (node->parent->child == node) {
190            node->parent->child = node->parent->child->next;
191        } else {
192            struct node *node2;
193            node2 = node->parent->child;
194            while (node2->next != node)
195                node2 = node2->next;
196            node2->next = node->next;
197        }
198        release_node_locked(node->parent);
199        node->parent = NULL;
200        node->next = NULL;
201    }
202}
203
204/* Gets the absolute path to a node into the provided buffer.
205 *
206 * Populates 'buf' with the path and returns the length of the path on success,
207 * or returns -1 if the path is too long for the provided buffer.
208 */
209static ssize_t get_node_path_locked(struct node* node, char* buf, size_t bufsize)
210{
211    size_t namelen = node->namelen;
212    if (bufsize < namelen + 1) {
213        return -1;
214    }
215
216    ssize_t pathlen = 0;
217    if (node->parent) {
218        pathlen = get_node_path_locked(node->parent, buf, bufsize - namelen - 2);
219        if (pathlen < 0) {
220            return -1;
221        }
222        buf[pathlen++] = '/';
223    }
224
225    const char* name = node->actual_name ? node->actual_name : node->name;
226    memcpy(buf + pathlen, name, namelen + 1); /* include trailing \0 */
227    return pathlen + namelen;
228}
229
230/* Finds the absolute path of a file within a given directory.
231 * Performs a case-insensitive search for the file and sets the buffer to the path
232 * of the first matching file.  If 'search' is zero or if no match is found, sets
233 * the buffer to the path that the file would have, assuming the name were case-sensitive.
234 *
235 * Populates 'buf' with the path and returns the actual name (within 'buf') on success,
236 * or returns NULL if the path is too long for the provided buffer.
237 */
238static char* find_file_within(const char* path, const char* name,
239        char* buf, size_t bufsize, int search)
240{
241    size_t pathlen = strlen(path);
242    size_t namelen = strlen(name);
243    size_t childlen = pathlen + namelen + 1;
244    char* actual;
245
246    if (bufsize <= childlen) {
247        return NULL;
248    }
249
250    memcpy(buf, path, pathlen);
251    buf[pathlen] = '/';
252    actual = buf + pathlen + 1;
253    memcpy(actual, name, namelen + 1);
254
255    if (search && access(buf, F_OK)) {
256        struct dirent* entry;
257        DIR* dir = opendir(path);
258        if (!dir) {
259            ERROR("opendir %s failed: %s", path, strerror(errno));
260            return actual;
261        }
262        while ((entry = readdir(dir))) {
263            if (!strcasecmp(entry->d_name, name)) {
264                /* we have a match - replace the name, don't need to copy the null again */
265                memcpy(actual, entry->d_name, namelen);
266                break;
267            }
268        }
269        closedir(dir);
270    }
271    return actual;
272}
273
274static void attr_from_stat(struct fuse_attr *attr, const struct stat *s, __u64 nid)
275{
276    attr->ino = nid;
277    attr->size = s->st_size;
278    attr->blocks = s->st_blocks;
279    attr->atime = s->st_atime;
280    attr->mtime = s->st_mtime;
281    attr->ctime = s->st_ctime;
282    attr->atimensec = s->st_atime_nsec;
283    attr->mtimensec = s->st_mtime_nsec;
284    attr->ctimensec = s->st_ctime_nsec;
285    attr->mode = s->st_mode;
286    attr->nlink = s->st_nlink;
287
288        /* force permissions to something reasonable:
289         * world readable
290         * writable by the sdcard group
291         */
292    if (attr->mode & 0100) {
293        attr->mode = (attr->mode & (~0777)) | 0775;
294    } else {
295        attr->mode = (attr->mode & (~0777)) | 0664;
296    }
297
298        /* all files owned by root.sdcard */
299    attr->uid = 0;
300    attr->gid = AID_SDCARD_RW;
301}
302
303struct node *create_node_locked(struct fuse* fuse,
304        struct node *parent, const char *name, const char* actual_name)
305{
306    struct node *node;
307    size_t namelen = strlen(name);
308
309    node = calloc(1, sizeof(struct node));
310    if (!node) {
311        return NULL;
312    }
313    node->name = malloc(namelen + 1);
314    if (!node->name) {
315        free(node);
316        return NULL;
317    }
318    memcpy(node->name, name, namelen + 1);
319    if (strcmp(name, actual_name)) {
320        node->actual_name = malloc(namelen + 1);
321        if (!node->actual_name) {
322            free(node->name);
323            free(node);
324            return NULL;
325        }
326        memcpy(node->actual_name, actual_name, namelen + 1);
327    }
328    node->namelen = namelen;
329    node->nid = ptr_to_id(node);
330    node->gen = fuse->next_generation++;
331    acquire_node_locked(node);
332    add_node_to_parent_locked(node, parent);
333    return node;
334}
335
336static int rename_node_locked(struct node *node, const char *name,
337        const char* actual_name)
338{
339    size_t namelen = strlen(name);
340    int need_actual_name = strcmp(name, actual_name);
341
342    /* make the storage bigger without actually changing the name
343     * in case an error occurs part way */
344    if (namelen > node->namelen) {
345        char* new_name = realloc(node->name, namelen + 1);
346        if (!new_name) {
347            return -ENOMEM;
348        }
349        node->name = new_name;
350        if (need_actual_name && node->actual_name) {
351            char* new_actual_name = realloc(node->actual_name, namelen + 1);
352            if (!new_actual_name) {
353                return -ENOMEM;
354            }
355            node->actual_name = new_actual_name;
356        }
357    }
358
359    /* update the name, taking care to allocate storage before overwriting the old name */
360    if (need_actual_name) {
361        if (!node->actual_name) {
362            node->actual_name = malloc(namelen + 1);
363            if (!node->actual_name) {
364                return -ENOMEM;
365            }
366        }
367        memcpy(node->actual_name, actual_name, namelen + 1);
368    } else {
369        free(node->actual_name);
370        node->actual_name = NULL;
371    }
372    memcpy(node->name, name, namelen + 1);
373    node->namelen = namelen;
374    return 0;
375}
376
377static struct node *lookup_node_by_id_locked(struct fuse *fuse, __u64 nid)
378{
379    if (nid == FUSE_ROOT_ID) {
380        return &fuse->root;
381    } else {
382        return id_to_ptr(nid);
383    }
384}
385
386static struct node* lookup_node_and_path_by_id_locked(struct fuse* fuse, __u64 nid,
387        char* buf, size_t bufsize)
388{
389    struct node* node = lookup_node_by_id_locked(fuse, nid);
390    if (node && get_node_path_locked(node, buf, bufsize) < 0) {
391        node = NULL;
392    }
393    return node;
394}
395
396static struct node *lookup_child_by_name_locked(struct node *node, const char *name)
397{
398    for (node = node->child; node; node = node->next) {
399        /* use exact string comparison, nodes that differ by case
400         * must be considered distinct even if they refer to the same
401         * underlying file as otherwise operations such as "mv x x"
402         * will not work because the source and target nodes are the same. */
403        if (!strcmp(name, node->name)) {
404            return node;
405        }
406    }
407    return 0;
408}
409
410static struct node* acquire_or_create_child_locked(
411        struct fuse* fuse, struct node* parent,
412        const char* name, const char* actual_name)
413{
414    struct node* child = lookup_child_by_name_locked(parent, name);
415    if (child) {
416        acquire_node_locked(child);
417    } else {
418        child = create_node_locked(fuse, parent, name, actual_name);
419    }
420    return child;
421}
422
423static void fuse_init(struct fuse *fuse, int fd, const char *source_path)
424{
425    pthread_mutex_init(&fuse->lock, NULL);
426
427    fuse->fd = fd;
428    fuse->next_generation = 0;
429
430    memset(&fuse->root, 0, sizeof(fuse->root));
431    fuse->root.nid = FUSE_ROOT_ID; /* 1 */
432    fuse->root.refcount = 2;
433    fuse->root.namelen = strlen(source_path);
434    fuse->root.name = strdup(source_path);
435}
436
437static void fuse_status(struct fuse *fuse, __u64 unique, int err)
438{
439    struct fuse_out_header hdr;
440    hdr.len = sizeof(hdr);
441    hdr.error = err;
442    hdr.unique = unique;
443    write(fuse->fd, &hdr, sizeof(hdr));
444}
445
446static void fuse_reply(struct fuse *fuse, __u64 unique, void *data, int len)
447{
448    struct fuse_out_header hdr;
449    struct iovec vec[2];
450    int res;
451
452    hdr.len = len + sizeof(hdr);
453    hdr.error = 0;
454    hdr.unique = unique;
455
456    vec[0].iov_base = &hdr;
457    vec[0].iov_len = sizeof(hdr);
458    vec[1].iov_base = data;
459    vec[1].iov_len = len;
460
461    res = writev(fuse->fd, vec, 2);
462    if (res < 0) {
463        ERROR("*** REPLY FAILED *** %d\n", errno);
464    }
465}
466
467static int fuse_reply_entry(struct fuse* fuse, __u64 unique,
468        struct node* parent, const char* name, const char* actual_name,
469        const char* path)
470{
471    struct node* node;
472    struct fuse_entry_out out;
473    struct stat s;
474
475    if (lstat(path, &s) < 0) {
476        return -errno;
477    }
478
479    pthread_mutex_lock(&fuse->lock);
480    node = acquire_or_create_child_locked(fuse, parent, name, actual_name);
481    if (!node) {
482        pthread_mutex_unlock(&fuse->lock);
483        return -ENOMEM;
484    }
485    memset(&out, 0, sizeof(out));
486    attr_from_stat(&out.attr, &s, node->nid);
487    out.attr_valid = 10;
488    out.entry_valid = 10;
489    out.nodeid = node->nid;
490    out.generation = node->gen;
491    pthread_mutex_unlock(&fuse->lock);
492    fuse_reply(fuse, unique, &out, sizeof(out));
493    return NO_STATUS;
494}
495
496static int fuse_reply_attr(struct fuse* fuse, __u64 unique, __u64 nid,
497        const char* path)
498{
499    struct fuse_attr_out out;
500    struct stat s;
501
502    if (lstat(path, &s) < 0) {
503        return -errno;
504    }
505    memset(&out, 0, sizeof(out));
506    attr_from_stat(&out.attr, &s, nid);
507    out.attr_valid = 10;
508    fuse_reply(fuse, unique, &out, sizeof(out));
509    return NO_STATUS;
510}
511
512static int handle_lookup(struct fuse* fuse, struct fuse_handler* handler,
513        const struct fuse_in_header *hdr, const char* name)
514{
515    struct node* parent_node;
516    char parent_path[PATH_MAX];
517    char child_path[PATH_MAX];
518    const char* actual_name;
519
520    pthread_mutex_lock(&fuse->lock);
521    parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
522            parent_path, sizeof(parent_path));
523    TRACE("[%d] LOOKUP %s @ %llx (%s)\n", handler->token, name, hdr->nodeid,
524        parent_node ? parent_node->name : "?");
525    pthread_mutex_unlock(&fuse->lock);
526
527    if (!parent_node || !(actual_name = find_file_within(parent_path, name,
528            child_path, sizeof(child_path), 1))) {
529        return -ENOENT;
530    }
531    return fuse_reply_entry(fuse, hdr->unique, parent_node, name, actual_name, child_path);
532}
533
534static int handle_forget(struct fuse* fuse, struct fuse_handler* handler,
535        const struct fuse_in_header *hdr, const struct fuse_forget_in *req)
536{
537    struct node* node;
538
539    pthread_mutex_lock(&fuse->lock);
540    node = lookup_node_by_id_locked(fuse, hdr->nodeid);
541    TRACE("[%d] FORGET #%lld @ %llx (%s)\n", handler->token, req->nlookup,
542            hdr->nodeid, node ? node->name : "?");
543    if (node) {
544        __u64 n = req->nlookup;
545        while (n--) {
546            release_node_locked(node);
547        }
548    }
549    pthread_mutex_unlock(&fuse->lock);
550    return NO_STATUS; /* no reply */
551}
552
553static int handle_getattr(struct fuse* fuse, struct fuse_handler* handler,
554        const struct fuse_in_header *hdr, const struct fuse_getattr_in *req)
555{
556    struct node* node;
557    char path[PATH_MAX];
558
559    pthread_mutex_lock(&fuse->lock);
560    node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid, path, sizeof(path));
561    TRACE("[%d] GETATTR flags=%x fh=%llx @ %llx (%s)\n", handler->token,
562            req->getattr_flags, req->fh, hdr->nodeid, node ? node->name : "?");
563    pthread_mutex_unlock(&fuse->lock);
564
565    if (!node) {
566        return -ENOENT;
567    }
568    return fuse_reply_attr(fuse, hdr->unique, hdr->nodeid, path);
569}
570
571static int handle_setattr(struct fuse* fuse, struct fuse_handler* handler,
572        const struct fuse_in_header *hdr, const struct fuse_setattr_in *req)
573{
574    struct node* node;
575    char path[PATH_MAX];
576    struct timespec times[2];
577
578    pthread_mutex_lock(&fuse->lock);
579    node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid, path, sizeof(path));
580    TRACE("[%d] SETATTR fh=%llx valid=%x @ %llx (%s)\n", handler->token,
581            req->fh, req->valid, hdr->nodeid, node ? node->name : "?");
582    pthread_mutex_unlock(&fuse->lock);
583
584    if (!node) {
585        return -ENOENT;
586    }
587
588    /* XXX: incomplete implementation on purpose.
589     * chmod/chown should NEVER be implemented.*/
590
591    if ((req->valid & FATTR_SIZE) && truncate(path, req->size) < 0) {
592        return -errno;
593    }
594
595    /* Handle changing atime and mtime.  If FATTR_ATIME_and FATTR_ATIME_NOW
596     * are both set, then set it to the current time.  Else, set it to the
597     * time specified in the request.  Same goes for mtime.  Use utimensat(2)
598     * as it allows ATIME and MTIME to be changed independently, and has
599     * nanosecond resolution which fuse also has.
600     */
601    if (req->valid & (FATTR_ATIME | FATTR_MTIME)) {
602        times[0].tv_nsec = UTIME_OMIT;
603        times[1].tv_nsec = UTIME_OMIT;
604        if (req->valid & FATTR_ATIME) {
605            if (req->valid & FATTR_ATIME_NOW) {
606              times[0].tv_nsec = UTIME_NOW;
607            } else {
608              times[0].tv_sec = req->atime;
609              times[0].tv_nsec = req->atimensec;
610            }
611        }
612        if (req->valid & FATTR_MTIME) {
613            if (req->valid & FATTR_MTIME_NOW) {
614              times[1].tv_nsec = UTIME_NOW;
615            } else {
616              times[1].tv_sec = req->mtime;
617              times[1].tv_nsec = req->mtimensec;
618            }
619        }
620        TRACE("[%d] Calling utimensat on %s with atime %ld, mtime=%ld\n",
621                handler->token, path, times[0].tv_sec, times[1].tv_sec);
622        if (utimensat(-1, path, times, 0) < 0) {
623            return -errno;
624        }
625    }
626    return fuse_reply_attr(fuse, hdr->unique, hdr->nodeid, path);
627}
628
629static int handle_mknod(struct fuse* fuse, struct fuse_handler* handler,
630        const struct fuse_in_header* hdr, const struct fuse_mknod_in* req, const char* name)
631{
632    struct node* parent_node;
633    char parent_path[PATH_MAX];
634    char child_path[PATH_MAX];
635    const char* actual_name;
636
637    pthread_mutex_lock(&fuse->lock);
638    parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
639            parent_path, sizeof(parent_path));
640    TRACE("[%d] MKNOD %s 0%o @ %llx (%s)\n", handler->token,
641            name, req->mode, hdr->nodeid, parent_node ? parent_node->name : "?");
642    pthread_mutex_unlock(&fuse->lock);
643
644    if (!parent_node || !(actual_name = find_file_within(parent_path, name,
645            child_path, sizeof(child_path), 1))) {
646        return -ENOENT;
647    }
648    __u32 mode = (req->mode & (~0777)) | 0664;
649    if (mknod(child_path, mode, req->rdev) < 0) {
650        return -errno;
651    }
652    return fuse_reply_entry(fuse, hdr->unique, parent_node, name, actual_name, child_path);
653}
654
655static int handle_mkdir(struct fuse* fuse, struct fuse_handler* handler,
656        const struct fuse_in_header* hdr, const struct fuse_mkdir_in* req, const char* name)
657{
658    struct node* parent_node;
659    char parent_path[PATH_MAX];
660    char child_path[PATH_MAX];
661    const char* actual_name;
662
663    pthread_mutex_lock(&fuse->lock);
664    parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
665            parent_path, sizeof(parent_path));
666    TRACE("[%d] MKDIR %s 0%o @ %llx (%s)\n", handler->token,
667            name, req->mode, hdr->nodeid, parent_node ? parent_node->name : "?");
668    pthread_mutex_unlock(&fuse->lock);
669
670    if (!parent_node || !(actual_name = find_file_within(parent_path, name,
671            child_path, sizeof(child_path), 1))) {
672        return -ENOENT;
673    }
674    __u32 mode = (req->mode & (~0777)) | 0775;
675    if (mkdir(child_path, mode) < 0) {
676        return -errno;
677    }
678    return fuse_reply_entry(fuse, hdr->unique, parent_node, name, actual_name, child_path);
679}
680
681static int handle_unlink(struct fuse* fuse, struct fuse_handler* handler,
682        const struct fuse_in_header* hdr, const char* name)
683{
684    struct node* parent_node;
685    char parent_path[PATH_MAX];
686    char child_path[PATH_MAX];
687
688    pthread_mutex_lock(&fuse->lock);
689    parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
690            parent_path, sizeof(parent_path));
691    TRACE("[%d] UNLINK %s @ %llx (%s)\n", handler->token,
692            name, hdr->nodeid, parent_node ? parent_node->name : "?");
693    pthread_mutex_unlock(&fuse->lock);
694
695    if (!parent_node || !find_file_within(parent_path, name,
696            child_path, sizeof(child_path), 1)) {
697        return -ENOENT;
698    }
699    if (unlink(child_path) < 0) {
700        return -errno;
701    }
702    return 0;
703}
704
705static int handle_rmdir(struct fuse* fuse, struct fuse_handler* handler,
706        const struct fuse_in_header* hdr, const char* name)
707{
708    struct node* parent_node;
709    char parent_path[PATH_MAX];
710    char child_path[PATH_MAX];
711
712    pthread_mutex_lock(&fuse->lock);
713    parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
714            parent_path, sizeof(parent_path));
715    TRACE("[%d] RMDIR %s @ %llx (%s)\n", handler->token,
716            name, hdr->nodeid, parent_node ? parent_node->name : "?");
717    pthread_mutex_unlock(&fuse->lock);
718
719    if (!parent_node || !find_file_within(parent_path, name,
720            child_path, sizeof(child_path), 1)) {
721        return -ENOENT;
722    }
723    if (rmdir(child_path) < 0) {
724        return -errno;
725    }
726    return 0;
727}
728
729static int handle_rename(struct fuse* fuse, struct fuse_handler* handler,
730        const struct fuse_in_header* hdr, const struct fuse_rename_in* req,
731        const char* old_name, const char* new_name)
732{
733    struct node* old_parent_node;
734    struct node* new_parent_node;
735    struct node* child_node;
736    char old_parent_path[PATH_MAX];
737    char new_parent_path[PATH_MAX];
738    char old_child_path[PATH_MAX];
739    char new_child_path[PATH_MAX];
740    const char* new_actual_name;
741    int res;
742
743    pthread_mutex_lock(&fuse->lock);
744    old_parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
745            old_parent_path, sizeof(old_parent_path));
746    new_parent_node = lookup_node_and_path_by_id_locked(fuse, req->newdir,
747            new_parent_path, sizeof(new_parent_path));
748    TRACE("[%d] RENAME %s->%s @ %llx (%s) -> %llx (%s)\n", handler->token,
749            old_name, new_name,
750            hdr->nodeid, old_parent_node ? old_parent_node->name : "?",
751            req->newdir, new_parent_node ? new_parent_node->name : "?");
752    if (!old_parent_node || !new_parent_node) {
753        res = -ENOENT;
754        goto lookup_error;
755    }
756    child_node = lookup_child_by_name_locked(old_parent_node, old_name);
757    if (!child_node || get_node_path_locked(child_node,
758            old_child_path, sizeof(old_child_path)) < 0) {
759        res = -ENOENT;
760        goto lookup_error;
761    }
762    acquire_node_locked(child_node);
763    pthread_mutex_unlock(&fuse->lock);
764
765    /* Special case for renaming a file where destination is same path
766     * differing only by case.  In this case we don't want to look for a case
767     * insensitive match.  This allows commands like "mv foo FOO" to work as expected.
768     */
769    int search = old_parent_node != new_parent_node
770            || strcasecmp(old_name, new_name);
771    if (!(new_actual_name = find_file_within(new_parent_path, new_name,
772            new_child_path, sizeof(new_child_path), search))) {
773        res = -ENOENT;
774        goto io_error;
775    }
776
777    TRACE("[%d] RENAME %s->%s\n", handler->token, old_child_path, new_child_path);
778    res = rename(old_child_path, new_child_path);
779    if (res < 0) {
780        res = -errno;
781        goto io_error;
782    }
783
784    pthread_mutex_lock(&fuse->lock);
785    res = rename_node_locked(child_node, new_name, new_actual_name);
786    if (!res) {
787        remove_node_from_parent_locked(child_node);
788        add_node_to_parent_locked(child_node, new_parent_node);
789    }
790    goto done;
791
792io_error:
793    pthread_mutex_lock(&fuse->lock);
794done:
795    release_node_locked(child_node);
796lookup_error:
797    pthread_mutex_unlock(&fuse->lock);
798    return res;
799}
800
801static int handle_open(struct fuse* fuse, struct fuse_handler* handler,
802        const struct fuse_in_header* hdr, const struct fuse_open_in* req)
803{
804    struct node* node;
805    char path[PATH_MAX];
806    struct fuse_open_out out;
807    struct handle *h;
808
809    pthread_mutex_lock(&fuse->lock);
810    node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid, path, sizeof(path));
811    TRACE("[%d] OPEN 0%o @ %llx (%s)\n", handler->token,
812            req->flags, hdr->nodeid, node ? node->name : "?");
813    pthread_mutex_unlock(&fuse->lock);
814
815    if (!node) {
816        return -ENOENT;
817    }
818    h = malloc(sizeof(*h));
819    if (!h) {
820        return -ENOMEM;
821    }
822    TRACE("[%d] OPEN %s\n", handler->token, path);
823    h->fd = open(path, req->flags);
824    if (h->fd < 0) {
825        free(h);
826        return -errno;
827    }
828    out.fh = ptr_to_id(h);
829    out.open_flags = 0;
830    out.padding = 0;
831    fuse_reply(fuse, hdr->unique, &out, sizeof(out));
832    return NO_STATUS;
833}
834
835static int handle_read(struct fuse* fuse, struct fuse_handler* handler,
836        const struct fuse_in_header* hdr, const struct fuse_read_in* req)
837{
838    struct handle *h = id_to_ptr(req->fh);
839    __u64 unique = hdr->unique;
840    __u32 size = req->size;
841    __u64 offset = req->offset;
842    int res;
843
844    /* Don't access any other fields of hdr or req beyond this point, the read buffer
845     * overlaps the request buffer and will clobber data in the request.  This
846     * saves us 128KB per request handler thread at the cost of this scary comment. */
847
848    TRACE("[%d] READ %p(%d) %u@%llu\n", handler->token,
849            h, h->fd, size, offset);
850    if (size > sizeof(handler->read_buffer)) {
851        return -EINVAL;
852    }
853    res = pread64(h->fd, handler->read_buffer, size, offset);
854    if (res < 0) {
855        return -errno;
856    }
857    fuse_reply(fuse, unique, handler->read_buffer, res);
858    return NO_STATUS;
859}
860
861static int handle_write(struct fuse* fuse, struct fuse_handler* handler,
862        const struct fuse_in_header* hdr, const struct fuse_write_in* req,
863        const void* buffer)
864{
865    struct fuse_write_out out;
866    struct handle *h = id_to_ptr(req->fh);
867    int res;
868
869    TRACE("[%d] WRITE %p(%d) %u@%llu\n", handler->token,
870            h, h->fd, req->size, req->offset);
871    res = pwrite64(h->fd, buffer, req->size, req->offset);
872    if (res < 0) {
873        return -errno;
874    }
875    out.size = res;
876    fuse_reply(fuse, hdr->unique, &out, sizeof(out));
877    return NO_STATUS;
878}
879
880static int handle_statfs(struct fuse* fuse, struct fuse_handler* handler,
881        const struct fuse_in_header* hdr)
882{
883    char path[PATH_MAX];
884    struct statfs stat;
885    struct fuse_statfs_out out;
886    int res;
887
888    pthread_mutex_lock(&fuse->lock);
889    TRACE("[%d] STATFS\n", handler->token);
890    res = get_node_path_locked(&fuse->root, path, sizeof(path));
891    pthread_mutex_unlock(&fuse->lock);
892    if (res < 0) {
893        return -ENOENT;
894    }
895    if (statfs(fuse->root.name, &stat) < 0) {
896        return -errno;
897    }
898    memset(&out, 0, sizeof(out));
899    out.st.blocks = stat.f_blocks;
900    out.st.bfree = stat.f_bfree;
901    out.st.bavail = stat.f_bavail;
902    out.st.files = stat.f_files;
903    out.st.ffree = stat.f_ffree;
904    out.st.bsize = stat.f_bsize;
905    out.st.namelen = stat.f_namelen;
906    out.st.frsize = stat.f_frsize;
907    fuse_reply(fuse, hdr->unique, &out, sizeof(out));
908    return NO_STATUS;
909}
910
911static int handle_release(struct fuse* fuse, struct fuse_handler* handler,
912        const struct fuse_in_header* hdr, const struct fuse_release_in* req)
913{
914    struct handle *h = id_to_ptr(req->fh);
915
916    TRACE("[%d] RELEASE %p(%d)\n", handler->token, h, h->fd);
917    close(h->fd);
918    free(h);
919    return 0;
920}
921
922static int handle_fsync(struct fuse* fuse, struct fuse_handler* handler,
923        const struct fuse_in_header* hdr, const struct fuse_fsync_in* req)
924{
925    int is_data_sync = req->fsync_flags & 1;
926    struct handle *h = id_to_ptr(req->fh);
927    int res;
928
929    TRACE("[%d] FSYNC %p(%d) is_data_sync=%d\n", handler->token,
930            h, h->fd, is_data_sync);
931    res = is_data_sync ? fdatasync(h->fd) : fsync(h->fd);
932    if (res < 0) {
933        return -errno;
934    }
935    return 0;
936}
937
938static int handle_flush(struct fuse* fuse, struct fuse_handler* handler,
939        const struct fuse_in_header* hdr)
940{
941    TRACE("[%d] FLUSH\n", handler->token);
942    return 0;
943}
944
945static int handle_opendir(struct fuse* fuse, struct fuse_handler* handler,
946        const struct fuse_in_header* hdr, const struct fuse_open_in* req)
947{
948    struct node* node;
949    char path[PATH_MAX];
950    struct fuse_open_out out;
951    struct dirhandle *h;
952
953    pthread_mutex_lock(&fuse->lock);
954    node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid, path, sizeof(path));
955    TRACE("[%d] OPENDIR @ %llx (%s)\n", handler->token,
956            hdr->nodeid, node ? node->name : "?");
957    pthread_mutex_unlock(&fuse->lock);
958
959    if (!node) {
960        return -ENOENT;
961    }
962    h = malloc(sizeof(*h));
963    if (!h) {
964        return -ENOMEM;
965    }
966    TRACE("[%d] OPENDIR %s\n", handler->token, path);
967    h->d = opendir(path);
968    if (!h->d) {
969        free(h);
970        return -errno;
971    }
972    out.fh = ptr_to_id(h);
973    fuse_reply(fuse, hdr->unique, &out, sizeof(out));
974    return NO_STATUS;
975}
976
977static int handle_readdir(struct fuse* fuse, struct fuse_handler* handler,
978        const struct fuse_in_header* hdr, const struct fuse_read_in* req)
979{
980    char buffer[8192];
981    struct fuse_dirent *fde = (struct fuse_dirent*) buffer;
982    struct dirent *de;
983    struct dirhandle *h = id_to_ptr(req->fh);
984
985    TRACE("[%d] READDIR %p\n", handler->token, h);
986    if (req->offset == 0) {
987        /* rewinddir() might have been called above us, so rewind here too */
988        TRACE("[%d] calling rewinddir()\n", handler->token);
989        rewinddir(h->d);
990    }
991    de = readdir(h->d);
992    if (!de) {
993        return 0;
994    }
995    fde->ino = FUSE_UNKNOWN_INO;
996    /* increment the offset so we can detect when rewinddir() seeks back to the beginning */
997    fde->off = req->offset + 1;
998    fde->type = de->d_type;
999    fde->namelen = strlen(de->d_name);
1000    memcpy(fde->name, de->d_name, fde->namelen + 1);
1001    fuse_reply(fuse, hdr->unique, fde,
1002            FUSE_DIRENT_ALIGN(sizeof(struct fuse_dirent) + fde->namelen));
1003    return NO_STATUS;
1004}
1005
1006static int handle_releasedir(struct fuse* fuse, struct fuse_handler* handler,
1007        const struct fuse_in_header* hdr, const struct fuse_release_in* req)
1008{
1009    struct dirhandle *h = id_to_ptr(req->fh);
1010
1011    TRACE("[%d] RELEASEDIR %p\n", handler->token, h);
1012    closedir(h->d);
1013    free(h);
1014    return 0;
1015}
1016
1017static int handle_init(struct fuse* fuse, struct fuse_handler* handler,
1018        const struct fuse_in_header* hdr, const struct fuse_init_in* req)
1019{
1020    struct fuse_init_out out;
1021
1022    TRACE("[%d] INIT ver=%d.%d maxread=%d flags=%x\n",
1023            handler->token, req->major, req->minor, req->max_readahead, req->flags);
1024    out.major = FUSE_KERNEL_VERSION;
1025    out.minor = FUSE_KERNEL_MINOR_VERSION;
1026    out.max_readahead = req->max_readahead;
1027    out.flags = FUSE_ATOMIC_O_TRUNC | FUSE_BIG_WRITES;
1028    out.max_background = 32;
1029    out.congestion_threshold = 32;
1030    out.max_write = MAX_WRITE;
1031    fuse_reply(fuse, hdr->unique, &out, sizeof(out));
1032    return NO_STATUS;
1033}
1034
1035static int handle_fuse_request(struct fuse *fuse, struct fuse_handler* handler,
1036        const struct fuse_in_header *hdr, const void *data, size_t data_len)
1037{
1038    switch (hdr->opcode) {
1039    case FUSE_LOOKUP: { /* bytez[] -> entry_out */
1040        const char* name = data;
1041        return handle_lookup(fuse, handler, hdr, name);
1042    }
1043
1044    case FUSE_FORGET: {
1045        const struct fuse_forget_in *req = data;
1046        return handle_forget(fuse, handler, hdr, req);
1047    }
1048
1049    case FUSE_GETATTR: { /* getattr_in -> attr_out */
1050        const struct fuse_getattr_in *req = data;
1051        return handle_getattr(fuse, handler, hdr, req);
1052    }
1053
1054    case FUSE_SETATTR: { /* setattr_in -> attr_out */
1055        const struct fuse_setattr_in *req = data;
1056        return handle_setattr(fuse, handler, hdr, req);
1057    }
1058
1059//    case FUSE_READLINK:
1060//    case FUSE_SYMLINK:
1061    case FUSE_MKNOD: { /* mknod_in, bytez[] -> entry_out */
1062        const struct fuse_mknod_in *req = data;
1063        const char *name = ((const char*) data) + sizeof(*req);
1064        return handle_mknod(fuse, handler, hdr, req, name);
1065    }
1066
1067    case FUSE_MKDIR: { /* mkdir_in, bytez[] -> entry_out */
1068        const struct fuse_mkdir_in *req = data;
1069        const char *name = ((const char*) data) + sizeof(*req);
1070        return handle_mkdir(fuse, handler, hdr, req, name);
1071    }
1072
1073    case FUSE_UNLINK: { /* bytez[] -> */
1074        const char* name = data;
1075        return handle_unlink(fuse, handler, hdr, name);
1076    }
1077
1078    case FUSE_RMDIR: { /* bytez[] -> */
1079        const char* name = data;
1080        return handle_rmdir(fuse, handler, hdr, name);
1081    }
1082
1083    case FUSE_RENAME: { /* rename_in, oldname, newname ->  */
1084        const struct fuse_rename_in *req = data;
1085        const char *old_name = ((const char*) data) + sizeof(*req);
1086        const char *new_name = old_name + strlen(old_name) + 1;
1087        return handle_rename(fuse, handler, hdr, req, old_name, new_name);
1088    }
1089
1090//    case FUSE_LINK:
1091    case FUSE_OPEN: { /* open_in -> open_out */
1092        const struct fuse_open_in *req = data;
1093        return handle_open(fuse, handler, hdr, req);
1094    }
1095
1096    case FUSE_READ: { /* read_in -> byte[] */
1097        const struct fuse_read_in *req = data;
1098        return handle_read(fuse, handler, hdr, req);
1099    }
1100
1101    case FUSE_WRITE: { /* write_in, byte[write_in.size] -> write_out */
1102        const struct fuse_write_in *req = data;
1103        const void* buffer = (const __u8*)data + sizeof(*req);
1104        return handle_write(fuse, handler, hdr, req, buffer);
1105    }
1106
1107    case FUSE_STATFS: { /* getattr_in -> attr_out */
1108        return handle_statfs(fuse, handler, hdr);
1109    }
1110
1111    case FUSE_RELEASE: { /* release_in -> */
1112        const struct fuse_release_in *req = data;
1113        return handle_release(fuse, handler, hdr, req);
1114    }
1115
1116    case FUSE_FSYNC: {
1117        const struct fuse_fsync_in *req = data;
1118        return handle_fsync(fuse, handler, hdr, req);
1119    }
1120
1121//    case FUSE_SETXATTR:
1122//    case FUSE_GETXATTR:
1123//    case FUSE_LISTXATTR:
1124//    case FUSE_REMOVEXATTR:
1125    case FUSE_FLUSH: {
1126        return handle_flush(fuse, handler, hdr);
1127    }
1128
1129    case FUSE_OPENDIR: { /* open_in -> open_out */
1130        const struct fuse_open_in *req = data;
1131        return handle_opendir(fuse, handler, hdr, req);
1132    }
1133
1134    case FUSE_READDIR: {
1135        const struct fuse_read_in *req = data;
1136        return handle_readdir(fuse, handler, hdr, req);
1137    }
1138
1139    case FUSE_RELEASEDIR: { /* release_in -> */
1140        const struct fuse_release_in *req = data;
1141        return handle_releasedir(fuse, handler, hdr, req);
1142    }
1143
1144//    case FUSE_FSYNCDIR:
1145    case FUSE_INIT: { /* init_in -> init_out */
1146        const struct fuse_init_in *req = data;
1147        return handle_init(fuse, handler, hdr, req);
1148    }
1149
1150    default: {
1151        TRACE("[%d] NOTIMPL op=%d uniq=%llx nid=%llx\n",
1152                handler->token, hdr->opcode, hdr->unique, hdr->nodeid);
1153        return -ENOSYS;
1154    }
1155    }
1156}
1157
1158static void handle_fuse_requests(struct fuse_handler* handler)
1159{
1160    struct fuse* fuse = handler->fuse;
1161    for (;;) {
1162        ssize_t len = read(fuse->fd,
1163                handler->request_buffer, sizeof(handler->request_buffer));
1164        if (len < 0) {
1165            if (errno != EINTR) {
1166                ERROR("[%d] handle_fuse_requests: errno=%d\n", handler->token, errno);
1167            }
1168            continue;
1169        }
1170
1171        if ((size_t)len < sizeof(struct fuse_in_header)) {
1172            ERROR("[%d] request too short: len=%zu\n", handler->token, (size_t)len);
1173            continue;
1174        }
1175
1176        const struct fuse_in_header *hdr = (void*)handler->request_buffer;
1177        if (hdr->len != (size_t)len) {
1178            ERROR("[%d] malformed header: len=%zu, hdr->len=%u\n",
1179                    handler->token, (size_t)len, hdr->len);
1180            continue;
1181        }
1182
1183        const void *data = handler->request_buffer + sizeof(struct fuse_in_header);
1184        size_t data_len = len - sizeof(struct fuse_in_header);
1185        __u64 unique = hdr->unique;
1186        int res = handle_fuse_request(fuse, handler, hdr, data, data_len);
1187
1188        /* We do not access the request again after this point because the underlying
1189         * buffer storage may have been reused while processing the request. */
1190
1191        if (res != NO_STATUS) {
1192            if (res) {
1193                TRACE("[%d] ERROR %d\n", handler->token, res);
1194            }
1195            fuse_status(fuse, unique, res);
1196        }
1197    }
1198}
1199
1200static void* start_handler(void* data)
1201{
1202    struct fuse_handler* handler = data;
1203    handle_fuse_requests(handler);
1204    return NULL;
1205}
1206
1207static int ignite_fuse(struct fuse* fuse, int num_threads)
1208{
1209    struct fuse_handler* handlers;
1210    int i;
1211
1212    handlers = malloc(num_threads * sizeof(struct fuse_handler));
1213    if (!handlers) {
1214        ERROR("cannot allocate storage for threads");
1215        return -ENOMEM;
1216    }
1217
1218    for (i = 0; i < num_threads; i++) {
1219        handlers[i].fuse = fuse;
1220        handlers[i].token = i;
1221    }
1222
1223    for (i = 1; i < num_threads; i++) {
1224        pthread_t thread;
1225        int res = pthread_create(&thread, NULL, start_handler, &handlers[i]);
1226        if (res) {
1227            ERROR("failed to start thread #%d, error=%d", i, res);
1228            goto quit;
1229        }
1230    }
1231    handle_fuse_requests(&handlers[0]);
1232    ERROR("terminated prematurely");
1233
1234    /* don't bother killing all of the other threads or freeing anything,
1235     * should never get here anyhow */
1236quit:
1237    exit(1);
1238}
1239
1240static int usage()
1241{
1242    ERROR("usage: sdcard [-t<threads>] <source_path> <dest_path> <uid> <gid>\n"
1243            "    -t<threads>: specify number of threads to use, default -t%d\n"
1244            "\n", DEFAULT_NUM_THREADS);
1245    return 1;
1246}
1247
1248static int run(const char* source_path, const char* dest_path, uid_t uid, gid_t gid,
1249        int num_threads) {
1250    int fd;
1251    char opts[256];
1252    int res;
1253    struct fuse fuse;
1254
1255    /* cleanup from previous instance, if necessary */
1256    umount2(dest_path, 2);
1257
1258    fd = open("/dev/fuse", O_RDWR);
1259    if (fd < 0){
1260        ERROR("cannot open fuse device (error %d)\n", errno);
1261        return -1;
1262    }
1263
1264    snprintf(opts, sizeof(opts),
1265            "fd=%i,rootmode=40000,default_permissions,allow_other,user_id=%d,group_id=%d",
1266            fd, uid, gid);
1267
1268    res = mount("/dev/fuse", dest_path, "fuse", MS_NOSUID | MS_NODEV, opts);
1269    if (res < 0) {
1270        ERROR("cannot mount fuse filesystem (error %d)\n", errno);
1271        goto error;
1272    }
1273
1274    res = setgid(gid);
1275    if (res < 0) {
1276        ERROR("cannot setgid (error %d)\n", errno);
1277        goto error;
1278    }
1279
1280    res = setuid(uid);
1281    if (res < 0) {
1282        ERROR("cannot setuid (error %d)\n", errno);
1283        goto error;
1284    }
1285
1286    fuse_init(&fuse, fd, source_path);
1287
1288    umask(0);
1289    res = ignite_fuse(&fuse, num_threads);
1290
1291    /* we do not attempt to umount the file system here because we are no longer
1292     * running as the root user */
1293
1294error:
1295    close(fd);
1296    return res;
1297}
1298
1299int main(int argc, char **argv)
1300{
1301    int res;
1302    const char *source_path = NULL;
1303    const char *dest_path = NULL;
1304    uid_t uid = 0;
1305    gid_t gid = 0;
1306    int num_threads = DEFAULT_NUM_THREADS;
1307    int i;
1308
1309    for (i = 1; i < argc; i++) {
1310        char* arg = argv[i];
1311        if (!strncmp(arg, "-t", 2))
1312            num_threads = strtoul(arg + 2, 0, 10);
1313        else if (!source_path)
1314            source_path = arg;
1315        else if (!dest_path)
1316            dest_path = arg;
1317        else if (!uid) {
1318            char* endptr = NULL;
1319            errno = 0;
1320            uid = strtoul(arg, &endptr, 10);
1321            if (*endptr != '\0' || errno != 0) {
1322                ERROR("Invalid uid");
1323                return usage();
1324            }
1325        } else if (!gid) {
1326            char* endptr = NULL;
1327            errno = 0;
1328            gid = strtoul(arg, &endptr, 10);
1329            if (*endptr != '\0' || errno != 0) {
1330                ERROR("Invalid gid");
1331                return usage();
1332            }
1333        } else {
1334            ERROR("too many arguments\n");
1335            return usage();
1336        }
1337    }
1338
1339    if (!source_path) {
1340        ERROR("no source path specified\n");
1341        return usage();
1342    }
1343    if (!dest_path) {
1344        ERROR("no dest path specified\n");
1345        return usage();
1346    }
1347    if (!uid || !gid) {
1348        ERROR("uid and gid must be nonzero\n");
1349        return usage();
1350    }
1351    if (num_threads < 1) {
1352        ERROR("number of threads must be at least 1\n");
1353        return usage();
1354    }
1355
1356    res = run(source_path, dest_path, uid, gid, num_threads);
1357    return res < 0 ? 1 : 0;
1358}
1359