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.66 by root, Tue Sep 12 22:43:31 2006 UTC vs.
Revision 1.84 by root, Mon Dec 11 02:54: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
16_init_vars; 21_init_vars;
17 22
18our %COMMAND = (); 23our %COMMAND = ();
20our $LIBDIR = maps_directory "perl"; 25our $LIBDIR = maps_directory "perl";
21 26
22our $TICK = MAX_TIME * 1e-6; 27our $TICK = MAX_TIME * 1e-6;
23our $TICK_WATCHER; 28our $TICK_WATCHER;
24our $NEXT_TICK; 29our $NEXT_TICK;
30
31our %CFG;
32
33our $UPTIME; $UPTIME ||= time;
34
35#############################################################################
36
37=head2 GLOBAL VARIABLES
38
39=over 4
40
41=item $cf::UPTIME
42
43The timestamp of the server start (so not actually an uptime).
44
45=item $cf::LIBDIR
46
47The perl library directory, where extensions and cf-specific modules can
48be found. It will be added to C<@INC> automatically.
49
50=item $cf::TICK
51
52The interval between server ticks, in seconds.
53
54=item %cf::CFG
55
56Configuration for the server, loaded from C</etc/crossfire/config>, or
57from wherever your confdir points to.
58
59=back
60
61=cut
25 62
26BEGIN { 63BEGIN {
27 *CORE::GLOBAL::warn = sub { 64 *CORE::GLOBAL::warn = sub {
28 my $msg = join "", @_; 65 my $msg = join "", @_;
29 $msg .= "\n" 66 $msg .= "\n"
51my @exts; 88my @exts;
52my @hook; 89my @hook;
53my %command; 90my %command;
54my %extcmd; 91my %extcmd;
55 92
56############################################################################# 93=head2 UTILITY FUNCTIONS
57# utility functions 94
95=over 4
96
97=cut
58 98
59use JSON::Syck (); # TODO# replace by JSON::PC once working 99use JSON::Syck (); # TODO# replace by JSON::PC once working
100
101=item $ref = cf::from_json $json
102
103Converts a JSON string into the corresponding perl data structure.
104
105=cut
60 106
61sub from_json($) { 107sub from_json($) {
62 $JSON::Syck::ImplicitUnicode = 1; # work around JSON::Syck bugs 108 $JSON::Syck::ImplicitUnicode = 1; # work around JSON::Syck bugs
63 JSON::Syck::Load $_[0] 109 JSON::Syck::Load $_[0]
64} 110}
65 111
112=item $json = cf::to_json $ref
113
114Converts a perl data structure into its JSON representation.
115
116=cut
117
66sub to_json($) { 118sub to_json($) {
67 $JSON::Syck::ImplicitUnicode = 0; # work around JSON::Syck bugs 119 $JSON::Syck::ImplicitUnicode = 0; # work around JSON::Syck bugs
68 JSON::Syck::Dump $_[0] 120 JSON::Syck::Dump $_[0]
69} 121}
70 122
123=back
124
125=cut
126
71############################################################################# 127#############################################################################
72# "new" plug-in system
73 128
74=head3 EVENTS AND OBJECT ATTACHMENTS 129=head2 EVENTS AND OBJECT ATTACHMENTS
75 130
76=over 4 131=over 4
77 132
78=item $object->attach ($attachment, key => $value...) 133=item $object->attach ($attachment, key => $value...)
79 134
379removed in future versions), and there is no public API to access override 434removed in future versions), and there is no public API to access override
380results (if you must, access C<@cf::invoke_results> directly). 435results (if you must, access C<@cf::invoke_results> directly).
381 436
382=back 437=back
383 438
384=head2 methods valid for all pointers 439=cut
440
441#############################################################################
442
443=head2 METHODS VALID FOR ALL CORE OBJECTS
385 444
386=over 4 445=over 4
387 446
388=item $object->valid 447=item $object->valid, $player->valid, $map->valid
389
390=item $player->valid
391
392=item $map->valid
393 448
394Just because you have a perl object does not mean that the corresponding 449Just 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 450C-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 451valid 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 452can be used to test for existence of the C object part without causing an
470 unlink $filename; 525 unlink $filename;
471 unlink "$filename.pst"; 526 unlink "$filename.pst";
472 } 527 }
473} 528}
474 529
530sub object_freezer_as_string {
531 my ($rdata, $objs) = @_;
532
533 use Data::Dumper;
534
535 $$rdata . Dumper $objs
536}
537
475sub object_thawer_load { 538sub object_thawer_load {
476 my ($filename) = @_; 539 my ($filename) = @_;
477 540
478 local $/; 541 local $/;
479 542
581 . "#line 1 \"$path\"\n{\n" 644 . "#line 1 \"$path\"\n{\n"
582 . (do { local $/; <$fh> }) 645 . (do { local $/; <$fh> })
583 . "\n};\n1"; 646 . "\n};\n1";
584 647
585 eval $source 648 eval $source
586 or die "$path: $@"; 649 or die $@ ? "$path: $@\n"
650 : "extension disabled.\n";
587 651
588 push @exts, $pkg; 652 push @exts, $pkg;
589 $ext_pkg{$base} = $pkg; 653 $ext_pkg{$base} = $pkg;
590 654
591# no strict 'refs'; 655# no strict 'refs';
704 } 768 }
705 }, 769 },
706; 770;
707 771
708############################################################################# 772#############################################################################
709# core extensions - in perl 773
774=head2 CORE EXTENSIONS
775
776Functions and methods that extend core crossfire objects.
777
778=over 4
710 779
711=item cf::player::exists $login 780=item cf::player::exists $login
712 781
713Returns true when the given account exists. 782Returns true when the given account exists.
714 783
717sub cf::player::exists($) { 786sub cf::player::exists($) {
718 cf::player::find $_[0] 787 cf::player::find $_[0]
719 or -f sprintf "%s/%s/%s/%s.pl", cf::localdir, cf::playerdir, ($_[0]) x 2; 788 or -f sprintf "%s/%s/%s/%s.pl", cf::localdir, cf::playerdir, ($_[0]) x 2;
720} 789}
721 790
722=item $player->reply ($npc, $msg[, $flags]) 791=item $player_object->reply ($npc, $msg[, $flags])
723 792
724Sends a message to the player, as if the npc C<$npc> replied. C<$npc> 793Sends 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 794can be C<undef>. Does the right thing when the player is currently in a
726dialogue with the given NPC character. 795dialogue with the given NPC character.
727 796
754 $msg{msgid} = $id; 823 $msg{msgid} = $id;
755 824
756 $self->send ("ext " . to_json \%msg); 825 $self->send ("ext " . to_json \%msg);
757} 826}
758 827
828=item $player_object->may ("access")
829
830Returns wether the given player is authorized to access resource "access"
831(e.g. "command_wizcast").
832
833=cut
834
835sub cf::object::player::may {
836 my ($self, $access) = @_;
837
838 $self->flag (cf::FLAG_WIZ) ||
839 (ref $cf::CFG{"may_$access"}
840 ? scalar grep $self->name eq $_, @{$cf::CFG{"may_$access"}}
841 : $cf::CFG{"may_$access"})
842}
843
844=cut
845
759############################################################################# 846#############################################################################
760# map scripting support 847
848=head2 SAFE SCRIPTING
849
850Functions that provide a safe environment to compile and execute
851snippets of perl code without them endangering the safety of the server
852itself. Looping constructs, I/O operators and other built-in functionality
853is not available in the safe scripting environment, and the number of
854functions and methods that can be called is greatly reduced.
855
856=cut
761 857
762our $safe = new Safe "safe"; 858our $safe = new Safe "safe";
763our $safe_hole = new Safe::Hole; 859our $safe_hole = new Safe::Hole;
764 860
765$SIG{FPE} = 'IGNORE'; 861$SIG{FPE} = 'IGNORE';
766 862
767$safe->permit_only (Opcode::opset qw(:base_core :base_mem :base_orig :base_math sort time)); 863$safe->permit_only (Opcode::opset qw(:base_core :base_mem :base_orig :base_math sort time));
768 864
769# here we export the classes and methods available to script code 865# here we export the classes and methods available to script code
866
867=pod
868
869The following fucntions and emthods are available within a safe environment:
870
871 cf::object contr pay_amount pay_player
872 cf::object::player player
873 cf::player peaceful
874
875=cut
770 876
771for ( 877for (
772 ["cf::object" => qw(contr pay_amount pay_player)], 878 ["cf::object" => qw(contr pay_amount pay_player)],
773 ["cf::object::player" => qw(player)], 879 ["cf::object::player" => qw(player)],
774 ["cf::player" => qw(peaceful)], 880 ["cf::player" => qw(peaceful)],
777 my ($pkg, @funs) = @$_; 883 my ($pkg, @funs) = @$_;
778 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"}) 884 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"})
779 for @funs; 885 for @funs;
780} 886}
781 887
888=over 4
889
890=item @retval = safe_eval $code, [var => value, ...]
891
892Compiled and executes the given perl code snippet. additional var/value
893pairs result in temporary local (my) scalar variables of the given name
894that are available in the code snippet. Example:
895
896 my $five = safe_eval '$first + $second', first => 1, second => 4;
897
898=cut
899
782sub safe_eval($;@) { 900sub safe_eval($;@) {
783 my ($code, %vars) = @_; 901 my ($code, %vars) = @_;
784 902
785 my $qcode = $code; 903 my $qcode = $code;
786 $qcode =~ s/"/‟/g; # not allowed in #line filenames 904 $qcode =~ s/"/‟/g; # not allowed in #line filenames
808 } 926 }
809 927
810 wantarray ? @res : $res[0] 928 wantarray ? @res : $res[0]
811} 929}
812 930
931=item cf::register_script_function $function => $cb
932
933Register a function that can be called from within map/npc scripts. The
934function should be reasonably secure and should be put into a package name
935like the extension.
936
937Example: register a function that gets called whenever a map script calls
938C<rent::overview>, as used by the C<rent> extension.
939
940 cf::register_script_function "rent::overview" => sub {
941 ...
942 };
943
944=cut
945
813sub register_script_function { 946sub register_script_function {
814 my ($fun, $cb) = @_; 947 my ($fun, $cb) = @_;
815 948
816 no strict 'refs'; 949 no strict 'refs';
817 *{"safe::$fun"} = $safe_hole->wrap ($cb); 950 *{"safe::$fun"} = $safe_hole->wrap ($cb);
818} 951}
952
953=back
954
955=cut
819 956
820############################################################################# 957#############################################################################
821 958
822=head2 EXTENSION DATABASE SUPPORT 959=head2 EXTENSION DATABASE SUPPORT
823 960
858 995
859Immediately write the database to disk I<if it is dirty>. 996Immediately write the database to disk I<if it is dirty>.
860 997
861=cut 998=cut
862 999
1000our $DB;
1001
863{ 1002{
864 my $db;
865 my $path = cf::localdir . "/database.pst"; 1003 my $path = cf::localdir . "/database.pst";
866 1004
867 sub db_load() { 1005 sub db_load() {
868 warn "loading database $path\n";#d# remove later 1006 warn "loading database $path\n";#d# remove later
869 $db = stat $path ? Storable::retrieve $path : { }; 1007 $DB = stat $path ? Storable::retrieve $path : { };
870 } 1008 }
871 1009
872 my $pid; 1010 my $pid;
873 1011
874 sub db_save() { 1012 sub db_save() {
875 warn "saving database $path\n";#d# remove later 1013 warn "saving database $path\n";#d# remove later
876 waitpid $pid, 0 if $pid; 1014 waitpid $pid, 0 if $pid;
877 unless ($pid = fork) { 1015 if (0 == ($pid = fork)) {
878 $db->{_meta}{version} = 1; 1016 $DB->{_meta}{version} = 1;
879 Storable::nstore $db, "$path~"; 1017 Storable::nstore $DB, "$path~";
880 rename "$path~", $path; 1018 rename "$path~", $path;
881 cf::_exit 0 if defined $pid; 1019 cf::_exit 0 if defined $pid;
882 } 1020 }
883 } 1021 }
884 1022
898 $idle->start; 1036 $idle->start;
899 } 1037 }
900 1038
901 sub db_get($;$) { 1039 sub db_get($;$) {
902 @_ >= 2 1040 @_ >= 2
903 ? $db->{$_[0]}{$_[1]} 1041 ? $DB->{$_[0]}{$_[1]}
904 : ($db->{$_[0]} ||= { }) 1042 : ($DB->{$_[0]} ||= { })
905 } 1043 }
906 1044
907 sub db_put($$;$) { 1045 sub db_put($$;$) {
908 if (@_ >= 3) { 1046 if (@_ >= 3) {
909 $db->{$_[0]}{$_[1]} = $_[2]; 1047 $DB->{$_[0]}{$_[1]} = $_[2];
910 } else { 1048 } else {
911 $db->{$_[0]} = $_[1]; 1049 $DB->{$_[0]} = $_[1];
912 } 1050 }
913 db_dirty; 1051 db_dirty;
914 } 1052 }
1053
1054 attach_global
1055 prio => 10000,
1056 on_cleanup => sub {
1057 db_sync;
1058 },
1059 ;
915} 1060}
916 1061
917############################################################################# 1062#############################################################################
918# the server's main() 1063# the server's main()
919 1064
1065sub cfg_load {
1066 open my $fh, "<:utf8", cf::confdir . "/config"
1067 or return;
1068
1069 local $/;
1070 *CFG = YAML::Syck::Load <$fh>;
1071}
1072
920sub main { 1073sub main {
1074 cfg_load;
921 db_load; 1075 db_load;
922 load_extensions; 1076 load_extensions;
923 Event::loop; 1077 Event::loop;
924} 1078}
925 1079
977 1131
978 # reload cf.pm 1132 # reload cf.pm
979 $msg->("reloading cf.pm"); 1133 $msg->("reloading cf.pm");
980 require cf; 1134 require cf;
981 1135
982 # load database again 1136 # load config and database again
1137 cf::cfg_load;
983 cf::db_load; 1138 cf::db_load;
984 1139
985 # load extensions 1140 # load extensions
986 $msg->("load extensions"); 1141 $msg->("load extensions");
987 cf::load_extensions; 1142 cf::load_extensions;
1016register "<global>", __PACKAGE__; 1171register "<global>", __PACKAGE__;
1017 1172
1018unshift @INC, $LIBDIR; 1173unshift @INC, $LIBDIR;
1019 1174
1020$TICK_WATCHER = Event->timer ( 1175$TICK_WATCHER = Event->timer (
1021 prio => 1, 1176 prio => 1,
1177 async => 1,
1022 at => $NEXT_TICK || 1, 1178 at => $NEXT_TICK || 1,
1023 cb => sub { 1179 cb => sub {
1024 cf::server_tick; # one server iteration 1180 cf::server_tick; # one server iteration
1025 1181
1026 my $NOW = Event::time; 1182 my $NOW = Event::time;
1027 $NEXT_TICK += $TICK; 1183 $NEXT_TICK += $TICK;
1028 1184
1029 # if we are delayed by four ticks, skip them all 1185 # if we are delayed by four ticks or more, skip them all
1030 $NEXT_TICK = $NOW if $NOW >= $NEXT_TICK + $TICK * 4; 1186 $NEXT_TICK = $NOW if $NOW >= $NEXT_TICK + $TICK * 4;
1031 1187
1032 $TICK_WATCHER->at ($NEXT_TICK); 1188 $TICK_WATCHER->at ($NEXT_TICK);
1033 $TICK_WATCHER->start; 1189 $TICK_WATCHER->start;
1034 }, 1190 },
1035); 1191);
1036 1192
1193IO::AIO::max_poll_time $TICK * 0.2;
1194
1195Event->io (fd => IO::AIO::poll_fileno,
1196 poll => 'r',
1197 prio => 5,
1198 cb => \&IO::AIO::poll_cb);
1199
10371 12001
1038 1201

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines