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.61 by root, Sun Sep 3 22:45:56 2006 UTC vs.
Revision 1.72 by root, Sun Oct 1 11:41:37 2006 UTC

5use Storable; 5use Storable;
6use Opcode; 6use Opcode;
7use Safe; 7use Safe;
8use Safe::Hole; 8use Safe::Hole;
9 9
10use YAML::Syck ();
10use Time::HiRes; 11use Time::HiRes;
11use Event; 12use Event;
12$Event::Eval = 1; # no idea why this is required, but it is 13$Event::Eval = 1; # no idea why this is required, but it is
13 14
15# work around bug in YAML::Syck - bad news for perl6, will it be as broken wrt. unicode?
16$YAML::Syck::ImplicitUnicode = 1;
17
14use strict; 18use strict;
15 19
16_reload_1; 20_init_vars;
17 21
18our %COMMAND = (); 22our %COMMAND = ();
19our @EVENT; 23our @EVENT;
20our %PROP_TYPE;
21our %PROP_IDX;
22our $LIBDIR = maps_directory "perl"; 24our $LIBDIR = maps_directory "perl";
23 25
24our $TICK = MAX_TIME * 1e-6; 26our $TICK = MAX_TIME * 1e-6;
25our $TICK_WATCHER; 27our $TICK_WATCHER;
26our $NEXT_TICK; 28our $NEXT_TICK;
29
30our %CFG;
31
32#############################################################################
33
34=head2 GLOBAL VARIABLES
35
36=over 4
37
38=item $cf::LIBDIR
39
40The perl library directory, where extensions and cf-specific modules can
41be found. It will be added to C<@INC> automatically.
42
43=item $cf::TICK
44
45The interval between server ticks, in seconds.
46
47=item %cf::CFG
48
49Configuration for the server, loaded from C</etc/crossfire/config>, or
50from wherever your confdir points to.
51
52=back
53
54=cut
27 55
28BEGIN { 56BEGIN {
29 *CORE::GLOBAL::warn = sub { 57 *CORE::GLOBAL::warn = sub {
30 my $msg = join "", @_; 58 my $msg = join "", @_;
31 $msg .= "\n" 59 $msg .= "\n"
34 print STDERR "cfperl: $msg"; 62 print STDERR "cfperl: $msg";
35 LOG llevError, "cfperl: $msg"; 63 LOG llevError, "cfperl: $msg";
36 }; 64 };
37} 65}
38 66
39my %ignore_set = (MAP_PROP_PATH => 1); # I hate the plug-in api. Deeply!
40
41# generate property mutators
42sub prop_gen {
43 my ($prefix, $class) = @_;
44
45 no strict 'refs';
46
47 for my $prop (keys %PROP_TYPE) {
48 $prop =~ /^\Q$prefix\E_(.*$)/ or next;
49 my $sub = lc $1;
50
51 my $type = $PROP_TYPE{$prop};
52 my $idx = $PROP_IDX {$prop};
53
54 *{"$class\::get_$sub"} = *{"$class\::$sub"} = sub {
55 $_[0]->get_property ($type, $idx)
56 };
57
58 *{"$class\::set_$sub"} = sub {
59 $_[0]->set_property ($type, $idx, $_[1]);
60 } unless $ignore_set{$prop};
61 }
62}
63
64# auto-generate most of the API
65
66prop_gen OBJECT_PROP => "cf::object";
67# CFAPI_OBJECT_ANIMATION?
68prop_gen PLAYER_PROP => "cf::object::player";
69
70prop_gen MAP_PROP => "cf::map";
71prop_gen ARCH_PROP => "cf::arch";
72
73@safe::cf::object::player::ISA = @cf::object::player::ISA = 'cf::object'; 67@safe::cf::object::player::ISA = @cf::object::player::ISA = 'cf::object';
74 68
75# we bless all objects into (empty) derived classes to force a method lookup 69# we bless all objects into (empty) derived classes to force a method lookup
76# within the Safe compartment. 70# within the Safe compartment.
77for my $pkg (qw(cf::object cf::object::player cf::player cf::map cf::party cf::region cf::arch cf::living)) { 71for my $pkg (qw(cf::object cf::object::player cf::player cf::map cf::party cf::region cf::arch cf::living)) {
87my @exts; 81my @exts;
88my @hook; 82my @hook;
89my %command; 83my %command;
90my %extcmd; 84my %extcmd;
91 85
92############################################################################# 86=head2 UTILITY FUNCTIONS
93# utility functions 87
88=over 4
89
90=cut
94 91
95use JSON::Syck (); # TODO# replace by JSON::PC once working 92use JSON::Syck (); # TODO# replace by JSON::PC once working
93
94=item $ref = cf::from_json $json
95
96Converts a JSON string into the corresponding perl data structure.
97
98=cut
96 99
97sub from_json($) { 100sub from_json($) {
98 $JSON::Syck::ImplicitUnicode = 1; # work around JSON::Syck bugs 101 $JSON::Syck::ImplicitUnicode = 1; # work around JSON::Syck bugs
99 JSON::Syck::Load $_[0] 102 JSON::Syck::Load $_[0]
100} 103}
101 104
105=item $json = cf::to_json $ref
106
107Converts a perl data structure into its JSON representation.
108
109=cut
110
102sub to_json($) { 111sub to_json($) {
103 $JSON::Syck::ImplicitUnicode = 0; # work around JSON::Syck bugs 112 $JSON::Syck::ImplicitUnicode = 0; # work around JSON::Syck bugs
104 JSON::Syck::Dump $_[0] 113 JSON::Syck::Dump $_[0]
105} 114}
106 115
107############################################################################# 116=back
108# "new" plug-in system
109 117
118=cut
119
120#############################################################################
121
110=head3 EVENTS AND OBJECT ATTACHMENTS 122=head2 EVENTS AND OBJECT ATTACHMENTS
111 123
112=over 4 124=over 4
113 125
114=item $object->attach ($attachment, key => $value...) 126=item $object->attach ($attachment, key => $value...)
115 127
389 for (@$callbacks) { 401 for (@$callbacks) {
390 eval { &{$_->[1]} }; 402 eval { &{$_->[1]} };
391 403
392 if ($@) { 404 if ($@) {
393 warn "$@"; 405 warn "$@";
394 warn "... while processing $EVENT[$event][0] event, skipping processing altogether.\n"; 406 warn "... while processing $EVENT[$event][0](@_) event, skipping processing altogether.\n";
395 override; 407 override;
396 } 408 }
397 409
398 return 1 if $override; 410 return 1 if $override;
399 } 411 }
415removed in future versions), and there is no public API to access override 427removed in future versions), and there is no public API to access override
416results (if you must, access C<@cf::invoke_results> directly). 428results (if you must, access C<@cf::invoke_results> directly).
417 429
418=back 430=back
419 431
420=head2 methods valid for all pointers 432=cut
433
434#############################################################################
435
436=head2 METHODS VALID FOR ALL CORE OBJECTS
421 437
422=over 4 438=over 4
423 439
424=item $object->valid 440=item $object->valid, $player->valid, $map->valid
425
426=item $player->valid
427
428=item $map->valid
429 441
430Just because you have a perl object does not mean that the corresponding 442Just because you have a perl object does not mean that the corresponding
431C-level object still exists. If you try to access an object that has no 443C-level object still exists. If you try to access an object that has no
432valid C counterpart anymore you get an exception at runtime. This method 444valid C counterpart anymore you get an exception at runtime. This method
433can be used to test for existence of the C object part without causing an 445can be used to test for existence of the C object part without causing an
679 1 691 1
680 } or warn "$ext not loaded: $@"; 692 } or warn "$ext not loaded: $@";
681 } 693 }
682} 694}
683 695
684sub _perl_reload(&) {
685 my ($msg) = @_;
686
687 $msg->("reloading...");
688
689 eval {
690 # 1. cancel all watchers
691 $_->cancel for Event::all_watchers;
692
693 # 2. unload all extensions
694 for (@exts) {
695 $msg->("unloading <$_>");
696 unload_extension $_;
697 }
698
699 # 3. unload all modules loaded from $LIBDIR
700 while (my ($k, $v) = each %INC) {
701 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/;
702
703 $msg->("removing <$k>");
704 delete $INC{$k};
705
706 $k =~ s/\.pm$//;
707 $k =~ s/\//::/g;
708
709 if (my $cb = $k->can ("unload_module")) {
710 $cb->();
711 }
712
713 Symbol::delete_package $k;
714 }
715
716 # 4. get rid of safe::, as good as possible
717 Symbol::delete_package "safe::$_"
718 for qw(cf::object cf::object::player cf::player cf::map cf::party cf::region);
719
720 # 5. remove register_script_function callbacks
721 # TODO
722
723 # 6. unload cf.pm "a bit"
724 delete $INC{"cf.pm"};
725
726 # don't, removes xs symbols, too,
727 # and global variables created in xs
728 #Symbol::delete_package __PACKAGE__;
729
730 # 7. reload cf.pm
731 $msg->("reloading cf.pm");
732 require cf;
733
734 $msg->("load extensions");
735 cf::load_extensions;
736 };
737 $msg->($@) if $@;
738
739 $msg->("reloaded");
740};
741
742sub perl_reload() {
743 _perl_reload {
744 warn $_[0];
745 print "$_[0]\n";
746 };
747}
748
749register_command "perl-reload", 0, sub {
750 my ($who, $arg) = @_;
751
752 if ($who->flag (FLAG_WIZ)) {
753 _perl_reload {
754 warn $_[0];
755 $who->message ($_[0]);
756 };
757 }
758};
759
760############################################################################# 696#############################################################################
761# extcmd framework, basically convert ext <msg> 697# extcmd framework, basically convert ext <msg>
762# into pkg::->on_extcmd_arg1 (...) while shortcutting a few 698# into pkg::->on_extcmd_arg1 (...) while shortcutting a few
763 699
764attach_to_players 700attach_to_players
816 } 752 }
817 }, 753 },
818; 754;
819 755
820############################################################################# 756#############################################################################
821# core extensions - in perl 757
758=head2 CORE EXTENSIONS
759
760Functions and methods that extend core crossfire objects.
761
762=over 4
822 763
823=item cf::player::exists $login 764=item cf::player::exists $login
824 765
825Returns true when the given account exists. 766Returns true when the given account exists.
826 767
866 $msg{msgid} = $id; 807 $msg{msgid} = $id;
867 808
868 $self->send ("ext " . to_json \%msg); 809 $self->send ("ext " . to_json \%msg);
869} 810}
870 811
812=back
813
814=cut
815
871############################################################################# 816#############################################################################
872# map scripting support 817
818=head2 SAFE SCRIPTING
819
820Functions that provide a safe environment to compile and execute
821snippets of perl code without them endangering the safety of the server
822itself. Looping constructs, I/O operators and other built-in functionality
823is not available in the safe scripting environment, and the number of
824functions and methods that cna be called is greatly reduced.
825
826=cut
873 827
874our $safe = new Safe "safe"; 828our $safe = new Safe "safe";
875our $safe_hole = new Safe::Hole; 829our $safe_hole = new Safe::Hole;
876 830
877$SIG{FPE} = 'IGNORE'; 831$SIG{FPE} = 'IGNORE';
878 832
879$safe->permit_only (Opcode::opset qw(:base_core :base_mem :base_orig :base_math sort time)); 833$safe->permit_only (Opcode::opset qw(:base_core :base_mem :base_orig :base_math sort time));
880 834
881# here we export the classes and methods available to script code 835# here we export the classes and methods available to script code
836
837=pod
838
839The following fucntions and emthods are available within a safe environment:
840
841 cf::object contr pay_amount pay_player
842 cf::object::player player
843 cf::player peaceful
844
845=cut
882 846
883for ( 847for (
884 ["cf::object" => qw(contr pay_amount pay_player)], 848 ["cf::object" => qw(contr pay_amount pay_player)],
885 ["cf::object::player" => qw(player)], 849 ["cf::object::player" => qw(player)],
886 ["cf::player" => qw(peaceful)], 850 ["cf::player" => qw(peaceful)],
889 my ($pkg, @funs) = @$_; 853 my ($pkg, @funs) = @$_;
890 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"}) 854 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"})
891 for @funs; 855 for @funs;
892} 856}
893 857
858=over 4
859
860=item @retval = safe_eval $code, [var => value, ...]
861
862Compiled and executes the given perl code snippet. additional var/value
863pairs result in temporary local (my) scalar variables of the given name
864that are available in the code snippet. Example:
865
866 my $five = safe_eval '$first + $second', first => 1, second => 4;
867
868=cut
869
894sub safe_eval($;@) { 870sub safe_eval($;@) {
895 my ($code, %vars) = @_; 871 my ($code, %vars) = @_;
896 872
897 my $qcode = $code; 873 my $qcode = $code;
898 $qcode =~ s/"/‟/g; # not allowed in #line filenames 874 $qcode =~ s/"/‟/g; # not allowed in #line filenames
920 } 896 }
921 897
922 wantarray ? @res : $res[0] 898 wantarray ? @res : $res[0]
923} 899}
924 900
901=item cf::register_script_function $function => $cb
902
903Register a function that can be called from within map/npc scripts. The
904function should be reasonably secure and should be put into a package name
905like the extension.
906
907Example: register a function that gets called whenever a map script calls
908C<rent::overview>, as used by the C<rent> extension.
909
910 cf::register_script_function "rent::overview" => sub {
911 ...
912 };
913
914=cut
915
925sub register_script_function { 916sub register_script_function {
926 my ($fun, $cb) = @_; 917 my ($fun, $cb) = @_;
927 918
928 no strict 'refs'; 919 no strict 'refs';
929 *{"safe::$fun"} = $safe_hole->wrap ($cb); 920 *{"safe::$fun"} = $safe_hole->wrap ($cb);
930} 921}
931 922
923=back
924
925=cut
926
927#############################################################################
928
929=head2 EXTENSION DATABASE SUPPORT
930
931Crossfire maintains a very simple database for extension use. It can
932currently store anything that can be serialised using Storable, which
933excludes objects.
934
935The parameter C<$family> should best start with the name of the extension
936using it, it should be unique.
937
938=over 4
939
940=item $hashref = cf::db_get $family
941
942Return a hashref for use by the extension C<$family>, which can be
943modified. After modifications, you have to call C<cf::db_dirty> or
944C<cf::db_sync>.
945
946=item $value = cf::db_get $family => $key
947
948Returns a single value from the database
949
950=item cf::db_put $family => $hashref
951
952Stores the given family hashref into the database. Updates are delayed, if
953you want the data to be synced to disk immediately, use C<cf::db_sync>.
954
955=item cf::db_put $family => $key => $value
956
957Stores the given C<$value> in the family hash. Updates are delayed, if you
958want the data to be synced to disk immediately, use C<cf::db_sync>.
959
960=item cf::db_dirty
961
962Marks the database as dirty, to be updated at a later time.
963
964=item cf::db_sync
965
966Immediately write the database to disk I<if it is dirty>.
967
968=cut
969
970{
971 my $db;
972 my $path = cf::localdir . "/database.pst";
973
974 sub db_load() {
975 warn "loading database $path\n";#d# remove later
976 $db = stat $path ? Storable::retrieve $path : { };
977 }
978
979 my $pid;
980
981 sub db_save() {
982 warn "saving database $path\n";#d# remove later
983 waitpid $pid, 0 if $pid;
984 if (0 == ($pid = fork)) {
985 $db->{_meta}{version} = 1;
986 Storable::nstore $db, "$path~";
987 rename "$path~", $path;
988 cf::_exit 0 if defined $pid;
989 }
990 }
991
992 my $dirty;
993
994 sub db_sync() {
995 db_save if $dirty;
996 undef $dirty;
997 }
998
999 my $idle = Event->idle (min => $TICK * 2.8, max => 10, repeat => 0, cb => sub {
1000 db_sync;
1001 });
1002
1003 sub db_dirty() {
1004 $dirty = 1;
1005 $idle->start;
1006 }
1007
1008 sub db_get($;$) {
1009 @_ >= 2
1010 ? $db->{$_[0]}{$_[1]}
1011 : ($db->{$_[0]} ||= { })
1012 }
1013
1014 sub db_put($$;$) {
1015 if (@_ >= 3) {
1016 $db->{$_[0]}{$_[1]} = $_[2];
1017 } else {
1018 $db->{$_[0]} = $_[1];
1019 }
1020 db_dirty;
1021 }
1022
1023 attach_global
1024 prio => 10000,
1025 on_cleanup => sub {
1026 db_sync;
1027 },
1028 ;
1029}
1030
932############################################################################# 1031#############################################################################
933# the server's main() 1032# the server's main()
934 1033
1034sub load_cfg {
1035 open my $fh, "<:utf8", cf::confdir . "/config"
1036 or return;
1037
1038 local $/;
1039 *CFG = YAML::Syck::Load <$fh>;
1040
1041 use Data::Dumper; warn Dumper \%CFG;
1042}
1043
935sub main { 1044sub main {
1045 load_cfg;
1046 db_load;
936 load_extensions; 1047 load_extensions;
937 Event::loop; 1048 Event::loop;
938} 1049}
939 1050
940############################################################################# 1051#############################################################################
941# initialisation 1052# initialisation
1053
1054sub _perl_reload(&) {
1055 my ($msg) = @_;
1056
1057 $msg->("reloading...");
1058
1059 eval {
1060 # cancel all watchers
1061 $_->cancel for Event::all_watchers;
1062
1063 # unload all extensions
1064 for (@exts) {
1065 $msg->("unloading <$_>");
1066 unload_extension $_;
1067 }
1068
1069 # unload all modules loaded from $LIBDIR
1070 while (my ($k, $v) = each %INC) {
1071 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/;
1072
1073 $msg->("removing <$k>");
1074 delete $INC{$k};
1075
1076 $k =~ s/\.pm$//;
1077 $k =~ s/\//::/g;
1078
1079 if (my $cb = $k->can ("unload_module")) {
1080 $cb->();
1081 }
1082
1083 Symbol::delete_package $k;
1084 }
1085
1086 # sync database to disk
1087 cf::db_sync;
1088
1089 # get rid of safe::, as good as possible
1090 Symbol::delete_package "safe::$_"
1091 for qw(cf::object cf::object::player cf::player cf::map cf::party cf::region);
1092
1093 # remove register_script_function callbacks
1094 # TODO
1095
1096 # unload cf.pm "a bit"
1097 delete $INC{"cf.pm"};
1098
1099 # don't, removes xs symbols, too,
1100 # and global variables created in xs
1101 #Symbol::delete_package __PACKAGE__;
1102
1103 # reload cf.pm
1104 $msg->("reloading cf.pm");
1105 require cf;
1106
1107 # load database again
1108 cf::db_load;
1109
1110 # load extensions
1111 $msg->("load extensions");
1112 cf::load_extensions;
1113
1114 # reattach attachments to objects
1115 $msg->("reattach");
1116 _global_reattach;
1117 };
1118 $msg->($@) if $@;
1119
1120 $msg->("reloaded");
1121};
1122
1123sub perl_reload() {
1124 _perl_reload {
1125 warn $_[0];
1126 print "$_[0]\n";
1127 };
1128}
1129
1130register_command "perl-reload", 0, sub {
1131 my ($who, $arg) = @_;
1132
1133 if ($who->flag (FLAG_WIZ)) {
1134 _perl_reload {
1135 warn $_[0];
1136 $who->message ($_[0]);
1137 };
1138 }
1139};
942 1140
943register "<global>", __PACKAGE__; 1141register "<global>", __PACKAGE__;
944 1142
945unshift @INC, $LIBDIR; 1143unshift @INC, $LIBDIR;
946 1144
959 $TICK_WATCHER->at ($NEXT_TICK); 1157 $TICK_WATCHER->at ($NEXT_TICK);
960 $TICK_WATCHER->start; 1158 $TICK_WATCHER->start;
961 }, 1159 },
962); 1160);
963 1161
964_reload_2;
965
9661 11621
967 1163

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines