--- deliantra/server/lib/cf.pm 2006/08/27 17:59:26 1.49 +++ deliantra/server/lib/cf.pm 2006/10/01 11:41:37 1.72 @@ -7,74 +7,68 @@ use Safe; use Safe::Hole; +use YAML::Syck (); use Time::HiRes; use Event; $Event::Eval = 1; # no idea why this is required, but it is +# work around bug in YAML::Syck - bad news for perl6, will it be as broken wrt. unicode? +$YAML::Syck::ImplicitUnicode = 1; + use strict; -_reload_1; +_init_vars; our %COMMAND = (); our @EVENT; -our %PROP_TYPE; -our %PROP_IDX; our $LIBDIR = maps_directory "perl"; our $TICK = MAX_TIME * 1e-6; our $TICK_WATCHER; our $NEXT_TICK; -BEGIN { - *CORE::GLOBAL::warn = sub { - my $msg = join "", @_; - $msg .= "\n" - unless $msg =~ /\n$/; +our %CFG; - print STDERR "cfperl: $msg"; - LOG llevError, "cfperl: $msg"; - }; -} +############################################################################# -my %ignore_set = (MAP_PROP_PATH => 1); # I hate the plug-in api. Deeply! +=head2 GLOBAL VARIABLES -# generate property mutators -sub prop_gen { - my ($prefix, $class) = @_; +=over 4 - no strict 'refs'; +=item $cf::LIBDIR - for my $prop (keys %PROP_TYPE) { - $prop =~ /^\Q$prefix\E_(.*$)/ or next; - my $sub = lc $1; +The perl library directory, where extensions and cf-specific modules can +be found. It will be added to C<@INC> automatically. - my $type = $PROP_TYPE{$prop}; - my $idx = $PROP_IDX {$prop}; +=item $cf::TICK - *{"$class\::get_$sub"} = *{"$class\::$sub"} = sub { - $_[0]->get_property ($type, $idx) - }; +The interval between server ticks, in seconds. - *{"$class\::set_$sub"} = sub { - $_[0]->set_property ($type, $idx, $_[1]); - } unless $ignore_set{$prop}; - } -} +=item %cf::CFG -# auto-generate most of the API +Configuration for the server, loaded from C, or +from wherever your confdir points to. -prop_gen OBJECT_PROP => "cf::object"; -# CFAPI_OBJECT_ANIMATION? -prop_gen PLAYER_PROP => "cf::object::player"; +=back + +=cut + +BEGIN { + *CORE::GLOBAL::warn = sub { + my $msg = join "", @_; + $msg .= "\n" + unless $msg =~ /\n$/; -prop_gen MAP_PROP => "cf::map"; -prop_gen ARCH_PROP => "cf::arch"; + print STDERR "cfperl: $msg"; + LOG llevError, "cfperl: $msg"; + }; +} @safe::cf::object::player::ISA = @cf::object::player::ISA = 'cf::object'; # we bless all objects into (empty) derived classes to force a method lookup # within the Safe compartment. -for my $pkg (qw(cf::object cf::object::player cf::player cf::map cf::party cf::region cf::arch)) { +for my $pkg (qw(cf::object cf::object::player cf::player cf::map cf::party cf::region cf::arch cf::living)) { no strict 'refs'; @{"safe::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg; } @@ -89,35 +83,71 @@ my %command; my %extcmd; -############################################################################# -# utility functions +=head2 UTILITY FUNCTIONS + +=over 4 + +=cut use JSON::Syck (); # TODO# replace by JSON::PC once working +=item $ref = cf::from_json $json + +Converts a JSON string into the corresponding perl data structure. + +=cut + sub from_json($) { $JSON::Syck::ImplicitUnicode = 1; # work around JSON::Syck bugs JSON::Syck::Load $_[0] } +=item $json = cf::to_json $ref + +Converts a perl data structure into its JSON representation. + +=cut + sub to_json($) { $JSON::Syck::ImplicitUnicode = 0; # work around JSON::Syck bugs JSON::Syck::Dump $_[0] } +=back + +=cut + ############################################################################# -# "new" plug-in system + +=head2 EVENTS AND OBJECT ATTACHMENTS + +=over 4 =item $object->attach ($attachment, key => $value...) -Attach a pre-registered attachment to an object. +=item $object->detach ($attachment) + +Attach/detach a pre-registered attachment to an object. =item $player->attach ($attachment, key => $value...) -Attach a pre-registered attachment to a player. +=item $player->detach ($attachment) + +Attach/detach a pre-registered attachment to a player. + +=item $map->attach ($attachment, key => $value...) + +=item $map->detach ($attachment) -=item $map->attach ($attachment, key => $value...) # not yet persistent +Attach/detach a pre-registered attachment to a map. -Attach a pre-registered attachment to a map. +=item $bool = $object->attached ($name) + +=item $bool = $player->attached ($name) + +=item $bool = $map->attached ($name) + +Checks wether the named attachment is currently attached to the object. =item cf::attach_global ... @@ -176,6 +206,19 @@ =item cf:register_attachment $name, ... +Register an attachment by name through which objects can refer to this +attachment. + +=item cf:register_player_attachment $name, ... + +Register an attachment by name through which players can refer to this +attachment. + +=item cf:register_map_attachment $name, ... + +Register an attachment by name through which maps can refer to this +attachment. + =cut # the following variables are defined in .xs and must not be re-created @@ -249,6 +292,8 @@ sub _attach_attachment { my ($obj, $name, %arg) = @_; + return if exists $obj->{_attachment}{$name}; + my $res; if (my $attach = $attachment{$name}) { @@ -264,29 +309,37 @@ warn "object uses attachment '$name' that is not available, postponing.\n"; } - push @{$obj->{_attachment}}, $name; + $obj->{_attachment}{$name} = undef; $res->{attachment} = $name; $res } -sub cf::object::attach { +*cf::object::attach = +*cf::player::attach = +*cf::map::attach = sub { my ($obj, $name, %arg) = @_; _attach_attachment $obj, $name, %arg; -} +}; -sub cf::player::attach { - my ($obj, $name, %arg) = @_; +# all those should be optimised +*cf::object::detach = +*cf::player::detach = +*cf::map::detach = sub { + my ($obj, $name) = @_; - _attach_attachment KLASS_PLAYER, $obj, $name, %arg; -} + delete $obj->{_attachment}{$name}; + reattach ($obj); +}; -sub cf::map::attach { - my ($obj, $name, %arg) = @_; +*cf::object::attached = +*cf::player::attached = +*cf::map::attached = sub { + my ($obj, $name) = @_; - _attach_attachment KLASS_MAP, $obj, $name, %arg; -} + exists $obj->{_attachment}{$name} +}; sub attach_global { _attach @CB_GLOBAL, KLASS_GLOBAL, @_ @@ -317,6 +370,18 @@ $attachment{$name} = [[KLASS_OBJECT, @_]]; } +sub register_player_attachment { + my $name = shift; + + $attachment{$name} = [[KLASS_PLAYER, @_]]; +} + +sub register_map_attachment { + my $name = shift; + + $attachment{$name} = [[KLASS_MAP, @_]]; +} + our $override; our @invoke_results = (); # referenced from .xs code. TODO: play tricks with reify and mortals? @@ -338,7 +403,7 @@ if ($@) { warn "$@"; - warn "... while processing $EVENT[$event][0] event, skipping processing altogether.\n"; + warn "... while processing $EVENT[$event][0](@_) event, skipping processing altogether.\n"; override; } @@ -348,6 +413,46 @@ 0 } +=item $bool = cf::invoke EVENT_GLOBAL_XXX, ... + +=item $bool = $object->invoke (EVENT_OBJECT_XXX, ...) + +=item $bool = $player->invoke (EVENT_PLAYER_XXX, ...) + +=item $bool = $map->invoke (EVENT_MAP_XXX, ...) + +Generate a global/object/player/map-specific event with the given arguments. + +This API is preliminary (most likely, the EVENT_KLASS_xxx prefix will be +removed in future versions), and there is no public API to access override +results (if you must, access C<@cf::invoke_results> directly). + +=back + +=cut + +############################################################################# + +=head2 METHODS VALID FOR ALL CORE OBJECTS + +=over 4 + +=item $object->valid, $player->valid, $map->valid + +Just because you have a perl object does not mean that the corresponding +C-level object still exists. If you try to access an object that has no +valid C counterpart anymore you get an exception at runtime. This method +can be used to test for existence of the C object part without causing an +exception. + +=back + +=cut + +*cf::object::valid = +*cf::player::valid = +*cf::map::valid = \&cf::_valid; + ############################################################################# # object support @@ -370,9 +475,9 @@ @$registry = (); - delete $obj->{_attachment} unless @{ $obj->{_attachment} || [] }; + delete $obj->{_attachment} unless scalar keys %{ $obj->{_attachment} || {} }; - for my $name (@{ $obj->{_attachment} || [] }) { + for my $name (keys %{ $obj->{_attachment} || {} }) { if (my $attach = $attachment{$name}) { for (@$attach) { my ($klass, @attach) = @$_; @@ -385,28 +490,53 @@ } sub object_freezer_save { - my ($filename, $objs) = @_; + my ($filename, $rdata, $objs) = @_; - $filename .= ".pst"; + if (length $$rdata) { + warn sprintf "saving %s (%d,%d)\n", + $filename, length $$rdata, scalar @$objs; + + if (open my $fh, ">:raw", "$filename~") { + chmod SAVE_MODE, $fh; + syswrite $fh, $$rdata; + close $fh; + + if (@$objs && open my $fh, ">:raw", "$filename.pst~") { + chmod SAVE_MODE, $fh; + syswrite $fh, Storable::nfreeze { version => 1, objs => $objs }; + close $fh; + rename "$filename.pst~", "$filename.pst"; + } else { + unlink "$filename.pst"; + } - if (@$objs) { - open my $fh, ">:raw", "$filename~"; - chmod $fh, SAVE_MODE; - syswrite $fh, Storable::nfreeze { version => 1, objs => $objs }; - close $fh; - rename "$filename~", $filename; + rename "$filename~", $filename; + } else { + warn "FATAL: $filename~: $!\n"; + } } else { unlink $filename; + unlink "$filename.pst"; } } sub object_thawer_load { my ($filename) = @_; - open my $fh, "<:raw:perlio", "$filename.pst" - or return; + local $/; + + my $av; - eval { local $/; (Storable::thaw <$fh>)->{objs} } + #TODO: use sysread etc. + if (open my $data, "<:raw:perlio", $filename) { + $data = <$data>; + if (open my $pst, "<:raw:perlio", "$filename.pst") { + $av = eval { (Storable::thaw <$pst>)->{objs} }; + } + return ($data, $av); + } + + () } attach_to_objects @@ -418,7 +548,7 @@ %$dst = %$src; - $dst->{_attachment} = [@{ $src->{_attachment} }] + %{$dst->{_attachment}} = %{$src->{_attachment}} if exists $src->{_attachment}; }, ; @@ -563,79 +693,6 @@ } } -sub _perl_reload(&) { - my ($msg) = @_; - - $msg->("reloading..."); - - eval { - # 1. cancel all watchers - $_->cancel for Event::all_watchers; - - # 2. unload all extensions - for (@exts) { - $msg->("unloading <$_>"); - unload_extension $_; - } - - # 3. unload all modules loaded from $LIBDIR - while (my ($k, $v) = each %INC) { - next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/; - - $msg->("removing <$k>"); - delete $INC{$k}; - - $k =~ s/\.pm$//; - $k =~ s/\//::/g; - - if (my $cb = $k->can ("unload_module")) { - $cb->(); - } - - Symbol::delete_package $k; - } - - # 4. get rid of safe::, as good as possible - Symbol::delete_package "safe::$_" - for qw(cf::object cf::object::player cf::player cf::map cf::party cf::region); - - # 5. remove register_script_function callbacks - # TODO - - # 6. unload cf.pm "a bit" - delete $INC{"cf.pm"}; - - # don't, removes xs symbols, too, - # and global variables created in xs - #Symbol::delete_package __PACKAGE__; - - # 7. reload cf.pm - $msg->("reloading cf.pm"); - require cf; - }; - $msg->($@) if $@; - - $msg->("reloaded"); -}; - -sub perl_reload() { - _perl_reload { - warn $_[0]; - print "$_[0]\n"; - }; -} - -register_command "perl-reload", 0, sub { - my ($who, $arg) = @_; - - if ($who->flag (FLAG_WIZ)) { - _perl_reload { - warn $_[0]; - $who->message ($_[0]); - }; - } -}; - ############################################################################# # extcmd framework, basically convert ext # into pkg::->on_extcmd_arg1 (...) while shortcutting a few @@ -669,28 +726,9 @@ my $path = $map->tmpname; defined $path or return; - unlink "$path.cfperl"; unlink "$path.pst"; }; -*cf::mapsupport::on_swapin = -*cf::mapsupport::on_load = sub { - my ($map) = @_; - - my $path = $map->tmpname; - $path = $map->path unless defined $path; - - open my $fh, "<:raw", "$path.cfperl" - or return; # no perl data - - my $data = Storable::thaw do { local $/; <$fh> }; - - $data->{version} <= 1 - or return; # too new - - $map->_set_obs ($data->{obs}); -}; - attach_to_maps prio => -10000, package => cf::mapsupport::; ############################################################################# @@ -700,6 +738,7 @@ @_, map all_objects ($_->inv), @_ } +# TODO: compatibility cruft, remove when no longer needed attach_to_players on_load => sub { my ($pl, $path) = @_; @@ -715,7 +754,12 @@ ; ############################################################################# -# core extensions - in perl + +=head2 CORE EXTENSIONS + +Functions and methods that extend core crossfire objects. + +=over 4 =item cf::player::exists $login @@ -765,8 +809,21 @@ $self->send ("ext " . to_json \%msg); } +=back + +=cut + ############################################################################# -# map scripting support + +=head2 SAFE SCRIPTING + +Functions that provide a safe environment to compile and execute +snippets of perl code without them endangering the safety of the server +itself. Looping constructs, I/O operators and other built-in functionality +is not available in the safe scripting environment, and the number of +functions and methods that cna be called is greatly reduced. + +=cut our $safe = new Safe "safe"; our $safe_hole = new Safe::Hole; @@ -777,6 +834,16 @@ # here we export the classes and methods available to script code +=pod + +The following fucntions and emthods are available within a safe environment: + + cf::object contr pay_amount pay_player + cf::object::player player + cf::player peaceful + +=cut + for ( ["cf::object" => qw(contr pay_amount pay_player)], ["cf::object::player" => qw(player)], @@ -788,6 +855,18 @@ for @funs; } +=over 4 + +=item @retval = safe_eval $code, [var => value, ...] + +Compiled and executes the given perl code snippet. additional var/value +pairs result in temporary local (my) scalar variables of the given name +that are available in the code snippet. Example: + + my $five = safe_eval '$first + $second', first => 1, second => 4; + +=cut + sub safe_eval($;@) { my ($code, %vars) = @_; @@ -819,6 +898,21 @@ wantarray ? @res : $res[0] } +=item cf::register_script_function $function => $cb + +Register a function that can be called from within map/npc scripts. The +function should be reasonably secure and should be put into a package name +like the extension. + +Example: register a function that gets called whenever a map script calls +C, as used by the C extension. + + cf::register_script_function "rent::overview" => sub { + ... + }; + +=cut + sub register_script_function { my ($fun, $cb) = @_; @@ -826,22 +920,228 @@ *{"safe::$fun"} = $safe_hole->wrap ($cb); } +=back + +=cut + +############################################################################# + +=head2 EXTENSION DATABASE SUPPORT + +Crossfire maintains a very simple database for extension use. It can +currently store anything that can be serialised using Storable, which +excludes objects. + +The parameter C<$family> should best start with the name of the extension +using it, it should be unique. + +=over 4 + +=item $hashref = cf::db_get $family + +Return a hashref for use by the extension C<$family>, which can be +modified. After modifications, you have to call C or +C. + +=item $value = cf::db_get $family => $key + +Returns a single value from the database + +=item cf::db_put $family => $hashref + +Stores the given family hashref into the database. Updates are delayed, if +you want the data to be synced to disk immediately, use C. + +=item cf::db_put $family => $key => $value + +Stores the given C<$value> in the family hash. Updates are delayed, if you +want the data to be synced to disk immediately, use C. + +=item cf::db_dirty + +Marks the database as dirty, to be updated at a later time. + +=item cf::db_sync + +Immediately write the database to disk I. + +=cut + +{ + my $db; + my $path = cf::localdir . "/database.pst"; + + sub db_load() { + warn "loading database $path\n";#d# remove later + $db = stat $path ? Storable::retrieve $path : { }; + } + + my $pid; + + sub db_save() { + warn "saving database $path\n";#d# remove later + waitpid $pid, 0 if $pid; + if (0 == ($pid = fork)) { + $db->{_meta}{version} = 1; + Storable::nstore $db, "$path~"; + rename "$path~", $path; + cf::_exit 0 if defined $pid; + } + } + + my $dirty; + + sub db_sync() { + db_save if $dirty; + undef $dirty; + } + + my $idle = Event->idle (min => $TICK * 2.8, max => 10, repeat => 0, cb => sub { + db_sync; + }); + + sub db_dirty() { + $dirty = 1; + $idle->start; + } + + sub db_get($;$) { + @_ >= 2 + ? $db->{$_[0]}{$_[1]} + : ($db->{$_[0]} ||= { }) + } + + sub db_put($$;$) { + if (@_ >= 3) { + $db->{$_[0]}{$_[1]} = $_[2]; + } else { + $db->{$_[0]} = $_[1]; + } + db_dirty; + } + + attach_global + prio => 10000, + on_cleanup => sub { + db_sync; + }, + ; +} + ############################################################################# # the server's main() +sub load_cfg { + open my $fh, "<:utf8", cf::confdir . "/config" + or return; + + local $/; + *CFG = YAML::Syck::Load <$fh>; + + use Data::Dumper; warn Dumper \%CFG; +} + sub main { + load_cfg; + db_load; + load_extensions; Event::loop; } ############################################################################# # initialisation +sub _perl_reload(&) { + my ($msg) = @_; + + $msg->("reloading..."); + + eval { + # cancel all watchers + $_->cancel for Event::all_watchers; + + # unload all extensions + for (@exts) { + $msg->("unloading <$_>"); + unload_extension $_; + } + + # unload all modules loaded from $LIBDIR + while (my ($k, $v) = each %INC) { + next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/; + + $msg->("removing <$k>"); + delete $INC{$k}; + + $k =~ s/\.pm$//; + $k =~ s/\//::/g; + + if (my $cb = $k->can ("unload_module")) { + $cb->(); + } + + Symbol::delete_package $k; + } + + # sync database to disk + cf::db_sync; + + # get rid of safe::, as good as possible + Symbol::delete_package "safe::$_" + for qw(cf::object cf::object::player cf::player cf::map cf::party cf::region); + + # remove register_script_function callbacks + # TODO + + # unload cf.pm "a bit" + delete $INC{"cf.pm"}; + + # don't, removes xs symbols, too, + # and global variables created in xs + #Symbol::delete_package __PACKAGE__; + + # reload cf.pm + $msg->("reloading cf.pm"); + require cf; + + # load database again + cf::db_load; + + # load extensions + $msg->("load extensions"); + cf::load_extensions; + + # reattach attachments to objects + $msg->("reattach"); + _global_reattach; + }; + $msg->($@) if $@; + + $msg->("reloaded"); +}; + +sub perl_reload() { + _perl_reload { + warn $_[0]; + print "$_[0]\n"; + }; +} + +register_command "perl-reload", 0, sub { + my ($who, $arg) = @_; + + if ($who->flag (FLAG_WIZ)) { + _perl_reload { + warn $_[0]; + $who->message ($_[0]); + }; + } +}; + register "", __PACKAGE__; unshift @INC, $LIBDIR; -load_extensions; - $TICK_WATCHER = Event->timer ( prio => 1, at => $NEXT_TICK || 1, @@ -859,7 +1159,5 @@ }, ); -_reload_2; - 1