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.67 by root, Tue Sep 12 23:22:32 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
808 } 919 }
809 920
810 wantarray ? @res : $res[0] 921 wantarray ? @res : $res[0]
811} 922}
812 923
924=item cf::register_script_function $function => $cb
925
926Register a function that can be called from within map/npc scripts. The
927function should be reasonably secure and should be put into a package name
928like the extension.
929
930Example: register a function that gets called whenever a map script calls
931C<rent::overview>, as used by the C<rent> extension.
932
933 cf::register_script_function "rent::overview" => sub {
934 ...
935 };
936
937=cut
938
813sub register_script_function { 939sub register_script_function {
814 my ($fun, $cb) = @_; 940 my ($fun, $cb) = @_;
815 941
816 no strict 'refs'; 942 no strict 'refs';
817 *{"safe::$fun"} = $safe_hole->wrap ($cb); 943 *{"safe::$fun"} = $safe_hole->wrap ($cb);
818} 944}
945
946=back
947
948=cut
819 949
820############################################################################# 950#############################################################################
821 951
822=head2 EXTENSION DATABASE SUPPORT 952=head2 EXTENSION DATABASE SUPPORT
823 953
858 988
859Immediately write the database to disk I<if it is dirty>. 989Immediately write the database to disk I<if it is dirty>.
860 990
861=cut 991=cut
862 992
993our $DB;
994
863{ 995{
864 my $db;
865 my $path = cf::localdir . "/database.pst"; 996 my $path = cf::localdir . "/database.pst";
866 997
867 sub db_load() { 998 sub db_load() {
868 warn "loading database $path\n";#d# remove later 999 warn "loading database $path\n";#d# remove later
869 $db = stat $path ? Storable::retrieve $path : { }; 1000 $DB = stat $path ? Storable::retrieve $path : { };
870 } 1001 }
871 1002
872 my $pid; 1003 my $pid;
873 1004
874 sub db_save() { 1005 sub db_save() {
875 warn "saving database $path\n";#d# remove later 1006 warn "saving database $path\n";#d# remove later
876 waitpid $pid, 0 if $pid; 1007 waitpid $pid, 0 if $pid;
877 if (0 == ($pid = fork)) { 1008 if (0 == ($pid = fork)) {
878 $db->{_meta}{version} = 1; 1009 $DB->{_meta}{version} = 1;
879 Storable::nstore $db, "$path~"; 1010 Storable::nstore $DB, "$path~";
880 rename "$path~", $path; 1011 rename "$path~", $path;
881 kill 9, $$ if defined $pid; #d# remove when binary updated
882 cf::_exit 0 if defined $pid; 1012 cf::_exit 0 if defined $pid;
883 } 1013 }
884 } 1014 }
885 1015
886 my $dirty; 1016 my $dirty;
899 $idle->start; 1029 $idle->start;
900 } 1030 }
901 1031
902 sub db_get($;$) { 1032 sub db_get($;$) {
903 @_ >= 2 1033 @_ >= 2
904 ? $db->{$_[0]}{$_[1]} 1034 ? $DB->{$_[0]}{$_[1]}
905 : ($db->{$_[0]} ||= { }) 1035 : ($DB->{$_[0]} ||= { })
906 } 1036 }
907 1037
908 sub db_put($$;$) { 1038 sub db_put($$;$) {
909 if (@_ >= 3) { 1039 if (@_ >= 3) {
910 $db->{$_[0]}{$_[1]} = $_[2]; 1040 $DB->{$_[0]}{$_[1]} = $_[2];
911 } else { 1041 } else {
912 $db->{$_[0]} = $_[1]; 1042 $DB->{$_[0]} = $_[1];
913 } 1043 }
914 db_dirty; 1044 db_dirty;
915 } 1045 }
916 1046
917 attach_global 1047 attach_global
923} 1053}
924 1054
925############################################################################# 1055#############################################################################
926# the server's main() 1056# the server's main()
927 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
928sub main { 1066sub main {
1067 cfg_load;
929 db_load; 1068 db_load;
930 load_extensions; 1069 load_extensions;
931 Event::loop; 1070 Event::loop;
932} 1071}
933 1072
985 1124
986 # reload cf.pm 1125 # reload cf.pm
987 $msg->("reloading cf.pm"); 1126 $msg->("reloading cf.pm");
988 require cf; 1127 require cf;
989 1128
990 # load database again 1129 # load config and database again
1130 cf::cfg_load;
991 cf::db_load; 1131 cf::db_load;
992 1132
993 # load extensions 1133 # load extensions
994 $msg->("load extensions"); 1134 $msg->("load extensions");
995 cf::load_extensions; 1135 cf::load_extensions;
1008 warn $_[0]; 1148 warn $_[0];
1009 print "$_[0]\n"; 1149 print "$_[0]\n";
1010 }; 1150 };
1011} 1151}
1012 1152
1153register "<global>", __PACKAGE__;
1154
1013register_command "perl-reload", 0, sub { 1155register_command "perl-reload" => sub {
1014 my ($who, $arg) = @_; 1156 my ($who, $arg) = @_;
1015 1157
1016 if ($who->flag (FLAG_WIZ)) { 1158 if ($who->flag (FLAG_WIZ)) {
1017 _perl_reload { 1159 _perl_reload {
1018 warn $_[0]; 1160 warn $_[0];
1019 $who->message ($_[0]); 1161 $who->message ($_[0]);
1020 }; 1162 };
1021 } 1163 }
1022}; 1164};
1023 1165
1024register "<global>", __PACKAGE__;
1025
1026unshift @INC, $LIBDIR; 1166unshift @INC, $LIBDIR;
1027 1167
1028$TICK_WATCHER = Event->timer ( 1168$TICK_WATCHER = Event->timer (
1029 prio => 1, 1169 prio => 1,
1170 async => 1,
1030 at => $NEXT_TICK || 1, 1171 at => $NEXT_TICK || 1,
1031 cb => sub { 1172 cb => sub {
1032 cf::server_tick; # one server iteration 1173 cf::server_tick; # one server iteration
1033 1174
1034 my $NOW = Event::time; 1175 my $NOW = Event::time;
1035 $NEXT_TICK += $TICK; 1176 $NEXT_TICK += $TICK;
1036 1177
1037 # if we are delayed by four ticks, skip them all 1178 # if we are delayed by four ticks or more, skip them all
1038 $NEXT_TICK = $NOW if $NOW >= $NEXT_TICK + $TICK * 4; 1179 $NEXT_TICK = $NOW if $NOW >= $NEXT_TICK + $TICK * 4;
1039 1180
1040 $TICK_WATCHER->at ($NEXT_TICK); 1181 $TICK_WATCHER->at ($NEXT_TICK);
1041 $TICK_WATCHER->start; 1182 $TICK_WATCHER->start;
1042 }, 1183 },
1043); 1184);
1044 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
10451 11931
1046 1194

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines