ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/deliantra/server/lib/cf.pm
(Generate patch)

Comparing deliantra/server/lib/cf.pm (file contents):
Revision 1.28 by root, Sun Jul 30 17:42:14 2006 UTC vs.
Revision 1.71 by root, Sun Oct 1 10:59:30 2006 UTC

5use Storable; 5use Storable;
6use Opcode; 6use Opcode;
7use Safe; 7use Safe;
8use Safe::Hole; 8use Safe::Hole;
9 9
10use Time::HiRes;
10use Event; 11use Event;
11$Event::Eval = 1; # no idea why this is required, but it is 12$Event::Eval = 1; # no idea why this is required, but it is
12 13
13use strict; 14use strict;
14 15
16_init_vars;
17
15our %COMMAND; 18our %COMMAND = ();
16our @EVENT; 19our @EVENT;
17our %PROP_TYPE;
18our %PROP_IDX;
19our $LIBDIR = maps_directory "perl"; 20our $LIBDIR = maps_directory "perl";
20 21
22our $TICK = MAX_TIME * 1e-6;
23our $TICK_WATCHER;
24our $NEXT_TICK;
25
26our %CFG;
27
28#############################################################################
29
30=head2 GLOBAL VARIABLES
31
32=over 4
33
34=item $cf::LIBDIR
35
36The perl library directory, where extensions and cf-specific modules can
37be found. It will be added to C<@INC> automatically.
38
39=item $cf::TICK
40
41The interval between server ticks, in seconds.
42
43=item %cf::CFG
44
45Configuration for the server, loaded from C</etc/crossfire/config>, or
46from wherever your confdir points to.
47
48=back
49
50=cut
51
21BEGIN { 52BEGIN {
22 @EVENT = map lc, @EVENT;
23
24 *CORE::GLOBAL::warn = sub { 53 *CORE::GLOBAL::warn = sub {
25 my $msg = join "", @_; 54 my $msg = join "", @_;
26 $msg .= "\n" 55 $msg .= "\n"
27 unless $msg =~ /\n$/; 56 unless $msg =~ /\n$/;
28 57
29 print STDERR "cfperl: $msg"; 58 print STDERR "cfperl: $msg";
30 LOG llevError, "cfperl: $msg"; 59 LOG llevError, "cfperl: $msg";
31 }; 60 };
32} 61}
33 62
34my %ignore_set = (MAP_PROP_PATH => 1); # I hate the plug-in api. Deeply! 63@safe::cf::object::player::ISA = @cf::object::player::ISA = 'cf::object';
35 64
36# generate property mutators 65# we bless all objects into (empty) derived classes to force a method lookup
37sub prop_gen { 66# within the Safe compartment.
38 my ($prefix, $class) = @_; 67for my $pkg (qw(cf::object cf::object::player cf::player cf::map cf::party cf::region cf::arch cf::living)) {
39
40 no strict 'refs'; 68 no strict 'refs';
41
42 for my $prop (keys %PROP_TYPE) {
43 $prop =~ /^\Q$prefix\E_(.*$)/ or next;
44 my $sub = lc $1;
45
46 my $type = $PROP_TYPE{$prop};
47 my $idx = $PROP_IDX {$prop};
48
49 *{"$class\::get_$sub"} = *{"$class\::$sub"} = sub {
50 $_[0]->get_property ($type, $idx)
51 };
52
53 *{"$class\::set_$sub"} = sub {
54 $_[0]->set_property ($type, $idx, $_[1]);
55 } unless $ignore_set{$prop};
56 }
57}
58
59# auto-generate most of the API
60
61prop_gen OBJECT_PROP => "cf::object";
62# CFAPI_OBJECT_ANIMATION?
63prop_gen PLAYER_PROP => "cf::object::player";
64
65prop_gen MAP_PROP => "cf::map";
66prop_gen ARCH_PROP => "cf::arch";
67
68# guessed hierarchies
69
70@ext::cf::object::player::ISA = @cf::object::player::ISA = 'cf::object';
71@ext::cf::object::map::ISA = @cf::object::map::ISA = 'cf::object';
72
73# we bless all objects into derived classes to force a method lookup
74# within the Safe compartment.
75for my $pkg (qw(cf::object cf::object::map cf::object::player cf::player cf::map cf::party cf::region)) {
76 no strict 'refs';
77 @{"ext::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg; 69 @{"safe::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg;
78} 70}
79 71
80$Event::DIED = sub { 72$Event::DIED = sub {
81 warn "error in event callback: @_"; 73 warn "error in event callback: @_";
82}; 74};
85my @exts; 77my @exts;
86my @hook; 78my @hook;
87my %command; 79my %command;
88my %extcmd; 80my %extcmd;
89 81
82=head2 UTILITY FUNCTIONS
83
84=over 4
85
86=cut
87
88use JSON::Syck (); # TODO# replace by JSON::PC once working
89
90=item $ref = cf::from_json $json
91
92Converts a JSON string into the corresponding perl data structure.
93
94=cut
95
96sub from_json($) {
97 $JSON::Syck::ImplicitUnicode = 1; # work around JSON::Syck bugs
98 JSON::Syck::Load $_[0]
99}
100
101=item $json = cf::to_json $ref
102
103Converts a perl data structure into its JSON representation.
104
105=cut
106
107sub to_json($) {
108 $JSON::Syck::ImplicitUnicode = 0; # work around JSON::Syck bugs
109 JSON::Syck::Dump $_[0]
110}
111
112=back
113
114=cut
115
116#############################################################################
117
118=head2 EVENTS AND OBJECT ATTACHMENTS
119
120=over 4
121
122=item $object->attach ($attachment, key => $value...)
123
124=item $object->detach ($attachment)
125
126Attach/detach a pre-registered attachment to an object.
127
128=item $player->attach ($attachment, key => $value...)
129
130=item $player->detach ($attachment)
131
132Attach/detach a pre-registered attachment to a player.
133
134=item $map->attach ($attachment, key => $value...)
135
136=item $map->detach ($attachment)
137
138Attach/detach a pre-registered attachment to a map.
139
140=item $bool = $object->attached ($name)
141
142=item $bool = $player->attached ($name)
143
144=item $bool = $map->attached ($name)
145
146Checks wether the named attachment is currently attached to the object.
147
148=item cf::attach_global ...
149
150Attach handlers for global events.
151
152This and all following C<attach_*>-functions expect any number of the
153following handler/hook descriptions:
154
155=over 4
156
157=item prio => $number
158
159Set the priority for all following handlers/hooks (unless overwritten
160by another C<prio> setting). Lower priority handlers get executed
161earlier. The default priority is C<0>, and many built-in handlers are
162registered at priority C<-1000>, so lower priorities should not be used
163unless you know what you are doing.
164
165=item on_I<event> => \&cb
166
167Call the given code reference whenever the named event happens (event is
168something like C<instantiate>, C<apply>, C<use_skill> and so on, and which
169handlers are recognised generally depends on the type of object these
170handlers attach to).
171
172See F<include/eventinc.h> for the full list of events supported, and their
173class.
174
175=item package => package::
176
177Look for sub functions of the name C<< on_I<event> >> in the given
178package and register them. Only handlers for eevents supported by the
179object/class are recognised.
180
181=back
182
183=item cf::attach_to_type $object_type, $subtype, ...
184
185Attach handlers for a specific object type (e.g. TRANSPORT) and
186subtype. If C<$subtype> is zero or undef, matches all objects of the given
187type.
188
189=item cf::attach_to_objects ...
190
191Attach handlers to all objects. Do not use this except for debugging or
192very rare events, as handlers are (obviously) called for I<all> objects in
193the game.
194
195=item cf::attach_to_players ...
196
197Attach handlers to all players.
198
199=item cf::attach_to_maps ...
200
201Attach handlers to all maps.
202
203=item cf:register_attachment $name, ...
204
205Register an attachment by name through which objects can refer to this
206attachment.
207
208=item cf:register_player_attachment $name, ...
209
210Register an attachment by name through which players can refer to this
211attachment.
212
213=item cf:register_map_attachment $name, ...
214
215Register an attachment by name through which maps can refer to this
216attachment.
217
218=cut
219
220# the following variables are defined in .xs and must not be re-created
221our @CB_GLOBAL = (); # registry for all global events
222our @CB_OBJECT = (); # all objects (should not be used except in emergency)
223our @CB_PLAYER = ();
224our @CB_TYPE = (); # registry for type (cf-object class) based events
225our @CB_MAP = ();
226
227my %attachment;
228
229sub _attach_cb($\%$$$) {
230 my ($registry, $undo, $event, $prio, $cb) = @_;
231
232 use sort 'stable';
233
234 $cb = [$prio, $cb];
235
236 @{$registry->[$event]} = sort
237 { $a->[0] cmp $b->[0] }
238 @{$registry->[$event] || []}, $cb;
239
240 push @{$undo->{cb}}, [$event, $cb];
241}
242
243# attach handles attaching event callbacks
244# the only thing the caller has to do is pass the correct
245# registry (== where the callback attaches to).
246sub _attach(\@$@) {
247 my ($registry, $klass, @arg) = @_;
248
249 my $prio = 0;
250
251 my %undo = (
252 registry => $registry,
253 cb => [],
254 );
255
256 my %cb_id = map +("on_" . lc $EVENT[$_][0], $_) , grep $EVENT[$_][1] == $klass, 0 .. $#EVENT;
257
258 while (@arg) {
259 my $type = shift @arg;
260
261 if ($type eq "prio") {
262 $prio = shift @arg;
263
264 } elsif ($type eq "package") {
265 my $pkg = shift @arg;
266
267 while (my ($name, $id) = each %cb_id) {
268 if (my $cb = $pkg->can ($name)) {
269 _attach_cb $registry, %undo, $id, $prio, $cb;
270 }
271 }
272
273 } elsif (exists $cb_id{$type}) {
274 _attach_cb $registry, %undo, $cb_id{$type}, $prio, shift @arg;
275
276 } elsif (ref $type) {
277 warn "attaching objects not supported, ignoring.\n";
278
279 } else {
280 shift @arg;
281 warn "attach argument '$type' not supported, ignoring.\n";
282 }
283 }
284
285 \%undo
286}
287
288sub _attach_attachment {
289 my ($obj, $name, %arg) = @_;
290
291 return if exists $obj->{_attachment}{$name};
292
293 my $res;
294
295 if (my $attach = $attachment{$name}) {
296 my $registry = $obj->registry;
297
298 for (@$attach) {
299 my ($klass, @attach) = @$_;
300 $res = _attach @$registry, $klass, @attach;
301 }
302
303 $obj->{$name} = \%arg;
304 } else {
305 warn "object uses attachment '$name' that is not available, postponing.\n";
306 }
307
308 $obj->{_attachment}{$name} = undef;
309
310 $res->{attachment} = $name;
311 $res
312}
313
314*cf::object::attach =
315*cf::player::attach =
316*cf::map::attach = sub {
317 my ($obj, $name, %arg) = @_;
318
319 _attach_attachment $obj, $name, %arg;
320};
321
322# all those should be optimised
323*cf::object::detach =
324*cf::player::detach =
325*cf::map::detach = sub {
326 my ($obj, $name) = @_;
327
328 delete $obj->{_attachment}{$name};
329 reattach ($obj);
330};
331
332*cf::object::attached =
333*cf::player::attached =
334*cf::map::attached = sub {
335 my ($obj, $name) = @_;
336
337 exists $obj->{_attachment}{$name}
338};
339
340sub attach_global {
341 _attach @CB_GLOBAL, KLASS_GLOBAL, @_
342}
343
344sub attach_to_type {
345 my $type = shift;
346 my $subtype = shift;
347
348 _attach @{$CB_TYPE[$type + $subtype * NUM_SUBTYPES]}, KLASS_OBJECT, @_
349}
350
351sub attach_to_objects {
352 _attach @CB_OBJECT, KLASS_OBJECT, @_
353}
354
355sub attach_to_players {
356 _attach @CB_PLAYER, KLASS_PLAYER, @_
357}
358
359sub attach_to_maps {
360 _attach @CB_MAP, KLASS_MAP, @_
361}
362
363sub register_attachment {
364 my $name = shift;
365
366 $attachment{$name} = [[KLASS_OBJECT, @_]];
367}
368
369sub register_player_attachment {
370 my $name = shift;
371
372 $attachment{$name} = [[KLASS_PLAYER, @_]];
373}
374
375sub register_map_attachment {
376 my $name = shift;
377
378 $attachment{$name} = [[KLASS_MAP, @_]];
379}
380
381our $override;
382our @invoke_results = (); # referenced from .xs code. TODO: play tricks with reify and mortals?
383
384sub override {
385 $override = 1;
386 @invoke_results = ();
387}
388
389sub do_invoke {
390 my $event = shift;
391 my $callbacks = shift;
392
393 @invoke_results = ();
394
395 local $override;
396
397 for (@$callbacks) {
398 eval { &{$_->[1]} };
399
400 if ($@) {
401 warn "$@";
402 warn "... while processing $EVENT[$event][0](@_) event, skipping processing altogether.\n";
403 override;
404 }
405
406 return 1 if $override;
407 }
408
409 0
410}
411
412=item $bool = cf::invoke EVENT_GLOBAL_XXX, ...
413
414=item $bool = $object->invoke (EVENT_OBJECT_XXX, ...)
415
416=item $bool = $player->invoke (EVENT_PLAYER_XXX, ...)
417
418=item $bool = $map->invoke (EVENT_MAP_XXX, ...)
419
420Generate a global/object/player/map-specific event with the given arguments.
421
422This API is preliminary (most likely, the EVENT_KLASS_xxx prefix will be
423removed in future versions), and there is no public API to access override
424results (if you must, access C<@cf::invoke_results> directly).
425
426=back
427
428=cut
429
430#############################################################################
431
432=head2 METHODS VALID FOR ALL CORE OBJECTS
433
434=over 4
435
436=item $object->valid, $player->valid, $map->valid
437
438Just because you have a perl object does not mean that the corresponding
439C-level object still exists. If you try to access an object that has no
440valid C counterpart anymore you get an exception at runtime. This method
441can be used to test for existence of the C object part without causing an
442exception.
443
444=back
445
446=cut
447
448*cf::object::valid =
449*cf::player::valid =
450*cf::map::valid = \&cf::_valid;
451
452#############################################################################
453# object support
454
455sub instantiate {
456 my ($obj, $data) = @_;
457
458 $data = from_json $data;
459
460 for (@$data) {
461 my ($name, $args) = @$_;
462
463 $obj->attach ($name, %{$args || {} });
464 }
465}
466
467# basically do the same as instantiate, without calling instantiate
468sub reattach {
469 my ($obj) = @_;
470 my $registry = $obj->registry;
471
472 @$registry = ();
473
474 delete $obj->{_attachment} unless scalar keys %{ $obj->{_attachment} || {} };
475
476 for my $name (keys %{ $obj->{_attachment} || {} }) {
477 if (my $attach = $attachment{$name}) {
478 for (@$attach) {
479 my ($klass, @attach) = @$_;
480 _attach @$registry, $klass, @attach;
481 }
482 } else {
483 warn "object uses attachment '$name' that is not available, postponing.\n";
484 }
485 }
486}
487
488sub object_freezer_save {
489 my ($filename, $rdata, $objs) = @_;
490
491 if (length $$rdata) {
492 warn sprintf "saving %s (%d,%d)\n",
493 $filename, length $$rdata, scalar @$objs;
494
495 if (open my $fh, ">:raw", "$filename~") {
496 chmod SAVE_MODE, $fh;
497 syswrite $fh, $$rdata;
498 close $fh;
499
500 if (@$objs && open my $fh, ">:raw", "$filename.pst~") {
501 chmod SAVE_MODE, $fh;
502 syswrite $fh, Storable::nfreeze { version => 1, objs => $objs };
503 close $fh;
504 rename "$filename.pst~", "$filename.pst";
505 } else {
506 unlink "$filename.pst";
507 }
508
509 rename "$filename~", $filename;
510 } else {
511 warn "FATAL: $filename~: $!\n";
512 }
513 } else {
514 unlink $filename;
515 unlink "$filename.pst";
516 }
517}
518
519sub object_thawer_load {
520 my ($filename) = @_;
521
522 local $/;
523
524 my $av;
525
526 #TODO: use sysread etc.
527 if (open my $data, "<:raw:perlio", $filename) {
528 $data = <$data>;
529 if (open my $pst, "<:raw:perlio", "$filename.pst") {
530 $av = eval { (Storable::thaw <$pst>)->{objs} };
531 }
532 return ($data, $av);
533 }
534
535 ()
536}
537
538attach_to_objects
539 prio => -1000000,
540 on_clone => sub {
541 my ($src, $dst) = @_;
542
543 @{$dst->registry} = @{$src->registry};
544
545 %$dst = %$src;
546
547 %{$dst->{_attachment}} = %{$src->{_attachment}}
548 if exists $src->{_attachment};
549 },
550;
551
552#############################################################################
553# old plug-in events
554
90sub inject_event { 555sub inject_event {
91 my $extension = shift; 556 my $extension = shift;
92 my $event_code = shift; 557 my $event_code = shift;
93 558
94 my $cb = $hook[$event_code]{$extension} 559 my $cb = $hook[$event_code]{$extension}
136} 601}
137 602
138sub register { 603sub register {
139 my ($base, $pkg) = @_; 604 my ($base, $pkg) = @_;
140 605
141 for my $idx (0 .. $#EVENT) { 606 #TODO
142 if (my $ref = $pkg->can ("on_$EVENT[$idx]")) {
143 #warn "registering $EVENT[$idx] hook to '$pkg'\n";
144 $hook[$idx]{$base} = $ref;
145 }
146 }
147} 607}
148 608
149sub load_extension { 609sub load_extension {
150 my ($path) = @_; 610 my ($path) = @_;
151 611
152 $path =~ /([^\/\\]+)\.ext$/ or die "$path"; 612 $path =~ /([^\/\\]+)\.ext$/ or die "$path";
153 my $base = $1; 613 my $base = $1;
154 my $pkg = $1; 614 my $pkg = $1;
155 $pkg =~ s/[^[:word:]]/_/g; 615 $pkg =~ s/[^[:word:]]/_/g;
156 $pkg = "cf::ext::$pkg"; 616 $pkg = "ext::$pkg";
157 617
158 warn "loading '$path' into '$pkg'\n"; 618 warn "loading '$path' into '$pkg'\n";
159 619
160 open my $fh, "<:utf8", $path 620 open my $fh, "<:utf8", $path
161 or die "$path: $!"; 621 or die "$path: $!";
181sub unload_extension { 641sub unload_extension {
182 my ($pkg) = @_; 642 my ($pkg) = @_;
183 643
184 warn "removing extension $pkg\n"; 644 warn "removing extension $pkg\n";
185 645
186 if (my $cb = $pkg->can ("on_unload")) {
187 $cb->($pkg);
188 }
189
190 # remove hooks 646 # remove hooks
647 #TODO
191 for my $idx (0 .. $#EVENT) { 648# for my $idx (0 .. $#PLUGIN_EVENT) {
192 delete $hook[$idx]{$pkg}; 649# delete $hook[$idx]{$pkg};
193 } 650# }
194 651
195 # remove commands 652 # remove commands
196 for my $name (keys %command) { 653 for my $name (keys %command) {
197 my @cb = grep $_->[2] ne $pkg, @{ $command{$name} }; 654 my @cb = grep $_->[2] ne $pkg, @{ $command{$name} };
198 655
208 # remove extcmds 665 # remove extcmds
209 for my $name (grep $extcmd{$_}[1] eq $pkg, keys %extcmd) { 666 for my $name (grep $extcmd{$_}[1] eq $pkg, keys %extcmd) {
210 delete $extcmd{$name}; 667 delete $extcmd{$name};
211 } 668 }
212 669
670 if (my $cb = $pkg->can ("unload")) {
671 eval {
672 $cb->($pkg);
673 1
674 } or warn "$pkg unloaded, but with errors: $@";
675 }
676
213 Symbol::delete_package $pkg; 677 Symbol::delete_package $pkg;
214} 678}
215 679
216sub load_extensions { 680sub load_extensions {
217 my $LIBDIR = maps_directory "perl"; 681 my $LIBDIR = maps_directory "perl";
223 1 687 1
224 } or warn "$ext not loaded: $@"; 688 } or warn "$ext not loaded: $@";
225 } 689 }
226} 690}
227 691
228register_command "perl-reload", 0, sub {
229 my ($who, $arg) = @_;
230
231 if ($who->flag (FLAG_WIZ)) {
232 $who->message ("reloading...");
233
234 warn "reloading...\n";
235 eval {
236 # 1. cancel all watchers
237 $_->cancel for Event::all_watchers;
238
239 # 2. unload all extensions
240 for (@exts) {
241 $who->message ("unloading <$_>");
242 unload_extension $_;
243 }
244
245 # 3. unload all modules loaded from $LIBDIR
246 while (my ($k, $v) = each %INC) {
247 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/;
248
249 $who->message ("removing <$k>");
250 delete $INC{$k};
251
252 $k =~ s/\.pm$//;
253 $k =~ s/\//::/g;
254
255 if (my $cb = $k->can ("unload_module")) {
256 $cb->();
257 }
258
259 Symbol::delete_package $k;
260 }
261
262 # 4. get rid of ext::, as good as possible
263 Symbol::delete_package "ext::$_"
264 for qw(cf::object cf::object::map cf::object::player cf::player cf::map cf::party cf::region);
265
266 # 5. remove register_script_function callbacks
267 # TODO
268
269 # 6. unload cf.pm "a bit"
270 delete $INC{"cf.pm"};
271
272 # don't, removes xs symbols, too
273 #Symbol::delete_package __PACKAGE__;
274
275 # 7. reload cf.pm
276 $who->message ("reloading cf.pm");
277 require cf;
278 };
279 warn $@ if $@;
280 $who->message ($@) if $@;
281 warn "reloaded\n";
282
283 $who->message ("reloaded");
284 } else {
285 $who->message ("Intruder Alert!");
286 }
287};
288
289#############################################################################
290# utility functions
291
292use JSON::Syck (); # TODO# replace by JSON::PC once working
293
294$JSON::Syck::ImplicitUnicode = 1;
295
296sub from_json($) {
297 JSON::Syck::Load $_[0]
298}
299
300sub to_json($) {
301 JSON::Syck::Dump $_[0]
302}
303
304############################################################################# 692#############################################################################
305# extcmd framework, basically convert ext <msg> 693# extcmd framework, basically convert ext <msg>
306# into pkg::->on_extcmd_arg1 (...) while shortcutting a few 694# into pkg::->on_extcmd_arg1 (...) while shortcutting a few
307 695
308sub on_extcmd { 696attach_to_players
697 on_extcmd => sub {
309 my ($pl, $buf) = @_; 698 my ($pl, $buf) = @_;
310 699
311 my $msg = eval { from_json $buf }; 700 my $msg = eval { from_json $buf };
312 701
313 if (ref $msg) { 702 if (ref $msg) {
314 if (my $cb = $extcmd{$msg->{msgtype}}) { 703 if (my $cb = $extcmd{$msg->{msgtype}}) {
315 if (my %reply = $cb->[0]->($pl, $msg)) { 704 if (my %reply = $cb->[0]->($pl, $msg)) {
316 $pl->ext_reply ($msg->{msgid}, %reply); 705 $pl->ext_reply ($msg->{msgid}, %reply);
706 }
317 } 707 }
318 }
319 } else { 708 } else {
320 warn "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n"; 709 warn "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n";
710 }
711
712 cf::override;
321 } 713 },
322 714;
323 1
324}
325 715
326############################################################################# 716#############################################################################
327# load/save/clean perl data associated with a map 717# load/save/clean perl data associated with a map
328 718
329*on_mapclean = sub { 719*cf::mapsupport::on_clean = sub {
330 my ($map) = @_; 720 my ($map) = @_;
331 721
332 my $path = $map->tmpname; 722 my $path = $map->tmpname;
333 defined $path or return; 723 defined $path or return;
334 724
335 unlink "$path.cfperl"; 725 unlink "$path.pst";
336}; 726};
337 727
338*on_mapin = 728attach_to_maps prio => -10000, package => cf::mapsupport::;
339*on_mapload = sub {
340 my ($map) = @_;
341
342 my $path = $map->tmpname;
343 $path = $map->path unless defined $path;
344
345 open my $fh, "<:raw", "$path.cfperl"
346 or return; # no perl data
347
348 my $data = Storable::thaw do { local $/; <$fh> };
349
350 $data->{version} <= 1
351 or return; # too new
352
353 $map->_set_obs ($data->{obs});
354};
355
356*on_mapout = sub {
357 my ($map) = @_;
358
359 my $path = $map->tmpname;
360 $path = $map->path unless defined $path;
361
362 my $obs = $map->_get_obs;
363
364 if (defined $obs) {
365 open my $fh, ">:raw", "$path.cfperl"
366 or die "$path.cfperl: $!";
367
368 stat $path;
369
370 print $fh Storable::nfreeze {
371 size => (stat _)[7],
372 time => (stat _)[9],
373 version => 1,
374 obs => $obs,
375 };
376
377 chmod SAVE_MODE, "$path.cfperl"; # very racy, but cf-compatible *g*
378 } else {
379 unlink "$path.cfperl";
380 }
381};
382 729
383############################################################################# 730#############################################################################
384# load/save perl data associated with player->ob objects 731# load/save perl data associated with player->ob objects
385 732
386*on_player_load = sub { 733sub all_objects(@) {
734 @_, map all_objects ($_->inv), @_
735}
736
737# TODO: compatibility cruft, remove when no longer needed
738attach_to_players
739 on_load => sub {
387 my ($ob, $path) = @_; 740 my ($pl, $path) = @_;
388 741
389 for my $o ($ob, $ob->inv) { 742 for my $o (all_objects $pl->ob) {
390 if (my $value = $o->get_ob_key_value ("_perl_data")) { 743 if (my $value = $o->get_ob_key_value ("_perl_data")) {
391 $o->set_ob_key_value ("_perl_data"); 744 $o->set_ob_key_value ("_perl_data");
392 745
393 %$o = %{ Storable::thaw pack "H*", $value }; 746 %$o = %{ Storable::thaw pack "H*", $value };
394 } 747 }
748 }
395 } 749 },
396}; 750;
397 751
398*on_player_save = sub {
399 my ($ob, $path) = @_;
400
401 $_->set_ob_key_value (_perl_data => unpack "H*", Storable::nfreeze $_)
402 for grep %$_, $ob, $ob->inv;
403};
404
405############################################################################# 752#############################################################################
406# core extensions - in perl 753
754=head2 CORE EXTENSIONS
755
756Functions and methods that extend core crossfire objects.
757
758=over 4
407 759
408=item cf::player::exists $login 760=item cf::player::exists $login
409 761
410Returns true when the given account exists. 762Returns true when the given account exists.
411 763
451 $msg{msgid} = $id; 803 $msg{msgid} = $id;
452 804
453 $self->send ("ext " . to_json \%msg); 805 $self->send ("ext " . to_json \%msg);
454} 806}
455 807
456############################################################################# 808=back
457# map scripting support
458 809
810=cut
811
812#############################################################################
813
814=head2 SAFE SCRIPTING
815
816Functions that provide a safe environment to compile and execute
817snippets of perl code without them endangering the safety of the server
818itself. Looping constructs, I/O operators and other built-in functionality
819is not available in the safe scripting environment, and the number of
820functions and methods that cna be called is greatly reduced.
821
822=cut
823
459our $safe = new Safe "ext"; 824our $safe = new Safe "safe";
460our $safe_hole = new Safe::Hole; 825our $safe_hole = new Safe::Hole;
461 826
462$SIG{FPE} = 'IGNORE'; 827$SIG{FPE} = 'IGNORE';
463 828
464$safe->permit_only (Opcode::opset qw(:base_core :base_mem :base_orig :base_math sort time)); 829$safe->permit_only (Opcode::opset qw(:base_core :base_mem :base_orig :base_math sort time));
465 830
466# here we export the classes and methods available to script code 831# here we export the classes and methods available to script code
832
833=pod
834
835The following fucntions and emthods are available within a safe environment:
836
837 cf::object contr pay_amount pay_player
838 cf::object::player player
839 cf::player peaceful
840
841=cut
467 842
468for ( 843for (
469 ["cf::object" => qw(contr pay_amount pay_player)], 844 ["cf::object" => qw(contr pay_amount pay_player)],
470 ["cf::object::player" => qw(player)], 845 ["cf::object::player" => qw(player)],
471 ["cf::player" => qw(peaceful)], 846 ["cf::player" => qw(peaceful)],
472) { 847) {
473 no strict 'refs'; 848 no strict 'refs';
474 my ($pkg, @funs) = @$_; 849 my ($pkg, @funs) = @$_;
475 *{"ext::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"}) 850 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"})
476 for @funs; 851 for @funs;
477} 852}
853
854=over 4
855
856=item @retval = safe_eval $code, [var => value, ...]
857
858Compiled and executes the given perl code snippet. additional var/value
859pairs result in temporary local (my) scalar variables of the given name
860that are available in the code snippet. Example:
861
862 my $five = safe_eval '$first + $second', first => 1, second => 4;
863
864=cut
478 865
479sub safe_eval($;@) { 866sub safe_eval($;@) {
480 my ($code, %vars) = @_; 867 my ($code, %vars) = @_;
481 868
482 my $qcode = $code; 869 my $qcode = $code;
483 $qcode =~ s/"/‟/g; # not allowed in #line filenames 870 $qcode =~ s/"/‟/g; # not allowed in #line filenames
484 $qcode =~ s/\n/\\n/g; 871 $qcode =~ s/\n/\\n/g;
485 872
486 local $_; 873 local $_;
487 local @ext::cf::_safe_eval_args = values %vars; 874 local @safe::cf::_safe_eval_args = values %vars;
488 875
489 $code = 876 my $eval =
490 "do {\n" 877 "do {\n"
491 . "my (" . (join ",", map "\$$_", keys %vars) . ") = \@cf::_safe_eval_args;\n" 878 . "my (" . (join ",", map "\$$_", keys %vars) . ") = \@cf::_safe_eval_args;\n"
492 . "#line 0 \"{$qcode}\"\n" 879 . "#line 0 \"{$qcode}\"\n"
493 . $code 880 . $code
494 . "\n}" 881 . "\n}"
495 ; 882 ;
496 883
497 sub_generation_inc; 884 sub_generation_inc;
498 my @res = wantarray ? $safe->reval ($code) : scalar $safe->reval ($code); 885 my @res = wantarray ? $safe->reval ($eval) : scalar $safe->reval ($eval);
499 sub_generation_inc; 886 sub_generation_inc;
500 887
888 if ($@) {
889 warn "$@";
890 warn "while executing safe code '$code'\n";
891 warn "with arguments " . (join " ", %vars) . "\n";
892 }
893
501 wantarray ? @res : $res[0] 894 wantarray ? @res : $res[0]
502} 895}
896
897=item cf::register_script_function $function => $cb
898
899Register a function that can be called from within map/npc scripts. The
900function should be reasonably secure and should be put into a package name
901like the extension.
902
903Example: register a function that gets called whenever a map script calls
904C<rent::overview>, as used by the C<rent> extension.
905
906 cf::register_script_function "rent::overview" => sub {
907 ...
908 };
909
910=cut
503 911
504sub register_script_function { 912sub register_script_function {
505 my ($fun, $cb) = @_; 913 my ($fun, $cb) = @_;
506 914
507 no strict 'refs'; 915 no strict 'refs';
508 *{"ext::$fun"} = $safe_hole->wrap ($cb); 916 *{"safe::$fun"} = $safe_hole->wrap ($cb);
917}
918
919=back
920
921=cut
922
923#############################################################################
924
925=head2 EXTENSION DATABASE SUPPORT
926
927Crossfire maintains a very simple database for extension use. It can
928currently store anything that can be serialised using Storable, which
929excludes objects.
930
931The parameter C<$family> should best start with the name of the extension
932using it, it should be unique.
933
934=over 4
935
936=item $hashref = cf::db_get $family
937
938Return a hashref for use by the extension C<$family>, which can be
939modified. After modifications, you have to call C<cf::db_dirty> or
940C<cf::db_sync>.
941
942=item $value = cf::db_get $family => $key
943
944Returns a single value from the database
945
946=item cf::db_put $family => $hashref
947
948Stores the given family hashref into the database. Updates are delayed, if
949you want the data to be synced to disk immediately, use C<cf::db_sync>.
950
951=item cf::db_put $family => $key => $value
952
953Stores the given C<$value> in the family hash. Updates are delayed, if you
954want the data to be synced to disk immediately, use C<cf::db_sync>.
955
956=item cf::db_dirty
957
958Marks the database as dirty, to be updated at a later time.
959
960=item cf::db_sync
961
962Immediately write the database to disk I<if it is dirty>.
963
964=cut
965
966{
967 my $db;
968 my $path = cf::localdir . "/database.pst";
969
970 sub db_load() {
971 warn "loading database $path\n";#d# remove later
972 $db = stat $path ? Storable::retrieve $path : { };
973 }
974
975 my $pid;
976
977 sub db_save() {
978 warn "saving database $path\n";#d# remove later
979 waitpid $pid, 0 if $pid;
980 if (0 == ($pid = fork)) {
981 $db->{_meta}{version} = 1;
982 Storable::nstore $db, "$path~";
983 rename "$path~", $path;
984 cf::_exit 0 if defined $pid;
985 }
986 }
987
988 my $dirty;
989
990 sub db_sync() {
991 db_save if $dirty;
992 undef $dirty;
993 }
994
995 my $idle = Event->idle (min => $TICK * 2.8, max => 10, repeat => 0, cb => sub {
996 db_sync;
997 });
998
999 sub db_dirty() {
1000 $dirty = 1;
1001 $idle->start;
1002 }
1003
1004 sub db_get($;$) {
1005 @_ >= 2
1006 ? $db->{$_[0]}{$_[1]}
1007 : ($db->{$_[0]} ||= { })
1008 }
1009
1010 sub db_put($$;$) {
1011 if (@_ >= 3) {
1012 $db->{$_[0]}{$_[1]} = $_[2];
1013 } else {
1014 $db->{$_[0]} = $_[1];
1015 }
1016 db_dirty;
1017 }
1018
1019 attach_global
1020 prio => 10000,
1021 on_cleanup => sub {
1022 db_sync;
1023 },
1024 ;
1025}
1026
1027#############################################################################
1028# the server's main()
1029
1030sub main {
1031 db_load;
1032 load_extensions;
1033 Event::loop;
509} 1034}
510 1035
511############################################################################# 1036#############################################################################
512# initialisation 1037# initialisation
513 1038
1039sub _perl_reload(&) {
1040 my ($msg) = @_;
1041
1042 $msg->("reloading...");
1043
1044 eval {
1045 # cancel all watchers
1046 $_->cancel for Event::all_watchers;
1047
1048 # unload all extensions
1049 for (@exts) {
1050 $msg->("unloading <$_>");
1051 unload_extension $_;
1052 }
1053
1054 # unload all modules loaded from $LIBDIR
1055 while (my ($k, $v) = each %INC) {
1056 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/;
1057
1058 $msg->("removing <$k>");
1059 delete $INC{$k};
1060
1061 $k =~ s/\.pm$//;
1062 $k =~ s/\//::/g;
1063
1064 if (my $cb = $k->can ("unload_module")) {
1065 $cb->();
1066 }
1067
1068 Symbol::delete_package $k;
1069 }
1070
1071 # sync database to disk
1072 cf::db_sync;
1073
1074 # get rid of safe::, as good as possible
1075 Symbol::delete_package "safe::$_"
1076 for qw(cf::object cf::object::player cf::player cf::map cf::party cf::region);
1077
1078 # remove register_script_function callbacks
1079 # TODO
1080
1081 # unload cf.pm "a bit"
1082 delete $INC{"cf.pm"};
1083
1084 # don't, removes xs symbols, too,
1085 # and global variables created in xs
1086 #Symbol::delete_package __PACKAGE__;
1087
1088 # reload cf.pm
1089 $msg->("reloading cf.pm");
1090 require cf;
1091
1092 # load database again
1093 cf::db_load;
1094
1095 # load extensions
1096 $msg->("load extensions");
1097 cf::load_extensions;
1098
1099 # reattach attachments to objects
1100 $msg->("reattach");
1101 _global_reattach;
1102 };
1103 $msg->($@) if $@;
1104
1105 $msg->("reloaded");
1106};
1107
1108sub perl_reload() {
1109 _perl_reload {
1110 warn $_[0];
1111 print "$_[0]\n";
1112 };
1113}
1114
1115register_command "perl-reload", 0, sub {
1116 my ($who, $arg) = @_;
1117
1118 if ($who->flag (FLAG_WIZ)) {
1119 _perl_reload {
1120 warn $_[0];
1121 $who->message ($_[0]);
1122 };
1123 }
1124};
1125
514register "<global>", __PACKAGE__; 1126register "<global>", __PACKAGE__;
515 1127
516unshift @INC, $LIBDIR; 1128unshift @INC, $LIBDIR;
517 1129
518load_extensions; 1130$TICK_WATCHER = Event->timer (
1131 prio => 1,
1132 at => $NEXT_TICK || 1,
1133 cb => sub {
1134 cf::server_tick; # one server iteration
1135
1136 my $NOW = Event::time;
1137 $NEXT_TICK += $TICK;
1138
1139 # if we are delayed by four ticks, skip them all
1140 $NEXT_TICK = $NOW if $NOW >= $NEXT_TICK + $TICK * 4;
1141
1142 $TICK_WATCHER->at ($NEXT_TICK);
1143 $TICK_WATCHER->start;
1144 },
1145);
519 1146
5201 11471
521 1148

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines