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.69 by root, Mon Sep 18 01:10:35 2006 UTC vs.
Revision 1.85 by root, Mon Dec 11 22:56:57 2006 UTC

5use Storable; 5use Storable;
6use Opcode; 6use Opcode;
7use Safe; 7use Safe;
8use Safe::Hole; 8use Safe::Hole;
9 9
10use IO::AIO ();
11use YAML::Syck ();
10use Time::HiRes; 12use Time::HiRes;
11use Event; 13use Event;
12$Event::Eval = 1; # no idea why this is required, but it is 14$Event::Eval = 1; # no idea why this is required, but it is
13 15
16# work around bug in YAML::Syck - bad news for perl6, will it be as broken wrt. unicode?
17$YAML::Syck::ImplicitUnicode = 1;
18
14use strict; 19use strict;
15 20
21our %COMMAND = ();
22our %COMMAND_TIME = ();
23our %EXTCMD = ();
24
16_init_vars; 25_init_vars;
17 26
18our %COMMAND = ();
19our @EVENT; 27our @EVENT;
20our $LIBDIR = maps_directory "perl"; 28our $LIBDIR = maps_directory "perl";
21 29
22our $TICK = MAX_TIME * 1e-6; 30our $TICK = MAX_TIME * 1e-6;
23our $TICK_WATCHER; 31our $TICK_WATCHER;
24our $NEXT_TICK; 32our $NEXT_TICK;
33
34our %CFG;
35
36our $UPTIME; $UPTIME ||= time;
37
38#############################################################################
39
40=head2 GLOBAL VARIABLES
41
42=over 4
43
44=item $cf::UPTIME
45
46The timestamp of the server start (so not actually an uptime).
47
48=item $cf::LIBDIR
49
50The perl library directory, where extensions and cf-specific modules can
51be found. It will be added to C<@INC> automatically.
52
53=item $cf::TICK
54
55The interval between server ticks, in seconds.
56
57=item %cf::CFG
58
59Configuration for the server, loaded from C</etc/crossfire/config>, or
60from wherever your confdir points to.
61
62=back
63
64=cut
25 65
26BEGIN { 66BEGIN {
27 *CORE::GLOBAL::warn = sub { 67 *CORE::GLOBAL::warn = sub {
28 my $msg = join "", @_; 68 my $msg = join "", @_;
29 $msg .= "\n" 69 $msg .= "\n"
48}; 88};
49 89
50my %ext_pkg; 90my %ext_pkg;
51my @exts; 91my @exts;
52my @hook; 92my @hook;
53my %command;
54my %extcmd;
55 93
56############################################################################# 94=head2 UTILITY FUNCTIONS
57# utility functions 95
96=over 4
97
98=cut
58 99
59use JSON::Syck (); # TODO# replace by JSON::PC once working 100use JSON::Syck (); # TODO# replace by JSON::PC once working
101
102=item $ref = cf::from_json $json
103
104Converts a JSON string into the corresponding perl data structure.
105
106=cut
60 107
61sub from_json($) { 108sub from_json($) {
62 $JSON::Syck::ImplicitUnicode = 1; # work around JSON::Syck bugs 109 $JSON::Syck::ImplicitUnicode = 1; # work around JSON::Syck bugs
63 JSON::Syck::Load $_[0] 110 JSON::Syck::Load $_[0]
64} 111}
65 112
113=item $json = cf::to_json $ref
114
115Converts a perl data structure into its JSON representation.
116
117=cut
118
66sub to_json($) { 119sub to_json($) {
67 $JSON::Syck::ImplicitUnicode = 0; # work around JSON::Syck bugs 120 $JSON::Syck::ImplicitUnicode = 0; # work around JSON::Syck bugs
68 JSON::Syck::Dump $_[0] 121 JSON::Syck::Dump $_[0]
69} 122}
70 123
124=back
125
126=cut
127
71############################################################################# 128#############################################################################
72# "new" plug-in system
73 129
74=head3 EVENTS AND OBJECT ATTACHMENTS 130=head2 EVENTS AND OBJECT ATTACHMENTS
75 131
76=over 4 132=over 4
77 133
78=item $object->attach ($attachment, key => $value...) 134=item $object->attach ($attachment, key => $value...)
79 135
379removed in future versions), and there is no public API to access override 435removed in future versions), and there is no public API to access override
380results (if you must, access C<@cf::invoke_results> directly). 436results (if you must, access C<@cf::invoke_results> directly).
381 437
382=back 438=back
383 439
384=head2 methods valid for all pointers 440=cut
441
442#############################################################################
443
444=head2 METHODS VALID FOR ALL CORE OBJECTS
385 445
386=over 4 446=over 4
387 447
388=item $object->valid 448=item $object->valid, $player->valid, $map->valid
389
390=item $player->valid
391
392=item $map->valid
393 449
394Just because you have a perl object does not mean that the corresponding 450Just because you have a perl object does not mean that the corresponding
395C-level object still exists. If you try to access an object that has no 451C-level object still exists. If you try to access an object that has no
396valid C counterpart anymore you get an exception at runtime. This method 452valid C counterpart anymore you get an exception at runtime. This method
397can be used to test for existence of the C object part without causing an 453can be used to test for existence of the C object part without causing an
470 unlink $filename; 526 unlink $filename;
471 unlink "$filename.pst"; 527 unlink "$filename.pst";
472 } 528 }
473} 529}
474 530
531sub object_freezer_as_string {
532 my ($rdata, $objs) = @_;
533
534 use Data::Dumper;
535
536 $$rdata . Dumper $objs
537}
538
475sub object_thawer_load { 539sub object_thawer_load {
476 my ($filename) = @_; 540 my ($filename) = @_;
477 541
478 local $/; 542 local $/;
479 543
504 if exists $src->{_attachment}; 568 if exists $src->{_attachment};
505 }, 569 },
506; 570;
507 571
508############################################################################# 572#############################################################################
509# old plug-in events 573# command handling &c
510 574
511sub inject_event { 575=item cf::register_command $name => \&callback($ob,$args);
512 my $extension = shift;
513 my $event_code = shift;
514 576
515 my $cb = $hook[$event_code]{$extension} 577Register a callback for execution when the client sends the user command
516 or return; 578$name.
517 579
518 &$cb 580=cut
519}
520
521sub inject_global_event {
522 my $event = shift;
523
524 my $cb = $hook[$event]
525 or return;
526
527 List::Util::max map &$_, values %$cb
528}
529
530sub inject_command {
531 my ($name, $obj, $params) = @_;
532
533 for my $cmd (@{ $command{$name} }) {
534 $cmd->[1]->($obj, $params);
535 }
536
537 -1
538}
539 581
540sub register_command { 582sub register_command {
541 my ($name, $time, $cb) = @_; 583 my ($name, $cb) = @_;
542 584
543 my $caller = caller; 585 my $caller = caller;
544 #warn "registering command '$name/$time' to '$caller'"; 586 #warn "registering command '$name/$time' to '$caller'";
545 587
546 push @{ $command{$name} }, [$time, $cb, $caller]; 588 push @{ $COMMAND{$name} }, [$caller, $cb];
547 $COMMAND{"$name\000"} = List::Util::max map $_->[0], @{ $command{$name} };
548} 589}
590
591=item cf::register_extcmd $name => \&callback($pl,$packet);
592
593Register a callbackf ro execution when the client sends an extcmd packet.
594
595If the callback returns something, it is sent back as if reply was being
596called.
597
598=cut
549 599
550sub register_extcmd { 600sub register_extcmd {
551 my ($name, $cb) = @_; 601 my ($name, $cb) = @_;
552 602
553 my $caller = caller; 603 my $caller = caller;
554 #warn "registering extcmd '$name' to '$caller'"; 604 #warn "registering extcmd '$name' to '$caller'";
555 605
556 $extcmd{$name} = [$cb, $caller]; 606 $EXTCMD{$name} = [$cb, $caller];
557} 607}
608
609attach_to_players
610 on_command => sub {
611 my ($pl, $name, $params) = @_;
612
613 my $cb = $COMMAND{$name}
614 or return;
615
616 for my $cmd (@$cb) {
617 $cmd->[1]->($pl->ob, $params);
618 }
619
620 cf::override;
621 },
622 on_extcmd => sub {
623 my ($pl, $buf) = @_;
624
625 my $msg = eval { from_json $buf };
626
627 if (ref $msg) {
628 if (my $cb = $EXTCMD{$msg->{msgtype}}) {
629 if (my %reply = $cb->[0]->($pl, $msg)) {
630 $pl->ext_reply ($msg->{msgid}, %reply);
631 }
632 }
633 } else {
634 warn "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n";
635 }
636
637 cf::override;
638 },
639;
558 640
559sub register { 641sub register {
560 my ($base, $pkg) = @_; 642 my ($base, $pkg) = @_;
561 643
562 #TODO 644 #TODO
581 . "#line 1 \"$path\"\n{\n" 663 . "#line 1 \"$path\"\n{\n"
582 . (do { local $/; <$fh> }) 664 . (do { local $/; <$fh> })
583 . "\n};\n1"; 665 . "\n};\n1";
584 666
585 eval $source 667 eval $source
586 or die "$path: $@"; 668 or die $@ ? "$path: $@\n"
669 : "extension disabled.\n";
587 670
588 push @exts, $pkg; 671 push @exts, $pkg;
589 $ext_pkg{$base} = $pkg; 672 $ext_pkg{$base} = $pkg;
590 673
591# no strict 'refs'; 674# no strict 'refs';
604# for my $idx (0 .. $#PLUGIN_EVENT) { 687# for my $idx (0 .. $#PLUGIN_EVENT) {
605# delete $hook[$idx]{$pkg}; 688# delete $hook[$idx]{$pkg};
606# } 689# }
607 690
608 # remove commands 691 # remove commands
609 for my $name (keys %command) { 692 for my $name (keys %COMMAND) {
610 my @cb = grep $_->[2] ne $pkg, @{ $command{$name} }; 693 my @cb = grep $_->[0] ne $pkg, @{ $COMMAND{$name} };
611 694
612 if (@cb) { 695 if (@cb) {
613 $command{$name} = \@cb; 696 $COMMAND{$name} = \@cb;
614 $COMMAND{"$name\000"} = List::Util::max map $_->[0], @cb;
615 } else { 697 } else {
616 delete $command{$name};
617 delete $COMMAND{"$name\000"}; 698 delete $COMMAND{$name};
618 } 699 }
619 } 700 }
620 701
621 # remove extcmds 702 # remove extcmds
622 for my $name (grep $extcmd{$_}[1] eq $pkg, keys %extcmd) { 703 for my $name (grep $EXTCMD{$_}[1] eq $pkg, keys %EXTCMD) {
623 delete $extcmd{$name}; 704 delete $EXTCMD{$name};
624 } 705 }
625 706
626 if (my $cb = $pkg->can ("unload")) { 707 if (my $cb = $pkg->can ("unload")) {
627 eval { 708 eval {
628 $cb->($pkg); 709 $cb->($pkg);
644 } or warn "$ext not loaded: $@"; 725 } or warn "$ext not loaded: $@";
645 } 726 }
646} 727}
647 728
648############################################################################# 729#############################################################################
649# extcmd framework, basically convert ext <msg>
650# into pkg::->on_extcmd_arg1 (...) while shortcutting a few
651
652attach_to_players
653 on_extcmd => sub {
654 my ($pl, $buf) = @_;
655
656 my $msg = eval { from_json $buf };
657
658 if (ref $msg) {
659 if (my $cb = $extcmd{$msg->{msgtype}}) {
660 if (my %reply = $cb->[0]->($pl, $msg)) {
661 $pl->ext_reply ($msg->{msgid}, %reply);
662 }
663 }
664 } else {
665 warn "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n";
666 }
667
668 cf::override;
669 },
670;
671
672#############################################################################
673# load/save/clean perl data associated with a map 730# load/save/clean perl data associated with a map
674 731
675*cf::mapsupport::on_clean = sub { 732*cf::mapsupport::on_clean = sub {
676 my ($map) = @_; 733 my ($map) = @_;
677 734
704 } 761 }
705 }, 762 },
706; 763;
707 764
708############################################################################# 765#############################################################################
709# core extensions - in perl 766
767=head2 CORE EXTENSIONS
768
769Functions and methods that extend core crossfire objects.
770
771=over 4
710 772
711=item cf::player::exists $login 773=item cf::player::exists $login
712 774
713Returns true when the given account exists. 775Returns true when the given account exists.
714 776
717sub cf::player::exists($) { 779sub cf::player::exists($) {
718 cf::player::find $_[0] 780 cf::player::find $_[0]
719 or -f sprintf "%s/%s/%s/%s.pl", cf::localdir, cf::playerdir, ($_[0]) x 2; 781 or -f sprintf "%s/%s/%s/%s.pl", cf::localdir, cf::playerdir, ($_[0]) x 2;
720} 782}
721 783
722=item $player->reply ($npc, $msg[, $flags]) 784=item $player_object->reply ($npc, $msg[, $flags])
723 785
724Sends a message to the player, as if the npc C<$npc> replied. C<$npc> 786Sends a message to the player, as if the npc C<$npc> replied. C<$npc>
725can be C<undef>. Does the right thing when the player is currently in a 787can be C<undef>. Does the right thing when the player is currently in a
726dialogue with the given NPC character. 788dialogue with the given NPC character.
727 789
754 $msg{msgid} = $id; 816 $msg{msgid} = $id;
755 817
756 $self->send ("ext " . to_json \%msg); 818 $self->send ("ext " . to_json \%msg);
757} 819}
758 820
821=item $player_object->may ("access")
822
823Returns wether the given player is authorized to access resource "access"
824(e.g. "command_wizcast").
825
826=cut
827
828sub cf::object::player::may {
829 my ($self, $access) = @_;
830
831 $self->flag (cf::FLAG_WIZ) ||
832 (ref $cf::CFG{"may_$access"}
833 ? scalar grep $self->name eq $_, @{$cf::CFG{"may_$access"}}
834 : $cf::CFG{"may_$access"})
835}
836
837=cut
838
759############################################################################# 839#############################################################################
760# map scripting support 840
841=head2 SAFE SCRIPTING
842
843Functions that provide a safe environment to compile and execute
844snippets of perl code without them endangering the safety of the server
845itself. Looping constructs, I/O operators and other built-in functionality
846is not available in the safe scripting environment, and the number of
847functions and methods that can be called is greatly reduced.
848
849=cut
761 850
762our $safe = new Safe "safe"; 851our $safe = new Safe "safe";
763our $safe_hole = new Safe::Hole; 852our $safe_hole = new Safe::Hole;
764 853
765$SIG{FPE} = 'IGNORE'; 854$SIG{FPE} = 'IGNORE';
766 855
767$safe->permit_only (Opcode::opset qw(:base_core :base_mem :base_orig :base_math sort time)); 856$safe->permit_only (Opcode::opset qw(:base_core :base_mem :base_orig :base_math sort time));
768 857
769# here we export the classes and methods available to script code 858# here we export the classes and methods available to script code
859
860=pod
861
862The following fucntions and emthods are available within a safe environment:
863
864 cf::object contr pay_amount pay_player
865 cf::object::player player
866 cf::player peaceful
867
868=cut
770 869
771for ( 870for (
772 ["cf::object" => qw(contr pay_amount pay_player)], 871 ["cf::object" => qw(contr pay_amount pay_player)],
773 ["cf::object::player" => qw(player)], 872 ["cf::object::player" => qw(player)],
774 ["cf::player" => qw(peaceful)], 873 ["cf::player" => qw(peaceful)],
777 my ($pkg, @funs) = @$_; 876 my ($pkg, @funs) = @$_;
778 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"}) 877 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"})
779 for @funs; 878 for @funs;
780} 879}
781 880
881=over 4
882
883=item @retval = safe_eval $code, [var => value, ...]
884
885Compiled and executes the given perl code snippet. additional var/value
886pairs result in temporary local (my) scalar variables of the given name
887that are available in the code snippet. Example:
888
889 my $five = safe_eval '$first + $second', first => 1, second => 4;
890
891=cut
892
782sub safe_eval($;@) { 893sub safe_eval($;@) {
783 my ($code, %vars) = @_; 894 my ($code, %vars) = @_;
784 895
785 my $qcode = $code; 896 my $qcode = $code;
786 $qcode =~ s/"/‟/g; # not allowed in #line filenames 897 $qcode =~ s/"/‟/g; # not allowed in #line filenames
830 941
831 no strict 'refs'; 942 no strict 'refs';
832 *{"safe::$fun"} = $safe_hole->wrap ($cb); 943 *{"safe::$fun"} = $safe_hole->wrap ($cb);
833} 944}
834 945
946=back
947
948=cut
949
835############################################################################# 950#############################################################################
836 951
837=head2 EXTENSION DATABASE SUPPORT 952=head2 EXTENSION DATABASE SUPPORT
838 953
839Crossfire maintains a very simple database for extension use. It can 954Crossfire maintains a very simple database for extension use. It can
873 988
874Immediately write the database to disk I<if it is dirty>. 989Immediately write the database to disk I<if it is dirty>.
875 990
876=cut 991=cut
877 992
993our $DB;
994
878{ 995{
879 my $db;
880 my $path = cf::localdir . "/database.pst"; 996 my $path = cf::localdir . "/database.pst";
881 997
882 sub db_load() { 998 sub db_load() {
883 warn "loading database $path\n";#d# remove later 999 warn "loading database $path\n";#d# remove later
884 $db = stat $path ? Storable::retrieve $path : { }; 1000 $DB = stat $path ? Storable::retrieve $path : { };
885 } 1001 }
886 1002
887 my $pid; 1003 my $pid;
888 1004
889 sub db_save() { 1005 sub db_save() {
890 warn "saving database $path\n";#d# remove later 1006 warn "saving database $path\n";#d# remove later
891 waitpid $pid, 0 if $pid; 1007 waitpid $pid, 0 if $pid;
892 if (0 == ($pid = fork)) { 1008 if (0 == ($pid = fork)) {
893 $db->{_meta}{version} = 1; 1009 $DB->{_meta}{version} = 1;
894 Storable::nstore $db, "$path~"; 1010 Storable::nstore $DB, "$path~";
895 rename "$path~", $path; 1011 rename "$path~", $path;
896 cf::_exit 0 if defined $pid; 1012 cf::_exit 0 if defined $pid;
897 } 1013 }
898 } 1014 }
899 1015
913 $idle->start; 1029 $idle->start;
914 } 1030 }
915 1031
916 sub db_get($;$) { 1032 sub db_get($;$) {
917 @_ >= 2 1033 @_ >= 2
918 ? $db->{$_[0]}{$_[1]} 1034 ? $DB->{$_[0]}{$_[1]}
919 : ($db->{$_[0]} ||= { }) 1035 : ($DB->{$_[0]} ||= { })
920 } 1036 }
921 1037
922 sub db_put($$;$) { 1038 sub db_put($$;$) {
923 if (@_ >= 3) { 1039 if (@_ >= 3) {
924 $db->{$_[0]}{$_[1]} = $_[2]; 1040 $DB->{$_[0]}{$_[1]} = $_[2];
925 } else { 1041 } else {
926 $db->{$_[0]} = $_[1]; 1042 $DB->{$_[0]} = $_[1];
927 } 1043 }
928 db_dirty; 1044 db_dirty;
929 } 1045 }
930 1046
931 attach_global 1047 attach_global
937} 1053}
938 1054
939############################################################################# 1055#############################################################################
940# the server's main() 1056# the server's main()
941 1057
1058sub cfg_load {
1059 open my $fh, "<:utf8", cf::confdir . "/config"
1060 or return;
1061
1062 local $/;
1063 *CFG = YAML::Syck::Load <$fh>;
1064}
1065
942sub main { 1066sub main {
1067 cfg_load;
943 db_load; 1068 db_load;
944 load_extensions; 1069 load_extensions;
945 Event::loop; 1070 Event::loop;
946} 1071}
947 1072
999 1124
1000 # reload cf.pm 1125 # reload cf.pm
1001 $msg->("reloading cf.pm"); 1126 $msg->("reloading cf.pm");
1002 require cf; 1127 require cf;
1003 1128
1004 # load database again 1129 # load config and database again
1130 cf::cfg_load;
1005 cf::db_load; 1131 cf::db_load;
1006 1132
1007 # load extensions 1133 # load extensions
1008 $msg->("load extensions"); 1134 $msg->("load extensions");
1009 cf::load_extensions; 1135 cf::load_extensions;
1022 warn $_[0]; 1148 warn $_[0];
1023 print "$_[0]\n"; 1149 print "$_[0]\n";
1024 }; 1150 };
1025} 1151}
1026 1152
1153register "<global>", __PACKAGE__;
1154
1027register_command "perl-reload", 0, sub { 1155register_command "perl-reload" => sub {
1028 my ($who, $arg) = @_; 1156 my ($who, $arg) = @_;
1029 1157
1030 if ($who->flag (FLAG_WIZ)) { 1158 if ($who->flag (FLAG_WIZ)) {
1031 _perl_reload { 1159 _perl_reload {
1032 warn $_[0]; 1160 warn $_[0];
1033 $who->message ($_[0]); 1161 $who->message ($_[0]);
1034 }; 1162 };
1035 } 1163 }
1036}; 1164};
1037 1165
1038register "<global>", __PACKAGE__;
1039
1040unshift @INC, $LIBDIR; 1166unshift @INC, $LIBDIR;
1041 1167
1042$TICK_WATCHER = Event->timer ( 1168$TICK_WATCHER = Event->timer (
1043 prio => 1, 1169 prio => 1,
1170 async => 1,
1044 at => $NEXT_TICK || 1, 1171 at => $NEXT_TICK || 1,
1045 cb => sub { 1172 cb => sub {
1046 cf::server_tick; # one server iteration 1173 cf::server_tick; # one server iteration
1047 1174
1048 my $NOW = Event::time; 1175 my $NOW = Event::time;
1049 $NEXT_TICK += $TICK; 1176 $NEXT_TICK += $TICK;
1050 1177
1051 # if we are delayed by four ticks, skip them all 1178 # if we are delayed by four ticks or more, skip them all
1052 $NEXT_TICK = $NOW if $NOW >= $NEXT_TICK + $TICK * 4; 1179 $NEXT_TICK = $NOW if $NOW >= $NEXT_TICK + $TICK * 4;
1053 1180
1054 $TICK_WATCHER->at ($NEXT_TICK); 1181 $TICK_WATCHER->at ($NEXT_TICK);
1055 $TICK_WATCHER->start; 1182 $TICK_WATCHER->start;
1056 }, 1183 },
1057); 1184);
1058 1185
1186IO::AIO::max_poll_time $TICK * 0.2;
1187
1188Event->io (fd => IO::AIO::poll_fileno,
1189 poll => 'r',
1190 prio => 5,
1191 cb => \&IO::AIO::poll_cb);
1192
10591 11931
1060 1194

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines