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.93 by root, Thu Dec 21 22:41:35 2006 UTC vs.
Revision 1.105 by root, Sun Dec 31 17:17:23 2006 UTC

1package cf; 1package cf;
2
3use utf8;
4use strict;
2 5
3use Symbol; 6use Symbol;
4use List::Util; 7use List::Util;
5use Storable; 8use Storable;
6use Opcode; 9use Opcode;
7use Safe; 10use Safe;
8use Safe::Hole; 11use Safe::Hole;
9 12
13use Coro 3.3;
14use Coro::Event;
15use Coro::Timer;
16use Coro::Signal;
17use Coro::Semaphore;
18use Coro::AIO;
19
20use Fcntl;
10use IO::AIO (); 21use IO::AIO 2.31 ();
11use YAML::Syck (); 22use YAML::Syck ();
12use Time::HiRes; 23use Time::HiRes;
13use Event; 24
14$Event::Eval = 1; # no idea why this is required, but it is 25use Event; $Event::Eval = 1; # no idea why this is required, but it is
15 26
16# work around bug in YAML::Syck - bad news for perl6, will it be as broken wrt. unicode? 27# work around bug in YAML::Syck - bad news for perl6, will it be as broken wrt. unicode?
17$YAML::Syck::ImplicitUnicode = 1; 28$YAML::Syck::ImplicitUnicode = 1;
18 29
19use strict; 30$Coro::main->prio (2); # run main coroutine ("the server") with very high priority
20 31
21sub WF_AUTOCANCEL () { 1 } # automatically cancel this watcher on reload 32sub WF_AUTOCANCEL () { 1 } # automatically cancel this watcher on reload
22 33
23our %COMMAND = (); 34our %COMMAND = ();
24our %COMMAND_TIME = (); 35our %COMMAND_TIME = ();
25our %EXTCMD = (); 36our %EXTCMD = ();
26 37
27_init_vars;
28
29our @EVENT; 38our @EVENT;
30our $LIBDIR = datadir . "/ext"; 39our $LIBDIR = datadir . "/ext";
31 40
32our $TICK = MAX_TIME * 1e-6; 41our $TICK = MAX_TIME * 1e-6;
33our $TICK_WATCHER; 42our $TICK_WATCHER;
34our $NEXT_TICK; 43our $NEXT_TICK;
44our $NOW;
35 45
36our %CFG; 46our %CFG;
37 47
38our $UPTIME; $UPTIME ||= time; 48our $UPTIME; $UPTIME ||= time;
49our $RUNTIME;
50
51our %MAP; # all maps
52our $LINK_MAP; # the special {link} map
53our $FREEZE;
54
55binmode STDOUT;
56binmode STDERR;
57
58# read virtual server time, if available
59unless ($RUNTIME || !-e cf::localdir . "/runtime") {
60 open my $fh, "<", cf::localdir . "/runtime"
61 or die "unable to read runtime file: $!";
62 $RUNTIME = <$fh> + 0.;
63}
64
65mkdir cf::localdir;
66mkdir cf::localdir . "/" . cf::playerdir;
67mkdir cf::localdir . "/" . cf::tmpdir;
68mkdir cf::localdir . "/" . cf::uniquedir;
69
70our %EXT_CORO;
39 71
40############################################################################# 72#############################################################################
41 73
42=head2 GLOBAL VARIABLES 74=head2 GLOBAL VARIABLES
43 75
44=over 4 76=over 4
45 77
46=item $cf::UPTIME 78=item $cf::UPTIME
47 79
48The timestamp of the server start (so not actually an uptime). 80The timestamp of the server start (so not actually an uptime).
81
82=item $cf::RUNTIME
83
84The time this server has run, starts at 0 and is increased by $cf::TICK on
85every server tick.
49 86
50=item $cf::LIBDIR 87=item $cf::LIBDIR
51 88
52The perl library directory, where extensions and cf-specific modules can 89The perl library directory, where extensions and cf-specific modules can
53be found. It will be added to C<@INC> automatically. 90be found. It will be added to C<@INC> automatically.
91
92=item $cf::NOW
93
94The time of the last (current) server tick.
54 95
55=item $cf::TICK 96=item $cf::TICK
56 97
57The interval between server ticks, in seconds. 98The interval between server ticks, in seconds.
58 99
66=cut 107=cut
67 108
68BEGIN { 109BEGIN {
69 *CORE::GLOBAL::warn = sub { 110 *CORE::GLOBAL::warn = sub {
70 my $msg = join "", @_; 111 my $msg = join "", @_;
112 utf8::encode $msg;
113
71 $msg .= "\n" 114 $msg .= "\n"
72 unless $msg =~ /\n$/; 115 unless $msg =~ /\n$/;
73 116
74 print STDERR "cfperl: $msg";
75 LOG llevError, "cfperl: $msg"; 117 LOG llevError, "cfperl: $msg";
76 }; 118 };
77} 119}
78 120
79@safe::cf::global::ISA = @cf::global::ISA = 'cf::attachable'; 121@safe::cf::global::ISA = @cf::global::ISA = 'cf::attachable';
84@safe::cf::object::player::ISA = @cf::object::player::ISA = 'cf::object'; 126@safe::cf::object::player::ISA = @cf::object::player::ISA = 'cf::object';
85 127
86# we bless all objects into (empty) derived classes to force a method lookup 128# we bless all objects into (empty) derived classes to force a method lookup
87# within the Safe compartment. 129# within the Safe compartment.
88for my $pkg (qw( 130for my $pkg (qw(
89 cf::global 131 cf::global cf::attachable
90 cf::object cf::object::player 132 cf::object cf::object::player
91 cf::client cf::player 133 cf::client cf::player
92 cf::arch cf::living 134 cf::arch cf::living
93 cf::map cf::party cf::region 135 cf::map cf::party cf::region
94)) { 136)) {
132sub to_json($) { 174sub to_json($) {
133 $JSON::Syck::ImplicitUnicode = 0; # work around JSON::Syck bugs 175 $JSON::Syck::ImplicitUnicode = 0; # work around JSON::Syck bugs
134 JSON::Syck::Dump $_[0] 176 JSON::Syck::Dump $_[0]
135} 177}
136 178
179# main coro must never ever "block" except in Event
180# sync_job ensures this by running the job in a coroutine
181# and waiting in Event while the server is otherwise frozen
182sub sync_job(&) {
183 my ($job) = @_;
184
185 my $busy = 1;
186 my @res;
187
188 local $FREEZE = 1;
189
190 my $coro = Coro::async {
191 @res = eval { $job->() };
192 warn $@ if $@;
193 undef $busy;
194 };
195
196 if ($Coro::current == $Coro::main) {
197 $coro->prio (Coro::PRIO_MAX);
198 while ($busy) {
199 Coro::cede_notself;
200 Event::one_event unless Coro::nready;
201 }
202 } else {
203 $coro->join;
204 }
205
206 wantarray ? @res : $res[0]
207}
208
209=item $coro = cf::coro { BLOCK }
210
211Creates and returns a new coro. This coro is automcatially being canceled
212when the extension calling this is being unloaded.
213
214=cut
215
216sub coro(&) {
217 my $cb = shift;
218
219 my $coro; $coro = async {
220 eval {
221 $cb->();
222 };
223 warn $@ if $@;
224 };
225
226 $coro->on_destroy (sub {
227 delete $EXT_CORO{$coro+0};
228 });
229 $EXT_CORO{$coro+0} = $coro;
230
231 $coro
232}
233
137=back 234=back
138 235
139=cut 236=cut
140 237
141############################################################################# 238#############################################################################
142 239
143=head2 ATTACHABLE OBJECTS 240=head2 ATTACHABLE OBJECTS
144 241
145You can define and attach attachments to each "attachable" object in 242Many objects in crossfire are so-called attachable objects. That means you can
146crossfire+ (objects, players, clients, maps and the special "global" 243attach callbacks/event handlers (a collection of which is called an "attachment")
244to it. All such attachable objects support the following methods.
245
147class). In the following description, CLASS can be any of C<global>, 246In the following description, CLASS can be any of C<global>, C<object>
148C<object> C<player>, C<client> or C<map>. 247C<player>, C<client> or C<map> (i.e. the attachable objects in
248crossfire+).
149 249
150=over 4 250=over 4
151 251
252=item $attachable->attach ($attachment, key => $value...)
253
254=item $attachable->detach ($attachment)
255
256Attach/detach a pre-registered attachment to a specific object and give it
257the specified key/value pairs as arguments.
258
259Example, attach a minesweeper attachment to the given object, making it a
26010x10 minesweeper game:
261
262 $obj->attach (minesweeper => width => 10, height => 10);
263
264=item $bool = $attachable->attached ($name)
265
266Checks wether the named attachment is currently attached to the object.
267
268=item cf::CLASS->attach ...
269
270=item cf::CLASS->detach ...
271
272Define an anonymous attachment and attach it to all objects of the given
273CLASS. See the next function for an explanation of its arguments.
274
275You can attach to global events by using the C<cf::global> class.
276
277Example, log all player logins:
278
279 cf::player->attach (
280 on_login => sub {
281 my ($pl) = @_;
282 ...
283 },
284 );
285
286Example, attach to the jeweler skill:
287
288 cf::object->attach (
289 type => cf::SKILL,
290 subtype => cf::SK_JEWELER,
291 on_use_skill => sub {
292 my ($sk, $ob, $part, $dir, $msg) = @_;
293 ...
294 },
295 );
296
152=item cf::CLASS::attachment $name, ... 297=item cf::CLASS::attachment $name, ...
153 298
154Register an attachment by name through which attachable objects can refer 299Register an attachment by C<$name> through which attachable objects of the
155to this attachment. 300given CLASS can refer to this attachment.
156 301
157=item $bool = $attachable->attached ($name) 302Some classes such as crossfire maps and objects can specify attachments
303that are attached at load/instantiate time, thus the need for a name.
158 304
159Checks wether the named attachment is currently attached to the object.
160
161=item $attachable->attach ($attachment, key => $value...)
162
163=item $attachable->detach ($attachment)
164
165Attach/detach a pre-registered attachment either to a specific object
166(C<$attachable>) or all objects of the given class (if C<$attachable> is a
167class in a static method call).
168
169You can attach to global events by using the C<cf::global> class.
170
171These method calls expect any number of the following handler/hook 305These calls expect any number of the following handler/hook descriptions:
172descriptions:
173 306
174=over 4 307=over 4
175 308
176=item prio => $number 309=item prio => $number
177 310
203package and register them. Only handlers for eevents supported by the 336package and register them. Only handlers for eevents supported by the
204object/class are recognised. 337object/class are recognised.
205 338
206=back 339=back
207 340
341Example, define an attachment called "sockpuppet" that calls the given
342event handler when a monster attacks:
343
344 cf::object::attachment sockpuppet =>
345 on_skill_attack => sub {
346 my ($self, $victim) = @_;
347 ...
348 }
349 }
350
351=item $attachable->valid
352
353Just because you have a perl object does not mean that the corresponding
354C-level object still exists. If you try to access an object that has no
355valid C counterpart anymore you get an exception at runtime. This method
356can be used to test for existence of the C object part without causing an
357exception.
358
208=cut 359=cut
209 360
210# the following variables are defined in .xs and must not be re-created 361# the following variables are defined in .xs and must not be re-created
211our @CB_GLOBAL = (); # registry for all global events 362our @CB_GLOBAL = (); # registry for all global events
363our @CB_ATTACHABLE = (); # registry for all attachables
212our @CB_OBJECT = (); # all objects (should not be used except in emergency) 364our @CB_OBJECT = (); # all objects (should not be used except in emergency)
213our @CB_PLAYER = (); 365our @CB_PLAYER = ();
214our @CB_CLIENT = (); 366our @CB_CLIENT = ();
215our @CB_TYPE = (); # registry for type (cf-object class) based events 367our @CB_TYPE = (); # registry for type (cf-object class) based events
216our @CB_MAP = (); 368our @CB_MAP = ();
217 369
218my %attachment; 370my %attachment;
219 371
220sub _attach_cb($$$$) { 372sub _attach_cb($$$$) {
221 my ($registry, $event, $prio, $cb) = @_; 373 my ($registry, $event, $prio, $cb) = @_;
226 378
227 @{$registry->[$event]} = sort 379 @{$registry->[$event]} = sort
228 { $a->[0] cmp $b->[0] } 380 { $a->[0] cmp $b->[0] }
229 @{$registry->[$event] || []}, $cb; 381 @{$registry->[$event] || []}, $cb;
230} 382}
383
384# hack
385my %attachable_klass = map +($_ => 1), KLASS_OBJECT, KLASS_CLIENT, KLASS_PLAYER, KLASS_MAP;
231 386
232# attach handles attaching event callbacks 387# attach handles attaching event callbacks
233# the only thing the caller has to do is pass the correct 388# the only thing the caller has to do is pass the correct
234# registry (== where the callback attaches to). 389# registry (== where the callback attaches to).
235sub _attach { 390sub _attach {
237 392
238 my $object_type; 393 my $object_type;
239 my $prio = 0; 394 my $prio = 0;
240 my %cb_id = map +("on_" . lc $EVENT[$_][0], $_) , grep $EVENT[$_][1] == $klass, 0 .. $#EVENT; 395 my %cb_id = map +("on_" . lc $EVENT[$_][0], $_) , grep $EVENT[$_][1] == $klass, 0 .. $#EVENT;
241 396
397 #TODO: get rid of this hack
398 if ($attachable_klass{$klass}) {
399 %cb_id = (%cb_id, map +("on_" . lc $EVENT[$_][0], $_) , grep $EVENT[$_][1] == KLASS_ATTACHABLE, 0 .. $#EVENT);
400 }
401
242 while (@arg) { 402 while (@arg) {
243 my $type = shift @arg; 403 my $type = shift @arg;
244 404
245 if ($type eq "prio") { 405 if ($type eq "prio") {
246 $prio = shift @arg; 406 $prio = shift @arg;
321 my ($obj, $name) = @_; 481 my ($obj, $name) = @_;
322 482
323 exists $obj->{_attachment}{$name} 483 exists $obj->{_attachment}{$name}
324} 484}
325 485
326for my $klass (qw(GLOBAL OBJECT PLAYER CLIENT MAP)) { 486for my $klass (qw(ATTACHABLE GLOBAL OBJECT PLAYER CLIENT MAP)) {
327 eval "#line " . __LINE__ . " 'cf.pm' 487 eval "#line " . __LINE__ . " 'cf.pm'
328 sub cf::\L$klass\E::_attach_registry { 488 sub cf::\L$klass\E::_attach_registry {
329 (\\\@CB_$klass, KLASS_$klass) 489 (\\\@CB_$klass, KLASS_$klass)
330 } 490 }
331 491
367 } 527 }
368 528
369 0 529 0
370} 530}
371 531
372=item $bool = cf::invoke EVENT_GLOBAL_XXX, ... 532=item $bool = cf::global::invoke (EVENT_CLASS_XXX, ...)
373 533
374=item $bool = $object->invoke (EVENT_OBJECT_XXX, ...)
375
376=item $bool = $player->invoke (EVENT_PLAYER_XXX, ...)
377
378=item $bool = $client->invoke (EVENT_CLIENT_XXX, ...) 534=item $bool = $attachable->invoke (EVENT_CLASS_XXX, ...)
379 535
380=item $bool = $map->invoke (EVENT_MAP_XXX, ...)
381
382Generate a global/object/player/map-specific event with the given arguments. 536Generate an object-specific event with the given arguments.
383 537
384This API is preliminary (most likely, the EVENT_KLASS_xxx prefix will be 538This API is preliminary (most likely, the EVENT_CLASS_xxx prefix will be
385removed in future versions), and there is no public API to access override 539removed in future versions), and there is no public API to access override
386results (if you must, access C<@cf::invoke_results> directly). 540results (if you must, access C<@cf::invoke_results> directly).
387 541
388=back 542=back
389 543
390=cut 544=cut
391 545
392############################################################################# 546#############################################################################
393
394=head2 METHODS VALID FOR ALL ATTACHABLE OBJECTS
395
396Attachable objects includes objects, players, clients and maps.
397
398=over 4
399
400=item $object->valid
401
402Just because you have a perl object does not mean that the corresponding
403C-level object still exists. If you try to access an object that has no
404valid C counterpart anymore you get an exception at runtime. This method
405can be used to test for existence of the C object part without causing an
406exception.
407
408=back
409
410=cut
411
412#############################################################################
413# object support 547# object support
414 548
415sub instantiate {
416 my ($obj, $data) = @_;
417
418 $data = from_json $data;
419
420 for (@$data) {
421 my ($name, $args) = @$_;
422
423 $obj->attach ($name, %{$args || {} });
424 }
425}
426
427# basically do the same as instantiate, without calling instantiate
428sub reattach { 549sub reattach {
550 # basically do the same as instantiate, without calling instantiate
429 my ($obj) = @_; 551 my ($obj) = @_;
552
430 my $registry = $obj->registry; 553 my $registry = $obj->registry;
431 554
432 @$registry = (); 555 @$registry = ();
433 556
434 delete $obj->{_attachment} unless scalar keys %{ $obj->{_attachment} || {} }; 557 delete $obj->{_attachment} unless scalar keys %{ $obj->{_attachment} || {} };
443 warn "object uses attachment '$name' that is not available, postponing.\n"; 566 warn "object uses attachment '$name' that is not available, postponing.\n";
444 } 567 }
445 } 568 }
446} 569}
447 570
448sub object_freezer_save { 571cf::attachable->attach (
449 my ($filename, $rdata, $objs) = @_;
450
451 if (length $$rdata) {
452 warn sprintf "saving %s (%d,%d)\n",
453 $filename, length $$rdata, scalar @$objs;
454
455 if (open my $fh, ">:raw", "$filename~") {
456 chmod SAVE_MODE, $fh;
457 syswrite $fh, $$rdata;
458 close $fh;
459
460 if (@$objs && open my $fh, ">:raw", "$filename.pst~") {
461 chmod SAVE_MODE, $fh;
462 syswrite $fh, Storable::nfreeze { version => 1, objs => $objs };
463 close $fh;
464 rename "$filename.pst~", "$filename.pst";
465 } else {
466 unlink "$filename.pst";
467 }
468
469 rename "$filename~", $filename;
470 } else {
471 warn "FATAL: $filename~: $!\n";
472 }
473 } else {
474 unlink $filename;
475 unlink "$filename.pst";
476 }
477}
478
479sub object_freezer_as_string {
480 my ($rdata, $objs) = @_;
481
482 use Data::Dumper;
483
484 $$rdata . Dumper $objs
485}
486
487sub object_thawer_load {
488 my ($filename) = @_;
489
490 local $/;
491
492 my $av;
493
494 #TODO: use sysread etc.
495 if (open my $data, "<:raw:perlio", $filename) {
496 $data = <$data>;
497 if (open my $pst, "<:raw:perlio", "$filename.pst") {
498 $av = eval { (Storable::thaw <$pst>)->{objs} };
499 }
500 return ($data, $av);
501 }
502
503 ()
504}
505
506cf::object->attach (
507 prio => -1000000, 572 prio => -1000000,
573 on_instantiate => sub {
574 my ($obj, $data) = @_;
575
576 $data = from_json $data;
577
578 for (@$data) {
579 my ($name, $args) = @$_;
580
581 $obj->attach ($name, %{$args || {} });
582 }
583 },
584 on_reattach => \&reattach,
508 on_clone => sub { 585 on_clone => sub {
509 my ($src, $dst) = @_; 586 my ($src, $dst) = @_;
510 587
511 @{$dst->registry} = @{$src->registry}; 588 @{$dst->registry} = @{$src->registry};
512 589
514 591
515 %{$dst->{_attachment}} = %{$src->{_attachment}} 592 %{$dst->{_attachment}} = %{$src->{_attachment}}
516 if exists $src->{_attachment}; 593 if exists $src->{_attachment};
517 }, 594 },
518); 595);
596
597sub object_freezer_save {
598 my ($filename, $rdata, $objs) = @_;
599
600 sync_job {
601 if (length $$rdata) {
602 warn sprintf "saving %s (%d,%d)\n",
603 $filename, length $$rdata, scalar @$objs;
604
605 if (my $fh = aio_open "$filename~", O_WRONLY | O_CREAT, 0600) {
606 chmod SAVE_MODE, $fh;
607 aio_write $fh, 0, (length $$rdata), $$rdata, 0;
608 aio_fsync $fh;
609 close $fh;
610
611 if (@$objs) {
612 if (my $fh = aio_open "$filename.pst~", O_WRONLY | O_CREAT, 0600) {
613 chmod SAVE_MODE, $fh;
614 my $data = Storable::nfreeze { version => 1, objs => $objs };
615 aio_write $fh, 0, (length $data), $data, 0;
616 aio_fsync $fh;
617 close $fh;
618 aio_rename "$filename.pst~", "$filename.pst";
619 }
620 } else {
621 aio_unlink "$filename.pst";
622 }
623
624 aio_rename "$filename~", $filename;
625 } else {
626 warn "FATAL: $filename~: $!\n";
627 }
628 } else {
629 aio_unlink $filename;
630 aio_unlink "$filename.pst";
631 }
632 }
633}
634
635sub object_freezer_as_string {
636 my ($rdata, $objs) = @_;
637
638 use Data::Dumper;
639
640 $$rdata . Dumper $objs
641}
642
643sub object_thawer_load {
644 my ($filename) = @_;
645
646 my ($data, $av);
647
648 (aio_load $filename, $data) >= 0
649 or return;
650
651 unless (aio_stat "$filename.pst") {
652 (aio_load "$filename.pst", $av) >= 0
653 or return;
654 $av = eval { (Storable::thaw <$av>)->{objs} };
655 }
656
657 return ($data, $av);
658}
519 659
520############################################################################# 660#############################################################################
521# command handling &c 661# command handling &c
522 662
523=item cf::register_command $name => \&callback($ob,$args); 663=item cf::register_command $name => \&callback($ob,$args);
712 852
713=head2 CORE EXTENSIONS 853=head2 CORE EXTENSIONS
714 854
715Functions and methods that extend core crossfire objects. 855Functions and methods that extend core crossfire objects.
716 856
857=head3 cf::player
858
717=over 4 859=over 4
718 860
719=item cf::player::exists $login 861=item cf::player::exists $login
720 862
721Returns true when the given account exists. 863Returns true when the given account exists.
725sub cf::player::exists($) { 867sub cf::player::exists($) {
726 cf::player::find $_[0] 868 cf::player::find $_[0]
727 or -f sprintf "%s/%s/%s/%s.pl", cf::localdir, cf::playerdir, ($_[0]) x 2; 869 or -f sprintf "%s/%s/%s/%s.pl", cf::localdir, cf::playerdir, ($_[0]) x 2;
728} 870}
729 871
872=item $player->ext_reply ($msgid, $msgtype, %msg)
873
874Sends an ext reply to the player.
875
876=cut
877
878sub cf::player::ext_reply($$$%) {
879 my ($self, $id, %msg) = @_;
880
881 $msg{msgid} = $id;
882
883 $self->send ("ext " . to_json \%msg);
884}
885
886=back
887
888=head3 cf::object::player
889
890=over 4
891
730=item $player_object->reply ($npc, $msg[, $flags]) 892=item $player_object->reply ($npc, $msg[, $flags])
731 893
732Sends a message to the player, as if the npc C<$npc> replied. C<$npc> 894Sends a message to the player, as if the npc C<$npc> replied. C<$npc>
733can be C<undef>. Does the right thing when the player is currently in a 895can be C<undef>. Does the right thing when the player is currently in a
734dialogue with the given NPC character. 896dialogue with the given NPC character.
735 897
736=cut 898=cut
737 899
738# rough implementation of a future "reply" method that works 900# rough implementation of a future "reply" method that works
739# with dialog boxes. 901# with dialog boxes.
902#TODO: the first argument must go, split into a $npc->reply_to ( method
740sub cf::object::player::reply($$$;$) { 903sub cf::object::player::reply($$$;$) {
741 my ($self, $npc, $msg, $flags) = @_; 904 my ($self, $npc, $msg, $flags) = @_;
742 905
743 $flags = cf::NDI_BROWN | cf::NDI_UNIQUE unless @_ >= 4; 906 $flags = cf::NDI_BROWN | cf::NDI_UNIQUE unless @_ >= 4;
744 907
748 $msg = $npc->name . " says: $msg" if $npc; 911 $msg = $npc->name . " says: $msg" if $npc;
749 $self->message ($msg, $flags); 912 $self->message ($msg, $flags);
750 } 913 }
751} 914}
752 915
753=item $player->ext_reply ($msgid, $msgtype, %msg)
754
755Sends an ext reply to the player.
756
757=cut
758
759sub cf::player::ext_reply($$$%) {
760 my ($self, $id, %msg) = @_;
761
762 $msg{msgid} = $id;
763
764 $self->send ("ext " . to_json \%msg);
765}
766
767=item $player_object->may ("access") 916=item $player_object->may ("access")
768 917
769Returns wether the given player is authorized to access resource "access" 918Returns wether the given player is authorized to access resource "access"
770(e.g. "command_wizcast"). 919(e.g. "command_wizcast").
771 920
778 (ref $cf::CFG{"may_$access"} 927 (ref $cf::CFG{"may_$access"}
779 ? scalar grep $self->name eq $_, @{$cf::CFG{"may_$access"}} 928 ? scalar grep $self->name eq $_, @{$cf::CFG{"may_$access"}}
780 : $cf::CFG{"may_$access"}) 929 : $cf::CFG{"may_$access"})
781} 930}
782 931
783=cut 932=head3 cf::client
784 933
785############################################################################# 934=over 4
935
936=item $client->send_drawinfo ($text, $flags)
937
938Sends a drawinfo packet to the client. Circumvents output buffering so
939should not be used under normal circumstances.
940
941=cut
942
943sub cf::client::send_drawinfo {
944 my ($self, $text, $flags) = @_;
945
946 utf8::encode $text;
947 $self->send_packet (sprintf "drawinfo %d %s", $flags, $text);
948}
949
950
951=item $success = $client->query ($flags, "text", \&cb)
952
953Queues a query to the client, calling the given callback with
954the reply text on a reply. flags can be C<cf::CS_QUERY_YESNO>,
955C<cf::CS_QUERY_SINGLECHAR> or C<cf::CS_QUERY_HIDEINPUT> or C<0>.
956
957Queries can fail, so check the return code. Or don't, as queries will become
958reliable at some point in the future.
959
960=cut
961
962sub cf::client::query {
963 my ($self, $flags, $text, $cb) = @_;
964
965 return unless $self->state == ST_PLAYING
966 || $self->state == ST_SETUP
967 || $self->state == ST_CUSTOM;
968
969 $self->state (ST_CUSTOM);
970
971 utf8::encode $text;
972 push @{ $self->{query_queue} }, [(sprintf "query %d %s", $flags, $text), $cb];
973
974 $self->send_packet ($self->{query_queue}[0][0])
975 if @{ $self->{query_queue} } == 1;
976}
977
978cf::client->attach (
979 on_reply => sub {
980 my ($ns, $msg) = @_;
981
982 # this weird shuffling is so that direct followup queries
983 # get handled first
984 my $queue = delete $ns->{query_queue};
985
986 (shift @$queue)->[1]->($msg);
987
988 push @{ $ns->{query_queue} }, @$queue;
989
990 if (@{ $ns->{query_queue} } == @$queue) {
991 if (@$queue) {
992 $ns->send_packet ($ns->{query_queue}[0][0]);
993 } else {
994 $ns->state (ST_PLAYING) if $ns->state == ST_CUSTOM;
995 }
996 }
997 },
998);
999
1000=item $client->coro (\&cb)
1001
1002Create a new coroutine, running the specified callback. The coroutine will
1003be automatically cancelled when the client gets destroyed (e.g. on logout,
1004or loss of connection).
1005
1006=cut
1007
1008sub cf::client::coro {
1009 my ($self, $cb) = @_;
1010
1011 my $coro; $coro = async {
1012 eval {
1013 $cb->();
1014 };
1015 warn $@ if $@;
1016 };
1017
1018 $coro->on_destroy (sub {
1019 delete $self->{_coro}{$coro+0};
1020 });
1021
1022 $self->{_coro}{$coro+0} = $coro;
1023
1024 $coro
1025}
1026
1027cf::client->attach (
1028 on_destroy => sub {
1029 my ($ns) = @_;
1030
1031 $_->cancel for values %{ (delete $ns->{_coro}) || {} };
1032 },
1033);
1034
1035=back
1036
786 1037
787=head2 SAFE SCRIPTING 1038=head2 SAFE SCRIPTING
788 1039
789Functions that provide a safe environment to compile and execute 1040Functions that provide a safe environment to compile and execute
790snippets of perl code without them endangering the safety of the server 1041snippets of perl code without them endangering the safety of the server
1019} 1270}
1020 1271
1021############################################################################# 1272#############################################################################
1022# initialisation 1273# initialisation
1023 1274
1024sub _perl_reload(&) { 1275sub _perl_reload() {
1025 my ($msg) = @_; 1276 warn "reloading...";
1026
1027 $msg->("reloading...");
1028 1277
1029 eval { 1278 eval {
1279 local $FREEZE = 1;
1280
1281 cf::emergency_save;
1282
1030 # cancel all watchers 1283 # cancel all watchers
1031 for (Event::all_watchers) { 1284 for (Event::all_watchers) {
1032 $_->cancel if $_->data & WF_AUTOCANCEL; 1285 $_->cancel if $_->data & WF_AUTOCANCEL;
1033 } 1286 }
1034 1287
1288 # cancel all extension coros
1289 $_->cancel for values %EXT_CORO;
1290 %EXT_CORO = ();
1291
1035 # unload all extensions 1292 # unload all extensions
1036 for (@exts) { 1293 for (@exts) {
1037 $msg->("unloading <$_>"); 1294 warn "unloading <$_>";
1038 unload_extension $_; 1295 unload_extension $_;
1039 } 1296 }
1040 1297
1041 # unload all modules loaded from $LIBDIR 1298 # unload all modules loaded from $LIBDIR
1042 while (my ($k, $v) = each %INC) { 1299 while (my ($k, $v) = each %INC) {
1043 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/; 1300 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/;
1044 1301
1045 $msg->("removing <$k>"); 1302 warn "removing <$k>";
1046 delete $INC{$k}; 1303 delete $INC{$k};
1047 1304
1048 $k =~ s/\.pm$//; 1305 $k =~ s/\.pm$//;
1049 $k =~ s/\//::/g; 1306 $k =~ s/\//::/g;
1050 1307
1055 Symbol::delete_package $k; 1312 Symbol::delete_package $k;
1056 } 1313 }
1057 1314
1058 # sync database to disk 1315 # sync database to disk
1059 cf::db_sync; 1316 cf::db_sync;
1317 IO::AIO::flush;
1060 1318
1061 # get rid of safe::, as good as possible 1319 # get rid of safe::, as good as possible
1062 Symbol::delete_package "safe::$_" 1320 Symbol::delete_package "safe::$_"
1063 for qw(cf::object cf::object::player cf::player cf::map cf::party cf::region); 1321 for qw(cf::attachable cf::object cf::object::player cf::client cf::player cf::map cf::party cf::region);
1064 1322
1065 # remove register_script_function callbacks 1323 # remove register_script_function callbacks
1066 # TODO 1324 # TODO
1067 1325
1068 # unload cf.pm "a bit" 1326 # unload cf.pm "a bit"
1071 # don't, removes xs symbols, too, 1329 # don't, removes xs symbols, too,
1072 # and global variables created in xs 1330 # and global variables created in xs
1073 #Symbol::delete_package __PACKAGE__; 1331 #Symbol::delete_package __PACKAGE__;
1074 1332
1075 # reload cf.pm 1333 # reload cf.pm
1076 $msg->("reloading cf.pm"); 1334 warn "reloading cf.pm";
1077 require cf; 1335 require cf;
1336 cf::_connect_to_perl; # nominally unnecessary, but cannot hurt
1078 1337
1079 # load config and database again 1338 # load config and database again
1080 cf::cfg_load; 1339 cf::cfg_load;
1081 cf::db_load; 1340 cf::db_load;
1082 1341
1083 # load extensions 1342 # load extensions
1084 $msg->("load extensions"); 1343 warn "load extensions";
1085 cf::load_extensions; 1344 cf::load_extensions;
1086 1345
1087 # reattach attachments to objects 1346 # reattach attachments to objects
1088 $msg->("reattach"); 1347 warn "reattach";
1089 _global_reattach; 1348 _global_reattach;
1090 }; 1349 };
1091 $msg->($@) if $@; 1350 warn $@ if $@;
1092 1351
1093 $msg->("reloaded"); 1352 warn "reloaded";
1094}; 1353};
1095 1354
1096sub perl_reload() { 1355sub perl_reload() {
1097 _perl_reload { 1356 _perl_reload;
1098 warn $_[0];
1099 print "$_[0]\n";
1100 };
1101} 1357}
1102 1358
1103register "<global>", __PACKAGE__; 1359register "<global>", __PACKAGE__;
1104 1360
1105register_command "perl-reload" => sub { 1361register_command "perl-reload" => sub {
1106 my ($who, $arg) = @_; 1362 my ($who, $arg) = @_;
1107 1363
1108 if ($who->flag (FLAG_WIZ)) { 1364 if ($who->flag (FLAG_WIZ)) {
1365 $who->message ("reloading...");
1109 _perl_reload { 1366 _perl_reload;
1110 warn $_[0];
1111 $who->message ($_[0]);
1112 };
1113 } 1367 }
1114}; 1368};
1115 1369
1116unshift @INC, $LIBDIR; 1370unshift @INC, $LIBDIR;
1117 1371
1118$TICK_WATCHER = Event->timer ( 1372$TICK_WATCHER = Event->timer (
1373 reentrant => 0,
1119 prio => 0, 1374 prio => 0,
1120 at => $NEXT_TICK || 1, 1375 at => $NEXT_TICK || $TICK,
1121 data => WF_AUTOCANCEL, 1376 data => WF_AUTOCANCEL,
1122 cb => sub { 1377 cb => sub {
1378 unless ($FREEZE) {
1123 cf::server_tick; # one server iteration 1379 cf::server_tick; # one server iteration
1380 $RUNTIME += $TICK;
1381 }
1124 1382
1125 my $NOW = Event::time;
1126 $NEXT_TICK += $TICK; 1383 $NEXT_TICK += $TICK;
1127 1384
1128 # if we are delayed by four ticks or more, skip them all 1385 # if we are delayed by four ticks or more, skip them all
1129 $NEXT_TICK = $NOW if $NOW >= $NEXT_TICK + $TICK * 4; 1386 $NEXT_TICK = Event::time if Event::time >= $NEXT_TICK + $TICK * 4;
1130 1387
1131 $TICK_WATCHER->at ($NEXT_TICK); 1388 $TICK_WATCHER->at ($NEXT_TICK);
1132 $TICK_WATCHER->start; 1389 $TICK_WATCHER->start;
1133 }, 1390 },
1134); 1391);
1139 poll => 'r', 1396 poll => 'r',
1140 prio => 5, 1397 prio => 5,
1141 data => WF_AUTOCANCEL, 1398 data => WF_AUTOCANCEL,
1142 cb => \&IO::AIO::poll_cb); 1399 cb => \&IO::AIO::poll_cb);
1143 1400
1401# we must not ever block the main coroutine
1402$Coro::idle = sub {
1403 #Carp::cluck "FATAL: Coro::idle was called, major BUG\n";#d#
1404 warn "FATAL: Coro::idle was called, major BUG\n";
1405 (Coro::unblock_sub {
1406 Event::one_event;
1407 })->();
1408};
1409
11441 14101
1145 1411

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines