blib/lib/Fuse/TM.pm untested

filter: Statementstmt 0.0% 0 / 747 Branchbran 0.0% 0 / 414 Conditioncond 0.0% 0 / 326 MC/DCmcdc 0.0% 0 / 203 Subroutinesub 0.0% 0 / 49 Podpod 0.0% 0 / 34 totaltotal 0.0% 0 / 1773 CC 208 SCAR 53.0
CC
208
Cov
0%
remove_rename
702.0
tm_rmdir
420.0
mkasshier
380.0
CRAP 201.3
1 package Fuse::TM;
2 # $Id: TM.pm,v 1.4 2009-12-09 06:35:01 az Exp $
3  
4 use strict;
5 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
6 $VERSION = qw(('$Revision: 1.4 $'))[1];
7  
8 use POSIX qw(:errno_h);
9 use Fuse qw(:all);
10 use Fcntl qw(:mode);
11 use File::Basename;
12 use File::Spec;
13 use Cwd qw(realpath);
14 use TM 1.43;
15 use TM::Index::Match;
16 use TM::Index::Characteristics;
17 use TM::Literal;
18 use Data::Dumper;
19 use Getopt::Std;
20 use Carp qw(verbose);
21  
22 =pod
23  
24 =head1 NAME
25  
26 Fuse::TM - Access a Topic Map as a Filesystem
27  
28 =head1 SYNOPSIS
29  
30 use Fuse::TM;
31 use TM;
32  
33 my $map;
34 # map must be created/synced in somehow, see TM(1).
35  
36 my $tmfs=Fuse::TM->new(tm=>$map,rw=>1,debug=>1);
37  
38 # this blocks until the filesystem is unmounted,
39 # see fusermount.
40 $tmfs->mount("/tmp/somedir");
41  
42 See also the L<tmfs(1)> front-end.
43  
44 =head1 DESCRIPTION
45  
46 This package provides access to a Topic Map in form of a filesystem.
47 Read-write access to the map is supported.
48  
49 =head1 Filesystem Layout
50  
51 The mountpoint will be populated with exactly two directories, F<topics>
52 and F<assocs>.
53  
54 =head2 Topics
55  
56 The topics in the map are modelled as directories, one per topic,
57 under the F<topics> directory.
58 Each topic directory contains a number of sub-directories and some files,
59 all of which have fixed names. The following list details those elements:
60  
61 =over 1
62  
63 =item F<instance>
64  
65 is a subdir which contains symlinks to all topics that are
66 instances of this topic. The topic ids are used as names
67 for the symlinks. If no instances are present then the directory is empty.
68  
69 =item F<isa>
70  
71 is a subdir which contains symlinks to all topics this
72 topic is an instance of (=classes).
73 The topic ids are used as names for the symlinks.
74 If no parent classes are present then the directory is empty.
75  
76 =item F<instances>
77  
78 is a read-only file that contains the topic ids of instances
79 of this topic, one per line. The file is empty if no
80 instances are present.
81  
82 =item F<isas>
83  
84 is a read-only file that contains the topic ids of all topics
85 this one is an instance of (=classes), one per line. The file is empty if no
86 classes are present.
87  
88 =item F<involved>
89  
90 is a read-only subdir which contains symlinks to all
91 associations where this topic is involved (as a player,
92 role or type). The names of the symlinks are of the
93 format I<N:T>, with N an arbitrary number and T
94 either "role", "player" or "type" depending on the involvement
95 of the topic. The dir is empty if no involvements are present.
96  
97 =item F<name>
98  
99 is a subdir that contains all basenames of this topic. The basenames
100 are presented in separate files, with all filenames following
101 the format I<N[@S][:T]>. N is a running number, S is the scope topic id if
102 the basename is (non-universally) scoped, and T is the type topic id if
103 the basename is (non-trivially) typed.
104 The content of the file is the basename text. The dir is empty if no
105 basenames are present.
106  
107 =item F<oc>
108  
109 is a subdir that contains all occurrences attached to this topic. The occurrences
110 are presented in separate files whose names follow the same scheme as basenames.
111 The file content is the occurrence (text or URI). The dir is empty if
112 no occurrences are present.
113  
114 =item F<~>
115  
116 is a file that contains all subject indicator URIs for this topic, one URI per line.
117 Present but empty if no subject indicators exist.
118  
119 =item F<=>
120  
121 is a symlink that points to a subject locator topic (=reified by this topic).
122 If the topic reifies another topic or association in the same map, then the
123 symlink points to that object. If the reified topic is given as URI, then the symlink will point
124 to that URI (and thus likely dangle).
125 The symlink is not present if this topic doesn't reify another.
126  
127 =back
128  
129 =head2 Associations
130  
131 Isa (class/instance) associations are presented as characteristics attached to
132 the relevant topics (see isa/instance above).
133  
134 All other, general, associations are modelled as directories under the F<assocs> directory.
135 For each association type there is a subdir under F<assocs> with the
136 type topic id as name. Within that, each thusly typed association instance
137 is represented as a subdir with a running number as name.
138  
139 This association instance directory contains one symlink named F<.type> pointing
140 back to the type topic for this association.
141 For each role in the association there is a subdir named after the role topic id,
142 which contains symlinks for all the player topics of this role.
143  
144 =cut
145  
146 my $td="topics";
147 my $ad="assocs";
148  
149 =pod
150  
151 =head1 METHODS
152  
153 =over 1
154  
155 =item new()
156  
157 $tmfs=Fuse::TM->new(tm=>$tmobj,I<option=E<gt>value,...>);
158  
159 The constructor requires a TM map object and accepts the following other options,
160 to be given as key/value pairs:
161  
162 =over 1
163  
164 =item debug
165  
166 Debugging: if set to 1, Fuse::TM internal debugging is enabled (to STDERR).
167 If set to 2, Fuse debugging is enabled additionally. Default: undef.
168  
169 =item rw
170  
171 Read-write mode: if set to 1 the filesystem is mounted read-write
172 and changes are written out the the map on unmounting. Defaults to undef: read-only mode.
173  
174 =item autocreate
175  
176 Autocreate implied topics. If set to 1 and read-write mode is active, then non-existent
177 topics are automatically created when a write action implies their existence.
178 Default: undef.
179  
180 For example writing to the file F<topics/x/oc/1:something> will create the topic
181 "something" if it didn't exist because the filename implies the occurrence
182 to be of type "something".
183  
184 =item hide
185  
186 Hide infrastructure items. If set to 1 infrastructure topics and associations are suppressed.
187 See L<TM::PSI> for details of what infrastructure elements are automatically created
188 (and subject to the hide option). Default: undef.
189  
190 =item output
191  
192 Output URI. If read-write mode is active and there were changes then the updated map
193 is written on unmount. This option controls whether the original map is overwritten (default)
194 or whether the new map is saved someplace else. The output parameter must follow the URI
195 format described in L<TM::Serializable> (i.e. io:stdout or file:something).
196  
197 =item outputdriver
198  
199 TM Driver to use for the output. Defaults to the driver of the input map.
200 Can be set to the name of a TM class that supports sync_out (i.e. TM::Materialized::*,
201 TM::Serializable::* or TM::Synchronizable::*).
202  
203 =back
204  
205 The constructor will croak() if problems are encountered.
206  
207 =cut
208  
209 sub new
210 {
211 my ($class,%o)=@_;
212  
213 # options:
214 # tm
215 # debug
216 # rw
217 # autocreate
218 # hide
219 # output
220 # outputdriver
221  
222 Carp::croak("no/invalid map object given!\n")
223 if (ref($o{tm}) !~ /^TM::(Materialized|Synchronizable|Serializable)/);
224 my $now=$o{tm}->mtime||time;
225 my $self=
226 {
227 tm=>$o{tm},
228 output=>$o{output},
229 outputdriver=>$o{outputdriver},
230 debug=>$o{debug},
231 rw=>$o{rw},
232 autocreate=>($o{rw} && $o{autocreate}),
233 hide=>$o{hide},
234 mtime=>$now,
235 };
236  
237 return bless $self,$class;
238 }
239  
240 =pod
241  
242 =item mount()
243  
244 $tmfs->mount("/some/mount/dir");
245  
246 Calls Fuse to mount the filesystem at the specified mount point, which must
247 be an existing directory. This function blocks until the filesystem is
248 unmounted. If read-write mode is enabled, then the updated map will be saved
249 on unmount. mount will croak() if problems are encountered.
250  
251 =back
252  
253 =cut
254  
255 sub mount
256 {
257 my ($self,$mountpt)=@_;
258  
259 Carp::croak("invalid object argument\n") if (!ref($self) || !$self->isa(__PACKAGE__));
260 Carp::croak("invalid mountpoint \"$mountpt\"\n")
261 if (!$mountpt || !-d $mountpt);
262  
263 $self->{tm}->sync_in;
264 $self->debug("done reading, starting indexing\n");
265 new TM::Index::Match($self->{tm});
266 new TM::Index::Characteristics($self->{tm});
267 $self->debug("building fs datastructure\n");
268 $self->maptofs;
269 $self->{mountpoint}=$mountpt;
270  
271 $self->debug("ready.\nmounting on $mountpt\n");
272 $mountpt=realpath($mountpt); # absolutize the mountpoint, for symlink lookups later
273 Fuse::main(mountpoint=>$mountpt,
274 debug=>$self->{debug}>1?1:0,
275 getattr=>sub { return $self->tm_getattr(@_); },
276 getdir=>sub { return $self->tm_getdir(@_); },
277 read=>sub { return $self->tm_read(@_); },
278 readlink=>sub { return $self->tm_readlink(@_); },
279 $self->{rw}?
280 ( write=>sub { return $self->tm_write(@_);},
281 release=>sub { return $self->tm_release(@_); },
282 chmod=>sub { return $self->tm_dummy(@_); },
283 chown=>sub { return $self->tm_dummy(@_); },
284 utime=>sub { return $self->tm_dummy(@_); },
285 truncate=>sub { return $self->tm_truncate(@_); },
286 rename=>sub { return $self->tm_rename(@_); },
287 mkdir=>sub { return $self->tm_mkdir(@_); },
288 symlink=>sub { return $self->tm_symlink(@_); },
289 unlink=>sub { return $self->tm_unlink(@_); },
290 rmdir=>sub { return $self->tm_rmdir(@_); },
291 mknod=>sub { return $self->tm_mknod(@_); }
292 ):()
293 );
294
295 if ($self->{rw})
296 {
297 $self->debug("unmounting, r/w-mode\n");
298 if (keys %{$self->{dirty}})
299 {
300 my $d=$self->{outputdriver};
301 if ($d)
302 {
303 $self->debug("changing output driver to '$d'");
304 Class::Trait->apply($self->{tm},$d);
305 }
306  
307 my $n=$self->{output};
308 if ($n)
309 {
310 $self->debug("changing output to '$n'\n");
311 $self->{tm}->url($n);
312 }
313 $self->debug("writing map out\n");
314 $self->{tm}->sync_out;
315 $self->debug("done.\n");
316 }
317 else
318 {
319 $self->debug("no dirty data needs syncing, done.\n");
320 }
321 }
322 else
323 {
324 $self->debug("unmounted, r/o-mode, done.\n");
325 }
326 return 0;
327 }
328  
329 # converts map content into fs-like structure, stores resulting data in self->{fsdata}
330 # this conversion of the whole map into an fs-like tree happens because:
331 # . repeating tm->match calls is prohibitively expensive (regardless of tm indices)
332 # . we need to keep track of assocs anyway, as they are not externally addressable
333 # . the collection of topic/assoc data needs to be done for every lookup
334  
335 # datastructure: /topics/tn/thingie/whatever => hashref or arrayref
336 # hashref: this is a dir, hash: files as keys
337 # arrayref: this is a leaf file, array: [value(ref),tmlid,stat]
338 # for dirs we use a dummy "." file with value = dir content arrayref.
339 # tmlid if a/v is name of corresponding toplet/assertion, stat is statarray
340 # for assocs: /assocs/atype/number/role/players, otherwise the same
341 sub maptofs
342 {
343 my ($self)=@_;
344 Carp::croak("invalid object argument\n") if (!ref($self) || !$self->isa(__PACKAGE__));
345  
346 my $tm=$self->{tm};
347 my %d;
348 $self->{fsdata}=\%d; # needs to be set before using the mk* methods
349
350 if ($self->{hide}) # determine what to hide
351 {
352 for ($tm->toplets(\ '+infrastructure'),$tm->asserts(\ '+infrastructure'))
353 {
354 $self->{infrastuff}->{$_->[TM->LID]}=1;
355 }
356 }
357  
358 # first pass: collect all the topicy things
359 # this makes topics and their fs locations known for later stages
360 for my $m ($tm->toplets)
361 {
362 my ($t,$sloc,$sin)=@{$m};
363 my $n=$self->lid2name($t);
364 $d{$td}->{$n}=$self->mktopichier($m); # does not cover slocs and dirs are semi-blank
365 }
366 # first pass over the assertions
367 for my $m ($tm->asserts)
368 {
369 $self->mkasshier(undef,0,$m);
370 }
371 # second pass: fixup directory modes
372 # fixup subject locators
373 # make content for instances and isas files
374 my @cand=(\%d);
375 while (my $e=pop @cand)
376 {
377 if (ref($e) eq "HASH") # a dir, look at its contents and update the "." entry with them
378 {
379 # topic? run topic fixerupper
380 # other stuff: just scan the dirs
381 if ($e->{"~"}) # only present with topics
382 {
383 $self->fixuptopic($e);
384 }
385 else
386 {
387 push @cand,values %$e; # check recursively
388 $self->scandir($e);
389 }
390 }
391 }
392 return \%d;
393 }
394  
395 # scans dir contents non-recursively, updates dir node with content listing
396 sub scandir
397 {
398 my ($self,$dirn)=@_;
399 Carp::croak("invalid object argument\n") if (!ref($self) || !$self->isa(__PACKAGE__));
400
401 # dir mode for blank dirs (ie. no subdirs)
402 my @dirmode=(0,1,S_IFDIR|S_IRUSR|S_IXUSR|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH,2,
403 0,0,0,0,$self->{mtime},$self->{mtime},$self->{mtime},0,0);
404 $dirmode[2]|=S_IWUSR if ($self->{rw});
405  
406 my $dircontent=[];
407 push @$dircontent,"." if (!$dirn->{"."});
408 push @$dircontent,"..",sort keys %$dirn;
409 my @mode=@dirmode;
410 $mode[3]+=(grep(ref($dirn->{$_}) eq "HASH", keys %$dirn)); # number of subdirs
411 $dirn->{"."}=[$dircontent,$dirn->{"."}->[1],\@mode];
412 return $dirn;
413 }
414  
415 # creates topic dir hierarchy for a given existing toplet
416 # does NOT cover assertions of any kind, leaves directory entries blank, slocs are unresolved plain
417 # returns said hierarchy. needs to be followed up by fixuptopic after matching assertions are covered
418 sub mktopichier
419 {
420 my ($self,$toplet)=@_;
421 Carp::croak("invalid object argument\n") if (!ref($self) || !$self->isa(__PACKAGE__));
422 Carp::croak ("invalid argument ".Dumper($toplet)) if (ref($toplet) ne "ARRAY" || @$toplet!=3);
423  
424 # subdirs present in every topic dir
425 my @dirkeys=qw(isa instance oc name involved);
426 # files present in every topic dir
427 # note: ~, = handled dynamically
428 my @filekeys=qw(isas instances);
429  
430 my ($t,$sloc,$sin)=@{$toplet};
431 my $tnode={"."=>[undef,$t,undef]};
432  
433 # general priming
434 map { $tnode->{$_}=$self->makefilenode(undef,$t) } (@filekeys);
435 map { $tnode->{$_}={"."=>[undef,$t,undef]} } (@dirkeys);
436  
437 # subject indicators
438 $tnode->{"~"}=$self->makefilenode((@$sin?join("\n",(@$sin,undef)):undef),$t);
439 # subject locator is stored as plain file, for now
440 $tnode->{"="}=$self->makefilenode($sloc,$t) if ($sloc);
441  
442 return $tnode;
443 }
444  
445 # resolves slocs, does instances/isas, involved assocs scans relevant directories
446 # operates on self->{fsdata}
447 sub fixuptopic
448 {
449 my ($self,$tnode)=@_;
450 Carp::croak("invalid object argument\n") if (!ref($self) || !$self->isa(__PACKAGE__));
451 Carp::croak ("invalid argument ".Dumper($tnode)) if (!$tnode || ref($tnode) ne "HASH");
452  
453 my $lid=$tnode->{"."}->[1]; # id is always present
454  
455 # does this contain an sloc we need to resolve?
456 if ($tnode->{"="} && S_ISREG($tnode->{"="}->[2]->[2])) # only unresolved slocs are regular files
457 {
458 my $link=$tnode->{"="}->[0];
459  
460 # if it's local: make it a working symlink
461 # alid2path remembers assertions
462 my $target=$self->{alid2path}->{$link};
463 undef $target if ref($target); # isa/instance are represented in two locs
464  
465 my $deboned=$self->unbase($link);
466 $target="/$td/$deboned" if (!$target && $self->{fsdata}->{$td}->{$deboned});
467
468 $tnode->{"="}=$self->makelinknode(($target?"../..$target":$link),$lid);
469 }
470
471 # gen list of instances/isas
472 for my $comp qw(instance isa)
473 {
474 my $tcomp=$comp."s";
475 my @things=sort(grep($_ ne ".", keys %{$tnode->{$comp}}));
476 $tnode->{$tcomp}=$self->makefilenode(join("\n",@things,undef),$lid) if (@things);
477 }
478
479 # now scan relevant dirs
480 for my $k (qw(isa instance oc name involved))
481 {
482 $self->scandir($tnode->{$k});
483 }
484 $self->scandir($tnode);
485 return $tnode;
486 }
487
488 sub makelinknode
489 {
490 my ($self,$target,$lid)=@_;
491 Carp::croak("invalid object argument\n") if (!ref($self) || !$self->isa(__PACKAGE__));
492 Carp::croak ("invalid arguments ".Dumper(\$target,\$lid)) if (!$target || !$lid);
493  
494 # link: size must reference actual link target text
495 my @linkmode=(0,1,S_IFLNK|S_IRWXU|S_IRWXG|S_IRWXO,1,
496 0,0,0,0,$self->{mtime},$self->{mtime},$self->{mtime},0,0);
497  
498 $linkmode[7]=length($target);
499 return [$target,$lid,\@linkmode];
500 }
501  
502 sub makefilenode
503 {
504 my ($self,$content,$lid)=@_;
505 Carp::croak("invalid object argument\n") if (!ref($self) || !$self->isa(__PACKAGE__));
506 Carp::croak ("invalid lid argument $lid") if (!$lid);
507  
508 # file mode: must be fixed with actual size info!
509 my @filemode=(0,1,S_IFREG|S_IRUSR|S_IRGRP|S_IROTH,1,
510 0,0,0,0,$self->{mtime},$self->{mtime},$self->{mtime},0,0);
511 $filemode[2]|=S_IWUSR if ($self->{rw});
512 $filemode[7]=length($content);
513 return [$content,$lid,\@filemode];
514 }
515  
516 # creates named (blank) topic, sets it up in the map and builds relevant fsdata structures
517 # optionally adds subject address and/or subject indicators.
518 # note: neither sloc nor sins can be removed via TM.
519 sub maketopic
520 {
521 my ($self,$tn,$sloc,$sins)=@_;
522 Carp::croak("invalid object argument\n") if (!ref($self) || !$self->isa(__PACKAGE__));
523 Carp::croak ("invalid topic argument $tn") if (!$tn);
524  
525 $tn=$self->unbase($tn); # for convenience in updating sins/slocs
526 my $tm=$self->{tm};
527  
528 my $lid=$tm->internalize(($tm->baseuri.$tn)=>$sloc);
529 my @sin; @sin=@$sins if $sins;
530 for my $s (@sin)
531 {
532 $tm->internalize($lid=>\ "$s");
533 }
534 my $toplet=$tm->toplet($lid);
535  
536 my $tnode=$self->mktopichier($toplet);
537 $self->fixuptopic($tnode);
538  
539 $self->{fsdata}->{$td}->{$tn}=$tnode;
540 $self->scandir($self->{fsdata}->{$td});
541 $self->{dirty}->{$tnode}=0;
542 }
543  
544 # creates fsdata hierarchy for the given assertion
545 # attaches this in the appropriate spot(s) in fsdata (as given)
546  
547 # this is necessary because the caller won't know where this ass is supposed to go,
548 # and because the ass may be reflected in multiple spots (isa!).
549  
550 # if a name is given, that name is used for attaching where possible
551 # updates all relevant dirs, returns nothing.
552 sub mkasshier
553 {
554 my ($self,$name,$isdirty,$m)=@_;
555 Carp::croak("invalid object argument\n") if (!ref($self) || !$self->isa(__PACKAGE__));
556 Carp::croak("invalid arguments ".Dumper(\$name,\$isdirty,$m)) if (ref($m) ne "Assertion");
557 my $tm=$self->{tm};
558  
559 my ($kind,$type,$scope,$lid)=($self->unbase(@{$m}[TM->KIND,TM->TYPE,TM->SCOPE]),$m->[TM->LID]);
560 my $rawtype=$m->[TM->TYPE];
561 my $d=$self->{fsdata};
562 if ($kind==TM->ASSOC)
563 {
564 # class-instance: ignore name, attach to involved topics - but only if not reified!
565 # if reified, we need to create an explicit assoc dir to represent the reificiation
566 if ($type eq "isa" && !$tm->is_reified($lid))
567 {
568 my ($p,$c,$raw);
569 $raw=($tm->get_x_players($m,"class"))[0];
570 $p=$self->lid2name($raw);
571
572 $raw=($tm->get_x_players($m,"instance"))[0];
573 $c=$self->lid2name($raw);
574
575 $d->{$td}->{$p}->{"instance"}->{$c}=$self->makelinknode("../../$c",$lid);
576 $self->{dirty}->{$d->{$td}->{$p}}=0 if ($isdirty);
577 $self->scandir($d->{$td}->{$p}->{"instance"});
578 $d->{$td}->{$c}->{"isa"}->{$p}=$self->makelinknode("../../$p",$lid);
579 $self->{dirty}->{$d->{$td}->{$c}}=0 if ($isdirty);
580 $self->scandir($d->{$td}->{$c}->{"isa"});
581  
582 $self->{alid2path}->{$lid}=["/$td/$p/instance/$c","/$td/$c/isa/$p"];
583 }
584 else # general assoc, attach in assoc area with given tag name (or next free tag)
585 {
586 my $istype=$self->lid2name($rawtype);
587  
588 my $tag=defined $name?$name:nextfreetag($d->{$ad}->{$type});
589  
590 my $an= $d->{$ad}->{$type}->{$tag} || {"."=>[undef,$lid,undef]};
591 $d->{$ad}->{$type}->{$tag} ||= $an;
592 $d->{$ad}->{$type}->{"."}||=[undef,$rawtype,undef];
593  
594 $an->{".type"}=$self->makelinknode("../../../$td/$istype",$rawtype); # .type has topic id
595  
596 # also attach to involved and to type-topic
597 my $itag=nextfreetag($d->{$td}->{$istype}->{"involved"}).":type";
598 my $thisasslink=$self->makelinknode("../../../$ad/$type/$tag",$lid);
599 $d->{$td}->{$istype}->{"involved"}->{$itag}=$thisasslink;
600  
601 # need to handle newly created, blank assocs cleanly: fallback ()
602 # get_role_s doesn't return unique roles :-((
603 my %messyroles;
604 for my $role ($tm->get_role_s($m)?@{$tm->get_role_s($m)}:())
605 {
606  
607 next if ($messyroles{$role});
608 $messyroles{$role}=1;
609  
610 my $short=$self->unbase($role);
611 $an->{$short}={"."=>[undef,$role,undef]};
612  
613 my $ishort=$self->lid2name($role);
614 my $rtag=nextfreetag($d->{$td}->{$ishort}->{"involved"}).":role";
615 $d->{$td}->{$ishort}->{"involved"}->{$rtag}=$thisasslink;
616  
617 for ($tm->get_x_players($m,$role))
618 {
619 my $player=$self->unbase($_);
620 my $target=$self->lid2name($_);
621 $an->{$short}->{$player}=$self->makelinknode("../../../../$td/$target",$_);
622
623 my $ptag=nextfreetag($d->{$td}->{$target}->{"involved"}).":player";
624 $d->{$td}->{$target}->{"involved"}->{$ptag}=$thisasslink;
625 $self->scandir($d->{$td}->{$target}->{"involved"});
626 }
627 $self->scandir($an->{$short});
628 }
629 $self->scandir($an);
630 $self->scandir($d->{$td}->{$istype}->{"involved"});
631 $self->scandir($d->{$ad}->{$type});
632 $self->{alid2path}->{$lid}="/$ad/$type/$tag";
633 $self->{dirty}->{$an}=0 if ($isdirty);
634 }
635 }
636 elsif ($kind==TM->NAME || $kind==TM->OCC)
637 {
638 my $key=($kind==TM->NAME?"name":"oc");
639 my $tname=$self->unbase(($tm->get_x_players($m,"thing"))[0]);
640
641 my $fn=$name;
642 if (!defined $name) # invent appropriate tag
643 {
644 $fn=nextfreetag($d->{$td}->{$tname}->{$key});
645 my $deftype=$key eq "oc"?"occurrence":"name";
646 $fn.=":$type" if ($type && $type ne $deftype);
647 $fn.="\@$scope" if ($scope && $scope ne "us");
648 }
649 $self->{alid2path}->{$lid}="/$td/$tname/$key/$fn";
650
651 my $r=($tm->get_x_players($m,"value"))[0]->[0];
652 $r.="\n" if ($r && $r!~/\n$/); # fs objects get trailing newline, tm stays clean of that
653 $d->{$td}->{$tname}->{$key}->{$fn}=$self->makefilenode($r,$lid);
654 $self->scandir($d->{$td}->{$tname}->{$key});
655 $self->{dirty}->{$d->{$td}->{$tname}}=0 if ($isdirty);
656 }
657 }
658  
659 # returns the next free tag for this dir node
660 sub nextfreetag
661 {
662 my ($node)=@_;
663 my $r=1;
664
665 return $r if (!$node);
666 while (grep($_ =~ /^$r($|\D)/, keys %{$node})) { $r++; };
667 return $r;
668 }
669  
670 # verifies a path being correct, returns stat-array of thing,
671 # or content/getdir if asked for
672 # returns (status,..stuff) with zero-status good
673 sub retrieve
674 {
675 my ($self,$file,$wantcontent)=@_;
676 Carp::croak("invalid object argument\n") if (!ref($self) || !$self->isa(__PACKAGE__));
677  
678 my ($found,$obj)=$self->lookup($file);
679 return -ENOENT() if (!$found);
680  
681 # obj should point to dir (=hash) or file (=array)
682 if (ref($obj) eq "HASH")
683 {
684 # get dir listing, contained in pseudo-file "."
685 my $aref=$obj->{"."}->[$wantcontent?0:2];
686 &Carp::croak("object unretrievable: ".Dumper($obj))
687 if (ref($aref) ne "ARRAY");
688 return (0,@$aref);
689 }
690 elsif (ref($obj) eq "ARRAY")
691 {
692 return (0,$wantcontent?$obj->[0]:@{$obj->[2]})
693 }
694 else
695 {
696 Carp::croak("dud object pointer ".Dumper($obj));
697 }
698 }
699  
700 # find an existing file node, return its reference and the parent container node
701 # returns 0,undef if no object can be found.
702 sub lookup
703 {
704 my ($self,$file)=@_;
705 Carp::croak("invalid object argument\n") if (!ref($self) || !$self->isa(__PACKAGE__));
706
707 my @pathcomps=split(m!/!,$file);
708 shift @pathcomps; # file paths are absolute
709 my $obj=$self->{fsdata};
710 my @nodes=($obj);
711  
712 while (defined(my $next=shift @pathcomps))
713 {
714 return 0 if (!$obj->{$next});
715 $obj=$obj->{$next};
716 unshift @nodes,$obj;
717 }
718 return (1,@nodes[0..1]);
719 }
720  
721 # checks xml/topic naming constraints
722 # returns 1 if fine, undef otherwise.
723 sub validname
724 {
725 my ($n)=@_;
726  
727 return 1 if ($n=~/^[a-z_:][0-9a-z_.:-]*$/i);
728 return undef;
729 }
730  
731 # take oc/bn, decomposes into components, checks for validity
732 # autocreates nonex scope/type topics if allowed to
733 # returns status, 1 is ok; and name components. does not return default scope or type!
734 sub split_and_complete
735 {
736 my ($self,$fn)=@_;
737 Carp::croak("invalid object argument\n") if (!ref($self) || !$self->isa(__PACKAGE__));
738
739 my ($tag,$type,$scope);
740
741 $fn=~s/(\@([^:@]+))// && ($scope=$2);
742 $fn=~s/(:([^:@]+))// && ($type=$2);
743 $tag=$fn if ($fn=~/^\d+$/);
744  
745 return 0 if (!defined($tag));
746 for my $ac (\$type,\$scope)
747 {
748 next if (!$$ac || $self->{fsdata}->{$td}->{$$ac});
749 return 0 if (!$self->{autocreate} || !validname($$ac));
750 $self->maketopic($$ac);
751 }
752 return (1,$tag,$type,$scope);
753 }
754  
755 # returns absolute, cleaned path.
756 # necessary because file::spec::rel2abs doesn't deal with ../ and cwd::realpath
757 # traverses the fs, forcing us into deadlock.
758 sub cleanpath
759 {
760 my ($target)=@_;
761 # damn rel2abs does NOT collapse x/../, but at least cleans ./ and /// and so on...sigh.
762 # and cwd::realpath locks us up because it actually traverses the filesystem.
763 my @dc=split(m!/!,$target);
764 for (my $i=0;$i<$#dc;)
765 {
766 if ($dc[$i+1] eq "..")
767 {
768 splice(@dc,$i,2);
769 --$i;
770 }
771 else
772 {
773 ++$i;
774 }
775 }
776 return join("/",@dc);
777 }
778  
779 # renames or removes a topic from the map, cleaning up all the mess left behind.
780 # returns undef if impossible to remove (topic is used as assoc type or assoc role), 1 if fine.
781 # input are topic names. removes if no new name given. new name mustn't pre-exist
782 # and a topic for it will be created and inserted in the relevant places.
783 sub remove_rename
784 {
785 my ($self,$rip,$revenant)=@_;
786 Carp::croak("invalid object argument\n") if (!ref($self) || !$self->isa(__PACKAGE__));
787 my $tm=$self->{tm};
788  
789 return 1 if ($rip && $rip eq $revenant); # pathological case...
790 # fail on pre-existing new topic or non-existent old
791 return undef if ($self->{fsdata}->{$td}->{$revenant}
792 || !$self->{fsdata}->{$td}->{$rip} || $revenant && !validname($revenant));
793
794 my $lid=$self->{fsdata}->{$td}->{$rip}->{"."}->[1];
795 Carp::croak("internal inconsistency: topic $rip has no topic id\n") if (!$lid);
796  
797 # for removals: we need to keep the map consistent, so this topic's traces must go, everywhere
798 # used as scope: change to us
799 # as occ/name type: change to appropriate default
800 # as instance/class: remove
801 # as player in assoc: remove
802 # as role or assoc type: REFUSE the removal, because there's no sensible automatic way to fix this
803  
804 if (!$revenant)
805 {
806 return undef if ($self->{fsdata}->{$ad}->{$rip} && keys %{$self->{fsdata}->{$ad}->{$rip}}); # assoc type or role
807 for my $type (grep($_ ne ".", keys %{$self->{fsdata}->{$ad}}))
808 {
809 for my $tag (grep($_ ne ".", keys %{$self->{fsdata}->{$ad}->{$type}}))
810 {
811 return undef if $self->{fsdata}->{$ad}->{$type}->{$tag}->{$rip};
812 }
813 }
814 }
815 else
816 {
817 my $oldtop=$tm->toplet($lid);
818 $self->maketopic($revenant,$oldtop->[TM->ADDRESS],$oldtop->[TM->INDICATORS]);
819 }
820  
821 my @involved;
822 for my $a ($tm->match(TM->FORALL,anyid=>$lid))
823 {
824 my $who=$self->{alid2path}->{$a->[TM->LID]};
825 Carp::croak("internal inconsistency: assertion $a->[TM->LID] without fs object\n") if (!$who);
826 push @involved,ref($who)?@{$who}:$who; # isa/instance represented in two places
827 }
828  
829 for my $p (@involved)
830 {
831 my ($found,$obj,$parent)=$self->lookup($p);
832 next if (!$found); # isas/instances are dual, removing one does the other
833
834 # what is the type of involvement?
835 my @pc=reverse(split(m!/!,$p)); pop @pc;
836 if (@pc==4 && $pc[-1] eq $td)
837 {
838 # "direct", ie. topic is player, or oc/name of topic: remove the path
839 if ($pc[-2] eq $rip)
840 {
841 return undef if ($self->tm_unlink($p));
842 }
843 # not "ours", but topic is scope or type of assertion? rename that, then.
844 elsif (grep($_ eq $pc[-3],qw(oc name)))
845 {
846 my ($status,$tag,$type,$scope)=$self->split_and_complete($pc[0]);
847 my $newname=join("/",undef,@pc[-1,-2,-3],undef).$tag;
848
849 # new topic? bring it in where appropriate
850 $type=$revenant if ($revenant && $type eq $rip);
851 $scope=$revenant if ($revenant && $scope eq $rip);
852
853 $newname.=":$type" if ($type && $type ne $rip);
854 $newname.="\@$scope" if ($scope && $scope ne $rip);
855  
856 return undef if ($self->tm_rename($p,$newname));
857 }
858 # note: the dual instance/isa is not explicitely handled
859 }
860 elsif (@pc==3 && $pc[-1] eq $ad)
861 {
862 my $anode=$self->{fsdata}->{$ad}->{$pc[-2]}->{$pc[-3]};
863 for my $role (grep($_ !~ /^\./, keys %{$anode}))
864 {
865 if ($anode->{$role}->{$rip})
866 {
867 return undef if ($self->tm_unlink("$p/$role/$rip"));
868 return undef if ($revenant && $self->tm_symlink("../../../../$td/$revenant","$p/$role/$revenant"));
869 }
870 }
871 }
872 }
873  
874 # update or get rid of reification (X reifies removed/renamed topic)
875 for my $t (grep($_->[TM->ADDRESS] eq $lid,($tm->toplets)))
876 {
877 my $loc="/$td/".$self->unbase($t->[TM->LID])."/=";
878 return undef if ($self->tm_unlink($loc));
879 return undef if ($revenant && $self->tm_symlink("../$revenant",$loc));
880 }
881 $self->{dirty}->{$lid}=0; # key is not relevant
882  
883 # finally remove the topic and its fsdata entries
884 # note: sloc and sin objects belonging to rip vanish automatically
885 $tm->externalize($lid);
886 delete $self->{fsdata}->{$td}->{$rip};
887 $self->scandir($self->{fsdata}->{$td});
888 return 1;
889 }
890  
891 sub debug
892 {
893 my ($self,@in)=@_;
894 Carp::croak("invalid object argument\n") if (!ref($self) || !$self->isa(__PACKAGE__));
895  
896 return if (!$self->{debug});
897 push @in,"\n" if ($in[-1]!~/\n$/);
898 print STDERR scalar(localtime)," ",@in;
899 }
900  
901  
902 # apply infrastructure and baseuri heuristic
903 # to create suitable topic name from lid
904 sub lid2name
905 {
906 my ($self,$lid)=@_;
907 Carp::croak("invalid object argument\n") if (!ref($self) || !$self->isa(__PACKAGE__));
908  
909 return ($self->{infrastuff}->{$lid}?".":"").$self->unbase($lid);
910 }
911  
912 # nuke tm baseuri
913 sub unbase
914 {
915 my ($self,@in)=@_;
916 Carp::croak("invalid object argument\n") if (!ref($self) || !$self->isa(__PACKAGE__));
917  
918 my $base=$self->{tm}->baseuri;
919 map { s/^$base//; } (@in);
920 return (wantarray?@in:$in[0]);
921 }
922  
923 sub tm_getattr
924 {
925 my ($self,$file) = @_;
926 Carp::croak("invalid object argument\n") if (!ref($self) || !$self->isa(__PACKAGE__));
927 my (@list,$errcode);
928  
929 $self->debug("getattr on $file\n");
930 ($errcode,@list)=$self->retrieve($file,0);
931 $self->debug( "returning errorcode $errcode\n");
932 return ($errcode) if ($errcode);
933 return @list;
934 }
935  
936 sub tm_getdir
937 {
938 my ($self,$file)=@_;
939 Carp::croak("invalid object argument\n") if (!ref($self) || !$self->isa(__PACKAGE__));
940 my (@list,$errcode);
941  
942 $self->debug( "getdir on $file\n");
943 ($errcode,@list)=$self->retrieve($file,1);
944 $self->debug( "returning: ".join(" ",@list)." and error code $errcode\n");
945 return (@list,$errcode);
946 }
947  
948 sub tm_readlink
949 {
950 my ($self,$file)=@_;
951 Carp::croak("invalid object argument\n") if (!ref($self) || !$self->isa(__PACKAGE__));
952 my ($content,$errcode);
953  
954 $self->debug("readlink on $file\n");
955 ($errcode,$content)=$self->retrieve($file,1);
956 $self->debug( "returns code $errcode result $content\n");
957 return $errcode||$content;
958 }
959
960 # return an error numeric, or binary/text string. (note: 0 means EOF, "0" will
961 # give a byte (ascii "0") to the reading program)
962 sub tm_read
963 {
964 my ($self,$file,$buf,$off)=@_;
965 Carp::croak("invalid object argument\n") if (!ref($self) || !$self->isa(__PACKAGE__));
966 my ($content,$errcode);
967  
968 $self->debug("reading $file offset $off\n");
969 ($errcode,$content)=$self->retrieve($file,1);
970 return $errcode if ($errcode);
971 return -EINVAL() if ($off>length($content));
972 return 0 if $off == length($content);
973 return substr($content,$off,$buf);
974 }
975  
976 # overwrite the contents of a file
977 # works only for existing files, and not all of them.
978 sub tm_write
979 {
980 my ($self,$file,$buf,$off)=@_;
981 Carp::croak("invalid object argument\n") if (!ref($self) || !$self->isa(__PACKAGE__));
982  
983 $self->debug("writing to $file at $off");
984
985 # find the thing
986 my ($found,$obj)=$self->lookup($file);
987 return -ENOENT() if (!$found);
988 return -EINVAL() if (ref($obj) ne "ARRAY" # dirs are hashes
989 || !S_ISREG($obj->[2]->[2]));
990  
991 # isas and instances: are read-only
992 return -EPERM() if ($file=~m!/(isas|instances)$!);
993  
994 # leaves us: subj indicators ~, names and occurrences
995 my $current=$obj->[0];
996 my ($before,$after);
997 $before=substr($current,0,$off) if ($off>0);
998 $after=substr($current,$off+length($buf)) if ($off+length($buf)<length($current));
999
1000 $obj->[0]=$before.$buf.$after;
1001 $obj->[2]->[7]=length($obj->[0]);
1002 $self->{dirty}->{$obj}=1;
1003 return length($buf);
1004 }
1005  
1006 # called on (devices and) regular files only, for us that's names/ocs, sins.
1007 sub tm_mknod
1008 {
1009 my ($self,$file,$mode,$dev)=@_;
1010 Carp::croak("invalid object argument\n") if (!ref($self) || !$self->isa(__PACKAGE__));
1011 $self->debug("mknod on $file, mode $mode dev $dev");
1012  
1013 my $tm=$self->{tm};
1014  
1015 # suitable type? we make regular files only.
1016 return -EPERM() if (!S_ISREG($mode) || $dev);
1017  
1018 # only creatable files: name and oc nodes, others auto-instantiated
1019 my ($alreadythere)=$self->lookup($file);
1020 return -EEXIST() if $alreadythere;
1021
1022 my ($localname,@rest)=reverse(split(m!/!,$file));
1023 pop @rest; # was abs path starting at mountpoint
1024
1025 if (@rest==3 && $rest[2] eq $td && $self->{fsdata}->{$td}->{$rest[1]} && $rest[0]=~/^(oc|name)$/)
1026 {
1027 my ($status,$tag,$type,$scope)=$self->split_and_complete($localname);
1028 return -EFAULT() if (!$status);
1029 my $kind=$rest[0] eq "oc"?TM->OCC:TM->NAME;
1030 $type||=($kind eq TM->OCC?"occurrence":"name");
1031 $scope||="us";
1032
1033 # now make the assertion
1034 my ($okass)=$tm->assert(Assertion->new(kind=>$kind,
1035 type=>$self->{fsdata}->{$td}->{$type}->{'.'}->[1],
1036 scope=>$self->{fsdata}->{$td}->{$scope}->{'.'}->[1],
1037 roles=>['thing','value'],
1038 players=>[ $self->{fsdata}->{$td}->{$rest[1]}->{'.'}->[1],
1039 TM::Literal->new("","xsd:string")]));
1040 $self->mkasshier($localname,1,$okass);
1041 return 0;
1042 }
1043 return -EPERM();
1044 }
1045
1046 # cut off a file's content, marks it as dirty
1047 sub tm_truncate
1048 {
1049 my ($self,$file,$length)=@_;
1050 Carp::croak("invalid object argument\n") if (!ref($self) || !$self->isa(__PACKAGE__));
1051  
1052 # find the thing
1053 my ($found,$obj)=$self->lookup($file);
1054 return -ENOENT() if (!$found);
1055 return -EINVAL() if (ref($obj) ne "ARRAY" # dirs are hashes
1056 || !S_ISREG($obj->[2]->[2]));
1057  
1058 # isas and instances: are read-only
1059 return -EPERM() if ($file=~m!/(isas|instances)$!);
1060  
1061 # leaves us: subj indicators ~, names and occurrences
1062 my $current=$obj->[0];
1063 my $curlen=length($current);
1064 my $tmobj=$obj->[1];
1065
1066 $self->debug("truncating $file at offset $length");
1067 $self->{dirty}->{$obj}=1;
1068  
1069 if ($length<$curlen)
1070 {
1071 $current=substr($current,0,$length);
1072 }
1073 elsif ($length>$curlen)
1074 {
1075 $current.="\0" x ($length-$curlen);
1076 }
1077 $obj->[0]=$current;
1078 $obj->[2]->[7]=$length;
1079 return 0;
1080 }
1081  
1082 # saves dirty file objects back into the topicmap, updates relevant stat buffer(s)
1083 # applies primarily to ~, names and occurrences (everything else are links, dirs and filenames)
1084 # minor problem: cannot return errors (would have to use flush for that)
1085 sub tm_release
1086 {
1087 my ($self,$file)=@_;
1088 Carp::croak("invalid object argument\n") if (!ref($self) || !$self->isa(__PACKAGE__));
1089 my $tm=$self->{tm};
1090
1091 $self->debug("releasing $file");
1092 my ($found,$obj)=$self->lookup($file);
1093 Carp::croak("release on nonexistent file $file!\n") if (!$found);
1094  
1095 if ($obj && $self->{dirty}->{$obj})
1096 {
1097 # a subject indicator?
1098 if ($file=~m!/~$!)
1099 {
1100 my $t=$tm->toplet($obj->[1]);
1101 $t->[TM->INDICATORS]=[split(/\n/,$obj->[0])];
1102 }
1103 # or a name/occurrence?
1104 else
1105 {
1106 my $a=$tm->retrieve($obj->[1]);
1107 my $content=$obj->[0]; # mapcontent without trailing newlines, please
1108 chomp $content;
1109  
1110 my $flavour="xsd:string";
1111 $flavour="xsd:uri"
1112 if ($a->[TM->KIND] eq TM->OCC && $content =~ m!^[a-zA-Z]+:.+$!i);
1113 $a->[TM->PLAYERS]->[1]=TM::Literal->new($content,$flavour);
1114 }
1115 $self->{dirty}->{$obj}=0;
1116 $obj->[2]->[7]=length($obj->[0]);
1117 }
1118 return 0;
1119 }
1120  
1121 # works on: names and ocs, but only when things stay with the same topic,
1122 # topic dirs
1123 sub tm_rename
1124 {
1125 my ($self,$old,$new)=@_;
1126 Carp::croak("invalid object argument\n") if (!ref($self) || !$self->isa(__PACKAGE__));
1127 $self->debug("rename $old to $new\n");
1128 my $tm=$self->{tm};
1129  
1130 my ($found,$oo,$parent)=$self->lookup($old);
1131 my ($newfound,$newo,$newparent)=$self->lookup($new);
1132 return -ENOENT() if (!$found);
1133 if (ref($oo) eq "ARRAY") # files: ~, oc, names, or links: =, instances, players etc.
1134 {
1135 return -EFAULT() if ($old=~m!/~$! # sins stay sins
1136 || S_ISLNK($oo->[2]->[2]) # link renaming is no good idea either
1137 || (dirname($new) ne dirname($old))); # no moving of names/ocs across topics.
1138  
1139 # is the requested new name acceptable?
1140 my $localname=basename($new);
1141 my ($status,$tag,$type,$scope)=$self->split_and_complete($localname);
1142 return -ENOENT() if (!$status);
1143
1144 # find object at the new name; scope and type are already guaranteed to exist
1145 if ($newfound)
1146 {
1147 # make room, remove the new object from both map and fsdata
1148 $tm->retract($newo->[1]);
1149 # it is highly unlikely that somebody managed to cook up an assoc reifier for this
1150 # oc/name assertion but BSTS
1151 for my $t (grep($_->[TM->ADDRESS] eq $newo->[1],($tm->toplets)))
1152 {
1153 return undef if ($self->tm_unlink("/$td/".$self->unbase($t->[TM->LID])."/="));
1154 }
1155 delete $newparent->{$localname};
1156 }
1157  
1158 # update name/oc in the map and rename it in fsdata
1159 my $ass=$tm->retrieve($oo->[1]);
1160 $scope||="us";
1161 $type||=($ass->[TM->KIND] eq TM->OCC?"occurrence":"name");
1162  
1163 $ass->[TM->SCOPE]=$self->{fsdata}->{$td}->{$scope}->{"."}->[1];
1164 $ass->[TM->TYPE]=$self->{fsdata}->{$td}->{$type}->{"."}->[1];
1165  
1166 $parent->{$localname}=$oo;
1167 delete $parent->{basename($old)};
1168 $self->scandir($parent);
1169 $self->{dirty}->{$oo}=0;
1170  
1171 return 0;
1172 }
1173 else # dirs
1174 {
1175 my @oldp=reverse(split(m!/!,$old)); pop @oldp;
1176 my @newp=reverse(split(m!/!,$new)); pop @newp;
1177 return -EFAULT() if (@oldp!=2 || @newp!=2
1178 || $oldp[-1] ne $td || $newp[-1] ne $td);
1179 return -EPERM() if (!validname($newp[0]));
1180 return ($self->remove_rename($oldp[0],$newp[0])?0:-EBUSY());
1181 }
1182 return -EPERM();
1183 }
1184  
1185 sub tm_mkdir
1186 {
1187 my ($self,$file,$mode)=@_;
1188 Carp::croak("invalid object argument\n") if (!ref($self) || !$self->isa(__PACKAGE__));
1189 my $tm=$self->{tm};
1190  
1191 $self->debug("mkdir $file mode $mode");
1192  
1193 my ($found)=$self->lookup($file);
1194 return -EEXIST() if ($found);
1195  
1196 # where are we?
1197 my ($n,@rest)=reverse(split(m!/!,$file));
1198 pop @rest;
1199  
1200  
1201 # in topics list: fine, make said topic
1202 if (@rest==1 && $rest[0] eq $td)
1203 {
1204 return -EFAULT() if (!validname($n));
1205 $self->maketopic($n);
1206 return 0;
1207 }
1208 # new assoc-type dir
1209 elsif (@rest==1 && $rest[-1] eq $ad)
1210 {
1211 if (!$self->{fsdata}->{$td}->{$n})
1212 {
1213 return -ENOENT() if (!$self->{autocreate} || !validname($n));
1214 $self->maketopic($n);
1215 }
1216  
1217 $self->{fsdata}->{$ad}->{$n}=
1218 {"."=>[undef,$self->{fsdata}->{$td}->{$n}->{"."}->[1],undef]};
1219 $self->scandir($self->{fsdata}->{$ad}->{$n});
1220 $self->scandir($self->{fsdata}->{$ad});
1221 return 0;
1222 }
1223 # new assoc tagdir
1224 elsif (@rest==2 && $rest[-1] eq $ad)
1225 {
1226 my $type=$rest[0];
1227 if ($type && $self->{fsdata}->{$ad}->{$type})
1228 {
1229 return -EFAULT() if ($n!~/^\d+$/);
1230
1231 # make new semiblank assertion
1232 # kind, type-lid, no roles or players
1233 my ($okass)=$tm->assert(Assertion->new(kind=>TM->ASSOC,
1234 type=>$self->{fsdata}->{$td}->{$type}->{"."}->[1]));
1235 $self->mkasshier($n,1,$okass);
1236 return 0;
1237 }
1238 return -ENOENT();
1239 }
1240 # new role dir, /a/type/tag/new role
1241 elsif (@rest==3 && $rest[-1] eq $ad)
1242 {
1243 my ($tag,$type)=@rest[0..1];
1244 if ($type && $self->{fsdata}->{$ad}->{$type} && defined($tag)
1245 && $self->{fsdata}->{$ad}->{$type}->{$tag} && defined $n)
1246 {
1247 # roletopic exists?
1248 if (!$self->{fsdata}->{$td}->{$n})
1249 {
1250 return -ENOENT() if (!$self->{autocreate} || !validname($n)); # no autocreation
1251 $self->maketopic($n);
1252 }
1253 # create dummy role dir, assoc changes happen on player symlink
1254 $self->{fsdata}->{$ad}->{$type}->{$tag}->{$n}=
1255 {"."=>[undef,$self->{fsdata}->{$td}->{$n}->{"."}->[1],undef]};
1256 $self->scandir($self->{fsdata}->{$ad}->{$type}->{$tag}->{$n});
1257 $self->scandir($self->{fsdata}->{$ad}->{$type}->{$tag});
1258 return 0;
1259 }
1260 return -ENOENT();
1261 }
1262 return -EPERM(); # not a spot where dirs can be made, sorry.
1263 }
1264  
1265 # newpath is given rel to our moutpoint and cleaned, oldpath is verbatim
1266 sub tm_symlink
1267 {
1268 my ($self,$target,$anchor)=@_;
1269 Carp::croak("invalid object argument\n") if (!ref($self) || !$self->isa(__PACKAGE__));
1270 my $tm=$self->{tm};
1271  
1272 $self->debug("symlink from $anchor to $target");
1273 my ($aname,@arest)=reverse(split(m!/!,$anchor)); pop @arest;
1274  
1275 my $mountpt=$self->{mountpoint};
1276 # first check/mangle the target, which is given verbatim...
1277 my $cleantarget=cleanpath(File::Spec->rel2abs($target,$mountpt.dirname($anchor)));
1278 my $isuri=($target=~m!^[a-zA-Z]+:.+$!i);
1279  
1280 return -EFAULT() if (!$isuri && $cleantarget!~/^$mountpt/); # links can't point outside our area...
1281  
1282 my $localized="/".File::Spec->abs2rel($cleantarget,$mountpt);
1283 my ($targetfound,$tobj)=$self->lookup($localized);
1284 my ($tname,@trest)=reverse(split(m!/!,$localized)); pop @trest;
1285  
1286 return -ENOENT() if (!$isuri && !$targetfound); # the link may point to topic/assoc or an uri only
1287  
1288 # topic-symlinks must have matching names for source and target
1289 return -EPERM() if ($aname ne "=" && $tname ne $aname);
1290  
1291 # the anchor mustn't pre-exist
1292 return -EEXIST() if (($self->lookup($anchor))[0]);
1293  
1294 # depending on where the anchor is, different targets are allowed
1295 # anchor =, sloc: only url or local topic or local assoc
1296 if ($aname eq "=" && @arest==2 && $arest[1] eq $td)
1297 {
1298 my $tnode=$self->{fsdata}->{$td}->{$arest[0]};
1299 return -ENOENT() if (!$tnode);
1300 my $lid=$tnode->{"."}->[1];
1301  
1302 # subject address can be uri, topic or assoc
1303 if (!$isuri)
1304 {
1305 # is the target an assoc dir or a topic dir?
1306 return -ENOENT() if (($trest[-1] eq $td && @trest!=1)
1307 || ($trest[-1] eq $ad && @trest!=2));
1308 $target=$tobj->{"."}->[1]; # actual topic/assoc lid
1309 }
1310  
1311 my $toplet=$tm->toplet($lid);
1312 $toplet->[TM->ADDRESS]=$target;
1313 $tnode->{"="}=$self->makefilenode($target,$lid);
1314 $self->fixuptopic($tnode);
1315 $self->{dirty}->{$tnode}=0;
1316 $self->debug("postlink: ".Dumper($tnode,$toplet));
1317 return 0;
1318 }
1319 # instance/isa: can only point to another topic
1320 elsif ($arest[-1] eq $td && @arest==3 && grep($arest[0] eq $_,qw(isa instance)))
1321 {
1322 # must point to topic, not to a url and not an assoc either
1323 return -EPERM() if ($isuri || $trest[-1] ne $td);
1324  
1325 my $atnode=$self->{fsdata}->{$td}->{$arest[1]}; # anchor topic
1326 my $alid=$atnode->{"."}->[1];
1327  
1328 my @players=($alid,$tobj->{"."}->[1]); # where we attach to, and where we point to
1329  
1330 my ($nass)=$tm->assert(Assertion->new(kind=>TM->ASSOC,
1331 type=>"isa",
1332 scope=>"us",
1333 roles=>[qw(class instance)],
1334 players=>[$arest[0] eq "isa"?reverse(@players):@players]));
1335 $self->mkasshier(undef,1,$nass); # fstag names n/a
1336 $self->fixuptopic($atnode);
1337 return 0;
1338 }
1339 # assoc player: can only point to another topic
1340 elsif ($arest[-1] eq $ad && @arest==4)
1341 {
1342 my ($aplayer,$arole,$atag,$atype)=($aname,@arest);
1343  
1344 return -EPERM() if ($isuri || $trest[-1] ne $td);
1345
1346 # everything up to role must exist
1347 return -ENOENT() if (!$self->{fsdata}->{$ad}->{$atype}
1348 || !$self->{fsdata}->{$ad}->{$atype}->{$atag}
1349 || !$self->{fsdata}->{$ad}->{$atype}->{$atag}->{$arole});
1350  
1351 my $a=$tm->retrieve($self->{fsdata}->{$ad}->{$atype}->{$atag}->{"."}->[1]);
1352  
1353 # attach this player/role combo to this existing assertion
1354 # (may be blankish one created earlier)
1355 push @{$a->[TM->ROLES]},$self->{fsdata}->{$td}->{$arole}->{"."}->[1];
1356 push @{$a->[TM->PLAYERS]},$tobj->{"."}->[1];
1357 $self->mkasshier($atag,1,$a);
1358 return 0;
1359 }
1360 return -EPERM(); # can't do this, sorry.
1361 }
1362  
1363 sub tm_unlink
1364 {
1365 my ($self,$path)=@_;
1366 Carp::croak("invalid object argument\n") if (!ref($self) || !$self->isa(__PACKAGE__));
1367 my $tm=$self->{tm};
1368  
1369 $self->debug("unlink $path");
1370 my ($found,$obj,$parent)=$self->lookup($path);
1371 return -ENOENT() if (!$found);
1372 return -EISDIR() if (ref($obj) ne "ARRAY"); # not a leaf file
1373  
1374 my ($localname,@rest)=reverse(split(m!/!,$path));
1375 pop @rest; # path is absolute, no need to keep the undef tail
1376  
1377 if ($rest[-1] eq $td)
1378 {
1379 if ($localname eq "=")
1380 {
1381 my $toplet=$tm->toplet($obj->[1]);
1382 delete $toplet->[TM->ADDRESS];
1383 }
1384 elsif ($rest[0] =~ /^(oc|name)$/)
1385 {
1386 $tm->retract($obj->[1]);
1387 delete $self->{alid2path}->{$obj->[1]};
1388 }
1389 elsif ($rest[0] =~ /^(isa|instance)$/)
1390 {
1391 # need to remove both this link as well as the opposite one...
1392 my $othertype=$rest[0] eq "isa"?"instance":"isa";
1393 my $tn=$rest[1];
1394 delete $self->{fsdata}->{$td}->{$localname}->{$othertype}->{$tn};
1395 $self->fixuptopic($self->{fsdata}->{$td}->{$localname});
1396
1397 delete $self->{alid2path}->{$obj->[1]};
1398 $tm->retract($obj->[1]);
1399 # but dirty-marking this side is enough
1400 }
1401 else
1402 {
1403 # fixme: lowprio: better to allow dud removals for rm -rf or not?
1404 # $self->debug("not allowed to remove: $path");
1405 # return -EPERM();
1406 $self->debug("dummy removal of $path");
1407 return 0;
1408 }
1409  
1410 # common deletion code: cleanup the fs-part of things
1411 delete $parent->{$localname};
1412 $self->fixuptopic($parent);
1413 $self->{dirty}->{$parent}=0;
1414 return 0;
1415 }
1416 elsif ($rest[-1] eq $ad)
1417 {
1418 # fixme lowprio: better to allow dud removals for rm -rf or not?
1419 # return -EPERM() if ($localname eq ".type");
1420 if ($localname eq ".type")
1421 {
1422 $self->debug("dummy removal of $path");
1423 return 0;
1424 }
1425
1426 my $aid=$self->{fsdata}->{$ad}->{$rest[2]}->{$rest[1]}->{"."}->[1];
1427 my $a=$tm->retrieve($aid);
1428 Carp::croak("internal inconsistency: no assoc for $aid") if (!$a);
1429  
1430 # keep other roles and players intact
1431 my (@np,@nr,$pn);
1432 $pn=$self->{fsdata}->{$td}->{$localname}->{"."}->[1];
1433 for my $i (0..$#{$a->[TM->PLAYERS]})
1434 {
1435 if ($a->[TM->PLAYERS]->[$i] eq $pn)
1436 {
1437 # get rid of involvement links
1438 my $pnode=$self->{fsdata}->{$td}->{$localname};
1439 map { delete $pnode->{"involved"}->{$_}
1440 if (/^\d:player$/ && $pnode->{"involved"}->{$_}->[1] eq $aid); }
1441 (keys %{$pnode->{"involved"}});
1442 $self->scandir($pnode->{"involved"});
1443 next;
1444 }
1445 unshift @np,$a->[TM->PLAYERS]->[$i];
1446 unshift @nr,$a->[TM->ROLES]->[$i];
1447 }
1448 $a->[TM->PLAYERS]=\@np;
1449 $a->[TM->ROLES]=\@nr;
1450
1451 delete $parent->{$localname};
1452 $self->scandir($parent);
1453 $self->{dirty}->{$parent}=0;
1454 return 0;
1455 }
1456 return -EPERM();
1457 }
1458  
1459 sub tm_rmdir
1460 {
1461 my ($self,$path)=@_;
1462 Carp::croak("invalid object argument\n") if (!ref($self) || !$self->isa(__PACKAGE__));
1463 my $tm=$self->{tm};
1464  
1465 $self->debug("rmdir $path");
1466 my ($found,$obj,$parent)=$self->lookup($path);
1467 return -ENOENT() if (!$found);
1468 return -EISDIR() if (ref($obj) ne "HASH"); # not a directory
1469  
1470 my ($localname,@rest)=reverse(split(m!/!,$path));
1471 pop @rest; # path is absolute, no need to keep the undef tail
1472  
1473 if ($rest[-1] eq $ad)
1474 {
1475 my $inv;
1476 # roledir? can be removed if empty
1477 if (@rest == 3)
1478 {
1479 return -ENOTEMPTY() if (keys(%{$obj})!=1); # the . entry
1480 $inv="role";
1481 }
1482 # tagdir? can be removed if empty except for .type
1483 elsif (@rest==2)
1484 {
1485 return -ENOTEMPTY() if (keys(%{$obj})!=2); # ., .type
1486 # removing a tagdir means removing the relevant assoc itself
1487 my $a=$obj->{'.'}->[1];
1488 $tm->retract($a);
1489 # now check if something was reifying this assoc and clean that up
1490 for my $t (grep($_->[TM->ADDRESS] eq $a,($tm->toplets)))
1491 {
1492 return -EFAULT() if ($self->tm_unlink("/$td/".$self->unbase($t->[TM->LID])."/="));
1493 }
1494 $self->{dirty}->{$a}=0; # key is not relevant
1495 $inv="type";
1496 }
1497 # typedir
1498 elsif (@rest==1)
1499 {
1500 return -ENOTEMPTY() if (keys(%{$obj})!=1); # the . entry
1501 }
1502 else
1503 {
1504 $self->debug("dud rmdir call, path $path");
1505 return -EPERM(); # something bad happened
1506 }
1507
1508 # get rid of involvements, not for typedir-removal: involvements apply
1509 # only to specific assocs
1510 if ($inv)
1511 {
1512 my ($compare,$node);
1513 if ($inv eq "type")
1514 {
1515 $node=$self->{fsdata}->{$td}->{$self->lid2name($parent->{"."}->[1])}; # localname is assoc tag,
1516 # parent (or .type child) has the type lid
1517 $compare=$obj->{"."}->[1];
1518 }
1519 else
1520 {
1521 $node=$self->{fsdata}->{$td}->{$localname}; # localname is role, which is the topic we look for
1522 $compare=$parent->{"."}->[1];
1523 }
1524 &Carp::croak("internal inconsistency: assoc has no type name ".Dumper($obj))
1525 if (ref($node) ne "HASH");
1526  
1527 map { delete $node->{"involved"}->{$_}
1528 if (/^\d:$inv$/ && $node->{"involved"}->{$_}->[1] eq $compare); }
1529 (keys %{$node->{"involved"}});
1530 $self->scandir($node->{"involved"});
1531 }
1532 # common code: nuke the fs object, rescan parent dir
1533 delete $parent->{$localname};
1534 $self->scandir($parent);
1535 return 0;
1536 }
1537 elsif ($rest[-1] eq $td)
1538 {
1539 # fixme: lowprio: should i allow a dummy removal of the aspect dirs and files?
1540 # that way, one could safely rm -rf and a stray rmdir would
1541 # only topics< themselves are removable, none of their aspect-dirs
1542 if (@rest eq 2 && grep($localname eq $_,qw(instance isa name oc involved)))
1543 {
1544 $self->debug("dummy rmdir of $path");
1545 return 0;
1546 }
1547 return -EPERM() if (@rest!=1);
1548
1549 return -EBUSY() if (!$self->remove_rename($localname,undef));
1550 return 0;
1551 }
1552 return -EPERM();
1553 }
1554  
1555 # for utime, chmod, chown and other, nonimplemented but commonly used functions
1556 sub tm_dummy
1557 {
1558 my ($self)=@_;
1559 Carp::croak("invalid object argument\n") if (!ref($self) || !$self->isa(__PACKAGE__));
1560  
1561 $self->debug("dummy called with args ".Dumper(\@_)."\n");
1562 return 0;
1563 }
1564  
1565 =pod
1566  
1567 =head1 LIMITATIONS
1568  
1569 =head2 Filesystem Attributes
1570  
1571 File ownership is not modelled at all: all files and dirs belong to uid 0, root.
1572  
1573 Permissions are not modelled fully: in read-only mode all files are mode 0444 and
1574 dirs 0555. In read-write mode all files are mode 0644 and dirs 0755.
1575  
1576 Mode or ownership changes are not supported.
1577  
1578 =head2 Write Support
1579  
1580 Until the filesystem is unmounted any modifications are kept in memory only.
1581  
1582 Overwriting files is only allowed for names, occurrences and subject indicators.
1583 Attempts to write to other files will result in EPERM errors.
1584  
1585 Creating new files or renaming them is only allowed for names and occurrences.
1586 Attempting others will result in an EPERM. Renaming works for names or occurrences
1587 if they stay with the same topic, or for topics. Nothing else can be renamed and
1588 EFAULT errors will result if you try.
1589  
1590 Renaming of topics is possible (and all involved others are updated accordingly).
1591 Neither fixed topic characteristic dirs (e.g. oc, name, isa) nor
1592 association instance dirs can be renamed.
1593  
1594 (Re)Naming something with an unacceptable name will cause ENOENT errors.
1595  
1596 Symbolic links cannot point outside the current map's filesystem,
1597 with the sole exception being a subject locator URI symlink.
1598  
1599 Removing a topic is not possible if it is used as an association type
1600 or association role: EBUSY will be the result if you try. To remove an
1601 association type topic first all association instances must be removed.
1602  
1603 Removing of a topic clears up all involvements: if used as a scope the scope
1604 will be changed to universal, if used as a type the type will be cleared, if
1605 used as role player then this player vanishes.
1606  
1607 =head1 SEE ALSO
1608  
1609 L<TM(3)>, L<tmfs(1)>
1610  
1611 =head1 AUTHOR
1612  
1613 Alexander Zangerl, <alphazulu@cpan.org>
1614  
1615 =head1 COPYRIGHT AND LICENSE
1616  
1617 Copyright 2009 Alexander Zangerl
1618  
1619 This library is free software; you can redistribute it and/or modify it under the same terms as Perl
1620 itself.
1621  
1622 =cut
1623  
1624  
1625 1;
1626  
1627  
1628