0d7b47496652a17c930b02c3cd5ab4cc6d3c8215
[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 opendir readdir releasedir fsyncdir);
81         my @subs = map {undef} @names;
82         my $tmp = 0;
83         my %mapping = map { $_ => $tmp++ } @names;
84         my @otherargs = qw(debug threaded mountpoint mountopts nullpath_ok);
85         my %otherargs = (
86                           debug         => 0,
87                           threaded      => 0,
88                           mountpoint    => "",
89                           mountopts     => "",
90                           nullpath_ok   => 0,
91                         );
92         while(my $name = shift) {
93                 my ($subref) = shift;
94                 if(exists($otherargs{$name})) {
95                         $otherargs{$name} = $subref;
96                 } else {
97                         croak "There is no function $name" unless exists($mapping{$name});
98                         croak "Usage: Fuse::main(getattr => \"main::my_getattr\", ...)" unless $subref;
99                         $subs[$mapping{$name}] = $subref;
100                 }
101         }
102         if($otherargs{threaded}) {
103                 # make sure threads are both available, and loaded.
104                 if($Config{useithreads}) {
105                         if(exists($threads::{VERSION})) {
106                                 if(exists($threads::shared::{VERSION})) {
107                                         # threads will work.
108                                 } else {
109                                         carp("Thread support requires you to use threads::shared.\nThreads are disabled.\n");
110                                         $otherargs{threaded} = 0;
111                                 }
112                         } else {
113                                 carp("Thread support requires you to use threads and threads::shared.\nThreads are disabled.\n");
114                                 $otherargs{threaded} = 0;
115                         }
116                 } else {
117                         carp("Thread support was not compiled into this build of perl.\nThreads are disabled.\n");
118                         $otherargs{threaded} = 0;
119                 }
120         }
121         perl_fuse_main(@otherargs{@otherargs},@subs);
122 }
123
124 # Autoload methods go after =cut, and are processed by the autosplit program.
125
126 1;
127 __END__
128
129 =head1 NAME
130
131 Fuse - write filesystems in Perl using FUSE
132
133 =head1 SYNOPSIS
134
135   use Fuse;
136   my ($mountpoint) = "";
137   $mountpoint = shift(@ARGV) if @ARGV;
138   Fuse::main(mountpoint=>$mountpoint, getattr=>"main::my_getattr", getdir=>"main::my_getdir", ...);
139
140 =head1 DESCRIPTION
141
142 This lets you implement filesystems in perl, through the FUSE
143 (Filesystem in USErspace) kernel/lib interface.
144
145 FUSE expects you to implement callbacks for the various functions.
146
147 In the following definitions, "errno" can be 0 (for a success),
148 -EINVAL, -ENOENT, -EONFIRE, any integer less than 1 really.
149
150 You can import standard error constants by saying something like
151 "use POSIX qw(EDOTDOT ENOANO);".
152
153 Every constant you need (file types, open() flags, error values,
154 etc) can be imported either from POSIX or from Fcntl, often both.
155 See their respective documentations, for more information.
156
157 =head2 EXPORTED SYMBOLS
158
159 None by default.
160
161 You can request all exportable symbols by using the tag ":all".
162
163 You can request the extended attribute symbols by using the tag ":xattr".
164 This will export XATTR_CREATE and XATTR_REPLACE.
165
166 =head2 FUNCTIONS
167
168 =head3 Fuse::main
169
170 Takes arguments in the form of hash key=>value pairs.  There are
171 many valid keys.  Most of them correspond with names of callback
172 functions, as described in section 'FUNCTIONS YOUR FILESYSTEM MAY IMPLEMENT'.
173 A few special keys also exist:
174
175
176 debug => boolean
177
178 =over 1
179
180 This turns FUSE call tracing on and off.  Default is 0 (which means off).
181
182 =back
183
184 mountpoint => string
185
186 =over 1
187
188 The point at which to mount this filesystem.  There is no default, you must
189 specify this.  An example would be '/mnt'.
190
191 =back
192
193 mountopts => string
194
195 =over 1
196
197 This is a comma seperated list of mount options to pass to the FUSE kernel
198 module.
199
200 At present, it allows the specification of the allow_other
201 argument when mounting the new FUSE filesystem. To use this, you will also
202 need 'user_allow_other' in /etc/fuse.conf as per the FUSE documention
203
204   mountopts => "allow_other" or
205   mountopts => ""
206
207 =back
208
209 threaded => boolean
210
211 =over 1
212
213 This turns FUSE multithreading on and off.  The default is 0, meaning your FUSE
214 script will run in single-threaded mode.  Note that single-threaded mode also
215 means that you will not have to worry about reentrancy, though you will have to
216 worry about recursive lookups.  In single-threaded mode, FUSE holds a global
217 lock on your filesystem, and will wait for one callback to return before
218 calling another.  This can lead to deadlocks, if your script makes any attempt
219 to access files or directories in the filesystem it is providing.  (This
220 includes calling stat() on the mount-point, statfs() calls from the 'df'
221 command, and so on and so forth.)  It is worth paying a little attention and
222 being careful about this.
223
224 Enabling multithreading will cause FUSE to make multiple simultaneous calls
225 into the various callback functions of your perl script.  If you enable 
226 threaded mode, you can enjoy all the parallel execution and interactive
227 response benefits of threads, and you get to enjoy all the benefits of race
228 conditions and locking bugs, too.  Please also ensure any other perl modules
229 you're using are also thread-safe.
230
231 (If enabled, this option will cause a warning if your perl interpreter was not
232 built with USE_ITHREADS, or if you have failed to use threads or
233 threads::shared.)
234
235 =back
236
237 nullpath_ok => boolean
238
239 =over 1
240
241 This flag tells Fuse to not pass paths for functions that operate on file
242 or directory handles. This will yield empty path parameters for functions
243 including read, write, flush, release, fsync, readdir, releasedir,
244 fsyncdir, truncate, fgetattr and lock. If you use this, you must return
245 file/directory handles from open, opendir and create. Default is 0 (off).
246 Only effective on Fuse 2.8 and up; with earlier versions, this does nothing.
247
248 =back
249
250 =head3 Fuse::fuse_get_context
251  
252  use Fuse "fuse_get_context";
253  my $caller_uid = fuse_get_context()->{"uid"};
254  my $caller_gid = fuse_get_context()->{"gid"};
255  my $caller_pid = fuse_get_context()->{"pid"};
256  
257 Access context information about the current Fuse operation. 
258
259 =head3 Fuse::fuse_version
260
261 Indicates the Fuse version in use; more accurately, indicates the version
262 of the Fuse API in use at build time. Returned as a decimal value; i.e.,
263 for Fuse API v2.6, will return "2.6".
264
265 =head2 FUNCTIONS YOUR FILESYSTEM MAY IMPLEMENT
266
267 =head3 getattr
268
269 Arguments:  filename.
270 Returns a list, very similar to the 'stat' function (see
271 perlfunc).  On error, simply return a single numeric scalar
272 value (e.g. "return -ENOENT();").
273
274 FIXME: the "ino" field is currently ignored.  I tried setting it to 0
275 in an example script, which consistently caused segfaults.
276
277 Fields (the following was stolen from perlfunc(1) with apologies):
278
279 ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
280         $atime,$mtime,$ctime,$blksize,$blocks)
281                          = getattr($filename);
282
283 Here are the meaning of the fields:
284
285  0 dev      device number of filesystem
286  1 ino      inode number
287  2 mode     file mode  (type and permissions)
288  3 nlink    number of (hard) links to the file
289  4 uid      numeric user ID of file's owner
290  5 gid      numeric group ID of file's owner
291  6 rdev     the device identifier (special files only)
292  7 size     total size of file, in bytes
293  8 atime    last access time in seconds since the epoch
294  9 mtime    last modify time in seconds since the epoch
295 10 ctime    inode change time (NOT creation time!) in seconds
296             since the epoch
297 11 blksize  preferred block size for file system I/O
298 12 blocks   actual number of blocks allocated
299
300 (The epoch was at 00:00 January 1, 1970 GMT.)
301
302 =head3 readlink
303
304 Arguments:  link pathname.
305 Returns a scalar: either a numeric constant, or a text string.
306
307 This is called when dereferencing symbolic links, to learn the target.
308
309 example rv: return "/proc/self/fd/stdin";
310
311 =head3 getdir
312
313 Arguments:  Containing directory name.
314 Returns a list: 0 or more text strings (the filenames), followed by a numeric errno (usually 0).
315
316 This is used to obtain directory listings.  It's opendir(), readdir(), filldir() and closedir() all in one call.
317
318 example rv: return ('.', 'a', 'b', 0);
319
320 =head3 readdir
321
322 Arguments: Directory name, offset
323 Returns: filename, offset to the next dirent, numeric errno 0 or -ENOENT()
324
325 =head3 mknod
326
327 Arguments:  Filename, numeric modes, numeric device
328 Returns an errno (0 upon success, as usual).
329
330 This function is called for all non-directory, non-symlink nodes,
331 not just devices.
332
333 =head3 mkdir
334
335 Arguments:  New directory pathname, numeric modes.
336 Returns an errno.
337
338 Called to create a directory.
339
340 =head3 unlink
341
342 Arguments:  Filename.
343 Returns an errno.
344
345 Called to remove a file, device, or symlink.
346
347 =head3 rmdir
348
349 Arguments:  Pathname.
350 Returns an errno.
351
352 Called to remove a directory.
353
354 =head3 symlink
355
356 Arguments:  Existing filename, symlink name.
357 Returns an errno.
358
359 Called to create a symbolic link.
360
361 =head3 rename
362
363 Arguments:  old filename, new filename.
364 Returns an errno.
365
366 Called to rename a file, and/or move a file from one directory to another.
367
368 =head3 link
369
370 Arguments:  Existing filename, hardlink name.
371 Returns an errno.
372
373 Called to create hard links.
374
375 =head3 chmod
376
377 Arguments:  Pathname, numeric modes.
378 Returns an errno.
379
380 Called to change permissions on a file/directory/device/symlink.
381
382 =head3 chown
383
384 Arguments:  Pathname, numeric uid, numeric gid.
385 Returns an errno.
386
387 Called to change ownership of a file/directory/device/symlink.
388
389 =head3 truncate
390
391 Arguments:  Pathname, numeric offset.
392 Returns an errno.
393
394 Called to truncate a file, at the given offset.
395
396 =head3 utime
397
398 Arguments:  Pathname, numeric actime, numeric modtime.
399 Returns an errno.
400
401 Called to change access/modification times for a file/directory/device/symlink.
402
403 =head3 open
404
405 Arguments:  Pathname, numeric flags (which is an OR-ing of stuff like O_RDONLY
406 and O_SYNC, constants you can import from POSIX), fileinfo hash reference.
407 Returns an errno, a file handle (optional).
408
409 No creation, or trunctation flags (O_CREAT, O_EXCL, O_TRUNC) will be passed to open().
410 The fileinfo hash reference contains flags from the Fuse open call which may be modified by the module. The only fields presently supported are:
411  direct_io (version 2.4 onwards)
412  keep_cache (version 2.4 onwards)
413  nonseekable (version 2.9 onwards)
414 Your open() method needs only check if the operation is permitted for the given flags, and return 0 for success.
415 Optionally a file handle may be returned, which will be passed to subsequent read, write, flush, fsync and release calls.
416
417 =head3 read
418
419 Arguments:  Pathname, numeric requested size, numeric offset, file handle
420 Returns a numeric errno, or a string scalar with up to $requestedsize bytes of data.
421
422 Called in an attempt to fetch a portion of the file.
423
424 =head3 write
425
426 Arguments:  Pathname, scalar buffer, numeric offset, file handle.  You can use length($buffer) to
427 find the buffersize.
428 Returns length($buffer) if successful (number of bytes written).
429
430 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.
431
432 =head3 statfs
433
434 Arguments:  none
435 Returns any of the following:
436
437 -ENOANO()
438
439 or
440
441 $namelen, $files, $files_free, $blocks, $blocks_avail, $blocksize
442
443 or
444
445 -ENOANO(), $namelen, $files, $files_free, $blocks, $blocks_avail, $blocksize
446
447 =head3 flush
448
449 Arguments: Pathname, file handle
450 Returns an errno or 0 on success.
451
452 Called to synchronise any cached data. This is called before the file
453 is closed. It may be called multiple times before a file is closed.
454
455 =head3 release
456
457 Arguments: Pathname, numeric flags passed to open, file handle
458 Returns an errno or 0 on success.
459
460 Called to indicate that there are no more references to the file. Called once
461 for every file with the same pathname and flags as were passed to open.
462
463 =head3 fsync
464
465 Arguments: Pathname, numeric flags
466 Returns an errno or 0 on success.
467
468 Called to synchronise the file's contents. If flags is non-zero,
469 only synchronise the user data. Otherwise synchronise the user and meta data.
470
471 =head3 setxattr
472
473 Arguments: Pathname, extended attribute's name, extended attribute's value, numeric flags (which is an OR-ing of XATTR_CREATE and XATTR_REPLACE 
474 Returns an errno or 0 on success.
475
476 Called to set the value of the named extended attribute.
477
478 If you wish to reject setting of a particular form of extended attribute name
479 (e.g.: regexps matching user\..* or security\..*), then return - EOPNOTSUPP.
480
481 If flags is set to XATTR_CREATE and the extended attribute already exists,
482 this should fail with - EEXIST. If flags is set to XATTR_REPLACE
483 and the extended attribute doesn't exist, this should fail with - ENOATTR.
484
485 XATTR_CREATE and XATTR_REPLACE are provided by this module, but not exported
486 by default. To import them:
487
488     use Fuse ':xattr';
489
490 or:
491
492     use Fuse ':all';
493
494 =head3 getxattr
495
496 Arguments: Pathname, extended attribute's name
497 Returns an errno, 0 if there was no value, or the extended attribute's value.
498
499 Called to get the value of the named extended attribute.
500
501 =head3 listxattr
502
503 Arguments: Pathname
504 Returns a list: 0 or more text strings (the extended attribute names), followed by a numeric errno (usually 0).
505
506 =head3 removexattr
507
508 Arguments: Pathname, extended attribute's name
509 Returns an errno or 0 on success.
510
511 =head1 AUTHOR
512
513 Mark Glines, E<lt>mark@glines.orgE<gt>
514
515 =head1 SEE ALSO
516
517 L<perl>, the FUSE documentation.
518
519 =cut