using k8clock() instead of clock()
[k8muffin.git] / src / fusedrv / fusedrv.c
blob88820f8d2d8d9a9c943583bc4211e9df27e44310
1 /* coded by Ketmar // Vampire Avalon (psyc://ketmar.no-ip.org/~Ketmar)
2 * Understanding is not required. Only obedience.
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 #define FUSE_USE_VERSION 26
19 #ifndef _BSD_SOURCE
20 # define _BSD_SOURCE
21 #endif
22 #ifndef _GNU_SOURCE
23 # define _GNU_SOURCE
24 #endif
26 #include <ctype.h>
27 #include <dirent.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <fuse.h>
31 #include <iconv.h>
32 #include <libgen.h>
33 #include <limits.h>
34 #include <stdint.h>
35 #include <stdlib.h>
36 #include <stdio.h>
37 #include <string.h>
38 #include <time.h>
39 #include <unistd.h>
41 #include <sys/stat.h>
42 #include <sys/types.h>
43 #include <sys/xattr.h>
45 #include "../libdbg/dbglog.h"
46 #include "../uthash.h"
47 #include "../translit.h"
48 #include "../k8clock.h"
51 ////////////////////////////////////////////////////////////////////////////////
52 #define NO_SEARCH_DBGLOG
53 //#define FUSEDRV_LOG_CALLS
56 ////////////////////////////////////////////////////////////////////////////////
57 static int opt_log_calls = 0;
59 # define fd_call_dlogf(...) do { \
60 if (opt_log_calls) dlogf(__VA_ARGS__); \
61 } while (0)
64 ////////////////////////////////////////////////////////////////////////////////
65 #include "../tagload.c"
66 #include "../search.c"
69 ////////////////////////////////////////////////////////////////////////////////
70 static char *tagfilename = NULL;
71 static int tfs_dirs_opened = 0; // # of opened dirs
72 static int tfs_need_reload = 0; // !0: reload when last dir closed
73 static uint64_t cur_dir_time = 1;
76 ////////////////////////////////////////////////////////////////////////////////
77 static inline void tagdb_check_and_reload (void) {
78 if (tfs_need_reload) {
79 if (tfs_dirs_opened == 0) {
80 dlogf("* reloading tagdb from '%s'...", tagfilename);
81 tfs_need_reload = 0;
82 clear_hashes();
83 dlogf("* hashes cleared");
84 tagdb_unload();
85 dlogf("* tagdb unloaded");
86 if (tagdb_load(tagfilename) != 0) {
87 dlogf("FATAL: can't load tagfile: '%s'!\n", tagfilename);
88 abort();
90 dlogf("* tagdb loaded");
91 build_hashes();
92 dlogf("* hashes built");
93 ++cur_dir_time;
99 ////////////////////////////////////////////////////////////////////////////////
100 static char *get_real_path (const char *fn, int add_slash) {
101 if (fn != NULL && fn[0]) {
102 char *pp = realpath(fn, NULL);
103 if (pp != NULL) {
104 if (pp[0]) {
105 if (add_slash && pp[strlen(pp)-1] != '/') {
106 char *t = malloc(strlen(pp)+2);
107 sprintf(t, "%s/", pp);
108 free(pp);
109 pp = t;
111 return pp;
113 free(pp);
116 return NULL;
120 ////////////////////////////////////////////////////////////////////////////////
121 //#define CTR ((my_data_struct_t *)(fuse_get_context()->private_data))
124 // report errors to logfile and give -errno to caller
126 static int tfs_error (const char *str) {
127 int ret = -errno;
128 fd_call_dlogf(" ERROR %s: %s", str, strerror(errno));
129 return ret;
134 static const fl_tagvalue_t *find_by_tag_name (const char *name) {
135 const char *t = strrchr(name, '/');
136 if (t == NULL) t = name; else ++t;
137 return get_tag_by_name(name, &tval_hash);
141 // short names are unique
142 static fl_fileinfo_t *find_by_short_name (const char *path) {
143 filename_t *sf;
144 const char *t = strrchr(path, '/');
145 if (t == NULL) t = path; else ++t;
146 HASH_FIND_STR(sname_hash, t, sf);
147 return (sf != NULL ? sf->fi : NULL);
151 ////////////////////////////////////////////////////////////////////////////////
152 typedef struct {
153 int fd; // <0: internal file
154 int space_eater;
155 int size;
156 char *data;
157 //UT_hash_handle hh;
158 } filehandle_t;
161 //static filehandle_t *fhandles = NULL;
164 static filehandle_t *colon_create_info_file (const char *path) {
165 filehandle_t *fh = NULL;
166 fd_call_dlogf("colon_create_info_file: [%s]\n", path);
167 if (strcmp(path, "/:/info") == 0) {
168 fh = calloc(1, sizeof(*fh));
169 fh->fd = -1;
170 fh->data = calloc(8192, 1);
171 //snprintf(fh->data, 8192, "files: %d; otags: %d; ntags: %d\n", HASH_COUNT(file_name_hash), HASH_COUNT(tagv_hash_o), HASH_COUNT(tagv_hash_t));
172 snprintf(fh->data, 8192, "files: %d; tags: %d; opened dirs: %d; reload deferred: %d\n", HASH_COUNT(sname_hash), HASH_COUNT(tval_hash),
173 tfs_dirs_opened, tfs_need_reload
175 fh->size = strlen(fh->data);
177 return fh;
181 static filehandle_t *fht_open (const char *realpath) {
182 int fd = open(realpath, O_RDONLY);
183 if (fd >= 0) {
184 filehandle_t *fh = calloc(1, sizeof(*fh));
185 fh->fd = fd;
186 return fh;
188 return NULL;
192 static filehandle_t *fht_create_eater (const char *realpath) {
193 filehandle_t *fh = calloc(1, sizeof(*fh));
194 fh->fd = -1;
195 fh->space_eater = 1;
196 return fh;
200 static void fht_close (filehandle_t *fh) {
201 if (fh != NULL) {
202 if (fh->fd >= 0) close(fh->fd);
203 if (fh->data != NULL) free(fh->data);
204 free(fh);
209 static int fht_read (const char *path, char *buf, size_t size, off_t offset, filehandle_t *fh) {
210 if (fh != NULL) {
211 if (fh->fd >= 0) {
212 ssize_t rd;
213 fd_call_dlogf("tfs_read: path=[%s], buf=0x%p, size=%d, offset=%lld", path, buf, size, offset);
214 if (fh->fd < 0) return -EPERM;
215 if (offset >= 0x7fffffff || size >= 0x7fffffff) return 0;/*-EPERM;*/ //???
216 if (lseek(fh->fd, offset, SEEK_SET) == (off_t)-1) return -EPERM;
217 rd = read(fh->fd, buf, size);
218 if (rd < 0) return -EPERM;
219 return rd;
221 if (fh->data != NULL) {
222 if (offset >= fh->size) return 0;
223 if ((uint64_t)offset+size > fh->size) size = fh->size-offset;
224 if (size == 0) return 0;
225 memcpy(buf, fh->data+offset, size);
226 return size;
229 return -EPERM;
233 static int fht_write (const char *path, const char *buf, size_t size, off_t offset, filehandle_t *fh) {
234 if (fh != NULL) {
235 if (fh->fd < 0) {
236 if (fh->space_eater) return size; // eat 'em alive!
239 return -EPERM;
243 ////////////////////////////////////////////////////////////////////////////////
244 // this is used in getattr() and readdir()
245 // note that readdir() will call this with 'filename.ext' and getattr() will call this with full path
246 static const char *spxnames[] = {
247 ":otags",
248 ":ttags",
249 ":files",
250 ":or",
251 ":and",
254 static int do_stat (const char *path, struct stat *statbuf) {
255 fl_fileinfo_t *nfo;
256 const char *name;
257 memset(statbuf, 0, sizeof(*statbuf));
259 fd_call_dlogf("do_stat: [%s]\n", path);
260 //FIXME!
261 statbuf->st_uid = fuse_get_context()->uid;
262 statbuf->st_gid = fuse_get_context()->gid;
264 //TODO: set to 2? do we rally want 'find' to work on muffin?
265 statbuf->st_nlink = 2; // actually, this should be set to 'subdir_count+2' (or 1), else 'find' will fail
266 statbuf->st_mode = S_IFDIR|0555;
267 //statbuf->st_dev = get_fi(0)->devid;
268 //statbuf->st_ino = get_fi(0)->inode;
269 statbuf->st_blksize = 4096; // i/o block size
270 //statbuf->st_blocks = 1;
271 //statbuf->st_size = 1;
272 statbuf->st_atime = statbuf->st_ctime = statbuf->st_mtime = cur_dir_time;
274 //stat(get_str(get_fi(0)->realname), statbuf);
275 //stat("/home/ketmar", statbuf);
276 statbuf->st_mode = S_IFDIR|0555;
278 if (strcmp(path, "/") == 0) {
279 return 0;
281 if (strcmp(path, "/:") == 0) {
282 statbuf->st_mode = S_IFDIR|0755; // writeable
283 return 0;
285 if (strncmp(path, "/:/", 3) == 0) {
286 // all files are regular ones here
287 statbuf->st_mode = S_IFREG|0444;
288 if (strcmp(path, "/:/reload") == 0) {
289 if (tfs_need_reload) {
290 fd_call_dlogf(" stat: eater is here\n");
291 statbuf->st_mode = S_IFREG|0777;
292 return 0;
294 return -ENOENT;
296 statbuf->st_size = 4096; // arbitrary, but must be bigger than the actual 'info' files
297 return 0;
300 name = strrchr(path, '/');
301 if (name == NULL) name = path; else ++name;
302 fd_call_dlogf(" do_stat_name: [%s]\n", name);
304 if (name[0] == ':') {
305 fd_call_dlogf(" do_spec_stat: [%s]\n", name);
306 for (size_t f = 0; f < ARRAYLEN(spxnames); ++f) if (strcmp(name, spxnames[f]) == 0) {
307 fd_call_dlogf(" stat: SPECIAL\n");
308 return 0;
310 for (size_t f = 0; f < ARRAYLEN(spec_dirs); ++f) if (strcmp(spec_dirs[f].name, name) == 0) {
311 fd_call_dlogf(" stat: SPECIAL\n");
312 return 0;
314 dlogf("baddir: [%s]\n", path);
315 return -ENOENT;
318 if ((nfo = find_by_short_name(name)) != NULL) {
319 // normal file
321 if (do_real_stat) {
322 if (stat(nfo->fullname, statbuf) == 0) return 0;
323 return -ENOENT; //TODO: return better error here
326 fd_call_dlogf(" stat: file\n");
327 statbuf->st_dev = nfo->devid;
328 statbuf->st_ino = nfo->inode;
329 statbuf->st_mode = S_IFREG|0444;
330 statbuf->st_size = nfo->size;
331 statbuf->st_blksize = 4096; // i/o block size
332 statbuf->st_blocks = (nfo->size/512)+(nfo->size%512 ? 1 : 0);
333 statbuf->st_atime = statbuf->st_ctime = statbuf->st_mtime = nfo->mtime;
334 return 0;
337 //dlogf("not-a-file: [%s]\n", path);
338 if (find_by_tag_name(name) != NULL) {
339 // this is dirs too
340 fd_call_dlogf(" stat: dir\n");
341 return 0;
344 dlogf(" stat: ***not-found: [%s]\n", path);
345 return -ENOENT;
349 /** Get file attributes.
351 * Similar to stat(). The 'st_dev' and 'st_blksize' fields are
352 * ignored. The 'st_ino' field is ignored except if the 'use_ino'
353 * mount option is given.
355 static int tfs_getattr (const char *path, struct stat *statbuf) {
356 fd_call_dlogf("tfs_getattr: path=[%s]", path);
357 return do_stat(path, statbuf);
361 /** Read the target of a symbolic link
363 * The buffer should be filled with a null terminated string. The
364 * buffer size argument includes the space for the terminating
365 * null character. If the linkname is too long to fit in the
366 * buffer, it should be truncated. The return value should be 0
367 * for success.
369 // Note the system readlink() will truncate and lose the terminating
370 // null. So, the size passed to to the system readlink() must be one
371 // less than the size passed to tfs_readlink()
372 static int tfs_readlink (const char *path, char *link, size_t size) {
373 fd_call_dlogf("tfs_readlink: path=[%s]", path);
374 return -ENOENT; // there are no symlinks
378 /** Create a file node
380 * This is called for creation of all non-directory, non-symlink
381 * nodes. If the filesystem defines a create() method, then for
382 * regular files that will be called instead.
384 static int tfs_mknod (const char *path, mode_t mode, dev_t dev) {
385 fd_call_dlogf("tfs_mknod: path=[%s], mode=0%03o, dev=%lld", path, mode, dev);
387 //if (!S_ISREG(mode)) return -EINVAL; // only regular files can be created
388 // no new files can be created here
389 //return (exists ? EEXIST : EFAULT);
390 return -EFAULT;
394 /** Create a directory
396 * Note that the mode argument may not have the type specification
397 * bits set, i.e. S_ISDIR(mode) can be false. To obtain the
398 * correct directory type bits use mode|S_IFDIR
400 static int tfs_mkdir (const char *path, mode_t mode) {
401 fd_call_dlogf("tfs_mkdir: path=[%s], mode=0%03o", path, mode);
402 // no new directories can be created here
403 return -EFAULT;
407 /** Remove a file */
408 static int tfs_unlink (const char *path) {
409 fd_call_dlogf("tfs_unlink: path=[%s]", path);
410 return -EFAULT;
414 /** Remove a directory */
415 static int tfs_rmdir (const char *path) {
416 fd_call_dlogf("tfs_rmdir: path=[%s]", path);
417 return -EFAULT;
421 /** Create a symbolic link */
422 // The parameters here are a little bit confusing, but do correspond
423 // to the symlink() system call. The 'path' is where the link points,
424 // while the 'link' is the link itself. So we need to leave the path
425 // unaltered, but insert the link into the mounted directory.
426 static int tfs_symlink (const char *path, const char *link) {
427 fd_call_dlogf("tfs_symlink: path=[%s]; link=[%s]", path, link);
428 return -EFAULT;
432 /** Rename a file */
433 // both path and newpath are fs-relative
434 static int tfs_rename (const char *path, const char *newpath) {
435 fd_call_dlogf("tfs_rename: path=[%s]; newpath=[%s]", path, newpath);
436 return -EFAULT;
440 /** Create a hard link to a file */
441 static int tfs_link (const char *path, const char *newpath) {
442 fd_call_dlogf("tfs_link: path=[%s]; newpath=[%s]", path, newpath);
443 return -EFAULT;
447 /** Change the permission bits of a file */
448 static int tfs_chmod (const char *path, mode_t mode) {
449 fd_call_dlogf("tfs_chmod: path=[%s], mode=0%03o", path, mode);
450 return 0;
454 /** Change the owner and group of a file */
455 static int tfs_chown (const char *path, uid_t uid, gid_t gid) {
456 fd_call_dlogf("tfs_chown: path=[%s], uid=%d, gid=%d", path, uid, gid);
457 return 0;
461 /** Change the size of a file */
462 static int tfs_truncate (const char *path, off_t newsize) {
463 fd_call_dlogf("tfs_truncate: path=[%s], newsize=%lld", path, newsize);
464 return -EFAULT;
468 /** Change the access and/or modification times of a file
470 * Deprecated, use utimens() instead.
473 static int tfs_utime (const char *path, struct utimbuf *ubuf) {
474 return 0;
479 /** File open operation
481 * No creation (O_CREAT, O_EXCL) and by default also no
482 * truncation (O_TRUNC) flags will be passed to open(). If an
483 * application specifies O_TRUNC, fuse first calls truncate()
484 * and then open(). Only if 'atomic_o_trunc' has been
485 * specified and kernel version is 2.6.24 or later, O_TRUNC is
486 * passed on to open.
488 * Unless the 'default_permissions' mount option is given,
489 * open should check if the operation is permitted for the
490 * given flags. Optionally open may also return an arbitrary
491 * filehandle in the fuse_file_info structure, which will be
492 * passed to all file operations.
494 * Changed in version 2.2
496 static int tfs_open (const char *path, struct fuse_file_info *fi) {
497 fl_fileinfo_t *nfo;
498 filehandle_t *fh = NULL;
499 fd_call_dlogf("tfs_open: path=[%s], fi=0x%p; append=%d; trunc=%d\n", path, fi, (fi->flags&O_APPEND ? 1 : 0), (fi->flags&O_TRUNC ? 1 : 0));
500 if ((fi->flags&O_APPEND) || (fi->flags&O_TRUNC)) {
501 fd_call_dlogf(" bad flags!\n");
502 return -EPERM;
504 switch (fi->flags&(O_RDONLY|O_WRONLY|O_RDWR)) {
505 case O_RDONLY: break;
506 case O_WRONLY:
507 case O_RDWR:
508 fd_call_dlogf(" bad access mode!\n");
509 return -EPERM;
512 if (strncmp(path, "/:/", 3) == 0) {
513 fh = colon_create_info_file(path);
514 } else {
515 if ((nfo = find_by_short_name(path)) != NULL) {
516 fd_call_dlogf(" found: [%s]\n", get_str(nfo->realname));
517 fh = fht_open(get_str(nfo->realname));
520 if (fh != NULL) {
521 fi->fh = (uintptr_t)fh;
522 return 0;
524 fd_call_dlogf(" shit!\n");
525 return -ENOENT;
529 /** Read data from an open file
531 * Read should return exactly the number of bytes requested except
532 * on EOF or error, otherwise the rest of the data will be
533 * substituted with zeroes. An exception to this is when the
534 * 'direct_io' mount option is specified, in which case the return
535 * value of the read system call will reflect the return value of
536 * this operation.
538 * Changed in version 2.2
540 static int tfs_read (const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi) {
541 filehandle_t *fh = (filehandle_t *)(uintptr_t)(fi->fh);
542 return fht_read(path, buf, size, offset, fh);
546 /** Write data to an open file
548 * Write should return exactly the number of bytes requested
549 * except on error. An exception to this is when the 'direct_io'
550 * mount option is specified (see read operation).
552 * Changed in version 2.2
554 static int tfs_write (const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fi) {
555 fd_call_dlogf("tfs_write: path=[%s], buf=0x%p, size=%d, offset=%lld, fi=0x%p", path, buf, size, offset, fi);
556 filehandle_t *fh = (filehandle_t *)(uintptr_t)(fi->fh);
557 return fht_write(path, buf, size, offset, fh);
561 /** Get file system statistics
563 * The 'f_frsize', 'f_favail', 'f_fsid' and 'f_flag' fields are ignored
565 * Replaced 'struct statfs' parameter with 'struct statvfs' in
566 * version 2.5
568 static int tfs_statfs (const char *path, struct statvfs *statv) {
569 return -EPERM;
571 //statvfs
572 //memset(statv, 0, sizeof(*statv));
573 //statv->f_bsize = 8192; // fixme
574 fd_call_dlogf("tfs_statfs: path=[%s], statv=0x%p", path, statv);
575 //return retstat;
579 /** Possibly flush cached data
581 * BIG NOTE: This is not equivalent to fsync(). It's not a
582 * request to sync dirty data.
584 * Flush is called on each close() of a file descriptor. So if a
585 * filesystem wants to return write errors in close() and the file
586 * has cached dirty data, this is a good place to write back data
587 * and return any errors. Since many applications ignore close()
588 * errors this is not always useful.
590 * NOTE: The flush() method may be called more than once for each
591 * open(). This happens if more than one file descriptor refers
592 * to an opened file due to dup(), dup2() or fork() calls. It is
593 * not possible to determine if a flush is final, so each flush
594 * should be treated equally. Multiple write-flush sequences are
595 * relatively rare, so this shouldn't be a problem.
597 * Filesystems shouldn't assume that flush will always be called
598 * after some writes, or that if will be called at all.
600 * Changed in version 2.2
602 static int tfs_flush (const char *path, struct fuse_file_info *fi) {
603 fd_call_dlogf("tfs_flush: path=[%s], fi=0x%p", path, fi);
604 return 0;
608 /** Release an open file
610 * Release is called when there are no more references to an open
611 * file: all file descriptors are closed and all memory mappings
612 * are unmapped.
614 * For every open() call there will be exactly one release() call
615 * with the same flags and file descriptor. It is possible to
616 * have a file opened more than once, in which case only the last
617 * release will mean, that no more reads/writes will happen on the
618 * file. The return value of release is ignored.
620 * Changed in version 2.2
622 static int tfs_release (const char *path, struct fuse_file_info *fi) {
623 filehandle_t *fh = (filehandle_t *)(uintptr_t)(fi->fh);
624 int is_eater = (fh != NULL ? fh->space_eater : 0);
625 fd_call_dlogf("tfs_release: path=[%s]; fh=%p; eater=%d\n", path, fh, is_eater);
626 fht_close(fh);
627 fi->fh = 0;
628 if (is_eater) tagdb_check_and_reload();
629 return 0;
633 /** Synchronize file contents
635 * If the datasync parameter is non-zero, then only the user data
636 * should be flushed, not the meta data.
638 * Changed in version 2.2
640 static int tfs_fsync (const char *path, int datasync, struct fuse_file_info *fi) {
641 fd_call_dlogf("tfs_fsync: path=[%s], datasync=%d, fi=0x%p", path, datasync, fi);
642 return 0;
646 /** Set extended attributes */
647 static int tfs_setxattr (const char *path, const char *name, const char *value, size_t size, int flags) {
648 fd_call_dlogf("tfs_setxattr: path=[%s], name=[%s], value=[%s], size=%d, flags=0x%08x", path, name, value, size, (unsigned int)flags);
649 return -EPERM;
653 static const struct {
654 const char *name;
655 int tflidx;
656 int hidden;
657 } xattr_tags[] = {
658 {.name="user.oartist", .tflidx=TFL_ARTIST_O, .hidden=1},
659 {.name="user.artist", .tflidx=TFL_ARTIST_O, .hidden=0},
660 {.name="user._artist", .tflidx=TFL_ARTIST_T, .hidden=0},
661 {.name="user.tartist", .tflidx=TFL_ARTIST_T, .hidden=1},
662 {.name="user.oalbum", .tflidx=TFL_ALBUM_O, .hidden=1},
663 {.name="user.album", .tflidx=TFL_ALBUM_O, .hidden=0},
664 {.name="user._album", .tflidx=TFL_ALBUM_T, .hidden=0},
665 {.name="user.talbum", .tflidx=TFL_ALBUM_T, .hidden=1},
666 {.name="user.otitle", .tflidx=TFL_TITLE_O, .hidden=1},
667 {.name="user.title", .tflidx=TFL_TITLE_O, .hidden=0},
668 {.name="user._title", .tflidx=TFL_TITLE_T, .hidden=0},
669 {.name="user.ttitle", .tflidx=TFL_TITLE_T, .hidden=1},
670 {.name="user.ogenre", .tflidx=TFL_GENRE_O, .hidden=1},
671 {.name="user.genre", .tflidx=TFL_GENRE_O, .hidden=0},
672 {.name="user._genre", .tflidx=TFL_GENRE_T, .hidden=0},
673 {.name="user.tgenre", .tflidx=TFL_GENRE_T, .hidden=1},
674 {.name="user.year", .tflidx=TFL_YEAR, .hidden=0},
678 /** Get extended attributes */
679 // If the given node described by path has the named extended attribute, and the vlen is zero,
680 // return the number of bytes required to provide the value of the extended attribute.
681 // The next call will have a buffer that is long enough to hold the value. Copy the value into
682 // the buffer and return the number of bytes that the value occupies.
683 static int tfs_getxattr (const char *path, const char *name, char *value, size_t size) {
684 fd_call_dlogf("tfs_getxattr: path=[%s], name=[%s], value=0x%p, size=%d", path, name, value, size);
685 if (name != NULL && name[0]) {
686 fl_fileinfo_t *nfo;
687 const char *val = NULL;
688 int len;
689 if ((nfo = find_by_short_name(path)) == NULL) {
690 // satisfy 'ls -l'
692 struct stat sb;
693 if (do_stat(path, &sb) != 0) return -ENOENT;
695 // just return 'no data' for any attribute of any path; it's harmful (i think)
696 return 0;
698 if (strcmp(name, "user.realname") == 0) {
699 val = get_str(nfo->realname);
700 } else {
701 for (size_t f = 0; f < ARRAYLEN(xattr_tags); ++f) {
702 if (strcmp(name, xattr_tags[f].name) == 0) {
703 val = get_str(get_tv(nfo->tags[xattr_tags[f].tflidx])->value);
704 break;
708 if (val != NULL) {
709 len = strlen(val);
710 if (size > 0 && len > 0) memcpy(value, val, len);
711 return len;
713 return 0;
715 //return -EPERM;
716 return 0;
720 #define STRXCPY(str) do { \
721 const char *s = (str); \
722 if (s != NULL && s[0]) { \
723 int xlen = strlen(s)+1; \
724 if (list != NULL) { memcpy(list, s, xlen); list += xlen; } \
725 tlen += xlen; \
727 } while (0)
730 /** List extended attributes */
731 // size: the same note as for getxattr applies here.
732 // fill 'list' with asciiz-strings, one just after another.
733 // note that 'getfattr -d' lists only 'user.' attributes
734 static int tfs_listxattr (const char *path, char *list, size_t size) {
735 fl_fileinfo_t *nfo;
736 int tlen = 0;
737 fd_call_dlogf("tfs_listxattr: path=[%s], list=0x%p, size=%d", path, list, size);
738 if ((nfo = find_by_short_name(path)) == NULL) return -ENOENT;
739 STRXCPY("user.realname");
741 for (size_t f = 0; f < ARRAYLEN(xattr_tags); ++f) if (!xattr_tags[f].hidden) STRXCPY(xattr_tags[f].name);
743 return tlen;
744 //return -EPERM;
748 /** Remove extended attributes */
749 static int tfs_removexattr (const char *path, const char *name) {
750 fd_call_dlogf("tfs_removexattr: path=[%s], name=[%s]", path, name);
751 return -EPERM;
755 /** Open directory
757 * Unless the 'default_permissions' mount option is given,
758 * this method should check if opendir is permitted for this
759 * directory. Optionally opendir may also return an arbitrary
760 * filehandle in the fuse_file_info structure, which will be
761 * passed to readdir, closedir and fsyncdir.
763 * Introduced in version 2.3
765 static int tfs_opendir (const char *path, struct fuse_file_info *fi) {
766 dirinfo_t *odir;
767 tagdb_check_and_reload();
768 odir = list_dir(path);
769 if (odir == NULL) {
770 fd_call_dlogf("tfs_opendir: BAD [%s]\n", path);
771 return -EPERM;
773 ++tfs_dirs_opened;
774 fd_call_dlogf("tfs_opendir: path=[%s], %d entries", path, odir->fcount);
775 fi->fh = (uintptr_t)odir; // fh is 64 bit, so this is safe
776 return 0;
780 /** Read directory
782 * This supersedes the old getdir() interface. New applications
783 * should use this.
785 * The filesystem may choose between two modes of operation:
787 * 1) The readdir implementation ignores the offset parameter, and
788 * passes zero to the filler function's offset. The filler
789 * function will not return '1' (unless an error happens), so the
790 * whole directory is read in a single readdir operation. This
791 * works just like the old getdir() method.
793 * 2) The readdir implementation keeps track of the offsets of the
794 * directory entries. It uses the offset parameter and always
795 * passes non-zero offset to the filler function. When the buffer
796 * is full (or an error happens) the filler function will return
797 * '1'.
799 * Introduced in version 2.3
802 * typedef int (*fuse_fill_dir_t) (void *buf, const char *name, const struct stat *stbuf, off_t off);
804 static int tfs_readdir (const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi) {
805 dirinfo_t *odir = (dirinfo_t *)(uintptr_t)fi->fh;
806 struct stat stbuf, *starg = &stbuf;
807 fd_call_dlogf("tfs_readdir: path=[%s], buf=0x%p, filler=0x%p, offset=%lld, fi=0x%p", path, buf, filler, offset, fi);
808 if (odir == NULL) return -EPERM;
809 //dlogf("tfs_readdir: path=[%s], %d entries", path, odir->fcount);
810 if (offset < 0 || offset >= odir->fcount) return 0;
811 // we can build 'struct stat' here, so readdir() will return some useful flags
812 // but this is not really necessary, and we can just pass NULL
813 if (do_stat(odir->names[offset], starg) != 0) starg = NULL; // don't pass anything on error
814 //starg = NULL;
815 if (filler(buf, odir->names[offset], starg, offset+1)) {
816 fd_call_dlogf("tfs_readdir: path=[%s], filler failed!", path);
817 return -ENOMEM;
819 //dlogf("tfs_readdir: path=[%s], name=[%s]", path, odir->names[offset]);
820 return 0;
824 /** Release directory
826 * Introduced in version 2.3
828 static int tfs_releasedir (const char *path, struct fuse_file_info *fi) {
829 dirinfo_t *odir = (dirinfo_t *)(uintptr_t)fi->fh;
830 fd_call_dlogf("tfs_releasedir: path=[%s], fi=0x%p", path, fi);
831 if (odir == NULL) {
832 tagdb_check_and_reload();
833 return -EPERM;
835 if (odir->names != NULL) free(odir->names);
836 free(odir);
837 fi->fh = 0;
838 --tfs_dirs_opened;
839 tagdb_check_and_reload();
840 return 0;
844 /** Synchronize directory contents
846 * If the datasync parameter is non-zero, then only the user data
847 * should be flushed, not the meta data
849 * Introduced in version 2.3
851 // when exactly is this called? when a user calls fsync and it
852 // happens to be a directory? ???
853 static int tfs_fsyncdir (const char *path, int datasync, struct fuse_file_info *fi) {
854 fd_call_dlogf("tfs_fsyncdir: path=[%s], datasync=%d, fi=0x%p", path, datasync, fi);
855 return 0;
860 * Initialize filesystem
862 * The return value will passed in the private_data field of
863 * fuse_context to all file operations and as a parameter to the
864 * destroy() method.
866 * Introduced in version 2.3
867 * Changed in version 2.6
869 // Undocumented but extraordinarily useful fact: the fuse_context is
870 // set up before this function is called, and
871 // fuse_get_context()->private_data returns the user_data passed to
872 // fuse_main(). Really seems like either it should be a third
873 // parameter coming in here, or else the fact should be documented
874 // (and this might as well return void, as it did in older versions of
875 // FUSE).
876 static void *tfs_init (struct fuse_conn_info *conn) {
877 char tmpbuf[4096];
878 dlogf("tfs_init: protocol v%u.%u", conn->proto_major, conn->proto_minor);
879 // dump caps
880 if (conn->capable) {
881 tmpbuf[0] = 0;
882 if (conn->capable&FUSE_CAP_ASYNC_READ) strcat(tmpbuf, " FUSE_CAP_ASYNC_READ");
883 if (conn->capable&FUSE_CAP_POSIX_LOCKS) strcat(tmpbuf, " FUSE_CAP_POSIX_LOCKS"); // filesystem supports "remote" locking
884 if (conn->capable&FUSE_CAP_ATOMIC_O_TRUNC) strcat(tmpbuf, " FUSE_CAP_ATOMIC_O_TRUNC"); // filesystem handles the O_TRUNC open flag
885 if (conn->capable&FUSE_CAP_EXPORT_SUPPORT) strcat(tmpbuf, " FUSE_CAP_EXPORT_SUPPORT"); // filesystem handles lookups of "." and ".."
886 if (conn->capable&FUSE_CAP_BIG_WRITES) strcat(tmpbuf, " FUSE_CAP_BIG_WRITES"); // filesystem can handle write size larger than 4kB
887 if (conn->capable&FUSE_CAP_DONT_MASK) strcat(tmpbuf, " FUSE_CAP_DONT_MASK"); // don't apply umask to file mode on create operations
888 dlogf("kernel caps:%s\n", tmpbuf);
890 // set our params
891 conn->want = 0; // the only flag we want is FUSE_CAP_BIG_WRITES, but we don't support writing
892 conn->async_read = 0; // we don't support async reads
893 return fuse_get_context()->private_data;
898 * Clean up filesystem
900 * Called on filesystem exit.
902 * Introduced in version 2.3
904 static void tfs_destroy (void *userdata) {
905 dlogf("tfs_destroy: userdata=0x%p", userdata);
910 * Check file access permissions
912 * This will be called for the access() system call. If the
913 * 'default_permissions' mount option is given, this method is not
914 * called.
916 * This method is not called under Linux kernel versions 2.4.x
918 * Introduced in version 2.5
920 //k8: don't know if mode can be combination of flags, and what to do then
921 static int tfs_access (const char *path, int mode) {
922 struct stat st;
923 int res;
924 //dlogf("tfs_access: path=[%s], mode=0x%02x", path, mode);
925 if (mode&W_OK) {
926 //dlogf(" W_OK: [%s]\n", path);
927 return -EPERM; // can't write
929 res = do_stat(path, &st);
930 if (res == 0) {
931 if (S_ISDIR(st.st_mode)) return 0;
932 if (mode&X_OK) return -EPERM; // can't execute
933 return 0;
935 return res;
940 * Create and open a file
942 * If the file does not exist, first create it with the specified
943 * mode, and then open it.
945 * If this method is not implemented or under Linux kernel
946 * versions earlier than 2.6.15, the mknod() and open() methods
947 * will be called instead.
949 * Introduced in version 2.5
951 static int tfs_create (const char *path, mode_t mode, struct fuse_file_info *fi) {
952 fd_call_dlogf("tfs_create: path=[%s], mode=0%03o, fi=0x%p", path, mode, fi);
953 if (strcmp(path, "/:/reload") == 0) {
954 // special action: reload tagdb
955 filehandle_t *fh;
956 tfs_need_reload = 1;
957 // defer reloading, 'cause FUSE will call tfs_getattr() just after creating the eater
958 //tagdb_check_and_reload();
959 if ((fh = fht_create_eater(path)) != NULL) {
960 fi->fh = (uintptr_t)fh;
961 return 0;
963 return -EPERM;
965 //fi->fh = fd;
966 return -EPERM;
971 * Change the size of an open file
973 * This method is called instead of the truncate() method if the
974 * truncation was invoked from an ftruncate() system call.
976 * If this method is not implemented or under Linux kernel
977 * versions earlier than 2.6.15, the truncate() method will be
978 * called instead.
980 * Introduced in version 2.5
982 static int tfs_ftruncate (const char *path, off_t offset, struct fuse_file_info *fi) {
983 //dlogf("tfs_ftruncate: path=[%s], offset=%lld, fi=0x%p", path, offset, fi);
984 return -EPERM;
989 * Get attributes from an open file
991 * This method is called instead of the getattr() method if the
992 * file information is available.
994 * Currently this is only called after the create() method if that
995 * is implemented (see above). Later it may be called for
996 * invocations of fstat() too.
998 * Introduced in version 2.5
1000 static int tfs_fgetattr (const char *path, struct stat *statbuf, struct fuse_file_info *fi) {
1001 //dlogf("tfs_fgetattr: path=[%s], statbuf=0x%p, fi=0x%p", path, statbuf, fi);
1002 return tfs_getattr(path, statbuf); // just pass it up
1007 * Perform POSIX file locking operation
1009 * The cmd argument will be either F_GETLK, F_SETLK or F_SETLKW.
1011 * For the meaning of fields in 'struct flock' see the man page
1012 * for fcntl(2). The l_whence field will always be set to
1013 * SEEK_SET.
1015 * For checking lock ownership, the 'fuse_file_info->owner'
1016 * argument must be used.
1018 * For F_GETLK operation, the library will first check currently
1019 * held locks, and if a conflicting lock is found it will return
1020 * information without calling this method. This ensures, that
1021 * for local locks the l_pid field is correctly filled in. The
1022 * results may not be accurate in case of race conditions and in
1023 * the presence of hard links, but it's unlikly that an
1024 * application would rely on accurate GETLK results in these
1025 * cases. If a conflicting lock is not found, this method will be
1026 * called, and the filesystem may fill out l_pid by a meaningful
1027 * value, or it may leave this field zero.
1029 * For F_SETLK and F_SETLKW the l_pid field will be set to the pid
1030 * of the process performing the locking operation.
1032 * Note: if this method is not implemented, the kernel will still
1033 * allow file locking to work locally. Hence it is only
1034 * interesting for network filesystems and similar.
1036 * Introduced in version 2.6
1039 static int tfs_lock (const char *path, struct fuse_file_info *fi, int cmd, struct flock *) {
1040 return -EPERM;
1046 * Change the access and modification times of a file with
1047 * nanosecond resolution
1049 * Introduced in version 2.6
1051 static int tfs_utimens (const char *path, const struct timespec tv[2]) {
1052 return 0; // pretend that we done it
1057 * Map block index within file to block index within device
1059 * Note: This makes sense only for block device backed filesystems
1060 * mounted with the 'blkdev' option
1062 * Introduced in version 2.6
1065 static int tfs_bmap (const char *path, size_t blocksize, uint64_t *idx) {
1066 return -EPERM;
1072 * Ioctl
1074 * flags will have FUSE_IOCTL_COMPAT set for 32bit ioctls in
1075 * 64bit environment. The size and direction of data is
1076 * determined by _IOC_*() decoding of cmd. For _IOC_NONE,
1077 * data will be NULL, for _IOC_WRITE data is out area, for
1078 * _IOC_READ in area and if both are set in/out area. In all
1079 * non-NULL cases, the area is of _IOC_SIZE(cmd) bytes.
1081 * Introduced in version 2.8
1084 static int tfs_ioctl (const char *path, int cmd, void *arg, struct fuse_file_info *, unsigned int flags, void *data) {
1085 return -EPERM;
1091 * Poll for IO readiness events
1093 * Note: If ph is non-NULL, the client should notify
1094 * when IO readiness events occur by calling
1095 * fuse_notify_poll() with the specified ph.
1097 * Regardless of the number of times poll with a non-NULL ph
1098 * is received, single notification is enough to clear all.
1099 * Notifying more times incurs overhead but doesn't harm
1100 * correctness.
1102 * The callee is responsible for destroying ph with
1103 * fuse_pollhandle_destroy() when no longer in use.
1105 * Introduced in version 2.8
1108 static int tfs_poll (const char *path, struct fuse_file_info *fi, struct fuse_pollhandle *ph, unsigned *reventsp) {
1109 return -EPERM;
1114 ////////////////////////////////////////////////////////////////////////////////
1115 static const struct fuse_operations tfs_oper = {
1116 .getattr = tfs_getattr,
1117 .readlink = tfs_readlink,
1118 .getdir = NULL, // deprecated
1119 .mknod = tfs_mknod,
1120 .mkdir = tfs_mkdir,
1121 .unlink = tfs_unlink,
1122 .rmdir = tfs_rmdir,
1123 .symlink = tfs_symlink,
1124 .rename = tfs_rename,
1125 .link = tfs_link,
1126 .chmod = tfs_chmod,
1127 .chown = tfs_chown,
1128 .truncate = tfs_truncate,
1129 .utime = NULL, // deprecated
1130 .open = tfs_open,
1131 .read = tfs_read,
1132 .write = tfs_write,
1133 .statfs = tfs_statfs,
1134 .flush = tfs_flush,
1135 .release = tfs_release,
1136 .fsync = tfs_fsync,
1137 .setxattr = tfs_setxattr,
1138 .getxattr = tfs_getxattr,
1139 .listxattr = tfs_listxattr,
1140 .removexattr = tfs_removexattr,
1141 .opendir = tfs_opendir,
1142 .readdir = tfs_readdir,
1143 .releasedir = tfs_releasedir,
1144 .fsyncdir = tfs_fsyncdir,
1145 .init = tfs_init,
1146 .destroy = tfs_destroy,
1147 .access = tfs_access,
1148 .create = tfs_create,
1149 .ftruncate = tfs_ftruncate,
1150 .fgetattr = tfs_fgetattr,
1151 //.lock = tfs_lock,
1152 .utimens = tfs_utimens,
1153 //.bmap = tfs_bmap,
1156 * Flag indicating, that the filesystem can accept a NULL path
1157 * as the first argument for the following operations:
1159 * read, write, flush, release, fsync, readdir, releasedir,
1160 * fsyncdir, ftruncate, fgetattr and lock
1162 //unsigned int flag_nullpath_ok : 1;
1163 .flag_nullpath_ok = 0,
1164 // 2.8 API
1165 //.ioctl = tfs_ioctl,
1166 //.poll = tfs_poll,
1170 static void tfs_usage (void) {
1171 fprintf(stderr,
1172 "usage: fusedrv [mount options] tags.dat mountpoint\n"
1173 "special options:\n"
1174 " --debug write some debug logs\n"
1175 " --files show files not only in /:files\n"
1177 exit(1);
1181 static int tagfile_loaded = 0;
1182 static const char *argv00 = "./me";
1185 // return -1 on error, 0 if arg is to be discarded, 1 if arg should be kept
1186 static int opt_processor (void *data, const char *arg, int key, struct fuse_args *outargs) {
1187 //fprintf(stderr, "key=%d; arg=%s\n", key, arg);
1189 if (key == FUSE_OPT_KEY_OPT) {
1190 // this is not FUSE option, handle it
1191 // question: how to handle cases like '-x fuck'?
1192 if (strcmp(arg, "--debug") == 0) {
1193 char *me = strdup(argv00), *logname;
1194 if (strrchr(me, '/')) strrchr(me, '/')[0] = 0;
1195 logname = get_real_path(me, 1);
1196 free(me);
1197 if (logname != NULL) {
1198 char *ln = malloc(strlen(logname)+128);
1199 sprintf(ln, "%smuffin.log", logname);
1200 dbglog_set_filename(ln);
1201 dbglog_set_screenout(0);
1202 dbglog_set_fileout(1);
1203 free(ln);
1204 free(logname);
1206 return 0;
1209 if (strcmp(arg, "--no-debug") == 0) {
1210 dbglog_set_screenout(0);
1211 dbglog_set_fileout(0);
1212 return 0;
1215 if (strcmp(arg, "--debug-calls") == 0) {
1216 opt_log_calls = 1;
1217 return 0;
1220 if (strcmp(arg, "--files") == 0) {
1221 opt_files_only_in_files = 0;
1222 return 0;
1225 if (strcmp(arg, "--no-files") == 0) {
1226 opt_files_only_in_files = 1;
1227 return 0;
1230 if (strcmp(arg, "--help") == 0) {
1231 tfs_usage();
1232 return 0;
1235 if (strcmp(arg, "-h") == 0) { tfs_usage(); exit(0); }
1236 //fprintf(stderr, "FATAL: unknown option '%s'!\n", arg);
1237 //exit(1);
1238 return 1;
1241 if (key == FUSE_OPT_KEY_NONOPT) {
1242 // not an option; first non-option arg is tagdb file name
1243 if (!tagfile_loaded) {
1244 uint64_t stt, ste;
1245 tagfilename = get_real_path(arg, 0);
1246 if (tagfilename == NULL) { fprintf(stderr, "FATAL: can't determine tag file name!\n"); return -1; }
1247 printf("loading database...\n");
1248 stt = k8clock();
1249 if (tagdb_load(tagfilename) != 0) { fprintf(stderr, "FATAL: can't load tagfile: '%s'!\n", tagfilename); return -1; }
1250 ste = k8clock();
1251 printf("database load time: %.15g seconds\n", (double)(ste-stt)/1000.0);
1252 printf("building hashes...\n");
1253 stt = k8clock();
1254 build_hashes();
1255 ste = k8clock();
1256 printf("hash build time: %.15g seconds\n", (double)(ste-stt)/1000.0);
1257 //if (file_info_count == 0) { fprintf(stderr, "FATAL: no valid files in tagfile: '%s'!\n", arg); exit(1); }
1258 tagfile_loaded = 1;
1259 return 0;
1262 return 1;
1265 return 1;
1269 int main (int argc, char *argv[]) {
1270 int fuse_stat;
1271 struct fuse_args args = FUSE_ARGS_INIT(argc, argv);
1273 if (argc > 0 && argv[0] != NULL) argv00 = argv[0];
1275 dbglog_set_screenout(0);
1276 dbglog_set_fileout(0);
1278 if (getuid() == 0 || geteuid() == 0) {
1279 fprintf(stderr, "FATAL: running fusedrv as root is inappropriate!\n");
1280 return 1;
1282 //dlogf("=== starting fusedrv ===");
1284 fuse_opt_parse(&args, NULL, NULL, opt_processor);
1285 if (!tagfile_loaded) tfs_usage();
1286 //fuse_opt_add_arg(&args, "-omodules=subdir,subdir=/foo");
1287 fuse_opt_add_arg(&args, "-s"); // single-threaded
1289 //for (int f = 0; f < args.argc; ++f) fprintf(stderr, "arg#%d: [%s]\n", f, args.argv[f]);
1291 //fprintf(stderr, "about to call fuse_main\n");
1292 fuse_stat = fuse_main(args.argc, args.argv, &tfs_oper, (void *)666);
1293 //fprintf(stderr, "fuse_main returned %d\n", fuse_stat);
1295 clear_hashes();
1296 tagdb_unload();
1297 fuse_opt_free_args(&args);
1298 return fuse_stat;