1d830398c839cbc9dccc3fdeec968163c39bb9be
[perl-fuse.git] / Fuse.pm
1 package Fuse;
2
3 use 5.006;
4 use strict;
5 use warnings;
6 use Errno;
7 use Carp;
8 use Config;
9
10 require Exporter;
11 require DynaLoader;
12 use AutoLoader;
13 use Data::Dumper;
14 our @ISA = qw(Exporter DynaLoader);
15
16 # Items to export into callers namespace by default. Note: do not export
17 # names by default without a very good reason. Use EXPORT_OK instead.
18 # Do not simply export all your public functions/methods/constants.
19
20 # This allows declaration       use Fuse ':all';
21 # If you do not need this, moving things directly into @EXPORT or @EXPORT_OK
22 # will save memory.
23 our %EXPORT_TAGS = (
24                     'all' => [ qw(XATTR_CREATE XATTR_REPLACE fuse_get_context fuse_version) ],
25                     'xattr' => [ qw(XATTR_CREATE XATTR_REPLACE) ]
26                     );
27
28 our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
29
30 our @EXPORT = ();
31 our $VERSION = '0.11';
32
33 sub AUTOLOAD {
34     # This AUTOLOAD is used to 'autoload' constants from the constant()
35     # XS function.  If a constant is not found then control is passed
36     # to the AUTOLOAD in AutoLoader.
37
38     my $constname;
39     our $AUTOLOAD;
40     ($constname = $AUTOLOAD) =~ s/.*:://;
41     croak "& not defined" if $constname eq 'constant';
42     my $val = constant($constname, @_ ? $_[0] : 0);
43     if ($! != 0) {
44         if ($!{EINVAL}) {
45             $AutoLoader::AUTOLOAD = $AUTOLOAD;
46             goto &AutoLoader::AUTOLOAD;
47         }
48         else {
49             croak "Your vendor has not defined Fuse macro $constname";
50         }
51     }
52     {
53         no strict 'refs';
54         # Fixed between 5.005_53 and 5.005_61
55         if ($] >= 5.00561) {
56             *$AUTOLOAD = sub () { $val };
57         }
58         else {
59             *$AUTOLOAD = sub { $val };
60         }
61     }
62     goto &$AUTOLOAD;
63 }
64
65 sub XATTR_CREATE {
66     # See <sys/xattr.h>.
67     return 1;
68 }
69
70 sub XATTR_REPLACE {
71     # See <sys/xattr.h>.
72     return 2;
73 }
74
75 bootstrap Fuse $VERSION;
76
77 sub main {
78         my @names = qw(getattr readlink getdir mknod mkdir unlink rmdir symlink
79                         rename link chmod chown truncate utime open read write statfs
80                         flush release fsync setxattr getxattr listxattr removexattr);
81         my $fuse_version = fuse_version();
82         if ($fuse_version >= 2.3) {
83                 push(@names, qw/opendir readdir releasedir fsyncdir init destroy/);
84         }
85         if ($fuse_version >= 2.5) {
86                 push(@names, qw/access create ftruncate fgetattr/);
87         }
88         if ($fuse_version >= 2.6) {
89                 push(@names, qw/lock utimens bmap/);
90         }
91 #       if ($fuse_version >= 2.8) {
92 #               # junk doesn't contain a function pointer, and hopefully
93 #               # never will; it's a "dead" zone in the struct
94 #               # fuse_operations where a flag bit is declared. we don't
95 #               # need to concern ourselves with it, and it appears any
96 #               # arch with a 64 bit pointer will align everything to
97 #               # 8 bytes, making the question of pointer alignment for
98 #               # the last 2 wrapper functions no big thing.
99 #               push(@names, qw/junk ioctl poll/);
100 #       }
101         my @subs = map {undef} @names;
102         my $tmp = 0;
103         my %mapping = map { $_ => $tmp++ } @names;
104         my @otherargs = qw(debug threaded mountpoint mountopts nullpath_ok);
105         my %otherargs = (
106                           debug         => 0,
107                           threaded      => 0,
108                           mountpoint    => "",
109                           mountopts     => "",
110                           nullpath_ok   => 0,
111                         );
112         while(my $name = shift) {
113                 my ($subref) = shift;
114                 if(exists($otherargs{$name})) {
115                         $otherargs{$name} = $subref;
116                 } else {
117                         croak "There is no function $name" unless exists($mapping{$name});
118                         croak "Usage: Fuse::main(getattr => \"main::my_getattr\", ...)" unless $subref;
119                         $subs[$mapping{$name}] = $subref;
120                 }
121         }
122         if($otherargs{threaded}) {
123                 # make sure threads are both available, and loaded.
124                 if($Config{useithreads}) {
125                         if(exists($threads::{VERSION})) {
126                                 if(exists($threads::shared::{VERSION})) {
127                                         # threads will work.
128                                 } else {
129                                         carp("Thread support requires you to use threads::shared.\nThreads are disabled.\n");
130                                         $otherargs{threaded} = 0;
131                                 }
132                         } else {
133                                 carp("Thread support requires you to use threads and threads::shared.\nThreads are disabled.\n");
134                                 $otherargs{threaded} = 0;
135                         }
136                 } else {
137                         carp("Thread support was not compiled into this build of perl.\nThreads are disabled.\n");
138                         $otherargs{threaded} = 0;
139                 }
140         }
141         perl_fuse_main(@otherargs{@otherargs},@subs);
142 }
143
144 # Autoload methods go after =cut, and are processed by the autosplit program.
145
146 1;
147 __END__
148
149 =head1 NAME
150
151 Fuse - write filesystems in Perl using FUSE
152
153 =head1 SYNOPSIS
154
155   use Fuse;
156   my ($mountpoint) = "";
157   $mountpoint = shift(@ARGV) if @ARGV;
158   Fuse::main(mountpoint=>$mountpoint, getattr=>"main::my_getattr", getdir=>"main::my_getdir", ...);
159
160 =head1 DESCRIPTION
161
162 This lets you implement filesystems in perl, through the FUSE
163 (Filesystem in USErspace) kernel/lib interface.
164
165 FUSE expects you to implement callbacks for the various functions.
166
167 In the following definitions, "errno" can be 0 (for a success),
168 -EINVAL, -ENOENT, -EONFIRE, any integer less than 1 really.
169
170 You can import standard error constants by saying something like
171 "use POSIX qw(EDOTDOT ENOANO);".
172
173 Every constant you need (file types, open() flags, error values,
174 etc) can be imported either from POSIX or from Fcntl, often both.
175 See their respective documentations, for more information.
176
177 =head2 EXPORTED SYMBOLS
178
179 None by default.
180
181 You can request all exportable symbols by using the tag ":all".
182
183 You can request the extended attribute symbols by using the tag ":xattr".
184 This will export XATTR_CREATE and XATTR_REPLACE.
185
186 =head2 FUNCTIONS
187
188 =head3 Fuse::main
189
190 Takes arguments in the form of hash key=>value pairs.  There are
191 many valid keys.  Most of them correspond with names of callback
192 functions, as described in section 'FUNCTIONS YOUR FILESYSTEM MAY IMPLEMENT'.
193 A few special keys also exist:
194
195
196 debug => boolean
197
198 =over 1
199
200 This turns FUSE call tracing on and off.  Default is 0 (which means off).
201
202 =back
203
204 mountpoint => string
205
206 =over 1
207
208 The point at which to mount this filesystem.  There is no default, you must
209 specify this.  An example would be '/mnt'.
210
211 =back
212
213 mountopts => string
214
215 =over 1
216
217 This is a comma seperated list of mount options to pass to the FUSE kernel
218 module.
219
220 At present, it allows the specification of the allow_other
221 argument when mounting the new FUSE filesystem. To use this, you will also
222 need 'user_allow_other' in /etc/fuse.conf as per the FUSE documention
223
224   mountopts => "allow_other" or
225   mountopts => ""
226
227 =back
228
229 threaded => boolean
230
231 =over 1
232
233 This turns FUSE multithreading on and off.  The default is 0, meaning your FUSE
234 script will run in single-threaded mode.  Note that single-threaded mode also
235 means that you will not have to worry about reentrancy, though you will have to
236 worry about recursive lookups.  In single-threaded mode, FUSE holds a global
237 lock on your filesystem, and will wait for one callback to return before
238 calling another.  This can lead to deadlocks, if your script makes any attempt
239 to access files or directories in the filesystem it is providing.  (This
240 includes calling stat() on the mount-point, statfs() calls from the 'df'
241 command, and so on and so forth.)  It is worth paying a little attention and
242 being careful about this.
243
244 Enabling multithreading will cause FUSE to make multiple simultaneous calls
245 into the various callback functions of your perl script.  If you enable 
246 threaded mode, you can enjoy all the parallel execution and interactive
247 response benefits of threads, and you get to enjoy all the benefits of race
248 conditions and locking bugs, too.  Please also ensure any other perl modules
249 you're using are also thread-safe.
250
251 (If enabled, this option will cause a warning if your perl interpreter was not
252 built with USE_ITHREADS, or if you have failed to use threads or
253 threads::shared.)
254
255 =back
256
257 nullpath_ok => boolean
258
259 =over 1
260
261 This flag tells Fuse to not pass paths for functions that operate on file
262 or directory handles. This will yield empty path parameters for functions
263 including read, write, flush, release, fsync, readdir, releasedir,
264 fsyncdir, truncate, fgetattr and lock. If you use this, you must return
265 file/directory handles from open, opendir and create. Default is 0 (off).
266 Only effective on Fuse 2.8 and up; with earlier versions, this does nothing.
267
268 =back
269
270 =head3 Fuse::fuse_get_context
271  
272  use Fuse "fuse_get_context";
273  my $caller_uid = fuse_get_context()->{"uid"};
274  my $caller_gid = fuse_get_context()->{"gid"};
275  my $caller_pid = fuse_get_context()->{"pid"};
276  
277 Access context information about the current Fuse operation. 
278
279 =head3 Fuse::fuse_version
280
281 Indicates the Fuse version in use; more accurately, indicates the version
282 of the Fuse API in use at build time. Returned as a decimal value; i.e.,
283 for Fuse API v2.6, will return "2.6".
284
285 =head2 FUNCTIONS YOUR FILESYSTEM MAY IMPLEMENT
286
287 =head3 getattr
288
289 Arguments:  filename.
290 Returns a list, very similar to the 'stat' function (see
291 perlfunc).  On error, simply return a single numeric scalar
292 value (e.g. "return -ENOENT();").
293
294 FIXME: the "ino" field is currently ignored.  I tried setting it to 0
295 in an example script, which consistently caused segfaults.
296
297 Fields (the following was stolen from perlfunc(1) with apologies):
298
299 ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
300         $atime,$mtime,$ctime,$blksize,$blocks)
301                          = getattr($filename);
302
303 Here are the meaning of the fields:
304
305  0 dev      device number of filesystem
306  1 ino      inode number
307  2 mode     file mode  (type and permissions)
308  3 nlink    number of (hard) links to the file
309  4 uid      numeric user ID of file's owner
310  5 gid      numeric group ID of file's owner
311  6 rdev     the device identifier (special files only)
312  7 size     total size of file, in bytes
313  8 atime    last access time in seconds since the epoch
314  9 mtime    last modify time in seconds since the epoch
315 10 ctime    inode change time (NOT creation time!) in seconds
316             since the epoch
317 11 blksize  preferred block size for file system I/O
318 12 blocks   actual number of blocks allocated
319
320 (The epoch was at 00:00 January 1, 1970 GMT.)
321
322 =head3 readlink
323
324 Arguments:  link pathname.
325 Returns a scalar: either a numeric constant, or a text string.
326
327 This is called when dereferencing symbolic links, to learn the target.
328
329 example rv: return "/proc/self/fd/stdin";
330
331 =head3 getdir
332
333 Arguments:  Containing directory name.
334 Returns a list: 0 or more text strings (the filenames), followed by a numeric errno (usually 0).
335
336 This is used to obtain directory listings.  It's opendir(), readdir(), filldir() and closedir() all in one call.
337
338 example rv: return ('.', 'a', 'b', 0);
339
340 =head3 readdir
341
342 Arguments: Directory name, offset
343 Returns: filename, offset to the next dirent, numeric errno 0 or -ENOENT()
344
345 =head3 mknod
346
347 Arguments:  Filename, numeric modes, numeric device
348 Returns an errno (0 upon success, as usual).
349
350 This function is called for all non-directory, non-symlink nodes,
351 not just devices.
352
353 =head3 mkdir
354
355 Arguments:  New directory pathname, numeric modes.
356 Returns an errno.
357
358 Called to create a directory.
359
360 =head3 unlink
361
362 Arguments:  Filename.
363 Returns an errno.
364
365 Called to remove a file, device, or symlink.
366
367 =head3 rmdir
368
369 Arguments:  Pathname.
370 Returns an errno.
371
372 Called to remove a directory.
373
374 =head3 symlink
375
376 Arguments:  Existing filename, symlink name.
377 Returns an errno.
378
379 Called to create a symbolic link.
380
381 =head3 rename
382
383 Arguments:  old filename, new filename.
384 Returns an errno.
385
386 Called to rename a file, and/or move a file from one directory to another.
387
388 =head3 link
389
390 Arguments:  Existing filename, hardlink name.
391 Returns an errno.
392
393 Called to create hard links.
394
395 =head3 chmod
396
397 Arguments:  Pathname, numeric modes.
398 Returns an errno.
399
400 Called to change permissions on a file/directory/device/symlink.
401
402 =head3 chown
403
404 Arguments:  Pathname, numeric uid, numeric gid.
405 Returns an errno.
406
407 Called to change ownership of a file/directory/device/symlink.
408
409 =head3 truncate
410
411 Arguments:  Pathname, numeric offset.
412 Returns an errno.
413
414 Called to truncate a file, at the given offset.
415
416 =head3 utime
417
418 Arguments:  Pathname, numeric actime, numeric modtime.
419 Returns an errno.
420
421 Called to change access/modification times for a file/directory/device/symlink.
422
423 =head3 open
424
425 Arguments:  Pathname, numeric flags (which is an OR-ing of stuff like O_RDONLY
426 and O_SYNC, constants you can import from POSIX), fileinfo hash reference.
427 Returns an errno, a file handle (optional).
428
429 No creation, or trunctation flags (O_CREAT, O_EXCL, O_TRUNC) will be passed to open().
430 The fileinfo hash reference contains flags from the Fuse open call which may be modified by the module. The only fields presently supported are:
431  direct_io (version 2.4 onwards)
432  keep_cache (version 2.4 onwards)
433  nonseekable (version 2.9 onwards)
434 Your open() method needs only check if the operation is permitted for the given flags, and return 0 for success.
435 Optionally a file handle may be returned, which will be passed to subsequent read, write, flush, fsync and release calls.
436
437 =head3 read
438
439 Arguments:  Pathname, numeric requested size, numeric offset, file handle
440 Returns a numeric errno, or a string scalar with up to $requestedsize bytes of data.
441
442 Called in an attempt to fetch a portion of the file.
443
444 =head3 write
445
446 Arguments:  Pathname, scalar buffer, numeric offset, file handle.  You can use length($buffer) to
447 find the buffersize.
448 Returns length($buffer) if successful (number of bytes written).
449
450 Called in an attempt to write (or overwrite) a portion of the file.  Be prepared because $buffer could contain random binary data with NULs and all sorts of other wonderful stuff.
451
452 =head3 statfs
453
454 Arguments:  none
455 Returns any of the following:
456
457 -ENOANO()
458
459 or
460
461 $namelen, $files, $files_free, $blocks, $blocks_avail, $blocksize
462
463 or
464
465 -ENOANO(), $namelen, $files, $files_free, $blocks, $blocks_avail, $blocksize
466
467 =head3 flush
468
469 Arguments: Pathname, file handle
470 Returns an errno or 0 on success.
471
472 Called to synchronise any cached data. This is called before the file
473 is closed. It may be called multiple times before a file is closed.
474
475 =head3 release
476
477 Arguments: Pathname, numeric flags passed to open, file handle
478 Returns an errno or 0 on success.
479
480 Called to indicate that there are no more references to the file. Called once
481 for every file with the same pathname and flags as were passed to open.
482
483 =head3 fsync
484
485 Arguments: Pathname, numeric flags
486 Returns an errno or 0 on success.
487
488 Called to synchronise the file's contents. If flags is non-zero,
489 only synchronise the user data. Otherwise synchronise the user and meta data.
490
491 =head3 setxattr
492
493 Arguments: Pathname, extended attribute's name, extended attribute's value, numeric flags (which is an OR-ing of XATTR_CREATE and XATTR_REPLACE 
494 Returns an errno or 0 on success.
495
496 Called to set the value of the named extended attribute.
497
498 If you wish to reject setting of a particular form of extended attribute name
499 (e.g.: regexps matching user\..* or security\..*), then return - EOPNOTSUPP.
500
501 If flags is set to XATTR_CREATE and the extended attribute already exists,
502 this should fail with - EEXIST. If flags is set to XATTR_REPLACE
503 and the extended attribute doesn't exist, this should fail with - ENOATTR.
504
505 XATTR_CREATE and XATTR_REPLACE are provided by this module, but not exported
506 by default. To import them:
507
508     use Fuse ':xattr';
509
510 or:
511
512     use Fuse ':all';
513
514 =head3 getxattr
515
516 Arguments: Pathname, extended attribute's name
517 Returns an errno, 0 if there was no value, or the extended attribute's value.
518
519 Called to get the value of the named extended attribute.
520
521 =head3 listxattr
522
523 Arguments: Pathname
524 Returns a list: 0 or more text strings (the extended attribute names), followed by a numeric errno (usually 0).
525
526 =head3 removexattr
527
528 Arguments: Pathname, extended attribute's name
529 Returns an errno or 0 on success.
530
531 =head3 opendir
532
533 Arguments: Pathname of a directory
534 Returns an errno, and a directory handle (optional)
535
536 Called when opening a directory for reading. If special handling is
537 required to open a directory, this operation can be implemented to handle
538 that.
539
540 =head3 readdir
541
542 Arguments: Pathname of a directory, numeric offset, (optional) directory handle
543 Returns a list of 0 or more entries, followed by a numeric errno (usually 0).
544 The entries can be simple strings (filenames), or arrays containing an
545 offset number, the filename, and optionally an array ref containing the
546 stat values (as would be returned from getattr()).
547
548 This is used to read entries from a directory. It can be used to return just
549 entry names like getdir(), or can get a segment of the available entries,
550 which requires using array refs and the 2- or 3-item form, with offset values
551 starting from 1. If you wish to return the parameters to fill each entry's
552 struct stat, but do not wish to do partial entry lists/entry counting, set
553 the first element of each array to 0 always.
554
555 Note that if this call is implemented, it overrides getdir() ALWAYS.
556
557 =head3 releasedir
558
559 Arguments: Pathname of a directory, (optional) directory handle
560 Returns an errno or 0 on success
561
562 Called when there are no more references to an opened directory. Called once
563 for each pathname or handle passed to opendir(). Similar to release(), but
564 for directories. Accepts a return value, but like release(), the response
565 code will not propagate to any corresponding closedir() calls.
566
567 =head3 fsyncdir
568
569 Arguments: Pathname of a directory, numeric flags, (optional) directory handle
570 Returns an errno or 0 on success.
571
572 Called to synchronize any changes to a directory's contents. If flag is
573 non-zero, only synchronize user data, otherwise synchronize user data and
574 metadata.
575
576 =head3 init
577
578 Arguments: None.
579 Returns (optionally) an SV to be passed as private_data via fuse_get_context().
580
581 =head3 destroy
582
583 Arguments: (optional) private data SV returned from init(), if any.
584 Returns nothing.
585
586 =head3 access
587
588 Arguments: Pathname, access mode flags
589 Returns an errno or 0 on success.
590
591 Determine if the user attempting to access the indicated file has access to
592 perform the requested actions. The user ID can be determined by calling
593 fuse_get_context(). See access(2) for more information.
594
595 =head3 create
596
597 Arguments: Pathname, create mask, open mode flags
598 Returns errno or 0 on success, and (optional) file handle.
599
600 Create a file with the path indicated, then open a handle for reading and/or
601 writing with the supplied mode flags. Can also return a file handle like
602 open() as part of the call.
603
604 =head3 ftruncate
605
606 Arguments: Pathname, numeric offset, (optional) file handle
607 Returns errno or 0 on success
608
609 Like truncate(), but on an opened file.
610
611 =head3 fgetattr
612
613 Arguments: Pathname, (optional) file handle
614 Returns a list, very similar to the 'stat' function (see
615 perlfunc).  On error, simply return a single numeric scalar
616 value (e.g. "return -ENOENT();").
617
618 Like getattr(), but on an opened file.
619
620 =head3 lock
621
622 Arguments: Pathname, numeric command code, hashref containing lock parameters, (optional) file handle
623 Returns errno or 0 on success
624
625 Used to lock or unlock regions of a file. Locking is handled locally, but this
626 allows (especially for networked file systems) for protocol-level locking
627 semantics to also be employed, if any are available.
628
629 See the Fuse documentation for more explanation of lock(). The needed symbols
630 for the lock constants can be obtained by importing Fcntl.
631
632 =head3 utimens
633
634 Arguments: Pathname, last accessed time, last modified time
635 Returns errno or 0 on success
636
637 Like utime(), but allows time resolution down to the nanosecond. Currently
638 times are passed as "numeric" (internally I believe these are represented
639 typically as "long double"), so the sub-second portion is represented as
640 fractions of a second.
641
642 Note that if this call is implemented, it overrides utime() ALWAYS.
643
644 =head3 bmap
645
646 Arguments: Pathname, numeric blocksize, numeric block number
647 Returns errno or 0 on success, and physical block number if successful
648
649 Used to map a block number offset in a file to the physical block offset
650 on the block device backing the file system. This is intended for
651 filesystems that are stored on an actual block device, with the 'blkdev'
652 option passed.
653
654 =head1 AUTHOR
655
656 Mark Glines, E<lt>mark@glines.orgE<gt>
657
658 =head1 SEE ALSO
659
660 L<perl>, the FUSE documentation.
661
662 =cut