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.31 by elmex, Mon Aug 14 04:22:04 2006 UTC vs.
Revision 1.43 by root, Fri Aug 25 17:11:53 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
15our %COMMAND; 16our %COMMAND = ();
16our @EVENT; 17our @EVENT;
18our @PLUGIN_EVENT;
17our %PROP_TYPE; 19our %PROP_TYPE;
18our %PROP_IDX; 20our %PROP_IDX;
19our $LIBDIR = maps_directory "perl"; 21our $LIBDIR = maps_directory "perl";
20 22
23our $TICK = MAX_TIME * 1e-6;
24our $TICK_WATCHER;
25our $NEXT_TICK;
26
21BEGIN { 27BEGIN {
22 @EVENT = map lc, @EVENT; 28 @PLUGIN_EVENT = map lc, @PLUGIN_EVENT;
23 29
24 *CORE::GLOBAL::warn = sub { 30 *CORE::GLOBAL::warn = sub {
25 my $msg = join "", @_; 31 my $msg = join "", @_;
26 $msg .= "\n" 32 $msg .= "\n"
27 unless $msg =~ /\n$/; 33 unless $msg =~ /\n$/;
65prop_gen MAP_PROP => "cf::map"; 71prop_gen MAP_PROP => "cf::map";
66prop_gen ARCH_PROP => "cf::arch"; 72prop_gen ARCH_PROP => "cf::arch";
67 73
68# guessed hierarchies 74# guessed hierarchies
69 75
70@ext::cf::object::player::ISA = @cf::object::player::ISA = 'cf::object'; 76@safe::cf::object::player::ISA = @cf::object::player::ISA = 'cf::object';
71@ext::cf::object::map::ISA = @cf::object::map::ISA = 'cf::object'; 77@safe::cf::object::map::ISA = @cf::object::map::ISA = 'cf::object';
72 78
73# we bless all objects into derived classes to force a method lookup 79# we bless all objects into (empty) derived classes to force a method lookup
74# within the Safe compartment. 80# within the Safe compartment.
75for my $pkg (qw(cf::object cf::object::map cf::object::player cf::player cf::map cf::party cf::region cf::arch)) { 81for my $pkg (qw(cf::object cf::object::map cf::object::player cf::player cf::map cf::party cf::region cf::arch)) {
76 no strict 'refs'; 82 no strict 'refs';
77 @{"ext::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg; 83 @{"safe::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg;
78} 84}
79 85
80$Event::DIED = sub { 86$Event::DIED = sub {
81 warn "error in event callback: @_"; 87 warn "error in event callback: @_";
82}; 88};
85my @exts; 91my @exts;
86my @hook; 92my @hook;
87my %command; 93my %command;
88my %extcmd; 94my %extcmd;
89 95
96#############################################################################
97# "new" plug-in system
98
99=item cf::object::attach ... # NYI
100
101=item cf::attach_global ...
102
103=item cf::attach_to_type ...
104
105=item cf::attach_to_objects ...
106
107=item cf::attach_to_players ...
108
109=item cf::attach_to_maps ...
110
111 prio => $number, # lower is earlier
112 on_xxx => \&cb,
113 package => package::,
114
115=cut
116
117# the following variables are defined in .xs and must not be re-created
118our @CB_GLOBAL = (); # registry for all global events
119our @CB_OBJECT = ();
120our @CB_PLAYER = ();
121our @CB_TYPE = (); # registry for type (cf-object class) based events
122our @CB_MAP = ();
123
124sub _attach_cb($\%$$$) {
125 my ($registry, $undo, $event, $prio, $cb) = @_;
126
127 use sort 'stable';
128
129 $cb = [$prio, $cb];
130
131 @{$registry->[$event]} = sort
132 { $a->[0] cmp $b->[0] }
133 @{$registry->[$event] || []}, $cb;
134
135 push @{$undo->{cb}}, [$event, $cb];
136}
137
138# attach handles attaching event callbacks
139# the only thing the caller has to do is pass the correct
140# registry (== where the callback attaches to).
141sub _attach(\@$\@) {
142 my ($registry, $klass, $arg) = @_;
143
144 my $prio = 0;
145
146 my %undo = (
147 registry => $registry,
148 cb => [],
149 );
150
151 my %cb_id = map +("on_" . lc $EVENT[$_][0], $_) , grep $EVENT[$_][1] == $klass, 0 .. $#EVENT;
152
153 while (@$arg) {
154 my $type = shift @$arg;
155
156 if ($type eq "prio") {
157 $prio = shift @$arg;
158
159 } elsif ($type eq "package") {
160 my $pkg = shift @$arg;
161
162 while (my ($name, $id) = each %cb_id) {
163 if (my $cb = $pkg->can ($name)) {
164 _attach_cb $registry, %undo, $id, $prio, $cb;
165 }
166 }
167
168 } elsif (exists $cb_id{$type}) {
169 _attach_cb $registry, %undo, $cb_id{$type}, $prio, shift @$arg;
170
171 } elsif (ref $type) {
172 warn "attaching objects not supported, ignoring.\n";
173
174 } else {
175 shift @$arg;
176 warn "attach argument '$type' not supported, ignoring.\n";
177 }
178 }
179
180 \%undo
181}
182
183sub cf::object::attach {
184 die;
185}
186
187sub attach_global {
188 _attach @CB_GLOBAL, KLASS_GLOBAL, @_
189}
190
191sub attach_to_type {
192 my $type = shift;
193 _attach @{$CB_TYPE[$type]}, KLASS_OBJECT, @_
194}
195
196sub attach_to_objects {
197 _attach @CB_OBJECT, KLASS_OBJECT, @_
198}
199
200sub attach_to_players {
201 _attach @CB_PLAYER, KLASS_PLAYER, @_
202}
203
204sub attach_to_maps {
205 _attach @CB_MAP, KLASS_MAP, @_
206}
207
208our $override;
209
210sub override() {
211 $override = 1
212}
213
214sub invoke {
215 my $event = shift;
216 my $callbacks = shift;
217
218 local $override;
219
220 for (@$callbacks) {
221 eval { &{$_->[1]} };
222
223 if ($@) {
224 warn "$@";
225 warn "... while processing $EVENT[$event][0] event, skipping processing altogether.\n";
226 override;
227 }
228
229 return 1 if $override;
230 }
231
232 0
233}
234
235#############################################################################
236# old plug-in events
237
90sub inject_event { 238sub inject_event {
91 my $extension = shift; 239 my $extension = shift;
92 my $event_code = shift; 240 my $event_code = shift;
93 241
94 my $cb = $hook[$event_code]{$extension} 242 my $cb = $hook[$event_code]{$extension}
136} 284}
137 285
138sub register { 286sub register {
139 my ($base, $pkg) = @_; 287 my ($base, $pkg) = @_;
140 288
141 for my $idx (0 .. $#EVENT) { 289 for my $idx (0 .. $#PLUGIN_EVENT) {
142 if (my $ref = $pkg->can ("on_$EVENT[$idx]")) { 290 if (my $ref = $pkg->can ("on_$PLUGIN_EVENT[$idx]")) {
143 #warn "registering $EVENT[$idx] hook to '$pkg'\n"; 291 #warn "registering $PLUGIN_EVENT[$idx] hook to '$pkg'\n";
144 $hook[$idx]{$base} = $ref; 292 $hook[$idx]{$base} = $ref;
145 } 293 }
146 } 294 }
147} 295}
148 296
151 299
152 $path =~ /([^\/\\]+)\.ext$/ or die "$path"; 300 $path =~ /([^\/\\]+)\.ext$/ or die "$path";
153 my $base = $1; 301 my $base = $1;
154 my $pkg = $1; 302 my $pkg = $1;
155 $pkg =~ s/[^[:word:]]/_/g; 303 $pkg =~ s/[^[:word:]]/_/g;
156 $pkg = "cf::ext::$pkg"; 304 $pkg = "ext::$pkg";
157 305
158 warn "loading '$path' into '$pkg'\n"; 306 warn "loading '$path' into '$pkg'\n";
159 307
160 open my $fh, "<:utf8", $path 308 open my $fh, "<:utf8", $path
161 or die "$path: $!"; 309 or die "$path: $!";
182 my ($pkg) = @_; 330 my ($pkg) = @_;
183 331
184 warn "removing extension $pkg\n"; 332 warn "removing extension $pkg\n";
185 333
186 # remove hooks 334 # remove hooks
187 for my $idx (0 .. $#EVENT) { 335 for my $idx (0 .. $#PLUGIN_EVENT) {
188 delete $hook[$idx]{$pkg}; 336 delete $hook[$idx]{$pkg};
189 } 337 }
190 338
191 # remove commands 339 # remove commands
192 for my $name (keys %command) { 340 for my $name (keys %command) {
204 # remove extcmds 352 # remove extcmds
205 for my $name (grep $extcmd{$_}[1] eq $pkg, keys %extcmd) { 353 for my $name (grep $extcmd{$_}[1] eq $pkg, keys %extcmd) {
206 delete $extcmd{$name}; 354 delete $extcmd{$name};
207 } 355 }
208 356
209 if (my $cb = $pkg->can ("on_unload")) { 357 if (my $cb = $pkg->can ("unload")) {
210 eval { 358 eval {
211 $cb->($pkg); 359 $cb->($pkg);
212 1 360 1
213 } or warn "$pkg unloaded, but with errors: $@"; 361 } or warn "$pkg unloaded, but with errors: $@";
214 } 362 }
226 1 374 1
227 } or warn "$ext not loaded: $@"; 375 } or warn "$ext not loaded: $@";
228 } 376 }
229} 377}
230 378
379sub _perl_reload(&) {
380 my ($msg) = @_;
381
382 $msg->("reloading...");
383
384 eval {
385 # 1. cancel all watchers
386 $_->cancel for Event::all_watchers;
387
388 # 2. unload all extensions
389 for (@exts) {
390 $msg->("unloading <$_>");
391 unload_extension $_;
392 }
393
394 # 3. unload all modules loaded from $LIBDIR
395 while (my ($k, $v) = each %INC) {
396 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/;
397
398 $msg->("removing <$k>");
399 delete $INC{$k};
400
401 $k =~ s/\.pm$//;
402 $k =~ s/\//::/g;
403
404 if (my $cb = $k->can ("unload_module")) {
405 $cb->();
406 }
407
408 Symbol::delete_package $k;
409 }
410
411 # 4. get rid of safe::, as good as possible
412 Symbol::delete_package "safe::$_"
413 for qw(cf::object cf::object::map cf::object::player cf::player cf::map cf::party cf::region);
414
415 # 5. remove register_script_function callbacks
416 # TODO
417
418 # 6. unload cf.pm "a bit"
419 delete $INC{"cf.pm"};
420
421 # don't, removes xs symbols, too,
422 # and global variables created in xs
423 #Symbol::delete_package __PACKAGE__;
424
425 # 7. reload cf.pm
426 $msg->("reloading cf.pm");
427 require cf;
428 };
429 $msg->($@) if $@;
430
431 $msg->("reloaded");
432};
433
434sub perl_reload() {
435 _perl_reload {
436 warn $_[0];
437 print "$_[0]\n";
438 };
439}
440
231register_command "perl-reload", 0, sub { 441register_command "perl-reload", 0, sub {
232 my ($who, $arg) = @_; 442 my ($who, $arg) = @_;
233 443
234 if ($who->flag (FLAG_WIZ)) { 444 if ($who->flag (FLAG_WIZ)) {
235 $who->message ("reloading..."); 445 _perl_reload {
236 446 warn $_[0];
237 warn "reloading...\n"; 447 $who->message ($_[0]);
238 eval {
239 # 1. cancel all watchers
240 $_->cancel for Event::all_watchers;
241
242 # 2. unload all extensions
243 for (@exts) {
244 $who->message ("unloading <$_>");
245 unload_extension $_;
246 }
247
248 # 3. unload all modules loaded from $LIBDIR
249 while (my ($k, $v) = each %INC) {
250 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/;
251
252 $who->message ("removing <$k>");
253 delete $INC{$k};
254
255 $k =~ s/\.pm$//;
256 $k =~ s/\//::/g;
257
258 if (my $cb = $k->can ("unload_module")) {
259 $cb->();
260 }
261
262 Symbol::delete_package $k;
263 }
264
265 # 4. get rid of ext::, as good as possible
266 Symbol::delete_package "ext::$_"
267 for qw(cf::object cf::object::map cf::object::player cf::player cf::map cf::party cf::region);
268
269 # 5. remove register_script_function callbacks
270 # TODO
271
272 # 6. unload cf.pm "a bit"
273 delete $INC{"cf.pm"};
274
275 # don't, removes xs symbols, too
276 #Symbol::delete_package __PACKAGE__;
277
278 # 7. reload cf.pm
279 $who->message ("reloading cf.pm");
280 require cf;
281 }; 448 };
282 warn $@ if $@;
283 $who->message ($@) if $@;
284 warn "reloaded\n";
285
286 $who->message ("reloaded");
287 } else {
288 $who->message ("Intruder Alert!");
289 } 449 }
290}; 450};
291 451
292############################################################################# 452#############################################################################
293# utility functions 453# utility functions
306 466
307############################################################################# 467#############################################################################
308# extcmd framework, basically convert ext <msg> 468# extcmd framework, basically convert ext <msg>
309# into pkg::->on_extcmd_arg1 (...) while shortcutting a few 469# into pkg::->on_extcmd_arg1 (...) while shortcutting a few
310 470
311sub on_extcmd { 471attach_global
472 on_extcmd => sub {
312 my ($pl, $buf) = @_; 473 my ($pl, $buf) = @_;
313 474
314 my $msg = eval { from_json $buf }; 475 my $msg = eval { from_json $buf };
315 476
316 if (ref $msg) { 477 if (ref $msg) {
317 if (my $cb = $extcmd{$msg->{msgtype}}) { 478 if (my $cb = $extcmd{$msg->{msgtype}}) {
318 if (my %reply = $cb->[0]->($pl, $msg)) { 479 if (my %reply = $cb->[0]->($pl, $msg)) {
319 $pl->ext_reply ($msg->{msgid}, %reply); 480 $pl->ext_reply ($msg->{msgid}, %reply);
481 }
320 } 482 }
483 } else {
484 warn "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n";
321 } 485 }
322 } else { 486
323 warn "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n"; 487 cf::override;
324 } 488 },
325 489;
326 1
327}
328 490
329############################################################################# 491#############################################################################
330# load/save/clean perl data associated with a map 492# load/save/clean perl data associated with a map
331 493
332*on_mapclean = sub { 494*cf::mapsupport::on_clean = sub {
333 my ($map) = @_; 495 my ($map) = @_;
334 496
335 my $path = $map->tmpname; 497 my $path = $map->tmpname;
336 defined $path or return; 498 defined $path or return;
337 499
338 unlink "$path.cfperl"; 500 unlink "$path.cfperl";
339}; 501};
340 502
341*on_mapin = 503*cf::mapsupport::on_swapin =
342*on_mapload = sub { 504*cf::mapsupport::on_load = sub {
343 my ($map) = @_; 505 my ($map) = @_;
344 506
345 my $path = $map->tmpname; 507 my $path = $map->tmpname;
346 $path = $map->path unless defined $path; 508 $path = $map->path unless defined $path;
347 509
354 or return; # too new 516 or return; # too new
355 517
356 $map->_set_obs ($data->{obs}); 518 $map->_set_obs ($data->{obs});
357}; 519};
358 520
359*on_mapout = sub { 521*cf::mapsupport::on_swapout = sub {
360 my ($map) = @_; 522 my ($map) = @_;
361 523
362 my $path = $map->tmpname; 524 my $path = $map->tmpname;
363 $path = $map->path unless defined $path; 525 $path = $map->path unless defined $path;
364 526
381 } else { 543 } else {
382 unlink "$path.cfperl"; 544 unlink "$path.cfperl";
383 } 545 }
384}; 546};
385 547
548attach_to_maps prio => -10000, package => cf::mapsupport::;
549
386############################################################################# 550#############################################################################
387# load/save perl data associated with player->ob objects 551# load/save perl data associated with player->ob objects
388 552
389*on_player_load = sub { 553sub all_objects(@) {
554 @_, map all_objects ($_->inv), @_
555}
556
557attach_to_players
558 on_load => sub {
390 my ($ob, $path) = @_; 559 my ($pl, $path) = @_;
391 560
392 for my $o ($ob, $ob->inv) { 561 for my $o (all_objects $pl->ob) {
393 if (my $value = $o->get_ob_key_value ("_perl_data")) { 562 if (my $value = $o->get_ob_key_value ("_perl_data")) {
394 $o->set_ob_key_value ("_perl_data"); 563 $o->set_ob_key_value ("_perl_data");
395 564
396 %$o = %{ Storable::thaw pack "H*", $value }; 565 %$o = %{ Storable::thaw pack "H*", $value };
566 }
397 } 567 }
398 } 568 },
399}; 569 on_save => sub {
400
401*on_player_save = sub {
402 my ($ob, $path) = @_; 570 my ($pl, $path) = @_;
403 571
404 $_->set_ob_key_value (_perl_data => unpack "H*", Storable::nfreeze $_) 572 $_->set_ob_key_value (_perl_data => unpack "H*", Storable::nfreeze $_)
405 for grep %$_, $ob, $ob->inv; 573 for grep %$_, all_objects $pl->ob;
406}; 574 },
575;
407 576
408############################################################################# 577#############################################################################
409# core extensions - in perl 578# core extensions - in perl
410 579
411=item cf::player::exists $login 580=item cf::player::exists $login
457} 626}
458 627
459############################################################################# 628#############################################################################
460# map scripting support 629# map scripting support
461 630
462our $safe = new Safe "ext"; 631our $safe = new Safe "safe";
463our $safe_hole = new Safe::Hole; 632our $safe_hole = new Safe::Hole;
464 633
465$SIG{FPE} = 'IGNORE'; 634$SIG{FPE} = 'IGNORE';
466 635
467$safe->permit_only (Opcode::opset qw(:base_core :base_mem :base_orig :base_math sort time)); 636$safe->permit_only (Opcode::opset qw(:base_core :base_mem :base_orig :base_math sort time));
473 ["cf::object::player" => qw(player)], 642 ["cf::object::player" => qw(player)],
474 ["cf::player" => qw(peaceful)], 643 ["cf::player" => qw(peaceful)],
475) { 644) {
476 no strict 'refs'; 645 no strict 'refs';
477 my ($pkg, @funs) = @$_; 646 my ($pkg, @funs) = @$_;
478 *{"ext::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"}) 647 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"})
479 for @funs; 648 for @funs;
480} 649}
481 650
482sub safe_eval($;@) { 651sub safe_eval($;@) {
483 my ($code, %vars) = @_; 652 my ($code, %vars) = @_;
485 my $qcode = $code; 654 my $qcode = $code;
486 $qcode =~ s/"/‟/g; # not allowed in #line filenames 655 $qcode =~ s/"/‟/g; # not allowed in #line filenames
487 $qcode =~ s/\n/\\n/g; 656 $qcode =~ s/\n/\\n/g;
488 657
489 local $_; 658 local $_;
490 local @ext::cf::_safe_eval_args = values %vars; 659 local @safe::cf::_safe_eval_args = values %vars;
491 660
492 $code = 661 my $eval =
493 "do {\n" 662 "do {\n"
494 . "my (" . (join ",", map "\$$_", keys %vars) . ") = \@cf::_safe_eval_args;\n" 663 . "my (" . (join ",", map "\$$_", keys %vars) . ") = \@cf::_safe_eval_args;\n"
495 . "#line 0 \"{$qcode}\"\n" 664 . "#line 0 \"{$qcode}\"\n"
496 . $code 665 . $code
497 . "\n}" 666 . "\n}"
498 ; 667 ;
499 668
500 sub_generation_inc; 669 sub_generation_inc;
501 my @res = wantarray ? $safe->reval ($code) : scalar $safe->reval ($code); 670 my @res = wantarray ? $safe->reval ($eval) : scalar $safe->reval ($eval);
502 sub_generation_inc; 671 sub_generation_inc;
672
673 if ($@) {
674 warn "$@";
675 warn "while executing safe code '$code'\n";
676 warn "with arguments " . (join " ", %vars) . "\n";
677 }
503 678
504 wantarray ? @res : $res[0] 679 wantarray ? @res : $res[0]
505} 680}
506 681
507sub register_script_function { 682sub register_script_function {
508 my ($fun, $cb) = @_; 683 my ($fun, $cb) = @_;
509 684
510 no strict 'refs'; 685 no strict 'refs';
511 *{"ext::$fun"} = $safe_hole->wrap ($cb); 686 *{"safe::$fun"} = $safe_hole->wrap ($cb);
687}
688
689#############################################################################
690# the server's main()
691
692sub main {
693 Event::loop;
512} 694}
513 695
514############################################################################# 696#############################################################################
515# initialisation 697# initialisation
516 698
518 700
519unshift @INC, $LIBDIR; 701unshift @INC, $LIBDIR;
520 702
521load_extensions; 703load_extensions;
522 704
705$TICK_WATCHER = Event->timer (
706 prio => 1,
707 at => $NEXT_TICK || 1,
708 cb => sub {
709 cf::server_tick; # one server iteration
710
711 my $NOW = Event::time;
712 $NEXT_TICK += $TICK;
713
714 # if we are delayed by four ticks, skip them all
715 $NEXT_TICK = $NOW if $NOW >= $NEXT_TICK + $TICK * 4;
716
717 $TICK_WATCHER->at ($NEXT_TICK);
718 $TICK_WATCHER->start;
719 },
720);
721
5231 7221
524 723

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines