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.83 by root, Mon Dec 11 01:30:41 2006 UTC vs.
Revision 1.158 by root, Wed Jan 10 19:52:43 2007 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 Data::Dumper;
21use Digest::MD5;
22use Fcntl;
10use IO::AIO (); 23use IO::AIO 2.32 ();
11use YAML::Syck (); 24use YAML::Syck ();
12use Time::HiRes; 25use Time::HiRes;
13use Event; 26
14$Event::Eval = 1; # no idea why this is required, but it is 27use Event; $Event::Eval = 1; # no idea why this is required, but it is
28
29sub WF_AUTOCANCEL () { 1 } # automatically cancel this watcher on reload
15 30
16# work around bug in YAML::Syck - bad news for perl6, will it be as broken wrt. unicode? 31# work around bug in YAML::Syck - bad news for perl6, will it be as broken wrt. unicode?
17$YAML::Syck::ImplicitUnicode = 1; 32$YAML::Syck::ImplicitUnicode = 1;
18 33
19use strict; 34$Coro::main->prio (Coro::PRIO_MAX); # run main coroutine ("the server") with very high priority
20 35
21_init_vars;
22
23our %COMMAND = (); 36our %COMMAND = ();
37our %COMMAND_TIME = ();
38our %EXTCMD = ();
39
24our @EVENT; 40our @EVENT;
25our $LIBDIR = maps_directory "perl"; 41our $LIBDIR = datadir . "/ext";
26 42
27our $TICK = MAX_TIME * 1e-6; 43our $TICK = MAX_TIME * 1e-6;
28our $TICK_WATCHER; 44our $TICK_WATCHER;
29our $NEXT_TICK; 45our $NEXT_TICK;
46our $NOW;
30 47
31our %CFG; 48our %CFG;
32 49
33our $uptime;#d# 50our $UPTIME; $UPTIME ||= time;
34our $UPTIME; 51our $RUNTIME;
35$UPTIME ||= $uptime;#d# 52
36$UPTIME ||= time; 53our %PLAYER; # all users
54our %MAP; # all maps
55our $LINK_MAP; # the special {link} map
56our $RANDOM_MAPS = cf::localdir . "/random";
57our %EXT_CORO; # coroutines bound to extensions
58
59our $WAIT_FOR_TICK; $WAIT_FOR_TICK ||= new Coro::Signal;
60our $WAIT_FOR_TICK_ONE; $WAIT_FOR_TICK_ONE ||= new Coro::Signal;
61
62binmode STDOUT;
63binmode STDERR;
64
65# read virtual server time, if available
66unless ($RUNTIME || !-e cf::localdir . "/runtime") {
67 open my $fh, "<", cf::localdir . "/runtime"
68 or die "unable to read runtime file: $!";
69 $RUNTIME = <$fh> + 0.;
70}
71
72mkdir cf::localdir;
73mkdir cf::localdir . "/" . cf::playerdir;
74mkdir cf::localdir . "/" . cf::tmpdir;
75mkdir cf::localdir . "/" . cf::uniquedir;
76mkdir $RANDOM_MAPS;
77
78# a special map that is always available
79our $LINK_MAP;
80our $EMERGENCY_POSITION;
37 81
38############################################################################# 82#############################################################################
39 83
40=head2 GLOBAL VARIABLES 84=head2 GLOBAL VARIABLES
41 85
42=over 4 86=over 4
43 87
44=item $cf::UPTIME 88=item $cf::UPTIME
45 89
46The timestamp of the server start (so not actually an uptime). 90The timestamp of the server start (so not actually an uptime).
91
92=item $cf::RUNTIME
93
94The time this server has run, starts at 0 and is increased by $cf::TICK on
95every server tick.
47 96
48=item $cf::LIBDIR 97=item $cf::LIBDIR
49 98
50The perl library directory, where extensions and cf-specific modules can 99The perl library directory, where extensions and cf-specific modules can
51be found. It will be added to C<@INC> automatically. 100be found. It will be added to C<@INC> automatically.
52 101
102=item $cf::NOW
103
104The time of the last (current) server tick.
105
53=item $cf::TICK 106=item $cf::TICK
54 107
55The interval between server ticks, in seconds. 108The interval between server ticks, in seconds.
56 109
57=item %cf::CFG 110=item %cf::CFG
58 111
59Configuration for the server, loaded from C</etc/crossfire/config>, or 112Configuration for the server, loaded from C</etc/crossfire/config>, or
60from wherever your confdir points to. 113from wherever your confdir points to.
114
115=item $cf::WAIT_FOR_TICK, $cf::WAIT_FOR_TICK_ONE
116
117These are Coro::Signal objects that are C<< ->broadcast >> (WAIT_FOR_TICK)
118or C<< ->send >> (WAIT_FOR_TICK_ONE) on after normal server tick
119processing has been done. Call C<< ->wait >> on them to maximise the
120window of cpu time available, or simply to synchronise to the server tick.
61 121
62=back 122=back
63 123
64=cut 124=cut
65 125
66BEGIN { 126BEGIN {
67 *CORE::GLOBAL::warn = sub { 127 *CORE::GLOBAL::warn = sub {
68 my $msg = join "", @_; 128 my $msg = join "", @_;
129 utf8::encode $msg;
130
69 $msg .= "\n" 131 $msg .= "\n"
70 unless $msg =~ /\n$/; 132 unless $msg =~ /\n$/;
71 133
72 print STDERR "cfperl: $msg";
73 LOG llevError, "cfperl: $msg"; 134 LOG llevError, $msg;
74 }; 135 };
75} 136}
76 137
138@safe::cf::global::ISA = @cf::global::ISA = 'cf::attachable';
139@safe::cf::object::ISA = @cf::object::ISA = 'cf::attachable';
140@safe::cf::player::ISA = @cf::player::ISA = 'cf::attachable';
141@safe::cf::client::ISA = @cf::client::ISA = 'cf::attachable';
142@safe::cf::map::ISA = @cf::map::ISA = 'cf::attachable';
77@safe::cf::object::player::ISA = @cf::object::player::ISA = 'cf::object'; 143@safe::cf::object::player::ISA = @cf::object::player::ISA = 'cf::object';
78 144
79# we bless all objects into (empty) derived classes to force a method lookup 145# we bless all objects into (empty) derived classes to force a method lookup
80# within the Safe compartment. 146# within the Safe compartment.
81for my $pkg (qw(cf::object cf::object::player cf::player cf::map cf::party cf::region cf::arch cf::living)) { 147for my $pkg (qw(
148 cf::global cf::attachable
149 cf::object cf::object::player
150 cf::client cf::player
151 cf::arch cf::living
152 cf::map cf::party cf::region
153)) {
82 no strict 'refs'; 154 no strict 'refs';
83 @{"safe::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg; 155 @{"safe::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg;
84} 156}
85 157
86$Event::DIED = sub { 158$Event::DIED = sub {
88}; 160};
89 161
90my %ext_pkg; 162my %ext_pkg;
91my @exts; 163my @exts;
92my @hook; 164my @hook;
93my %command;
94my %extcmd;
95 165
96=head2 UTILITY FUNCTIONS 166=head2 UTILITY FUNCTIONS
97 167
98=over 4 168=over 4
99 169
170=item dumpval $ref
171
100=cut 172=cut
173
174sub dumpval {
175 eval {
176 local $SIG{__DIE__};
177 my $d;
178 if (1) {
179 $d = new Data::Dumper([$_[0]], ["*var"]);
180 $d->Terse(1);
181 $d->Indent(2);
182 $d->Quotekeys(0);
183 $d->Useqq(1);
184 #$d->Bless(...);
185 $d->Seen($_[1]) if @_ > 1;
186 $d = $d->Dump();
187 }
188 $d =~ s/([\x00-\x07\x09\x0b\x0c\x0e-\x1f])/sprintf "\\x%02x", ord($1)/ge;
189 $d
190 } || "[unable to dump $_[0]: '$@']";
191}
101 192
102use JSON::Syck (); # TODO# replace by JSON::PC once working 193use JSON::Syck (); # TODO# replace by JSON::PC once working
103 194
104=item $ref = cf::from_json $json 195=item $ref = cf::from_json $json
105 196
121sub to_json($) { 212sub to_json($) {
122 $JSON::Syck::ImplicitUnicode = 0; # work around JSON::Syck bugs 213 $JSON::Syck::ImplicitUnicode = 0; # work around JSON::Syck bugs
123 JSON::Syck::Dump $_[0] 214 JSON::Syck::Dump $_[0]
124} 215}
125 216
217=item cf::lock_wait $string
218
219Wait until the given lock is available. See cf::lock_acquire.
220
221=item my $lock = cf::lock_acquire $string
222
223Wait until the given lock is available and then acquires it and returns
224a Coro::guard object. If the guard object gets destroyed (goes out of scope,
225for example when the coroutine gets canceled), the lock is automatically
226returned.
227
228Lock names should begin with a unique identifier (for example, cf::map::find
229uses map_find and cf::map::load uses map_load).
230
231=cut
232
233our %LOCK;
234
235sub lock_wait($) {
236 my ($key) = @_;
237
238 # wait for lock, if any
239 while ($LOCK{$key}) {
240 push @{ $LOCK{$key} }, $Coro::current;
241 Coro::schedule;
242 }
243}
244
245sub lock_acquire($) {
246 my ($key) = @_;
247
248 # wait, to be sure we are not locked
249 lock_wait $key;
250
251 $LOCK{$key} = [];
252
253 Coro::guard {
254 # wake up all waiters, to be on the safe side
255 $_->ready for @{ delete $LOCK{$key} };
256 }
257}
258
259sub freeze_mainloop {
260 return unless $TICK_WATCHER->is_active;
261
262 my $guard = Coro::guard { $TICK_WATCHER->start };
263 $TICK_WATCHER->stop;
264 $guard
265}
266
267=item cf::async { BLOCK }
268
269Currently the same as Coro::async_pool, meaning you cannot use
270C<on_destroy>, C<join> or other gimmicks on these coroutines. The only
271thing you are allowed to do is call C<prio> on it.
272
273=cut
274
275BEGIN { *async = \&Coro::async_pool }
276
277=item cf::sync_job { BLOCK }
278
279The design of crossfire+ requires that the main coro ($Coro::main) is
280always able to handle events or runnable, as crossfire+ is only partly
281reentrant. Thus "blocking" it by e.g. waiting for I/O is not acceptable.
282
283If it must be done, put the blocking parts into C<sync_job>. This will run
284the given BLOCK in another coroutine while waiting for the result. The
285server will be frozen during this time, so the block should either finish
286fast or be very important.
287
288=cut
289
290sub sync_job(&) {
291 my ($job) = @_;
292
293 if ($Coro::current == $Coro::main) {
294 # this is the main coro, too bad, we have to block
295 # till the operation succeeds, freezing the server :/
296
297 # TODO: use suspend/resume instead
298 # (but this is cancel-safe)
299 my $freeze_guard = freeze_mainloop;
300
301 my $busy = 1;
302 my @res;
303
304 (async {
305 @res = eval { $job->() };
306 warn $@ if $@;
307 undef $busy;
308 })->prio (Coro::PRIO_MAX);
309
310 while ($busy) {
311 Coro::cede or Event::one_event;
312 }
313
314 wantarray ? @res : $res[0]
315 } else {
316 # we are in another coroutine, how wonderful, everything just works
317
318 $job->()
319 }
320}
321
322=item $coro = cf::async_ext { BLOCK }
323
324Like async, but this coro is automcatially being canceled when the
325extension calling this is being unloaded.
326
327=cut
328
329sub async_ext(&) {
330 my $cb = shift;
331
332 my $coro = &Coro::async ($cb);
333
334 $coro->on_destroy (sub {
335 delete $EXT_CORO{$coro+0};
336 });
337 $EXT_CORO{$coro+0} = $coro;
338
339 $coro
340}
341
342sub write_runtime {
343 my $runtime = cf::localdir . "/runtime";
344
345 my $fh = aio_open "$runtime~", O_WRONLY | O_CREAT, 0644
346 or return;
347
348 my $value = $cf::RUNTIME + 1 + 10; # 10 is the runtime save interval, for a monotonic clock
349 (aio_write $fh, 0, (length $value), $value, 0) <= 0
350 and return;
351
352 aio_fsync $fh
353 and return;
354
355 close $fh
356 or return;
357
358 aio_rename "$runtime~", $runtime
359 and return;
360
361 1
362}
363
126=back 364=back
127 365
128=cut 366=cut
129 367
130############################################################################# 368#############################################################################
131 369
132=head2 EVENTS AND OBJECT ATTACHMENTS 370package cf::path;
371
372use overload
373 '""' => \&as_string;
374
375# used to convert map paths into valid unix filenames by repalcing / by ∕
376our $PATH_SEP = "∕"; # U+2215, chosen purely for visual reasons
377
378sub new {
379 my ($class, $path, $base) = @_;
380
381 $path = $path->as_string if ref $path;
382
383 my $self = bless { }, $class;
384
385 # {... are special paths that are not touched
386 # ?xxx/... are special absolute paths
387 # ?random/... random maps
388 # /! non-realised random map exit
389 # /... normal maps
390 # ~/... per-player maps without a specific player (DO NOT USE)
391 # ~user/... per-player map of a specific user
392
393 $path =~ s/$PATH_SEP/\//go;
394
395 if ($path =~ /^{/) {
396 # fine as it is
397 } elsif ($path =~ s{^\?random/}{}) {
398 Coro::AIO::aio_load "$cf::RANDOM_MAPS/$path.meta", my $data;
399 $self->{random} = cf::from_json $data;
400 } else {
401 if ($path =~ s{^~([^/]+)?}{}) {
402 $self->{user_rel} = 1;
403
404 if (defined $1) {
405 $self->{user} = $1;
406 } elsif ($base =~ m{^~([^/]+)/}) {
407 $self->{user} = $1;
408 } else {
409 warn "cannot resolve user-relative path without user <$path,$base>\n";
410 }
411 } elsif ($path =~ /^\//) {
412 # already absolute
413 } else {
414 $base =~ s{[^/]+/?$}{};
415 return $class->new ("$base/$path");
416 }
417
418 for ($path) {
419 redo if s{/\.?/}{/};
420 redo if s{/[^/]+/\.\./}{/};
421 }
422 }
423
424 $self->{path} = $path;
425
426 $self
427}
428
429# the name / primary key / in-game path
430sub as_string {
431 my ($self) = @_;
432
433 $self->{user_rel} ? "~$self->{user}$self->{path}"
434 : $self->{random} ? "?random/$self->{path}"
435 : $self->{path}
436}
437
438# the displayed name, this is a one way mapping
439sub visible_name {
440 my ($self) = @_;
441
442# if (my $rmp = $self->{random}) {
443# # todo: be more intelligent about this
444# "?random/$rmp->{origin_map}+$rmp->{origin_x}+$rmp->{origin_y}/$rmp->{dungeon_level}"
445# } else {
446 $self->as_string
447# }
448}
449
450# escape the /'s in the path
451sub _escaped_path {
452 (my $path = $_[0]{path}) =~ s/\//$PATH_SEP/g;
453 $path
454}
455
456# the original (read-only) location
457sub load_path {
458 my ($self) = @_;
459
460 sprintf "%s/%s/%s", cf::datadir, cf::mapdir, $self->{path}
461}
462
463# the temporary/swap location
464sub save_path {
465 my ($self) = @_;
466
467 $self->{user_rel} ? sprintf "%s/%s/%s/%s", cf::localdir, cf::playerdir, $self->{user}, $self->_escaped_path
468 : $self->{random} ? sprintf "%s/%s", $RANDOM_MAPS, $self->{path}
469 : sprintf "%s/%s/%s", cf::localdir, cf::tmpdir, $self->_escaped_path
470}
471
472# the unique path, might be eq to save_path
473sub uniq_path {
474 my ($self) = @_;
475
476 $self->{user_rel} || $self->{random}
477 ? undef
478 : sprintf "%s/%s/%s", cf::localdir, cf::uniquedir, $self->_escaped_path
479}
480
481# return random map parameters, or undef
482sub random_map_params {
483 my ($self) = @_;
484
485 $self->{random}
486}
487
488# this is somewhat ugly, but style maps do need special treatment
489sub is_style_map {
490 $_[0]{path} =~ m{^/styles/}
491}
492
493package cf;
494
495#############################################################################
496
497=head2 ATTACHABLE OBJECTS
498
499Many objects in crossfire are so-called attachable objects. That means you can
500attach callbacks/event handlers (a collection of which is called an "attachment")
501to it. All such attachable objects support the following methods.
502
503In the following description, CLASS can be any of C<global>, C<object>
504C<player>, C<client> or C<map> (i.e. the attachable objects in
505crossfire+).
133 506
134=over 4 507=over 4
135 508
136=item $object->attach ($attachment, key => $value...)
137
138=item $object->detach ($attachment)
139
140Attach/detach a pre-registered attachment to an object.
141
142=item $player->attach ($attachment, key => $value...)
143
144=item $player->detach ($attachment)
145
146Attach/detach a pre-registered attachment to a player.
147
148=item $map->attach ($attachment, key => $value...) 509=item $attachable->attach ($attachment, key => $value...)
149 510
150=item $map->detach ($attachment) 511=item $attachable->detach ($attachment)
151 512
152Attach/detach a pre-registered attachment to a map. 513Attach/detach a pre-registered attachment to a specific object and give it
514the specified key/value pairs as arguments.
153 515
154=item $bool = $object->attached ($name) 516Example, attach a minesweeper attachment to the given object, making it a
51710x10 minesweeper game:
155 518
156=item $bool = $player->attached ($name) 519 $obj->attach (minesweeper => width => 10, height => 10);
157 520
158=item $bool = $map->attached ($name) 521=item $bool = $attachable->attached ($name)
159 522
160Checks wether the named attachment is currently attached to the object. 523Checks wether the named attachment is currently attached to the object.
161 524
162=item cf::attach_global ... 525=item cf::CLASS->attach ...
163 526
164Attach handlers for global events. 527=item cf::CLASS->detach ...
165 528
166This and all following C<attach_*>-functions expect any number of the 529Define an anonymous attachment and attach it to all objects of the given
167following handler/hook descriptions: 530CLASS. See the next function for an explanation of its arguments.
531
532You can attach to global events by using the C<cf::global> class.
533
534Example, log all player logins:
535
536 cf::player->attach (
537 on_login => sub {
538 my ($pl) = @_;
539 ...
540 },
541 );
542
543Example, attach to the jeweler skill:
544
545 cf::object->attach (
546 type => cf::SKILL,
547 subtype => cf::SK_JEWELER,
548 on_use_skill => sub {
549 my ($sk, $ob, $part, $dir, $msg) = @_;
550 ...
551 },
552 );
553
554=item cf::CLASS::attachment $name, ...
555
556Register an attachment by C<$name> through which attachable objects of the
557given CLASS can refer to this attachment.
558
559Some classes such as crossfire maps and objects can specify attachments
560that are attached at load/instantiate time, thus the need for a name.
561
562These calls expect any number of the following handler/hook descriptions:
168 563
169=over 4 564=over 4
170 565
171=item prio => $number 566=item prio => $number
172 567
174by another C<prio> setting). Lower priority handlers get executed 569by another C<prio> setting). Lower priority handlers get executed
175earlier. The default priority is C<0>, and many built-in handlers are 570earlier. The default priority is C<0>, and many built-in handlers are
176registered at priority C<-1000>, so lower priorities should not be used 571registered at priority C<-1000>, so lower priorities should not be used
177unless you know what you are doing. 572unless you know what you are doing.
178 573
574=item type => $type
575
576(Only for C<< cf::object->attach >> calls), limits the attachment to the
577given type of objects only (the additional parameter C<subtype> can be
578used to further limit to the given subtype).
579
179=item on_I<event> => \&cb 580=item on_I<event> => \&cb
180 581
181Call the given code reference whenever the named event happens (event is 582Call the given code reference whenever the named event happens (event is
182something like C<instantiate>, C<apply>, C<use_skill> and so on, and which 583something like C<instantiate>, C<apply>, C<use_skill> and so on, and which
183handlers are recognised generally depends on the type of object these 584handlers are recognised generally depends on the type of object these
192package and register them. Only handlers for eevents supported by the 593package and register them. Only handlers for eevents supported by the
193object/class are recognised. 594object/class are recognised.
194 595
195=back 596=back
196 597
197=item cf::attach_to_type $object_type, $subtype, ... 598Example, define an attachment called "sockpuppet" that calls the given
599event handler when a monster attacks:
198 600
199Attach handlers for a specific object type (e.g. TRANSPORT) and 601 cf::object::attachment sockpuppet =>
200subtype. If C<$subtype> is zero or undef, matches all objects of the given 602 on_skill_attack => sub {
201type. 603 my ($self, $victim) = @_;
202 604 ...
203=item cf::attach_to_objects ...
204
205Attach handlers to all objects. Do not use this except for debugging or
206very rare events, as handlers are (obviously) called for I<all> objects in
207the game.
208
209=item cf::attach_to_players ...
210
211Attach handlers to all players.
212
213=item cf::attach_to_maps ...
214
215Attach handlers to all maps.
216
217=item cf:register_attachment $name, ...
218
219Register an attachment by name through which objects can refer to this
220attachment.
221
222=item cf:register_player_attachment $name, ...
223
224Register an attachment by name through which players can refer to this
225attachment.
226
227=item cf:register_map_attachment $name, ...
228
229Register an attachment by name through which maps can refer to this
230attachment.
231
232=cut
233
234# the following variables are defined in .xs and must not be re-created
235our @CB_GLOBAL = (); # registry for all global events
236our @CB_OBJECT = (); # all objects (should not be used except in emergency)
237our @CB_PLAYER = ();
238our @CB_TYPE = (); # registry for type (cf-object class) based events
239our @CB_MAP = ();
240
241my %attachment;
242
243sub _attach_cb($\%$$$) {
244 my ($registry, $undo, $event, $prio, $cb) = @_;
245
246 use sort 'stable';
247
248 $cb = [$prio, $cb];
249
250 @{$registry->[$event]} = sort
251 { $a->[0] cmp $b->[0] }
252 @{$registry->[$event] || []}, $cb;
253
254 push @{$undo->{cb}}, [$event, $cb];
255}
256
257# attach handles attaching event callbacks
258# the only thing the caller has to do is pass the correct
259# registry (== where the callback attaches to).
260sub _attach(\@$@) {
261 my ($registry, $klass, @arg) = @_;
262
263 my $prio = 0;
264
265 my %undo = (
266 registry => $registry,
267 cb => [],
268 );
269
270 my %cb_id = map +("on_" . lc $EVENT[$_][0], $_) , grep $EVENT[$_][1] == $klass, 0 .. $#EVENT;
271
272 while (@arg) {
273 my $type = shift @arg;
274
275 if ($type eq "prio") {
276 $prio = shift @arg;
277
278 } elsif ($type eq "package") {
279 my $pkg = shift @arg;
280
281 while (my ($name, $id) = each %cb_id) {
282 if (my $cb = $pkg->can ($name)) {
283 _attach_cb $registry, %undo, $id, $prio, $cb;
284 }
285 } 605 }
286
287 } elsif (exists $cb_id{$type}) {
288 _attach_cb $registry, %undo, $cb_id{$type}, $prio, shift @arg;
289
290 } elsif (ref $type) {
291 warn "attaching objects not supported, ignoring.\n";
292
293 } else {
294 shift @arg;
295 warn "attach argument '$type' not supported, ignoring.\n";
296 }
297 }
298
299 \%undo
300}
301
302sub _attach_attachment {
303 my ($obj, $name, %arg) = @_;
304
305 return if exists $obj->{_attachment}{$name};
306
307 my $res;
308
309 if (my $attach = $attachment{$name}) {
310 my $registry = $obj->registry;
311
312 for (@$attach) {
313 my ($klass, @attach) = @$_;
314 $res = _attach @$registry, $klass, @attach;
315 }
316
317 $obj->{$name} = \%arg;
318 } else {
319 warn "object uses attachment '$name' that is not available, postponing.\n";
320 }
321
322 $obj->{_attachment}{$name} = undef;
323
324 $res->{attachment} = $name;
325 $res
326}
327
328*cf::object::attach =
329*cf::player::attach =
330*cf::map::attach = sub {
331 my ($obj, $name, %arg) = @_;
332
333 _attach_attachment $obj, $name, %arg;
334};
335
336# all those should be optimised
337*cf::object::detach =
338*cf::player::detach =
339*cf::map::detach = sub {
340 my ($obj, $name) = @_;
341
342 delete $obj->{_attachment}{$name};
343 reattach ($obj);
344};
345
346*cf::object::attached =
347*cf::player::attached =
348*cf::map::attached = sub {
349 my ($obj, $name) = @_;
350
351 exists $obj->{_attachment}{$name}
352};
353
354sub attach_global {
355 _attach @CB_GLOBAL, KLASS_GLOBAL, @_
356}
357
358sub attach_to_type {
359 my $type = shift;
360 my $subtype = shift;
361
362 _attach @{$CB_TYPE[$type + $subtype * NUM_SUBTYPES]}, KLASS_OBJECT, @_
363}
364
365sub attach_to_objects {
366 _attach @CB_OBJECT, KLASS_OBJECT, @_
367}
368
369sub attach_to_players {
370 _attach @CB_PLAYER, KLASS_PLAYER, @_
371}
372
373sub attach_to_maps {
374 _attach @CB_MAP, KLASS_MAP, @_
375}
376
377sub register_attachment {
378 my $name = shift;
379
380 $attachment{$name} = [[KLASS_OBJECT, @_]];
381}
382
383sub register_player_attachment {
384 my $name = shift;
385
386 $attachment{$name} = [[KLASS_PLAYER, @_]];
387}
388
389sub register_map_attachment {
390 my $name = shift;
391
392 $attachment{$name} = [[KLASS_MAP, @_]];
393}
394
395our $override;
396our @invoke_results = (); # referenced from .xs code. TODO: play tricks with reify and mortals?
397
398sub override {
399 $override = 1;
400 @invoke_results = ();
401}
402
403sub do_invoke {
404 my $event = shift;
405 my $callbacks = shift;
406
407 @invoke_results = ();
408
409 local $override;
410
411 for (@$callbacks) {
412 eval { &{$_->[1]} };
413
414 if ($@) {
415 warn "$@";
416 warn "... while processing $EVENT[$event][0](@_) event, skipping processing altogether.\n";
417 override;
418 }
419
420 return 1 if $override;
421 }
422
423 0 606 }
424}
425 607
426=item $bool = cf::invoke EVENT_GLOBAL_XXX, ... 608=item $attachable->valid
427
428=item $bool = $object->invoke (EVENT_OBJECT_XXX, ...)
429
430=item $bool = $player->invoke (EVENT_PLAYER_XXX, ...)
431
432=item $bool = $map->invoke (EVENT_MAP_XXX, ...)
433
434Generate a global/object/player/map-specific event with the given arguments.
435
436This API is preliminary (most likely, the EVENT_KLASS_xxx prefix will be
437removed in future versions), and there is no public API to access override
438results (if you must, access C<@cf::invoke_results> directly).
439
440=back
441
442=cut
443
444#############################################################################
445
446=head2 METHODS VALID FOR ALL CORE OBJECTS
447
448=over 4
449
450=item $object->valid, $player->valid, $map->valid
451 609
452Just because you have a perl object does not mean that the corresponding 610Just because you have a perl object does not mean that the corresponding
453C-level object still exists. If you try to access an object that has no 611C-level object still exists. If you try to access an object that has no
454valid C counterpart anymore you get an exception at runtime. This method 612valid C counterpart anymore you get an exception at runtime. This method
455can be used to test for existence of the C object part without causing an 613can be used to test for existence of the C object part without causing an
456exception. 614exception.
457 615
616=cut
617
618# the following variables are defined in .xs and must not be re-created
619our @CB_GLOBAL = (); # registry for all global events
620our @CB_ATTACHABLE = (); # registry for all attachables
621our @CB_OBJECT = (); # all objects (should not be used except in emergency)
622our @CB_PLAYER = ();
623our @CB_CLIENT = ();
624our @CB_TYPE = (); # registry for type (cf-object class) based events
625our @CB_MAP = ();
626
627my %attachment;
628
629sub _attach_cb($$$$) {
630 my ($registry, $event, $prio, $cb) = @_;
631
632 use sort 'stable';
633
634 $cb = [$prio, $cb];
635
636 @{$registry->[$event]} = sort
637 { $a->[0] cmp $b->[0] }
638 @{$registry->[$event] || []}, $cb;
639}
640
641# hack
642my %attachable_klass = map +($_ => 1), KLASS_OBJECT, KLASS_CLIENT, KLASS_PLAYER, KLASS_MAP;
643
644# attach handles attaching event callbacks
645# the only thing the caller has to do is pass the correct
646# registry (== where the callback attaches to).
647sub _attach {
648 my ($registry, $klass, @arg) = @_;
649
650 my $object_type;
651 my $prio = 0;
652 my %cb_id = map +("on_" . lc $EVENT[$_][0], $_) , grep $EVENT[$_][1] == $klass, 0 .. $#EVENT;
653
654 #TODO: get rid of this hack
655 if ($attachable_klass{$klass}) {
656 %cb_id = (%cb_id, map +("on_" . lc $EVENT[$_][0], $_) , grep $EVENT[$_][1] == KLASS_ATTACHABLE, 0 .. $#EVENT);
657 }
658
659 while (@arg) {
660 my $type = shift @arg;
661
662 if ($type eq "prio") {
663 $prio = shift @arg;
664
665 } elsif ($type eq "type") {
666 $object_type = shift @arg;
667 $registry = $CB_TYPE[$object_type] ||= [];
668
669 } elsif ($type eq "subtype") {
670 defined $object_type or Carp::croak "subtype specified without type";
671 my $object_subtype = shift @arg;
672 $registry = $CB_TYPE[$object_type + $object_subtype * NUM_SUBTYPES] ||= [];
673
674 } elsif ($type eq "package") {
675 my $pkg = shift @arg;
676
677 while (my ($name, $id) = each %cb_id) {
678 if (my $cb = $pkg->can ($name)) {
679 _attach_cb $registry, $id, $prio, $cb;
680 }
681 }
682
683 } elsif (exists $cb_id{$type}) {
684 _attach_cb $registry, $cb_id{$type}, $prio, shift @arg;
685
686 } elsif (ref $type) {
687 warn "attaching objects not supported, ignoring.\n";
688
689 } else {
690 shift @arg;
691 warn "attach argument '$type' not supported, ignoring.\n";
692 }
693 }
694}
695
696sub _object_attach {
697 my ($obj, $name, %arg) = @_;
698
699 return if exists $obj->{_attachment}{$name};
700
701 if (my $attach = $attachment{$name}) {
702 my $registry = $obj->registry;
703
704 for (@$attach) {
705 my ($klass, @attach) = @$_;
706 _attach $registry, $klass, @attach;
707 }
708
709 $obj->{$name} = \%arg;
710 } else {
711 warn "object uses attachment '$name' that is not available, postponing.\n";
712 }
713
714 $obj->{_attachment}{$name} = undef;
715}
716
717sub cf::attachable::attach {
718 if (ref $_[0]) {
719 _object_attach @_;
720 } else {
721 _attach shift->_attach_registry, @_;
722 }
723};
724
725# all those should be optimised
726sub cf::attachable::detach {
727 my ($obj, $name) = @_;
728
729 if (ref $obj) {
730 delete $obj->{_attachment}{$name};
731 reattach ($obj);
732 } else {
733 Carp::croak "cannot, currently, detach class attachments";
734 }
735};
736
737sub cf::attachable::attached {
738 my ($obj, $name) = @_;
739
740 exists $obj->{_attachment}{$name}
741}
742
743for my $klass (qw(ATTACHABLE GLOBAL OBJECT PLAYER CLIENT MAP)) {
744 eval "#line " . __LINE__ . " 'cf.pm'
745 sub cf::\L$klass\E::_attach_registry {
746 (\\\@CB_$klass, KLASS_$klass)
747 }
748
749 sub cf::\L$klass\E::attachment {
750 my \$name = shift;
751
752 \$attachment{\$name} = [[KLASS_$klass, \@_]];
753 }
754 ";
755 die if $@;
756}
757
758our $override;
759our @invoke_results = (); # referenced from .xs code. TODO: play tricks with reify and mortals?
760
761sub override {
762 $override = 1;
763 @invoke_results = ();
764}
765
766sub do_invoke {
767 my $event = shift;
768 my $callbacks = shift;
769
770 @invoke_results = ();
771
772 local $override;
773
774 for (@$callbacks) {
775 eval { &{$_->[1]} };
776
777 if ($@) {
778 warn "$@";
779 warn "... while processing $EVENT[$event][0](@_) event, skipping processing altogether.\n";
780 override;
781 }
782
783 return 1 if $override;
784 }
785
786 0
787}
788
789=item $bool = cf::global::invoke (EVENT_CLASS_XXX, ...)
790
791=item $bool = $attachable->invoke (EVENT_CLASS_XXX, ...)
792
793Generate an object-specific event with the given arguments.
794
795This API is preliminary (most likely, the EVENT_CLASS_xxx prefix will be
796removed in future versions), and there is no public API to access override
797results (if you must, access C<@cf::invoke_results> directly).
798
458=back 799=back
459 800
460=cut 801=cut
461
462*cf::object::valid =
463*cf::player::valid =
464*cf::map::valid = \&cf::_valid;
465 802
466############################################################################# 803#############################################################################
467# object support 804# object support
468 805
469sub instantiate {
470 my ($obj, $data) = @_;
471
472 $data = from_json $data;
473
474 for (@$data) {
475 my ($name, $args) = @$_;
476
477 $obj->attach ($name, %{$args || {} });
478 }
479}
480
481# basically do the same as instantiate, without calling instantiate
482sub reattach { 806sub reattach {
807 # basically do the same as instantiate, without calling instantiate
483 my ($obj) = @_; 808 my ($obj) = @_;
809
484 my $registry = $obj->registry; 810 my $registry = $obj->registry;
485 811
486 @$registry = (); 812 @$registry = ();
487 813
488 delete $obj->{_attachment} unless scalar keys %{ $obj->{_attachment} || {} }; 814 delete $obj->{_attachment} unless scalar keys %{ $obj->{_attachment} || {} };
489 815
490 for my $name (keys %{ $obj->{_attachment} || {} }) { 816 for my $name (keys %{ $obj->{_attachment} || {} }) {
491 if (my $attach = $attachment{$name}) { 817 if (my $attach = $attachment{$name}) {
492 for (@$attach) { 818 for (@$attach) {
493 my ($klass, @attach) = @$_; 819 my ($klass, @attach) = @$_;
494 _attach @$registry, $klass, @attach; 820 _attach $registry, $klass, @attach;
495 } 821 }
496 } else { 822 } else {
497 warn "object uses attachment '$name' that is not available, postponing.\n"; 823 warn "object uses attachment '$name' that is not available, postponing.\n";
498 } 824 }
499 } 825 }
500} 826}
501 827
502sub object_freezer_save { 828cf::attachable->attach (
503 my ($filename, $rdata, $objs) = @_;
504
505 if (length $$rdata) {
506 warn sprintf "saving %s (%d,%d)\n",
507 $filename, length $$rdata, scalar @$objs;
508
509 if (open my $fh, ">:raw", "$filename~") {
510 chmod SAVE_MODE, $fh;
511 syswrite $fh, $$rdata;
512 close $fh;
513
514 if (@$objs && open my $fh, ">:raw", "$filename.pst~") {
515 chmod SAVE_MODE, $fh;
516 syswrite $fh, Storable::nfreeze { version => 1, objs => $objs };
517 close $fh;
518 rename "$filename.pst~", "$filename.pst";
519 } else {
520 unlink "$filename.pst";
521 }
522
523 rename "$filename~", $filename;
524 } else {
525 warn "FATAL: $filename~: $!\n";
526 }
527 } else {
528 unlink $filename;
529 unlink "$filename.pst";
530 }
531}
532
533sub object_freezer_as_string {
534 my ($rdata, $objs) = @_;
535
536 use Data::Dumper;
537
538 $$rdata . Dumper $objs
539}
540
541sub object_thawer_load {
542 my ($filename) = @_;
543
544 local $/;
545
546 my $av;
547
548 #TODO: use sysread etc.
549 if (open my $data, "<:raw:perlio", $filename) {
550 $data = <$data>;
551 if (open my $pst, "<:raw:perlio", "$filename.pst") {
552 $av = eval { (Storable::thaw <$pst>)->{objs} };
553 }
554 return ($data, $av);
555 }
556
557 ()
558}
559
560attach_to_objects
561 prio => -1000000, 829 prio => -1000000,
830 on_instantiate => sub {
831 my ($obj, $data) = @_;
832
833 $data = from_json $data;
834
835 for (@$data) {
836 my ($name, $args) = @$_;
837
838 $obj->attach ($name, %{$args || {} });
839 }
840 },
841 on_reattach => \&reattach,
562 on_clone => sub { 842 on_clone => sub {
563 my ($src, $dst) = @_; 843 my ($src, $dst) = @_;
564 844
565 @{$dst->registry} = @{$src->registry}; 845 @{$dst->registry} = @{$src->registry};
566 846
567 %$dst = %$src; 847 %$dst = %$src;
568 848
569 %{$dst->{_attachment}} = %{$src->{_attachment}} 849 %{$dst->{_attachment}} = %{$src->{_attachment}}
570 if exists $src->{_attachment}; 850 if exists $src->{_attachment};
571 }, 851 },
572; 852);
853
854sub object_freezer_save {
855 my ($filename, $rdata, $objs) = @_;
856
857 sync_job {
858 if (length $$rdata) {
859 warn sprintf "saving %s (%d,%d)\n",
860 $filename, length $$rdata, scalar @$objs;
861
862 if (my $fh = aio_open "$filename~", O_WRONLY | O_CREAT, 0600) {
863 chmod SAVE_MODE, $fh;
864 aio_write $fh, 0, (length $$rdata), $$rdata, 0;
865 aio_fsync $fh;
866 close $fh;
867
868 if (@$objs) {
869 if (my $fh = aio_open "$filename.pst~", O_WRONLY | O_CREAT, 0600) {
870 chmod SAVE_MODE, $fh;
871 my $data = Storable::nfreeze { version => 1, objs => $objs };
872 aio_write $fh, 0, (length $data), $data, 0;
873 aio_fsync $fh;
874 close $fh;
875 aio_rename "$filename.pst~", "$filename.pst";
876 }
877 } else {
878 aio_unlink "$filename.pst";
879 }
880
881 aio_rename "$filename~", $filename;
882 } else {
883 warn "FATAL: $filename~: $!\n";
884 }
885 } else {
886 aio_unlink $filename;
887 aio_unlink "$filename.pst";
888 }
889 }
890}
891
892sub object_freezer_as_string {
893 my ($rdata, $objs) = @_;
894
895 use Data::Dumper;
896
897 $$rdata . Dumper $objs
898}
899
900sub object_thawer_load {
901 my ($filename) = @_;
902
903 my ($data, $av);
904
905 (aio_load $filename, $data) >= 0
906 or return;
907
908 unless (aio_stat "$filename.pst") {
909 (aio_load "$filename.pst", $av) >= 0
910 or return;
911 $av = eval { (Storable::thaw $av)->{objs} };
912 }
913
914 warn sprintf "loading %s (%d)\n",
915 $filename, length $data, scalar @{$av || []};#d#
916 return ($data, $av);
917}
573 918
574############################################################################# 919#############################################################################
575# old plug-in events 920# command handling &c
576 921
577sub inject_event { 922=item cf::register_command $name => \&callback($ob,$args);
578 my $extension = shift;
579 my $event_code = shift;
580 923
581 my $cb = $hook[$event_code]{$extension} 924Register a callback for execution when the client sends the user command
582 or return; 925$name.
583 926
584 &$cb 927=cut
585}
586
587sub inject_global_event {
588 my $event = shift;
589
590 my $cb = $hook[$event]
591 or return;
592
593 List::Util::max map &$_, values %$cb
594}
595
596sub inject_command {
597 my ($name, $obj, $params) = @_;
598
599 for my $cmd (@{ $command{$name} }) {
600 $cmd->[1]->($obj, $params);
601 }
602
603 -1
604}
605 928
606sub register_command { 929sub register_command {
607 my ($name, $time, $cb) = @_; 930 my ($name, $cb) = @_;
608 931
609 my $caller = caller; 932 my $caller = caller;
610 #warn "registering command '$name/$time' to '$caller'"; 933 #warn "registering command '$name/$time' to '$caller'";
611 934
612 push @{ $command{$name} }, [$time, $cb, $caller]; 935 push @{ $COMMAND{$name} }, [$caller, $cb];
613 $COMMAND{"$name\000"} = List::Util::max map $_->[0], @{ $command{$name} };
614} 936}
937
938=item cf::register_extcmd $name => \&callback($pl,$packet);
939
940Register a callbackf ro execution when the client sends an extcmd packet.
941
942If the callback returns something, it is sent back as if reply was being
943called.
944
945=cut
615 946
616sub register_extcmd { 947sub register_extcmd {
617 my ($name, $cb) = @_; 948 my ($name, $cb) = @_;
618 949
619 my $caller = caller; 950 my $caller = caller;
620 #warn "registering extcmd '$name' to '$caller'"; 951 #warn "registering extcmd '$name' to '$caller'";
621 952
622 $extcmd{$name} = [$cb, $caller]; 953 $EXTCMD{$name} = [$cb, $caller];
623} 954}
955
956cf::player->attach (
957 on_command => sub {
958 my ($pl, $name, $params) = @_;
959
960 my $cb = $COMMAND{$name}
961 or return;
962
963 for my $cmd (@$cb) {
964 $cmd->[1]->($pl->ob, $params);
965 }
966
967 cf::override;
968 },
969 on_extcmd => sub {
970 my ($pl, $buf) = @_;
971
972 my $msg = eval { from_json $buf };
973
974 if (ref $msg) {
975 if (my $cb = $EXTCMD{$msg->{msgtype}}) {
976 if (my %reply = $cb->[0]->($pl, $msg)) {
977 $pl->ext_reply ($msg->{msgid}, %reply);
978 }
979 }
980 } else {
981 warn "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n";
982 }
983
984 cf::override;
985 },
986);
624 987
625sub register { 988sub register {
626 my ($base, $pkg) = @_; 989 my ($base, $pkg) = @_;
627 990
628 #TODO 991 #TODO
671# for my $idx (0 .. $#PLUGIN_EVENT) { 1034# for my $idx (0 .. $#PLUGIN_EVENT) {
672# delete $hook[$idx]{$pkg}; 1035# delete $hook[$idx]{$pkg};
673# } 1036# }
674 1037
675 # remove commands 1038 # remove commands
676 for my $name (keys %command) { 1039 for my $name (keys %COMMAND) {
677 my @cb = grep $_->[2] ne $pkg, @{ $command{$name} }; 1040 my @cb = grep $_->[0] ne $pkg, @{ $COMMAND{$name} };
678 1041
679 if (@cb) { 1042 if (@cb) {
680 $command{$name} = \@cb; 1043 $COMMAND{$name} = \@cb;
681 $COMMAND{"$name\000"} = List::Util::max map $_->[0], @cb;
682 } else { 1044 } else {
683 delete $command{$name};
684 delete $COMMAND{"$name\000"}; 1045 delete $COMMAND{$name};
685 } 1046 }
686 } 1047 }
687 1048
688 # remove extcmds 1049 # remove extcmds
689 for my $name (grep $extcmd{$_}[1] eq $pkg, keys %extcmd) { 1050 for my $name (grep $EXTCMD{$_}[1] eq $pkg, keys %EXTCMD) {
690 delete $extcmd{$name}; 1051 delete $EXTCMD{$name};
691 } 1052 }
692 1053
693 if (my $cb = $pkg->can ("unload")) { 1054 if (my $cb = $pkg->can ("unload")) {
694 eval { 1055 eval {
695 $cb->($pkg); 1056 $cb->($pkg);
699 1060
700 Symbol::delete_package $pkg; 1061 Symbol::delete_package $pkg;
701} 1062}
702 1063
703sub load_extensions { 1064sub load_extensions {
704 my $LIBDIR = maps_directory "perl";
705
706 for my $ext (<$LIBDIR/*.ext>) { 1065 for my $ext (<$LIBDIR/*.ext>) {
707 next unless -r $ext; 1066 next unless -r $ext;
708 eval { 1067 eval {
709 load_extension $ext; 1068 load_extension $ext;
710 1 1069 1
711 } or warn "$ext not loaded: $@"; 1070 } or warn "$ext not loaded: $@";
712 } 1071 }
713} 1072}
714 1073
715############################################################################# 1074#############################################################################
716# extcmd framework, basically convert ext <msg>
717# into pkg::->on_extcmd_arg1 (...) while shortcutting a few
718
719attach_to_players
720 on_extcmd => sub {
721 my ($pl, $buf) = @_;
722
723 my $msg = eval { from_json $buf };
724
725 if (ref $msg) {
726 if (my $cb = $extcmd{$msg->{msgtype}}) {
727 if (my %reply = $cb->[0]->($pl, $msg)) {
728 $pl->ext_reply ($msg->{msgid}, %reply);
729 }
730 }
731 } else {
732 warn "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n";
733 }
734
735 cf::override;
736 },
737;
738
739#############################################################################
740# load/save/clean perl data associated with a map 1075# load/save/clean perl data associated with a map
741 1076
742*cf::mapsupport::on_clean = sub { 1077*cf::mapsupport::on_clean = sub {
743 my ($map) = @_; 1078 my ($map) = @_;
744 1079
746 defined $path or return; 1081 defined $path or return;
747 1082
748 unlink "$path.pst"; 1083 unlink "$path.pst";
749}; 1084};
750 1085
751attach_to_maps prio => -10000, package => cf::mapsupport::; 1086cf::map->attach (prio => -10000, package => cf::mapsupport::);
752 1087
753############################################################################# 1088#############################################################################
754# load/save perl data associated with player->ob objects
755 1089
756sub all_objects(@) { 1090=head2 CORE EXTENSIONS
757 @_, map all_objects ($_->inv), @_
758}
759 1091
760# TODO: compatibility cruft, remove when no longer needed 1092Functions and methods that extend core crossfire objects.
761attach_to_players 1093
762 on_load => sub { 1094=cut
1095
1096package cf::player;
1097
1098use Coro::AIO;
1099
1100=head3 cf::player
1101
1102=over 4
1103
1104=item cf::player::find $login
1105
1106Returns the given player object, loading it if necessary (might block).
1107
1108=cut
1109
1110sub playerdir($) {
1111 cf::localdir
1112 . "/"
1113 . cf::playerdir
1114 . "/"
1115 . (ref $_[0] ? $_[0]->ob->name : $_[0])
1116}
1117
1118sub path($) {
1119 my $login = ref $_[0] ? $_[0]->ob->name : $_[0];
1120
1121 (playerdir $login) . "/$login.pl"
1122}
1123
1124sub find_active($) {
1125 $cf::PLAYER{$_[0]}
1126 and $cf::PLAYER{$_[0]}->active
1127 and $cf::PLAYER{$_[0]}
1128}
1129
1130sub exists($) {
1131 my ($login) = @_;
1132
1133 $cf::PLAYER{$login}
1134 or cf::sync_job { !aio_stat $login }
1135}
1136
1137sub find($) {
1138 return $cf::PLAYER{$_[0]} || do {
1139 my $login = $_[0];
1140
1141 my $guard = cf::lock_acquire "user_find:$login";
1142
1143 $cf::PLAYER{$_[0]} || do {
1144 my $pl = load_pl path $login
1145 or return;
1146 $cf::PLAYER{$login} = $pl
1147 }
1148 }
1149}
1150
1151sub save($) {
1152 my ($pl) = @_;
1153
1154 return if $pl->{deny_save};
1155
1156 my $path = path $pl;
1157 my $guard = cf::lock_acquire "user_save:$path";
1158
1159 return if $pl->{deny_save};
1160
1161 aio_mkdir playerdir $pl, 0770;
1162 $pl->{last_save} = $cf::RUNTIME;
1163
1164 $pl->save_pl ($path);
1165 Coro::cede;
1166}
1167
1168sub new($) {
1169 my ($login) = @_;
1170
1171 my $self = create;
1172
1173 $self->ob->name ($login);
1174 $self->{deny_save} = 1;
1175
1176 $cf::PLAYER{$login} = $self;
1177
1178 $self
1179}
1180
1181=item $pl->quit_character
1182
1183Nukes the player without looking back. If logged in, the connection will
1184be destroyed. May block for a long time.
1185
1186=cut
1187
1188sub quit_character {
1189 my ($pl) = @_;
1190
1191 $pl->{deny_save} = 1;
1192 $pl->password ("*"); # this should lock out the player until we nuked the dir
1193
1194 $pl->invoke (cf::EVENT_PLAYER_LOGOUT, 1) if $pl->active;
1195 $pl->deactivate;
1196 $pl->invoke (cf::EVENT_PLAYER_QUIT);
1197 $pl->ns->destroy if $pl->ns;
1198
1199 my $path = playerdir $pl;
1200 my $temp = "$path~$cf::RUNTIME~deleting~";
1201 aio_rename $path, $temp;
1202 delete $cf::PLAYER{$pl->ob->name};
1203 $pl->destroy;
1204 IO::AIO::aio_rmtree $temp;
1205}
1206
1207=item cf::player::list_logins
1208
1209Returns am arrayref of all valid playernames in the system, can take a
1210while and may block, so not sync_job-capable, ever.
1211
1212=cut
1213
1214sub list_logins {
1215 my $dirs = aio_readdir cf::localdir . "/" . cf::playerdir
1216 or return [];
1217
1218 my @logins;
1219
1220 for my $login (@$dirs) {
1221 my $fh = aio_open path $login, Fcntl::O_RDONLY, 0 or next;
1222 aio_read $fh, 0, 512, my $buf, 0 or next;
1223 $buf !~ /^password -------------$/m or next; # official not-valid tag
1224
1225 utf8::decode $login;
1226 push @logins, $login;
1227 }
1228
1229 \@logins
1230}
1231
1232=item $player->maps
1233
1234Returns an arrayref of cf::path's of all maps that are private for this
1235player. May block.
1236
1237=cut
1238
1239sub maps($) {
1240 my ($pl) = @_;
1241
1242 my $files = aio_readdir playerdir $pl
1243 or return;
1244
1245 my @paths;
1246
1247 for (@$files) {
1248 utf8::decode $_;
1249 next if /\.(?:pl|pst)$/;
1250 next unless /^$PATH_SEP/o;
1251
1252 push @paths, new cf::path "~" . $pl->ob->name . "/" . $_;
1253 }
1254
1255 \@paths
1256}
1257
1258=item $player->ext_reply ($msgid, $msgtype, %msg)
1259
1260Sends an ext reply to the player.
1261
1262=cut
1263
1264sub ext_reply($$$%) {
1265 my ($self, $id, %msg) = @_;
1266
1267 $msg{msgid} = $id;
1268
1269 $self->send ("ext " . cf::to_json \%msg);
1270}
1271
1272package cf;
1273
1274=back
1275
1276
1277=head3 cf::map
1278
1279=over 4
1280
1281=cut
1282
1283package cf::map;
1284
1285use Fcntl;
1286use Coro::AIO;
1287
1288our $MAX_RESET = 3600;
1289our $DEFAULT_RESET = 3000;
1290
1291sub generate_random_map {
1292 my ($path, $rmp) = @_;
1293
1294 # mit "rum" bekleckern, nicht
1295 cf::map::_create_random_map
1296 $path,
1297 $rmp->{wallstyle}, $rmp->{wall_name}, $rmp->{floorstyle}, $rmp->{monsterstyle},
1298 $rmp->{treasurestyle}, $rmp->{layoutstyle}, $rmp->{doorstyle}, $rmp->{decorstyle},
1299 $rmp->{origin_map}, $rmp->{final_map}, $rmp->{exitstyle}, $rmp->{this_map},
1300 $rmp->{exit_on_final_map},
1301 $rmp->{xsize}, $rmp->{ysize},
1302 $rmp->{expand2x}, $rmp->{layoutoptions1}, $rmp->{layoutoptions2}, $rmp->{layoutoptions3},
1303 $rmp->{symmetry}, $rmp->{difficulty}, $rmp->{difficulty_given}, $rmp->{difficulty_increase},
1304 $rmp->{dungeon_level}, $rmp->{dungeon_depth}, $rmp->{decoroptions}, $rmp->{orientation},
1305 $rmp->{origin_y}, $rmp->{origin_x}, $rmp->{random_seed}, $rmp->{total_map_hp},
1306 $rmp->{map_layout_style}, $rmp->{treasureoptions}, $rmp->{symmetry_used},
1307 (cf::region::find $rmp->{region})
1308}
1309
1310# and all this just because we cannot iterate over
1311# all maps in C++...
1312sub change_all_map_light {
1313 my ($change) = @_;
1314
1315 $_->change_map_light ($change)
1316 for grep $_->outdoor, values %cf::MAP;
1317}
1318
1319sub try_load_header($) {
763 my ($pl, $path) = @_; 1320 my ($path) = @_;
764 1321
765 for my $o (all_objects $pl->ob) { 1322 utf8::encode $path;
766 if (my $value = $o->get_ob_key_value ("_perl_data")) { 1323 aio_open $path, O_RDONLY, 0
767 $o->set_ob_key_value ("_perl_data"); 1324 or return;
768 1325
769 %$o = %{ Storable::thaw pack "H*", $value }; 1326 my $map = cf::map::new
1327 or return;
1328
1329 # for better error messages only, will be overwritten
1330 $map->path ($path);
1331
1332 $map->load_header ($path)
1333 or return;
1334
1335 $map->{load_path} = $path;
1336
1337 $map
1338}
1339
1340sub find;
1341sub find {
1342 my ($path, $origin) = @_;
1343
1344 #warn "find<$path,$origin>\n";#d#
1345
1346 $path = new cf::path $path, $origin && $origin->path;
1347 my $key = $path->as_string;
1348
1349 cf::lock_wait "map_find:$key";
1350
1351 $cf::MAP{$key} || do {
1352 my $guard = cf::lock_acquire "map_find:$key";
1353
1354 # do it the slow way
1355 my $map = try_load_header $path->save_path;
1356
1357 Coro::cede;
1358
1359 if ($map) {
1360 $map->last_access ((delete $map->{last_access})
1361 || $cf::RUNTIME); #d#
1362 # safety
1363 $map->{instantiate_time} = $cf::RUNTIME
1364 if $map->{instantiate_time} > $cf::RUNTIME;
1365 } else {
1366 if (my $rmp = $path->random_map_params) {
1367 $map = generate_random_map $key, $rmp;
1368 } else {
1369 $map = try_load_header $path->load_path;
770 } 1370 }
1371
1372 $map or return;
1373
1374 $map->{load_original} = 1;
1375 $map->{instantiate_time} = $cf::RUNTIME;
1376 $map->last_access ($cf::RUNTIME);
1377 $map->instantiate;
1378
1379 # per-player maps become, after loading, normal maps
1380 $map->per_player (0) if $path->{user_rel};
771 } 1381 }
1382
1383 $map->path ($key);
1384 $map->{path} = $path;
1385 $map->{last_save} = $cf::RUNTIME;
1386
1387 Coro::cede;
1388
1389 if ($map->should_reset) {
1390 $map->reset;
1391 undef $guard;
1392 $map = find $path
1393 or return;
1394 }
1395
1396 $cf::MAP{$key} = $map
772 }, 1397 }
773; 1398}
774 1399
775############################################################################# 1400sub load {
1401 my ($self) = @_;
776 1402
777=head2 CORE EXTENSIONS 1403 my $path = $self->{path};
1404 my $guard = cf::lock_acquire "map_load:" . $path->as_string;
778 1405
779Functions and methods that extend core crossfire objects. 1406 return if $self->in_memory != cf::MAP_SWAPPED;
1407
1408 $self->in_memory (cf::MAP_LOADING);
1409
1410 $self->alloc;
1411 $self->load_objects ($self->{load_path}, 1)
1412 or return;
1413
1414 $self->set_object_flag (cf::FLAG_OBJ_ORIGINAL, 1)
1415 if delete $self->{load_original};
1416
1417 if (my $uniq = $path->uniq_path) {
1418 utf8::encode $uniq;
1419 if (aio_open $uniq, O_RDONLY, 0) {
1420 $self->clear_unique_items;
1421 $self->load_objects ($uniq, 0);
1422 }
1423 }
1424
1425 Coro::cede;
1426
1427 # now do the right thing for maps
1428 $self->link_multipart_objects;
1429
1430 if ($self->{path}->is_style_map) {
1431 $self->{deny_save} = 1;
1432 $self->{deny_reset} = 1;
1433 } else {
1434 $self->fix_auto_apply;
1435 $self->decay_objects;
1436 $self->update_buttons;
1437 $self->set_darkness_map;
1438 $self->difficulty ($self->estimate_difficulty)
1439 unless $self->difficulty;
1440 $self->activate;
1441 }
1442
1443 Coro::cede;
1444
1445 $self->in_memory (cf::MAP_IN_MEMORY);
1446}
1447
1448# find and load all maps in the 3x3 area around a map
1449sub load_diag {
1450 my ($map) = @_;
1451
1452 my @diag; # diagonal neighbours
1453
1454 for (0 .. 3) {
1455 my $neigh = $map->tile_path ($_)
1456 or next;
1457 $neigh = find $neigh, $map
1458 or next;
1459 $neigh->load;
1460
1461 push @diag, [$neigh->tile_path (($_ + 3) % 4), $neigh],
1462 [$neigh->tile_path (($_ + 1) % 4), $neigh];
1463 }
1464
1465 for (@diag) {
1466 my $neigh = find @$_
1467 or next;
1468 $neigh->load;
1469 }
1470}
1471
1472sub find_sync {
1473 my ($path, $origin) = @_;
1474
1475 cf::sync_job { find $path, $origin }
1476}
1477
1478sub do_load_sync {
1479 my ($map) = @_;
1480
1481 cf::sync_job { $map->load };
1482}
1483
1484our %MAP_PREFETCH;
1485our $MAP_PREFETCHER = Coro::async {
1486 while () {
1487 while (%MAP_PREFETCH) {
1488 my $key = each %MAP_PREFETCH
1489 or next;
1490 my $path = delete $MAP_PREFETCH{$key};
1491
1492 my $map = find $path
1493 or next;
1494 $map->load;
1495 }
1496 Coro::schedule;
1497 }
1498};
1499
1500sub find_async {
1501 my ($path, $origin) = @_;
1502
1503 $path = new cf::path $path, $origin && $origin->path;
1504 my $key = $path->as_string;
1505
1506 if (my $map = $cf::MAP{$key}) {
1507 return $map if $map->in_memory == cf::MAP_IN_MEMORY;
1508 }
1509
1510 $MAP_PREFETCH{$key} = $path;
1511 $MAP_PREFETCHER->ready;
1512
1513 ()
1514}
1515
1516sub save {
1517 my ($self) = @_;
1518
1519 my $lock = cf::lock_acquire "map_data:" . $self->path;
1520
1521 $self->{last_save} = $cf::RUNTIME;
1522
1523 return unless $self->dirty;
1524
1525 my $save = $self->{path}->save_path; utf8::encode $save;
1526 my $uniq = $self->{path}->uniq_path; utf8::encode $uniq;
1527
1528 $self->{load_path} = $save;
1529
1530 return if $self->{deny_save};
1531
1532 local $self->{last_access} = $self->last_access;#d#
1533
1534 cf::async {
1535 $_->contr->save for $self->players;
1536 };
1537
1538 if ($uniq) {
1539 $self->save_objects ($save, cf::IO_HEADER | cf::IO_OBJECTS);
1540 $self->save_objects ($uniq, cf::IO_UNIQUES);
1541 } else {
1542 $self->save_objects ($save, cf::IO_HEADER | cf::IO_OBJECTS | cf::IO_UNIQUES);
1543 }
1544}
1545
1546sub swap_out {
1547 my ($self) = @_;
1548
1549 # save first because save cedes
1550 $self->save;
1551
1552 my $lock = cf::lock_acquire "map_data:" . $self->path;
1553
1554 return if $self->players;
1555 return if $self->in_memory != cf::MAP_IN_MEMORY;
1556 return if $self->{deny_save};
1557
1558 $self->clear;
1559 $self->in_memory (cf::MAP_SWAPPED);
1560}
1561
1562sub reset_at {
1563 my ($self) = @_;
1564
1565 # TODO: safety, remove and allow resettable per-player maps
1566 return 1e99 if $self->{path}{user_rel};
1567 return 1e99 if $self->{deny_reset};
1568
1569 my $time = $self->fixed_resettime ? $self->{instantiate_time} : $self->last_access;
1570 my $to = List::Util::min $MAX_RESET, $self->reset_timeout || $DEFAULT_RESET;
1571
1572 $time + $to
1573}
1574
1575sub should_reset {
1576 my ($self) = @_;
1577
1578 $self->reset_at <= $cf::RUNTIME
1579}
1580
1581sub unlink_save {
1582 my ($self) = @_;
1583
1584 utf8::encode (my $save = $self->{path}->save_path);
1585 aioreq_pri 3; IO::AIO::aio_unlink $save;
1586 aioreq_pri 3; IO::AIO::aio_unlink "$save.pst";
1587}
1588
1589sub rename {
1590 my ($self, $new_path) = @_;
1591
1592 $self->unlink_save;
1593
1594 delete $cf::MAP{$self->path};
1595 $self->{path} = new cf::path $new_path;
1596 $self->path ($self->{path}->as_string);
1597 $cf::MAP{$self->path} = $self;
1598
1599 $self->save;
1600}
1601
1602sub reset {
1603 my ($self) = @_;
1604
1605 my $lock = cf::lock_acquire "map_data:" . $self->path;
1606
1607 return if $self->players;
1608 return if $self->{path}{user_rel};#d#
1609
1610 warn "resetting map ", $self->path;#d#
1611
1612 delete $cf::MAP{$self->path};
1613
1614 $_->clear_links_to ($self) for values %cf::MAP;
1615
1616 $self->unlink_save;
1617 $self->destroy;
1618}
1619
1620my $nuke_counter = "aaaa";
1621
1622sub nuke {
1623 my ($self) = @_;
1624
1625 $self->{deny_save} = 1;
1626 $self->reset_timeout (1);
1627 $self->rename ("{nuke}/" . ($nuke_counter++));
1628 $self->reset; # polite request, might not happen
1629}
1630
1631sub customise_for {
1632 my ($map, $ob) = @_;
1633
1634 if ($map->per_player) {
1635 return cf::map::find "~" . $ob->name . "/" . $map->{path}{path};
1636 }
1637
1638 $map
1639}
1640
1641=item cf::map::unique_maps
1642
1643Returns an arrayref of cf::path's of all shared maps that have
1644instantiated unique items. May block.
1645
1646=cut
1647
1648sub unique_maps() {
1649 my $files = aio_readdir cf::localdir . "/" . cf::uniquedir
1650 or return;
1651
1652 my @paths;
1653
1654 for (@$files) {
1655 utf8::decode $_;
1656 next if /\.pst$/;
1657 next unless /^$PATH_SEP/o;
1658
1659 push @paths, new cf::path $_;
1660 }
1661
1662 \@paths
1663}
1664
1665package cf;
1666
1667=back
1668
1669=head3 cf::object
1670
1671=cut
1672
1673package cf::object;
780 1674
781=over 4 1675=over 4
782 1676
783=item cf::player::exists $login 1677=item $ob->inv_recursive
784 1678
785Returns true when the given account exists. 1679Returns the inventory of the object _and_ their inventories, recursively.
786 1680
787=cut 1681=cut
788 1682
789sub cf::player::exists($) { 1683sub inv_recursive_;
790 cf::player::find $_[0] 1684sub inv_recursive_ {
791 or -f sprintf "%s/%s/%s/%s.pl", cf::localdir, cf::playerdir, ($_[0]) x 2; 1685 map { $_, inv_recursive_ $_->inv } @_
792} 1686}
1687
1688sub inv_recursive {
1689 inv_recursive_ inv $_[0]
1690}
1691
1692package cf;
1693
1694=back
1695
1696=head3 cf::object::player
1697
1698=over 4
793 1699
794=item $player_object->reply ($npc, $msg[, $flags]) 1700=item $player_object->reply ($npc, $msg[, $flags])
795 1701
796Sends a message to the player, as if the npc C<$npc> replied. C<$npc> 1702Sends a message to the player, as if the npc C<$npc> replied. C<$npc>
797can be C<undef>. Does the right thing when the player is currently in a 1703can be C<undef>. Does the right thing when the player is currently in a
799 1705
800=cut 1706=cut
801 1707
802# rough implementation of a future "reply" method that works 1708# rough implementation of a future "reply" method that works
803# with dialog boxes. 1709# with dialog boxes.
1710#TODO: the first argument must go, split into a $npc->reply_to ( method
804sub cf::object::player::reply($$$;$) { 1711sub cf::object::player::reply($$$;$) {
805 my ($self, $npc, $msg, $flags) = @_; 1712 my ($self, $npc, $msg, $flags) = @_;
806 1713
807 $flags = cf::NDI_BROWN | cf::NDI_UNIQUE unless @_ >= 4; 1714 $flags = cf::NDI_BROWN | cf::NDI_UNIQUE unless @_ >= 4;
808 1715
812 $msg = $npc->name . " says: $msg" if $npc; 1719 $msg = $npc->name . " says: $msg" if $npc;
813 $self->message ($msg, $flags); 1720 $self->message ($msg, $flags);
814 } 1721 }
815} 1722}
816 1723
817=item $player->ext_reply ($msgid, $msgtype, %msg)
818
819Sends an ext reply to the player.
820
821=cut
822
823sub cf::player::ext_reply($$$%) {
824 my ($self, $id, %msg) = @_;
825
826 $msg{msgid} = $id;
827
828 $self->send ("ext " . to_json \%msg);
829}
830
831=item $player_object->may ("access") 1724=item $player_object->may ("access")
832 1725
833Returns wether the given player is authorized to access resource "access" 1726Returns wether the given player is authorized to access resource "access"
834(e.g. "command_wizcast"). 1727(e.g. "command_wizcast").
835 1728
842 (ref $cf::CFG{"may_$access"} 1735 (ref $cf::CFG{"may_$access"}
843 ? scalar grep $self->name eq $_, @{$cf::CFG{"may_$access"}} 1736 ? scalar grep $self->name eq $_, @{$cf::CFG{"may_$access"}}
844 : $cf::CFG{"may_$access"}) 1737 : $cf::CFG{"may_$access"})
845} 1738}
846 1739
847=cut 1740=item $player_object->enter_link
848 1741
849############################################################################# 1742Freezes the player and moves him/her to a special map (C<{link}>).
1743
1744The player should be reaosnably safe there for short amounts of time. You
1745I<MUST> call C<leave_link> as soon as possible, though.
1746
1747=item $player_object->leave_link ($map, $x, $y)
1748
1749Moves the player out of the specila link map onto the given map. If the
1750map is not valid (or omitted), the player will be moved back to the
1751location he/she was before the call to C<enter_link>, or, if that fails,
1752to the emergency map position.
1753
1754Might block.
1755
1756=cut
1757
1758sub cf::object::player::enter_link {
1759 my ($self) = @_;
1760
1761 $self->deactivate_recursive;
1762
1763 return if $self->map == $LINK_MAP;
1764
1765 $self->{_link_pos} ||= [$self->map->{path}, $self->x, $self->y]
1766 if $self->map;
1767
1768 $self->enter_map ($LINK_MAP, 20, 20);
1769}
1770
1771sub cf::object::player::leave_link {
1772 my ($self, $map, $x, $y) = @_;
1773
1774 my $link_pos = delete $self->{_link_pos};
1775
1776 unless ($map) {
1777 # restore original map position
1778 ($map, $x, $y) = @{ $link_pos || [] };
1779 $map = cf::map::find $map;
1780
1781 unless ($map) {
1782 ($map, $x, $y) = @$EMERGENCY_POSITION;
1783 $map = cf::map::find $map
1784 or die "FATAL: cannot load emergency map\n";
1785 }
1786 }
1787
1788 ($x, $y) = (-1, -1)
1789 unless (defined $x) && (defined $y);
1790
1791 # use -1 or undef as default coordinates, not 0, 0
1792 ($x, $y) = ($map->enter_x, $map->enter_y)
1793 if $x <=0 && $y <= 0;
1794
1795 $map->load;
1796 $map->load_diag;
1797
1798 return unless $self->contr->active;
1799 $self->activate_recursive;
1800 $self->enter_map ($map, $x, $y);
1801}
1802
1803cf::player->attach (
1804 on_logout => sub {
1805 my ($pl) = @_;
1806
1807 # abort map switching before logout
1808 if ($pl->ob->{_link_pos}) {
1809 cf::sync_job {
1810 $pl->ob->leave_link
1811 };
1812 }
1813 },
1814 on_login => sub {
1815 my ($pl) = @_;
1816
1817 # try to abort aborted map switching on player login :)
1818 # should happen only on crashes
1819 if ($pl->ob->{_link_pos}) {
1820 $pl->ob->enter_link;
1821 (async {
1822 # we need this sleep as the login has a concurrent enter_exit running
1823 # and this sleep increases chances of the player not ending up in scorn
1824 $pl->ob->reply (undef,
1825 "There was an internal problem at your last logout, "
1826 . "the server will try to bring you to your intended destination in a second.",
1827 cf::NDI_RED);
1828 Coro::Timer::sleep 1;
1829 $pl->ob->leave_link;
1830 })->prio (2);
1831 }
1832 },
1833);
1834
1835=item $player_object->goto ($path, $x, $y)
1836
1837=cut
1838
1839sub cf::object::player::goto {
1840 my ($self, $path, $x, $y) = @_;
1841
1842 $path = new cf::path $path;
1843
1844 $self->enter_link;
1845
1846 (async {
1847 my $map = cf::map::find $path->as_string;
1848 $map = $map->customise_for ($self) if $map;
1849
1850# warn "entering ", $map->path, " at ($x, $y)\n"
1851# if $map;
1852
1853 $map or $self->message ("The exit to '" . ($path->visible_name) . "' is closed", cf::NDI_UNIQUE | cf::NDI_RED);
1854
1855 $self->leave_link ($map, $x, $y);
1856 })->prio (1);
1857}
1858
1859=item $player_object->enter_exit ($exit_object)
1860
1861=cut
1862
1863sub parse_random_map_params {
1864 my ($spec) = @_;
1865
1866 my $rmp = { # defaults
1867 xsize => 10,
1868 ysize => 10,
1869 };
1870
1871 for (split /\n/, $spec) {
1872 my ($k, $v) = split /\s+/, $_, 2;
1873
1874 $rmp->{lc $k} = $v if (length $k) && (length $v);
1875 }
1876
1877 $rmp
1878}
1879
1880sub prepare_random_map {
1881 my ($exit) = @_;
1882
1883 # all this does is basically replace the /! path by
1884 # a new random map path (?random/...) with a seed
1885 # that depends on the exit object
1886
1887 my $rmp = parse_random_map_params $exit->msg;
1888
1889 if ($exit->map) {
1890 $rmp->{region} = $exit->map->region_name;
1891 $rmp->{origin_map} = $exit->map->path;
1892 $rmp->{origin_x} = $exit->x;
1893 $rmp->{origin_y} = $exit->y;
1894 }
1895
1896 $rmp->{random_seed} ||= $exit->random_seed;
1897
1898 my $data = cf::to_json $rmp;
1899 my $md5 = Digest::MD5::md5_hex $data;
1900
1901 if (my $fh = aio_open "$cf::RANDOM_MAPS/$md5.meta", O_WRONLY | O_CREAT, 0666) {
1902 aio_write $fh, 0, (length $data), $data, 0;
1903
1904 $exit->slaying ("?random/$md5");
1905 $exit->msg (undef);
1906 }
1907}
1908
1909sub cf::object::player::enter_exit {
1910 my ($self, $exit) = @_;
1911
1912 return unless $self->type == cf::PLAYER;
1913
1914 $self->enter_link;
1915
1916 (async {
1917 $self->deactivate_recursive; # just to be sure
1918 unless (eval {
1919 prepare_random_map $exit
1920 if $exit->slaying eq "/!";
1921
1922 my $path = new cf::path $exit->slaying, $exit->map && $exit->map->path;
1923 $self->goto ($path, $exit->stats->hp, $exit->stats->sp);
1924
1925 1;
1926 }) {
1927 $self->message ("Something went wrong deep within the crossfire server. "
1928 . "I'll try to bring you back to the map you were before. "
1929 . "Please report this to the dungeon master!",
1930 cf::NDI_UNIQUE | cf::NDI_RED);
1931
1932 warn "ERROR in enter_exit: $@";
1933 $self->leave_link;
1934 }
1935 })->prio (1);
1936}
1937
1938=head3 cf::client
1939
1940=over 4
1941
1942=item $client->send_drawinfo ($text, $flags)
1943
1944Sends a drawinfo packet to the client. Circumvents output buffering so
1945should not be used under normal circumstances.
1946
1947=cut
1948
1949sub cf::client::send_drawinfo {
1950 my ($self, $text, $flags) = @_;
1951
1952 utf8::encode $text;
1953 $self->send_packet (sprintf "drawinfo %d %s", $flags, $text);
1954}
1955
1956
1957=item $success = $client->query ($flags, "text", \&cb)
1958
1959Queues a query to the client, calling the given callback with
1960the reply text on a reply. flags can be C<cf::CS_QUERY_YESNO>,
1961C<cf::CS_QUERY_SINGLECHAR> or C<cf::CS_QUERY_HIDEINPUT> or C<0>.
1962
1963Queries can fail, so check the return code. Or don't, as queries will become
1964reliable at some point in the future.
1965
1966=cut
1967
1968sub cf::client::query {
1969 my ($self, $flags, $text, $cb) = @_;
1970
1971 return unless $self->state == ST_PLAYING
1972 || $self->state == ST_SETUP
1973 || $self->state == ST_CUSTOM;
1974
1975 $self->state (ST_CUSTOM);
1976
1977 utf8::encode $text;
1978 push @{ $self->{query_queue} }, [(sprintf "query %d %s", $flags, $text), $cb];
1979
1980 $self->send_packet ($self->{query_queue}[0][0])
1981 if @{ $self->{query_queue} } == 1;
1982}
1983
1984cf::client->attach (
1985 on_reply => sub {
1986 my ($ns, $msg) = @_;
1987
1988 # this weird shuffling is so that direct followup queries
1989 # get handled first
1990 my $queue = delete $ns->{query_queue}
1991 or return; # be conservative, not sure how that can happen, but we saw a crash here
1992
1993 (shift @$queue)->[1]->($msg);
1994
1995 push @{ $ns->{query_queue} }, @$queue;
1996
1997 if (@{ $ns->{query_queue} } == @$queue) {
1998 if (@$queue) {
1999 $ns->send_packet ($ns->{query_queue}[0][0]);
2000 } else {
2001 $ns->state (ST_PLAYING) if $ns->state == ST_CUSTOM;
2002 }
2003 }
2004 },
2005);
2006
2007=item $client->async (\&cb)
2008
2009Create a new coroutine, running the specified callback. The coroutine will
2010be automatically cancelled when the client gets destroyed (e.g. on logout,
2011or loss of connection).
2012
2013=cut
2014
2015sub cf::client::async {
2016 my ($self, $cb) = @_;
2017
2018 my $coro = &Coro::async ($cb);
2019
2020 $coro->on_destroy (sub {
2021 delete $self->{_coro}{$coro+0};
2022 });
2023
2024 $self->{_coro}{$coro+0} = $coro;
2025
2026 $coro
2027}
2028
2029cf::client->attach (
2030 on_destroy => sub {
2031 my ($ns) = @_;
2032
2033 $_->cancel for values %{ (delete $ns->{_coro}) || {} };
2034 },
2035);
2036
2037=back
2038
850 2039
851=head2 SAFE SCRIPTING 2040=head2 SAFE SCRIPTING
852 2041
853Functions that provide a safe environment to compile and execute 2042Functions that provide a safe environment to compile and execute
854snippets of perl code without them endangering the safety of the server 2043snippets of perl code without them endangering the safety of the server
869 2058
870=pod 2059=pod
871 2060
872The following fucntions and emthods are available within a safe environment: 2061The following fucntions and emthods are available within a safe environment:
873 2062
874 cf::object contr pay_amount pay_player 2063 cf::object contr pay_amount pay_player map
875 cf::object::player player 2064 cf::object::player player
876 cf::player peaceful 2065 cf::player peaceful
2066 cf::map trigger
877 2067
878=cut 2068=cut
879 2069
880for ( 2070for (
881 ["cf::object" => qw(contr pay_amount pay_player)], 2071 ["cf::object" => qw(contr pay_amount pay_player map)],
882 ["cf::object::player" => qw(player)], 2072 ["cf::object::player" => qw(player)],
883 ["cf::player" => qw(peaceful)], 2073 ["cf::player" => qw(peaceful)],
2074 ["cf::map" => qw(trigger)],
884) { 2075) {
885 no strict 'refs'; 2076 no strict 'refs';
886 my ($pkg, @funs) = @$_; 2077 my ($pkg, @funs) = @$_;
887 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"}) 2078 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"})
888 for @funs; 2079 for @funs;
1004 2195
1005{ 2196{
1006 my $path = cf::localdir . "/database.pst"; 2197 my $path = cf::localdir . "/database.pst";
1007 2198
1008 sub db_load() { 2199 sub db_load() {
1009 warn "loading database $path\n";#d# remove later
1010 $DB = stat $path ? Storable::retrieve $path : { }; 2200 $DB = stat $path ? Storable::retrieve $path : { };
1011 } 2201 }
1012 2202
1013 my $pid; 2203 my $pid;
1014 2204
1015 sub db_save() { 2205 sub db_save() {
1016 warn "saving database $path\n";#d# remove later
1017 waitpid $pid, 0 if $pid; 2206 waitpid $pid, 0 if $pid;
1018 if (0 == ($pid = fork)) { 2207 if (0 == ($pid = fork)) {
1019 $DB->{_meta}{version} = 1; 2208 $DB->{_meta}{version} = 1;
1020 Storable::nstore $DB, "$path~"; 2209 Storable::nstore $DB, "$path~";
1021 rename "$path~", $path; 2210 rename "$path~", $path;
1028 sub db_sync() { 2217 sub db_sync() {
1029 db_save if $dirty; 2218 db_save if $dirty;
1030 undef $dirty; 2219 undef $dirty;
1031 } 2220 }
1032 2221
1033 my $idle = Event->idle (min => $TICK * 2.8, max => 10, repeat => 0, cb => sub { 2222 my $idle = Event->idle (min => $TICK * 2.8, max => 10, repeat => 0, data => WF_AUTOCANCEL, cb => sub {
1034 db_sync; 2223 db_sync;
1035 }); 2224 });
1036 2225
1037 sub db_dirty() { 2226 sub db_dirty() {
1038 $dirty = 1; 2227 $dirty = 1;
1052 $DB->{$_[0]} = $_[1]; 2241 $DB->{$_[0]} = $_[1];
1053 } 2242 }
1054 db_dirty; 2243 db_dirty;
1055 } 2244 }
1056 2245
1057 attach_global 2246 cf::global->attach (
1058 prio => 10000, 2247 prio => 10000,
1059 on_cleanup => sub { 2248 on_cleanup => sub {
1060 db_sync; 2249 db_sync;
1061 }, 2250 },
1062 ; 2251 );
1063} 2252}
1064 2253
1065############################################################################# 2254#############################################################################
1066# the server's main() 2255# the server's main()
1067 2256
1069 open my $fh, "<:utf8", cf::confdir . "/config" 2258 open my $fh, "<:utf8", cf::confdir . "/config"
1070 or return; 2259 or return;
1071 2260
1072 local $/; 2261 local $/;
1073 *CFG = YAML::Syck::Load <$fh>; 2262 *CFG = YAML::Syck::Load <$fh>;
2263
2264 $EMERGENCY_POSITION = $CFG{emergency_position} || ["/world/world_105_115", 5, 37];
2265
2266 $cf::map::MAX_RESET = $CFG{map_max_reset} if exists $CFG{map_max_reset};
2267 $cf::map::DEFAULT_RESET = $CFG{map_default_reset} if exists $CFG{map_default_reset};
2268
2269 if (exists $CFG{mlockall}) {
2270 eval {
2271 $CFG{mlockall} ? eval "mlockall()" : eval "munlockall()"
2272 and die "WARNING: m(un)lockall failed: $!\n";
2273 };
2274 warn $@ if $@;
2275 }
1074} 2276}
1075 2277
1076sub main { 2278sub main {
2279 # we must not ever block the main coroutine
2280 local $Coro::idle = sub {
2281 Carp::cluck "FATAL: Coro::idle was called, major BUG, use cf::sync_job!\n";#d#
2282 async { Event::one_event };
2283 };
2284
1077 cfg_load; 2285 cfg_load;
1078 db_load; 2286 db_load;
1079 load_extensions; 2287 load_extensions;
1080 Event::loop; 2288 Event::loop;
1081} 2289}
1082 2290
1083############################################################################# 2291#############################################################################
1084# initialisation 2292# initialisation and cleanup
1085 2293
2294# install some emergency cleanup handlers
2295BEGIN {
2296 for my $signal (qw(INT HUP TERM)) {
2297 Event->signal (
2298 data => WF_AUTOCANCEL,
2299 signal => $signal,
2300 cb => sub {
2301 cf::cleanup "SIG$signal";
2302 },
2303 );
2304 }
2305}
2306
2307sub emergency_save() {
2308 my $freeze_guard = cf::freeze_mainloop;
2309
2310 warn "enter emergency perl save\n";
2311
2312 cf::sync_job {
2313 # use a peculiar iteration method to avoid tripping on perl
2314 # refcount bugs in for. also avoids problems with players
2315 # and maps saved/Destroyed asynchronously.
2316 warn "begin emergency player save\n";
2317 for my $login (keys %cf::PLAYER) {
2318 my $pl = $cf::PLAYER{$login} or next;
2319 $pl->valid or next;
2320 $pl->save;
2321 }
2322 warn "end emergency player save\n";
2323
2324 warn "begin emergency map save\n";
2325 for my $path (keys %cf::MAP) {
2326 my $map = $cf::MAP{$path} or next;
2327 $map->valid or next;
2328 $map->save;
2329 }
2330 warn "end emergency map save\n";
2331 };
2332
2333 warn "leave emergency perl save\n";
2334}
2335
1086sub _perl_reload(&) { 2336sub reload() {
1087 my ($msg) = @_; 2337 # can/must only be called in main
2338 if ($Coro::current != $Coro::main) {
2339 warn "can only reload from main coroutine\n";
2340 return;
2341 }
1088 2342
1089 $msg->("reloading..."); 2343 warn "reloading...";
2344
2345 my $guard = freeze_mainloop;
2346 cf::emergency_save;
1090 2347
1091 eval { 2348 eval {
2349 # if anything goes wrong in here, we should simply crash as we already saved
2350
1092 # cancel all watchers 2351 # cancel all watchers
1093 $_->cancel for Event::all_watchers; 2352 for (Event::all_watchers) {
2353 $_->cancel if $_->data & WF_AUTOCANCEL;
2354 }
2355
2356 # cancel all extension coros
2357 $_->cancel for values %EXT_CORO;
2358 %EXT_CORO = ();
1094 2359
1095 # unload all extensions 2360 # unload all extensions
1096 for (@exts) { 2361 for (@exts) {
1097 $msg->("unloading <$_>"); 2362 warn "unloading <$_>";
1098 unload_extension $_; 2363 unload_extension $_;
1099 } 2364 }
1100 2365
1101 # unload all modules loaded from $LIBDIR 2366 # unload all modules loaded from $LIBDIR
1102 while (my ($k, $v) = each %INC) { 2367 while (my ($k, $v) = each %INC) {
1103 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/; 2368 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/;
1104 2369
1105 $msg->("removing <$k>"); 2370 warn "removing <$k>";
1106 delete $INC{$k}; 2371 delete $INC{$k};
1107 2372
1108 $k =~ s/\.pm$//; 2373 $k =~ s/\.pm$//;
1109 $k =~ s/\//::/g; 2374 $k =~ s/\//::/g;
1110 2375
1115 Symbol::delete_package $k; 2380 Symbol::delete_package $k;
1116 } 2381 }
1117 2382
1118 # sync database to disk 2383 # sync database to disk
1119 cf::db_sync; 2384 cf::db_sync;
2385 IO::AIO::flush;
1120 2386
1121 # get rid of safe::, as good as possible 2387 # get rid of safe::, as good as possible
1122 Symbol::delete_package "safe::$_" 2388 Symbol::delete_package "safe::$_"
1123 for qw(cf::object cf::object::player cf::player cf::map cf::party cf::region); 2389 for qw(cf::attachable cf::object cf::object::player cf::client cf::player cf::map cf::party cf::region);
1124 2390
1125 # remove register_script_function callbacks 2391 # remove register_script_function callbacks
1126 # TODO 2392 # TODO
1127 2393
1128 # unload cf.pm "a bit" 2394 # unload cf.pm "a bit"
1131 # don't, removes xs symbols, too, 2397 # don't, removes xs symbols, too,
1132 # and global variables created in xs 2398 # and global variables created in xs
1133 #Symbol::delete_package __PACKAGE__; 2399 #Symbol::delete_package __PACKAGE__;
1134 2400
1135 # reload cf.pm 2401 # reload cf.pm
1136 $msg->("reloading cf.pm"); 2402 warn "reloading cf.pm";
1137 require cf; 2403 require cf;
2404 cf::_connect_to_perl; # nominally unnecessary, but cannot hurt
1138 2405
1139 # load config and database again 2406 # load config and database again
1140 cf::cfg_load; 2407 cf::cfg_load;
1141 cf::db_load; 2408 cf::db_load;
1142 2409
1143 # load extensions 2410 # load extensions
1144 $msg->("load extensions"); 2411 warn "load extensions";
1145 cf::load_extensions; 2412 cf::load_extensions;
1146 2413
1147 # reattach attachments to objects 2414 # reattach attachments to objects
1148 $msg->("reattach"); 2415 warn "reattach";
1149 _global_reattach; 2416 _global_reattach;
2417 reattach $_ for values %MAP;
1150 }; 2418 };
1151 $msg->($@) if $@;
1152 2419
1153 $msg->("reloaded"); 2420 if ($@) {
2421 warn $@;
2422 warn "error while reloading, exiting.";
2423 exit 1;
2424 }
2425
2426 warn "reloaded successfully";
1154}; 2427};
1155 2428
1156sub perl_reload() { 2429#############################################################################
1157 _perl_reload {
1158 warn $_[0];
1159 print "$_[0]\n";
1160 };
1161}
1162 2430
2431unless ($LINK_MAP) {
2432 $LINK_MAP = cf::map::new;
2433
2434 $LINK_MAP->width (41);
2435 $LINK_MAP->height (41);
2436 $LINK_MAP->alloc;
2437 $LINK_MAP->path ("{link}");
2438 $LINK_MAP->{path} = bless { path => "{link}" }, "cf::path";
2439 $LINK_MAP->in_memory (MAP_IN_MEMORY);
2440
2441 # dirty hack because... archetypes are not yet loaded
2442 Event->timer (
2443 after => 10,
2444 cb => sub {
2445 $_[0]->w->cancel;
2446
2447 # provide some exits "home"
2448 my $exit = cf::object::new "exit";
2449
2450 $exit->slaying ($EMERGENCY_POSITION->[0]);
2451 $exit->stats->hp ($EMERGENCY_POSITION->[1]);
2452 $exit->stats->sp ($EMERGENCY_POSITION->[2]);
2453
2454 $LINK_MAP->insert ($exit->clone, 19, 19);
2455 $LINK_MAP->insert ($exit->clone, 19, 20);
2456 $LINK_MAP->insert ($exit->clone, 19, 21);
2457 $LINK_MAP->insert ($exit->clone, 20, 19);
2458 $LINK_MAP->insert ($exit->clone, 20, 21);
2459 $LINK_MAP->insert ($exit->clone, 21, 19);
2460 $LINK_MAP->insert ($exit->clone, 21, 20);
2461 $LINK_MAP->insert ($exit->clone, 21, 21);
2462
2463 $exit->destroy;
2464 });
2465
2466 $LINK_MAP->{deny_save} = 1;
2467 $LINK_MAP->{deny_reset} = 1;
2468
2469 $cf::MAP{$LINK_MAP->path} = $LINK_MAP;
2470}
2471
2472register "<global>", __PACKAGE__;
2473
1163register_command "perl-reload", 0, sub { 2474register_command "reload" => sub {
1164 my ($who, $arg) = @_; 2475 my ($who, $arg) = @_;
1165 2476
1166 if ($who->flag (FLAG_WIZ)) { 2477 if ($who->flag (FLAG_WIZ)) {
1167 _perl_reload { 2478 $who->message ("start of reload.");
1168 warn $_[0]; 2479 reload;
1169 $who->message ($_[0]); 2480 $who->message ("end of reload.");
1170 };
1171 } 2481 }
1172}; 2482};
1173 2483
1174register "<global>", __PACKAGE__;
1175
1176unshift @INC, $LIBDIR; 2484unshift @INC, $LIBDIR;
1177 2485
1178$TICK_WATCHER = Event->timer ( 2486$TICK_WATCHER = Event->timer (
2487 reentrant => 0,
1179 prio => 1, 2488 prio => 0,
1180 async => 1,
1181 at => $NEXT_TICK || 1, 2489 at => $NEXT_TICK || $TICK,
2490 data => WF_AUTOCANCEL,
1182 cb => sub { 2491 cb => sub {
1183 cf::server_tick; # one server iteration 2492 cf::server_tick; # one server iteration
1184 2493 $RUNTIME += $TICK;
1185 my $NOW = Event::time;
1186 $NEXT_TICK += $TICK; 2494 $NEXT_TICK += $TICK;
1187 2495
2496 $WAIT_FOR_TICK->broadcast;
2497 $WAIT_FOR_TICK_ONE->send if $WAIT_FOR_TICK_ONE->awaited;
2498
1188 # if we are delayed by four ticks or more, skip them all 2499 # if we are delayed by four ticks or more, skip them all
1189 $NEXT_TICK = $NOW if $NOW >= $NEXT_TICK + $TICK * 4; 2500 $NEXT_TICK = Event::time if Event::time >= $NEXT_TICK + $TICK * 4;
1190 2501
1191 $TICK_WATCHER->at ($NEXT_TICK); 2502 $TICK_WATCHER->at ($NEXT_TICK);
1192 $TICK_WATCHER->start; 2503 $TICK_WATCHER->start;
1193 }, 2504 },
1194); 2505);
1195 2506
1196IO::AIO::max_poll_time $TICK * 0.2; 2507IO::AIO::max_poll_time $TICK * 0.2;
1197 2508
2509Event->io (
1198Event->io (fd => IO::AIO::poll_fileno, 2510 fd => IO::AIO::poll_fileno,
1199 poll => 'r', 2511 poll => 'r',
1200 prio => 5, 2512 prio => 5,
2513 data => WF_AUTOCANCEL,
1201 cb => \&IO::AIO::poll_cb); 2514 cb => \&IO::AIO::poll_cb,
2515);
2516
2517Event->timer (
2518 data => WF_AUTOCANCEL,
2519 after => 0,
2520 interval => 10,
2521 cb => sub {
2522 (Coro::unblock_sub {
2523 write_runtime
2524 or warn "ERROR: unable to write runtime file: $!";
2525 })->();
2526 },
2527);
2528
2529END { cf::emergency_save }
1202 2530
12031 25311
1204 2532

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines