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.34 by root, Thu Aug 24 13:13:49 2006 UTC vs.
Revision 1.73 by root, Sun Oct 1 11:46:51 2006 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines