Blob


1 /*
2 * 9P to FUSE translator. Acts as FUSE server, 9P client.
3 * Mounts 9P servers via FUSE kernel module.
4 *
5 * There are four procs in this threaded program
6 * (ignoring the one that runs main and then exits).
7 * The first proc reads FUSE requests from /dev/fuse.
8 * It sends the requests over a channel to a second proc,
9 * which serves the requests. Each request runs in a
10 * thread in that second proc. Those threads do write
11 * FUSE replies, which in theory might block, but in practice don't.
12 * The 9P interactions are handled by lib9pclient, which
13 * allocates two more procs, one for reading and one for
14 * writing the 9P connection. Thus the many threads in the
15 * request proc can do 9P interactions without blocking.
16 */
18 #define _GNU_SOURCE 1 /* for O_DIRECTORY on Linux */
19 #include "a.h"
21 /* GNUisms */
22 #ifndef O_DIRECTORY
23 #define O_DIRECTORY 0
24 #endif
26 #ifndef O_LARGEFILE
27 # define O_LARGEFILE 0
28 #endif
30 /*
31 * Work around glibc's broken <bits/fcntl.h> which defines
32 * O_LARGEFILE to 0 on 64 bit architectures. But, on those same
33 * architectures, linux _forces_ O_LARGEFILE (which is always
34 * 0100000 in the kernel) at each file open. FUSE is all too
35 * happy to pass the flag onto us, where we'd have no idea what
36 * to do with it if we trusted glibc.
37 */
38 #if defined(__linux__)
39 # undef O_LARGEFILE
40 # define O_LARGEFILE 0100000
41 #endif
43 #ifndef O_CLOEXEC
44 # if defined(__linux__)
45 # define O_CLOEXEC 02000000 /* Sigh */
46 # else
47 # define O_CLOEXEC 0
48 # endif
49 #endif
51 int debug;
52 char *argv0;
53 char *aname = "";
54 void fusedispatch(void*);
55 Channel *fusechan;
57 enum
58 {
59 STACK = 8192
60 };
62 /*
63 * The number of seconds that the kernel can cache
64 * returned file attributes. FUSE's default is 1.0.
65 * I haven't experimented with using 0.
66 */
67 double attrtimeout = 1.0;
69 /*
70 * The number of seconds that the kernel can cache
71 * the returned entry nodeids returned by lookup.
72 * I haven't experimented with other values.
73 */
74 double entrytimeout = 1.0;
76 CFsys *fsys;
77 CFid *fsysroot;
78 void init9p(char*, char*);
80 void
81 usage(void)
82 {
83 fprint(2, "usage: 9pfuse [-D] [-A attrtimeout] [-a aname] address mtpt\n");
84 exit(1);
85 }
87 void fusereader(void*);
88 void watchfd(void*);
90 void
91 threadmain(int argc, char **argv)
92 {
93 ARGBEGIN{
94 case 'D':
95 chatty9pclient++;
96 debug++;
97 break;
98 case 'A':
99 attrtimeout = atof(EARGF(usage()));
100 break;
101 case 'a':
102 aname = EARGF(usage());
103 break;
104 default:
105 usage();
106 }ARGEND
108 if(argc != 2)
109 usage();
111 quotefmtinstall();
112 fmtinstall('F', fcallfmt);
113 fmtinstall('M', dirmodefmt);
114 fmtinstall('G', fusefmt);
116 setsid(); /* won't be able to use console, but can't be interrupted */
118 init9p(argv[0], aname);
119 initfuse(argv[1]);
121 fusechan = chancreate(sizeof(void*), 0);
122 proccreate(fusedispatch, nil, STACK);
123 sendp(fusechan, nil); /* sync */
125 proccreate(fusereader, nil, STACK);
126 /*
127 * Now that we're serving FUSE, we can wait
128 * for the mount to finish and exit back to the user.
129 */
130 waitfuse();
131 threadexits(0);
134 void
135 fusereader(void *v)
137 FuseMsg *m;
139 while((m = readfusemsg()) != nil)
140 sendp(fusechan, m);
142 fusemtpt = nil; /* no need to unmount */
143 threadexitsall(0);
146 void
147 init9p(char *addr, char *spec)
149 int fd;
151 if(strcmp(addr, "-") == 0)
152 fd = 0;
153 else
154 if((fd = dial(netmkaddr(addr, "tcp", "564"), nil, nil, nil)) < 0)
155 sysfatal("dial %s: %r", addr);
156 proccreate(watchfd, (void*)(uintptr)fd, STACK);
157 if((fsys = fsmount(fd, spec)) == nil)
158 sysfatal("fsmount: %r");
159 fsysroot = fsroot(fsys);
162 /*
163 * FUSE uses nodeids to refer to active "struct inodes"
164 * (9P's unopened fids). FUSE uses fhs to refer to active
165 * "struct fuse_files" (9P's opened fids). The choice of
166 * numbers is up to us except that nodeid 1 is the root directory.
167 * We use the same number space for both and call the
168 * bookkeeping structure a FuseFid.
170 * FUSE requires nodeids to have associated generation
171 * numbers. If we reuse a nodeid, we have to bump the
172 * generation number to guarantee that the nodeid,gen
173 * combination is never reused.
175 * There are also inode numbers returned in directory reads
176 * and file attributes, but these do NOT need to match the nodeids.
177 * We use a combination of qid.path and qid.type as the inode
178 * number.
179 */
180 /*
181 * TO DO: reference count the fids.
182 */
183 typedef struct Fusefid Fusefid;
184 struct Fusefid
186 Fusefid *next;
187 CFid *fid;
188 int ref;
189 int id;
190 int gen;
191 int isnodeid;
193 /* directory read state */
194 Dir *d0;
195 Dir *d;
196 int nd;
197 int off;
198 };
200 Fusefid **fusefid;
201 int nfusefid;
202 Fusefid *freefusefidlist;
204 Fusefid*
205 allocfusefid(void)
207 Fusefid *f;
209 if((f = freefusefidlist) == nil){
210 f = emalloc(sizeof *f);
211 fusefid = erealloc(fusefid, (nfusefid+1)*sizeof *fusefid);
212 f->id = nfusefid;
213 fusefid[f->id] = f;
214 nfusefid++;
215 }else
216 freefusefidlist = f->next;
217 f->next = nil;
218 f->ref = 1;
219 f->isnodeid = -1;
220 return f;
223 void
224 freefusefid(Fusefid *f)
226 if(--f->ref > 0)
227 return;
228 assert(f->ref == 0);
229 if(f->fid)
230 fsclose(f->fid);
231 if(f->d0)
232 free(f->d0);
233 f->off = 0;
234 f->d0 = nil;
235 f->fid = nil;
236 f->d = nil;
237 f->nd = 0;
238 f->next = freefusefidlist;
239 f->isnodeid = -1;
240 freefusefidlist = f;
243 uvlong
244 _alloc(CFid *fid, int isnodeid)
246 Fusefid *ff;
248 ff = allocfusefid();
249 ff->fid = fid;
250 ff->isnodeid = isnodeid;
251 ff->gen++;
252 return ff->id+2; /* skip 0 and 1 */
255 uvlong
256 allocfh(CFid *fid)
258 return _alloc(fid, 0);
260 uvlong
261 allocnodeid(CFid *fid)
263 return _alloc(fid, 1);
266 Fusefid*
267 lookupfusefid(uvlong id, int isnodeid)
269 Fusefid *ff;
270 if(id < 2 || id >= nfusefid+2)
271 return nil;
272 ff = fusefid[(int)id-2];
273 if(ff->isnodeid != isnodeid)
274 return nil;
275 return ff;
278 CFid*
279 _lookupcfid(uvlong id, int isnodeid)
281 Fusefid *ff;
283 if((ff = lookupfusefid(id, isnodeid)) == nil)
284 return nil;
285 return ff->fid;
288 CFid*
289 fh2fid(uvlong fh)
291 return _lookupcfid(fh, 0);
294 CFid*
295 nodeid2fid(uvlong nodeid)
297 if(nodeid == 1)
298 return fsysroot;
299 return _lookupcfid(nodeid, 1);
302 uvlong
303 qid2inode(Qid q)
305 return q.path | ((uvlong)q.type<<56);
308 void
309 dir2attr(Dir *d, struct fuse_attr *attr)
311 attr->ino = qid2inode(d->qid);
312 attr->size = d->length;
313 attr->blocks = (d->length+8191)/8192;
314 attr->atime = d->atime;
315 attr->mtime = d->mtime;
316 attr->ctime = d->mtime; /* not right */
317 attr->atimensec = 0;
318 attr->mtimensec = 0;
319 attr->ctimensec = 0;
320 attr->mode = d->mode&0777;
321 if(d->mode&DMDIR)
322 attr->mode |= S_IFDIR;
323 else if(d->mode&DMSYMLINK)
324 attr->mode |= S_IFLNK;
325 else
326 attr->mode |= S_IFREG;
327 attr->nlink = 1; /* works for directories! - see FUSE FAQ */
328 attr->uid = getuid();
329 attr->gid = getgid();
330 attr->rdev = 0;
333 void
334 f2timeout(double f, __u64 *s, __u32 *ns)
336 *s = f;
337 *ns = (f - (int)f)*1e9;
340 void
341 dir2attrout(Dir *d, struct fuse_attr_out *out)
343 f2timeout(attrtimeout, &out->attr_valid, &out->attr_valid_nsec);
344 dir2attr(d, &out->attr);
347 /*
348 * Lookup. Walk to the name given as the argument.
349 * The response is a fuse_entry_out giving full stat info.
350 */
351 void
352 fuselookup(FuseMsg *m)
354 char *name;
355 Fusefid *ff;
356 CFid *fid, *newfid;
357 Dir *d;
358 struct fuse_entry_out out;
360 name = m->tx;
361 if((fid = nodeid2fid(m->hdr->nodeid)) == nil){
362 replyfuseerrno(m, ESTALE);
363 return;
365 if(strchr(name, '/')){
366 replyfuseerrno(m, ENOENT);
367 return;
369 if((newfid = fswalk(fid, name)) == nil){
370 replyfuseerrstr(m);
371 return;
373 if((d = fsdirfstat(newfid)) == nil){
374 fsclose(newfid);
375 replyfuseerrstr(m);
376 return;
378 out.nodeid = allocnodeid(newfid);
379 ff = lookupfusefid(out.nodeid, 1);
380 out.generation = ff->gen;
381 f2timeout(attrtimeout, &out.attr_valid, &out.attr_valid_nsec);
382 f2timeout(entrytimeout, &out.entry_valid, &out.entry_valid_nsec);
383 dir2attr(d, &out.attr);
384 free(d);
385 replyfuse(m, &out, sizeof out);
388 /*
389 * Forget. Reference-counted clunk for nodeids.
390 * Does not send a reply.
391 * Each lookup response gives the kernel an additional reference
392 * to the returned nodeid. Forget says "drop this many references
393 * to this nodeid". Our fuselookup, when presented with the same query,
394 * does not return the same results (it allocates a new nodeid for each
395 * call), but if that ever changes, fuseforget already handles the ref
396 * counts properly.
397 */
398 void
399 fuseforget(FuseMsg *m)
401 struct fuse_forget_in *in;
402 Fusefid *ff;
404 in = m->tx;
405 if((ff = lookupfusefid(m->hdr->nodeid, 1)) == nil)
406 return;
407 if(ff->ref > in->nlookup){
408 ff->ref -= in->nlookup;
409 return;
411 if(ff->ref < in->nlookup)
412 fprint(2, "bad count in forget\n");
413 ff->ref = 1;
414 freefusefid(ff);
417 /*
418 * Getattr.
419 * Replies with a fuse_attr_out structure giving the
420 * attr for the requested nodeid in out.attr.
421 * Out.attr_valid and out.attr_valid_nsec give
422 * the amount of time that the attributes can
423 * be cached.
425 * Empirically, though, if I run ls -ld on the root
426 * twice back to back, I still get two getattrs,
427 * even with a one second attribute timeout!
428 */
429 void
430 fusegetattr(FuseMsg *m)
432 CFid *fid;
433 struct fuse_attr_out out;
434 Dir *d;
436 if((fid = nodeid2fid(m->hdr->nodeid)) == nil){
437 replyfuseerrno(m, ESTALE);
438 return;
440 if((d = fsdirfstat(fid)) == nil){
441 replyfuseerrstr(m);
442 return;
444 memset(&out, 0, sizeof out);
445 dir2attrout(d, &out);
446 free(d);
447 replyfuse(m, &out, sizeof out);
450 /*
451 * Setattr.
452 * FUSE treats the many Unix attribute setting routines
453 * more or less like 9P does, with a single message.
454 */
455 void
456 fusesetattr(FuseMsg *m)
458 CFid *fid, *nfid;
459 Dir d, *dd;
460 struct fuse_setattr_in *in;
461 struct fuse_attr_out out;
463 in = m->tx;
464 if(in->valid&FATTR_FH){
465 if((fid = fh2fid(in->fh)) == nil){
466 replyfuseerrno(m, ESTALE);
467 return;
469 }else{
470 if((fid = nodeid2fid(m->hdr->nodeid)) == nil){
471 replyfuseerrno(m, ESTALE);
472 return;
474 /*
475 * Special case: Linux issues a size change to
476 * truncate a file before opening it OTRUNC.
477 * Synthetic file servers (e.g., plumber) honor
478 * open(OTRUNC) but not wstat.
479 */
480 if(in->valid == FATTR_SIZE && in->size == 0){
481 if((nfid = fswalk(fid, nil)) == nil){
482 replyfuseerrstr(m);
483 return;
485 if(fsfopen(nfid, OWRITE|OTRUNC) < 0){
486 replyfuseerrstr(m);
487 fsclose(nfid);
488 return;
490 fsclose(nfid);
491 goto stat;
495 nulldir(&d);
496 if(in->valid&FATTR_SIZE)
497 d.length = in->size;
498 if(in->valid&FATTR_ATIME)
499 d.atime = in->atime;
500 if(in->valid&FATTR_MTIME)
501 d.mtime = in->mtime;
502 if(in->valid&FATTR_MODE)
503 d.mode = in->mode;
504 if((in->valid&FATTR_UID) || (in->valid&FATTR_GID)){
505 /*
506 * I can't be bothered with these yet.
507 */
508 replyfuseerrno(m, EPERM);
509 return;
511 if(fsdirfwstat(fid, &d) < 0){
512 replyfuseerrstr(m);
513 return;
515 stat:
516 if((dd = fsdirfstat(fid)) == nil){
517 replyfuseerrstr(m);
518 return;
520 memset(&out, 0, sizeof out);
521 dir2attrout(dd, &out);
522 free(dd);
523 replyfuse(m, &out, sizeof out);
526 CFid*
527 _fuseopenfid(uvlong nodeid, int isdir, int openmode, int *err)
529 CFid *fid, *newfid;
531 if((fid = nodeid2fid(nodeid)) == nil){
532 *err = ESTALE;
533 return nil;
535 if(isdir && !(fsqid(fid).type&QTDIR)){
536 *err = ENOTDIR;
537 return nil;
539 if(openmode != OREAD && fsqid(fid).type&QTDIR){
540 *err = EISDIR;
541 return nil;
544 /* Clone fid to get one we can open. */
545 newfid = fswalk(fid, nil);
546 if(newfid == nil){
547 *err = errstr2errno();
548 return nil;
551 if(fsfopen(newfid, openmode) < 0){
552 *err = errstr2errno();
553 fsclose(newfid);
554 return nil;
557 return newfid;
560 /*
561 * Open & Opendir.
562 * Argument is a struct fuse_open_in.
563 * The mode field is ignored (presumably permission bits)
564 * and flags is the open mode.
565 * Replies with a struct fuse_open_out.
566 */
567 void
568 _fuseopen(FuseMsg *m, int isdir)
570 struct fuse_open_in *in;
571 struct fuse_open_out out;
572 CFid *fid;
573 int openmode, flags, err;
575 in = m->tx;
576 flags = in->flags;
577 openmode = flags&3;
578 flags &= ~3;
579 flags &= ~(O_DIRECTORY|O_NONBLOCK|O_LARGEFILE|O_CLOEXEC);
580 /*
581 * Discarding O_APPEND here is not completely wrong,
582 * because the host kernel will rewrite the offsets
583 * of write system calls for us. That's the best we
584 * can do on Unix anyway.
585 */
586 flags &= ~O_APPEND;
587 if(flags & O_TRUNC){
588 openmode |= OTRUNC;
589 flags &= ~O_TRUNC;
591 /*
592 * Could translate but not standard 9P:
593 * O_DIRECT -> ODIRECT
594 * O_NONBLOCK -> ONONBLOCK
595 */
596 if(flags){
597 fprint(2, "unexpected open flags %#uo", (uint)in->flags);
598 replyfuseerrno(m, EACCES);
599 return;
601 if((fid = _fuseopenfid(m->hdr->nodeid, isdir, openmode, &err)) == nil){
602 replyfuseerrno(m, err);
603 return;
605 out.fh = allocfh(fid);
606 out.open_flags = FOPEN_DIRECT_IO; /* no page cache */
607 replyfuse(m, &out, sizeof out);
610 void
611 fuseopen(FuseMsg *m)
613 _fuseopen(m, 0);
616 void
617 fuseopendir(FuseMsg *m)
619 _fuseopen(m, 1);
622 /*
623 * Create & Mkdir.
624 */
625 CFid*
626 _fusecreate(uvlong nodeid, char *name, int perm, int ismkdir, int omode, struct fuse_entry_out *out, int *err)
628 CFid *fid, *newfid, *newfid2;
629 Dir *d;
630 Fusefid *ff;
632 if((fid = nodeid2fid(nodeid)) == nil){
633 *err = ESTALE;
634 return nil;
636 perm &= 0777;
637 if(ismkdir)
638 perm |= DMDIR;
639 if(ismkdir && omode != OREAD){
640 *err = EPERM;
641 return nil;
643 if((newfid = fswalk(fid, nil)) == nil){
644 *err = errstr2errno();
645 return nil;
647 if(fsfcreate(newfid, name, omode, perm) < 0){
648 *err = errstr2errno();
649 fsclose(newfid);
650 return nil;
652 if((d = fsdirfstat(newfid)) == nil){
653 *err = errstr2errno();
654 fsfremove(newfid);
655 return nil;
657 /*
658 * This fid is no good, because it's open.
659 * We need an unopened fid. Sigh.
660 */
661 if((newfid2 = fswalk(fid, name)) == nil){
662 *err = errstr2errno();
663 free(d);
664 fsfremove(newfid);
665 return nil;
667 out->nodeid = allocnodeid(newfid2);
668 ff = lookupfusefid(out->nodeid, 1);
669 out->generation = ff->gen;
670 f2timeout(attrtimeout, &out->attr_valid, &out->attr_valid_nsec);
671 f2timeout(entrytimeout, &out->entry_valid, &out->entry_valid_nsec);
672 dir2attr(d, &out->attr);
673 free(d);
674 return newfid;
677 void
678 fusemkdir(FuseMsg *m)
680 struct fuse_mkdir_in *in;
681 struct fuse_entry_out out;
682 CFid *fid;
683 int err;
684 char *name;
686 in = m->tx;
687 name = (char*)(in+1);
688 if((fid = _fusecreate(m->hdr->nodeid, name, in->mode, 1, OREAD, &out, &err)) == nil){
689 replyfuseerrno(m, err);
690 return;
692 /* Toss the open fid. */
693 fsclose(fid);
694 replyfuse(m, &out, sizeof out);
697 void
698 fusecreate(FuseMsg *m)
700 struct fuse_open_in *in;
701 struct fuse_create_out out;
702 CFid *fid;
703 int err, openmode, flags;
704 char *name;
706 in = m->tx;
707 flags = in->flags;
708 openmode = in->flags&3;
709 flags &= ~3;
710 flags &= ~(O_DIRECTORY|O_NONBLOCK|O_LARGEFILE|O_EXCL);
711 flags &= ~O_APPEND; /* see comment in _fuseopen */
712 flags &= ~(O_CREAT|O_TRUNC); /* huh? */
713 if(flags){
714 fprint(2, "bad mode %#uo\n", in->flags);
715 replyfuseerrno(m, EACCES);
716 return;
718 name = (char*)(in+1);
719 if((fid = _fusecreate(m->hdr->nodeid, name, in->mode, 0, openmode, &out.e, &err)) == nil){
720 replyfuseerrno(m, err);
721 return;
723 out.o.fh = allocfh(fid);
724 out.o.open_flags = FOPEN_DIRECT_IO; /* no page cache */
725 replyfuse(m, &out, sizeof out);
728 /*
729 * Access.
730 * Lib9pclient implements this just as Plan 9 does,
731 * by opening the file (or not) and then closing it.
732 */
733 void
734 fuseaccess(FuseMsg *m)
736 struct fuse_access_in *in;
737 CFid *fid;
738 int err, omode;
739 static int a2o[] = {
740 0,
741 OEXEC,
742 OWRITE,
743 ORDWR,
744 OREAD,
745 OEXEC,
746 ORDWR,
747 ORDWR
748 };
750 in = m->tx;
751 if(in->mask >= nelem(a2o)){
752 replyfuseerrno(m, EINVAL);
753 return;
755 omode = a2o[in->mask];
756 if((fid = nodeid2fid(m->hdr->nodeid)) == nil){
757 replyfuseerrno(m, ESTALE);
758 return;
760 if(fsqid(fid).type&QTDIR)
761 omode = OREAD;
762 if((fid = _fuseopenfid(m->hdr->nodeid, 0, omode, &err)) == nil){
763 replyfuseerrno(m, err);
764 return;
766 fsclose(fid);
767 replyfuse(m, nil, 0);
770 /*
771 * Release.
772 * Equivalent of clunk for file handles.
773 * in->flags is the open mode used in Open or Opendir.
774 */
775 void
776 fuserelease(FuseMsg *m)
778 struct fuse_release_in *in;
779 Fusefid *ff;
781 in = m->tx;
782 if((ff = lookupfusefid(in->fh, 0)) != nil)
783 freefusefid(ff);
784 else
785 fprint(2, "fuserelease: fh not found\n");
786 replyfuse(m, nil, 0);
789 void
790 fusereleasedir(FuseMsg *m)
792 fuserelease(m);
795 /*
796 * Read.
797 * Read from file handle in->fh at offset in->offset for size in->size.
798 * We truncate size to maxwrite just to keep the buffer reasonable.
799 */
800 void
801 fuseread(FuseMsg *m)
803 int n;
804 uchar *buf;
805 CFid *fid;
806 struct fuse_read_in *in;
808 in = m->tx;
809 if((fid = fh2fid(in->fh)) == nil){
810 replyfuseerrno(m, ESTALE);
811 return;
813 n = in->size;
814 if(n > fusemaxwrite)
815 n = fusemaxwrite;
816 buf = emalloc(n);
817 n = fspread(fid, buf, n, in->offset);
818 if(n < 0){
819 free(buf);
820 replyfuseerrstr(m);
821 return;
823 replyfuse(m, buf, n);
824 free(buf);
827 /*
828 * Readlink.
829 */
830 void
831 fusereadlink(FuseMsg *m)
833 Dir *d;
834 CFid *fid;
836 if((fid = nodeid2fid(m->hdr->nodeid)) == nil){
837 replyfuseerrno(m, ESTALE);
838 return;
840 if((d = fsdirfstat(fid)) == nil){
841 replyfuseerrstr(m);
842 return;
844 if(!(d->mode&DMSYMLINK)){
845 replyfuseerrno(m, EINVAL);
846 return;
848 replyfuse(m, d->ext, strlen(d->ext));
849 free(d);
850 return;
853 /*
854 * Readdir.
855 * Read from file handle in->fh at offset in->offset for size in->size.
856 * We truncate size to maxwrite just to keep the buffer reasonable.
857 * We assume 9P directory read semantics: a read at offset 0 rewinds
858 * and a read at any other offset starts where we left off.
859 * If it became necessary, we could implement a crude seek
860 * or cache the entire list of directory entries.
861 * Directory entries read from 9P but not yet handed to FUSE
862 * are stored in m->d,nd,d0.
863 */
864 int canpack(Dir*, uvlong, uchar**, uchar*);
865 Dir *dotdirs(CFid*);
866 void
867 fusereaddir(FuseMsg *m)
869 struct fuse_read_in *in;
870 uchar *buf, *p, *ep;
871 int n;
872 Fusefid *ff;
874 in = m->tx;
875 if((ff = lookupfusefid(in->fh, 0)) == nil){
876 replyfuseerrno(m, ESTALE);
877 return;
879 if(in->offset == 0){
880 fsseek(ff->fid, 0, 0);
881 free(ff->d0);
882 ff->d0 = ff->d = dotdirs(ff->fid);
883 ff->nd = 2;
885 n = in->size;
886 if(n > fusemaxwrite)
887 n = fusemaxwrite;
888 buf = emalloc(n);
889 p = buf;
890 ep = buf + n;
891 for(;;){
892 while(ff->nd > 0){
893 if(!canpack(ff->d, ff->off, &p, ep))
894 goto out;
895 ff->off++;
896 ff->d++;
897 ff->nd--;
899 free(ff->d0);
900 ff->d0 = nil;
901 ff->d = nil;
902 if((ff->nd = fsdirread(ff->fid, &ff->d0)) < 0){
903 replyfuseerrstr(m);
904 free(buf);
905 return;
907 if(ff->nd == 0)
908 break;
909 ff->d = ff->d0;
911 out:
912 replyfuse(m, buf, p - buf);
913 free(buf);
916 /*
917 * Fuse assumes that it can always read two directory entries.
918 * If it gets just one, it will double it in the dirread results.
919 * Thus if a directory contains just "a", you see "a" twice.
920 * Adding . as the first directory entry works around this.
921 * We could add .. too, but it isn't necessary.
922 */
923 Dir*
924 dotdirs(CFid *f)
926 Dir *d;
927 CFid *f1;
929 d = emalloc(2*sizeof *d);
930 d[0].name = ".";
931 d[0].qid = fsqid(f);
932 d[1].name = "..";
933 f1 = fswalk(f, "..");
934 if(f1){
935 d[1].qid = fsqid(f1);
936 fsclose(f1);
938 return d;
941 int
942 canpack(Dir *d, uvlong off, uchar **pp, uchar *ep)
944 uchar *p;
945 struct fuse_dirent *de;
946 int pad, size;
948 p = *pp;
949 size = FUSE_NAME_OFFSET + strlen(d->name);
950 pad = 0;
951 if(size%8)
952 pad = 8 - size%8;
953 if(size+pad > ep - p)
954 return 0;
955 de = (struct fuse_dirent*)p;
956 de->ino = qid2inode(d->qid);
957 de->off = off;
958 de->namelen = strlen(d->name);
959 memmove(de->name, d->name, de->namelen);
960 if(pad > 0)
961 memset(de->name+de->namelen, 0, pad);
962 *pp = p+size+pad;
963 return 1;
966 /*
967 * Write.
968 * Write from file handle in->fh at offset in->offset for size in->size.
969 * Don't know what in->write_flags means.
971 * Apparently implementations are allowed to buffer these writes
972 * and wait until Flush is sent, but FUSE docs say flush may be
973 * called zero, one, or even more times per close. So better do the
974 * actual writing here. Also, errors that happen during Flush just
975 * show up in the close() return status, which no one checks anyway.
976 */
977 void
978 fusewrite(FuseMsg *m)
980 struct fuse_write_in *in;
981 struct fuse_write_out out;
982 void *a;
983 CFid *fid;
984 int n;
986 in = m->tx;
987 a = in+1;
988 if((fid = fh2fid(in->fh)) == nil){
989 replyfuseerrno(m, ESTALE);
990 return;
992 if(in->size > fusemaxwrite){
993 replyfuseerrno(m, EINVAL);
994 return;
996 n = fspwrite(fid, a, in->size, in->offset);
997 if(n < 0){
998 replyfuseerrstr(m);
999 return;
1001 out.size = n;
1002 replyfuse(m, &out, sizeof out);
1006 * Flush. Supposed to flush any buffered writes. Don't use this.
1008 * Flush is a total crock. It gets called on close() of a file descriptor
1009 * associated with this open file. Some open files have multiple file
1010 * descriptors and thus multiple closes of those file descriptors.
1011 * In those cases, Flush is called multiple times. Some open files
1012 * have file descriptors that are closed on process exit instead of
1013 * closed explicitly. For those files, Flush is never called.
1014 * Even more amusing, Flush gets called before close() of read-only
1015 * file descriptors too!
1017 * This is just a bad idea.
1019 void
1020 fuseflush(FuseMsg *m)
1022 replyfuse(m, nil, 0);
1026 * Unlink & Rmdir.
1028 void
1029 _fuseremove(FuseMsg *m, int isdir)
1031 char *name;
1032 CFid *fid, *newfid;
1034 name = m->tx;
1035 if((fid = nodeid2fid(m->hdr->nodeid)) == nil){
1036 replyfuseerrno(m, ESTALE);
1037 return;
1039 if(strchr(name, '/')){
1040 replyfuseerrno(m, ENOENT);
1041 return;
1043 if((newfid = fswalk(fid, name)) == nil){
1044 replyfuseerrstr(m);
1045 return;
1047 if(isdir && !(fsqid(newfid).type&QTDIR)){
1048 replyfuseerrno(m, ENOTDIR);
1049 fsclose(newfid);
1050 return;
1052 if(!isdir && (fsqid(newfid).type&QTDIR)){
1053 replyfuseerrno(m, EISDIR);
1054 fsclose(newfid);
1055 return;
1057 if(fsfremove(newfid) < 0){
1058 replyfuseerrstr(m);
1059 return;
1061 replyfuse(m, nil, 0);
1064 void
1065 fuseunlink(FuseMsg *m)
1067 _fuseremove(m, 0);
1070 void
1071 fusermdir(FuseMsg *m)
1073 _fuseremove(m, 1);
1077 * Rename.
1079 * FUSE sends the nodeid for the source and destination
1080 * directory and then the before and after names as strings.
1081 * 9P can only do the rename if the source and destination
1082 * are the same. If the same nodeid is used for source and
1083 * destination, we're fine, but if FUSE gives us different nodeids
1084 * that happen to correspond to the same directory, we have
1085 * no way of figuring that out. Let's hope it doesn't happen too often.
1087 void
1088 fuserename(FuseMsg *m)
1090 struct fuse_rename_in *in;
1091 char *before, *after;
1092 CFid *fid, *newfid;
1093 Dir d;
1095 in = m->tx;
1096 if(in->newdir != m->hdr->nodeid){
1097 replyfuseerrno(m, EXDEV);
1098 return;
1100 before = (char*)(in+1);
1101 after = before + strlen(before) + 1;
1102 if((fid = nodeid2fid(m->hdr->nodeid)) == nil){
1103 replyfuseerrno(m, ESTALE);
1104 return;
1106 if(strchr(before, '/') || strchr(after, '/')){
1107 replyfuseerrno(m, ENOENT);
1108 return;
1110 if((newfid = fswalk(fid, before)) == nil){
1111 replyfuseerrstr(m);
1112 return;
1114 nulldir(&d);
1115 d.name = after;
1116 if(fsdirfwstat(newfid, &d) < 0){
1117 replyfuseerrstr(m);
1118 fsclose(newfid);
1119 return;
1121 fsclose(newfid);
1122 replyfuse(m, nil, 0);
1126 * Fsync. Commit file info to stable storage.
1127 * Not sure what in->fsync_flags are.
1129 void
1130 fusefsync(FuseMsg *m)
1132 struct fuse_fsync_in *in;
1133 CFid *fid;
1134 Dir d;
1136 in = m->tx;
1137 if((fid = fh2fid(in->fh)) == nil){
1138 replyfuseerrno(m, ESTALE);
1139 return;
1141 nulldir(&d);
1142 if(fsdirfwstat(fid, &d) < 0){
1143 replyfuseerrstr(m);
1144 return;
1146 replyfuse(m, nil, 0);
1150 * Fsyncdir. Commit dir info to stable storage?
1152 void
1153 fusefsyncdir(FuseMsg *m)
1155 fusefsync(m);
1159 * Statfs. Send back information about file system.
1160 * Not really worth implementing, except that if we
1161 * reply with ENOSYS, programs like df print messages like
1162 * df: `/tmp/z': Function not implemented
1163 * and that gets annoying. Returning all zeros excludes
1164 * us from df without appearing to cause any problems.
1166 void
1167 fusestatfs(FuseMsg *m)
1169 struct fuse_statfs_out out;
1171 memset(&out, 0, sizeof out);
1172 replyfuse(m, &out, sizeof out);
1175 void (*fusehandlers[100])(FuseMsg*);
1177 struct {
1178 int op;
1179 void (*fn)(FuseMsg*);
1180 } fuselist[] = {
1181 { FUSE_LOOKUP, fuselookup },
1182 { FUSE_FORGET, fuseforget },
1183 { FUSE_GETATTR, fusegetattr },
1184 { FUSE_SETATTR, fusesetattr },
1186 * FUSE_SYMLINK, FUSE_MKNOD are unimplemented.
1188 { FUSE_READLINK, fusereadlink },
1189 { FUSE_MKDIR, fusemkdir },
1190 { FUSE_UNLINK, fuseunlink },
1191 { FUSE_RMDIR, fusermdir },
1192 { FUSE_RENAME, fuserename },
1194 * FUSE_LINK is unimplemented.
1196 { FUSE_OPEN, fuseopen },
1197 { FUSE_READ, fuseread },
1198 { FUSE_WRITE, fusewrite },
1199 { FUSE_STATFS, fusestatfs },
1200 { FUSE_RELEASE, fuserelease },
1201 { FUSE_FSYNC, fusefsync },
1203 * FUSE_SETXATTR, FUSE_GETXATTR, FUSE_LISTXATTR, and
1204 * FUSE_REMOVEXATTR are unimplemented.
1205 * FUSE will stop sending these requests after getting
1206 * an -ENOSYS reply (see dispatch below).
1208 { FUSE_FLUSH, fuseflush },
1210 * FUSE_INIT is handled in initfuse and should not be seen again.
1212 { FUSE_OPENDIR, fuseopendir },
1213 { FUSE_READDIR, fusereaddir },
1214 { FUSE_RELEASEDIR, fusereleasedir },
1215 { FUSE_FSYNCDIR, fusefsyncdir },
1216 { FUSE_ACCESS, fuseaccess },
1217 { FUSE_CREATE, fusecreate },
1220 void
1221 fusethread(void *v)
1223 FuseMsg *m;
1225 m = v;
1226 if((uint)m->hdr->opcode >= nelem(fusehandlers)
1227 || !fusehandlers[m->hdr->opcode]){
1228 replyfuseerrno(m, ENOSYS);
1229 return;
1231 fusehandlers[m->hdr->opcode](m);
1234 void
1235 fusedispatch(void *v)
1237 int i;
1238 FuseMsg *m;
1240 eofkill9pclient = 1; /* threadexitsall on 9P eof */
1241 atexit(unmountatexit);
1243 recvp(fusechan); /* sync */
1245 for(i=0; i<nelem(fuselist); i++){
1246 if(fuselist[i].op >= nelem(fusehandlers))
1247 sysfatal("make fusehandlers bigger op=%d", fuselist[i].op);
1248 fusehandlers[fuselist[i].op] = fuselist[i].fn;
1251 while((m = recvp(fusechan)) != nil)
1252 threadcreate(fusethread, m, STACK);
1255 void*
1256 emalloc(uint n)
1258 void *p;
1260 p = malloc(n);
1261 if(p == nil)
1262 sysfatal("malloc(%d): %r", n);
1263 memset(p, 0, n);
1264 return p;
1267 void*
1268 erealloc(void *p, uint n)
1270 p = realloc(p, n);
1271 if(p == nil)
1272 sysfatal("realloc(..., %d): %r", n);
1273 return p;
1276 char*
1277 estrdup(char *p)
1279 char *pp;
1280 pp = strdup(p);
1281 if(pp == nil)
1282 sysfatal("strdup(%.20s): %r", p);
1283 return pp;
1286 void
1287 watchfd(void *v)
1289 int fd = (int)(uintptr)v;
1291 /* wait for exception (file closed) */
1292 fd_set set;
1293 FD_ZERO(&set);
1294 FD_SET(fd, &set);
1295 if(select(fd+1, NULL, NULL, &set, NULL) >= 0)
1296 threadexitsall(nil);
1297 return;