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