1 # This is part of ypp-sc-tools, a set of third-party tools for assisting
2 # players of Yohoho Puzzle Pirates.
4 # Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19 # Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
20 # are used without permission. This program is not endorsed or
21 # sponsored by Three Rings.
25 use HTTP::Request::Common ();
34 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
37 @EXPORT = qw(&parse_info_clientside &fetch_with_rsync
38 &parse_info_serverside &parse_info_serverside_ocean
39 %oceans %commods %clients
40 %vessels %shotname2damage
41 &parse_pctb_commodmap %pctb_commodmap @pctb_commodmap
42 &get_our_version &check_tsv_line
43 &pipethrough_prep &pipethrough_run
44 &pipethrough_run_along &pipethrough_run_finish
45 &pipethrough_run_gzip &http_useragent &version_core
46 &http_useragent_string_map
47 &cgipostform &yarrgpostform &cgi_get_caller
48 &set_ctype_utf8 $masterinfoversion);
54 our $masterinfoversion= 2; # version we understand
56 our %oceans; # eg $oceans{'Midnight'}{'Ruby'}{'Eta Island'}= $sources;
57 our %clients; # eg $clients{'ypp-sc-tools'}= [ qw(last-page) ];
58 our %vessels; # eg $vessels{'War Brig'}{Shot}='medium'
59 # $vessels{'War Brig'}{Volume}= 81000
60 # $vessels{'War Brig'}{Mass}= 54000
61 our %shotname2damage; # eg $shotname2damage{'medium'}= 3;
63 # 's' = Special Circumstances; 'l' = local ; B = with Bleach
66 # eg $commods{'Fine black cloth'}{Srcs}= $sources;
67 # eg $commods{'Fine black cloth'}{Mass}= 700 [g]
68 # eg $commods{'Fine black cloth'}{Volume}= 1000 [ml]
70 our (%pctb_commodmap,@pctb_commodmap);
72 my %colours; # eg $colours{'c'}{'black'}= $sources
73 my (@rawcm, @nocm); # eg $rawcm[0]='fine rum'; $rawcm[1]='fine %c cloth'
76 # when extending the format of source-info in a non-backward
77 # compatible way, be sure to update update-master-info too.
79 sub parse_info1 ($$$) {
80 my ($mmfn,$src,$enoentok)= @_;
81 my $mm= new IO::File $mmfn, 'r';
83 return if $enoentok && $!==&ENOENT;
93 @ctx= (sub { $colours{$colourkind}{lc $_} .= $src; });
94 } elsif (m/^commods$/) {
95 @ctx= (sub { push @rawcm, lc $_; });
96 } elsif (m/^nocommods$/) {
97 @ctx= (sub { push @nocm, lc $_; });
98 } elsif (m/^ocean (\w+)$/) {
100 keys %{ $oceans{$ocean} };
102 $ocean or die; # ref to $ocean needed to work
105 keys %{ $oceans{$ocean}{$arch} };
107 $oceans{$ocean}{$arch}{$_} .= $src;
110 } elsif (m/^vessels$/) {
112 return if m/^[-+|]+$/;
113 m/^ \| \s* ([A-Z][a-z\ ]+[a-z]) \s*
114 \| \s* (small|medium|large) \s*
115 \| \s* ([1-9][0-9,]+) \s*
116 \| \s* ([1-9][0-9,]+) \s*
120 my $v= { Shot => $2, Volume => $3, Mass => $4 };
121 foreach my $vm (qw(Volume Mass)) { $v->{$vm} =~ s/,//g; }
124 } elsif (m/^shot$/) {
126 m/^ ([a-z]+) \s+ (\d+) $/x or die;
127 $shotname2damage{$1}= $2;
129 } elsif (m/^client (\S+.*\S)$/) {
131 $clients{$client}= [ ];
134 push @{ $clients{$client} }, $bug;
137 my $indent= length $&;
138 die "wrong indent $indent" unless defined $ctx[$indent-1];
139 &{ $ctx[$indent-1] }();
144 $mm->error and die $!;
147 #print Dumper(\%oceans);
148 #print Dumper(\@rawcm);
155 if ($s !~ m/\%(\w+)/) {
156 my ($name, $props) = $s =~
157 /^(\S[^\t]*\S)(?:\t+(\S[^\t]*\S))?$/
158 or die "bad commodspec $s";
159 return if grep { $name eq $_ } @nocm;
160 my $ucname= ucfirst $name;
161 $commods{$ucname}{Srcs} .= $ss;
162 my $c= $commods{$ucname};
164 foreach my $prop (defined $props ? split /\s+/, $props : ()) {
165 if ($prop =~ m/^([1-9]\d*)(k?)g$/) {
166 $c->{Mass}= $1 * ($2 ? 1000 : 1);
167 } elsif ($prop =~m/^([1-9]\d*)l$/) {
168 $c->{Volume}= $1 * 1000;
170 die "unknown property $prop for $ucname";
175 die "unknown $&" unless defined $colours{$1};
176 my ($lhs,$pctlet,$rhs)= ($`,$1,$');
177 foreach my $c (keys %{ $colours{$pctlet} }) {
178 &$ca($lhs.$c.$rhs, $ss .'%'. $colours{$pctlet}{$c});
181 foreach (@rawcm) { &$ca($_,$src); }
184 sub parse_info_clientside () {
185 my $master= fetch_with_rsync("info-v$masterinfoversion");
186 parse_info1($master,'s',1);
187 parse_info1('_local-info.txt','s',1);
190 sub fetch_with_rsync ($) {
193 my $rsync= $ENV{'YPPSC_YARRG_RSYNC'};
194 $rsync= 'rsync' if !defined $rsync;
196 my $local= "_master-$stem.txt";
197 my $src= $ENV{'YPPSC_YARRG_DICT_UPDATE'};
199 my $remote= "$src/master-$stem.txt";
200 $!=0; system 'rsync','-Lt','--',$remote,$local;
201 die "$? $!" if $! or $?;
206 sub parse_info_serverside () {
207 parse_info1('source-info.txt','s',0);
209 sub parse_info_serverside_ocean ($) {
210 my ($oceanname) = @_;
211 die "unknown ocean $oceanname ?" unless exists $oceans{$oceanname};
212 parse_info1("_ocean-".(lc $oceanname).".txt", 's',0);
215 sub parse_pctb_commodmap () {
216 undef %pctb_commodmap;
217 foreach my $commod (keys %commods) { $commods{$commod}{Srcs} =~ s/b//; }
219 my $c= new IO::File '_commodmap.tsv';
220 if (!$c) { $!==&ENOENT or die $!; return 0; }
223 m/^(\S.*\S)\t(\d+)\n$/ or die "$_";
224 die if defined $pctb_commodmap{$1}; $pctb_commodmap{$1}= $2;
225 die if defined $pctb_commodmap[$2]; $pctb_commodmap[$2]= $1;
226 $commods{$1}{Srcs} .= 'b';
228 $c->error and die $!;
233 sub get_our_version ($$) {
234 my ($aref,$prefix) = @_;
235 $aref->{"${prefix}name"}= 'ypp-sc-tools yarrg';
236 $aref->{"${prefix}fixes"}= 'lastpage checkpager';
237 $aref->{"${prefix}version"}= version_core();
239 # clientname "ypp-sc-tools"
240 # clientversion 2.1-g2e06a26 [from git-describe --tags HEAD]
241 # clientfixes "lastpage" [space separated list]
244 sub version_core () {
246 if type -p git-describe >/dev/null 2>&1; then
251 \$gd --tags HEAD || echo 0unknown
257 sub pipethrough_prep () {
258 my $tf= IO::File::new_tmpfile() or die $!;
262 sub pipethrough_run_along ($$$@) {
263 my ($tf, $childprep, $cmd, @a) = @_;
264 $tf->error and die $!;
265 $tf->flush or die $!;
266 $tf->seek(0,0) or die $!;
267 my $fh= new IO::File;
268 my $child= $fh->open("-|"); defined $child or die $!;
270 open STDIN, "<&", $tf;
271 &$childprep() if defined $childprep;
272 exec $cmd @a; die "@a $!";
276 sub pipethrough_run_finish ($$) {
278 $fh->error and die $!;
279 close $fh or die "$what $! $?"; die $? if $?;
282 sub pipethrough_run ($$$@) {
283 my ($tf, $childprep, $cmd, @a) = @_;
284 my $pt= pipethrough_run_along($tf,$childprep,$cmd,@a);
286 { undef $/; $!=0; $r= <$pt>; }
287 defined $r or die $!;
288 pipethrough_run_finish($pt, "@a");
291 sub pipethrough_run_gzip ($) {
292 pipethrough_run($_[0],undef,'gzip','gzip');
295 sub yarrgpostform ($$) {
296 my ($ua, $form) = @_;
297 my $dest= $ENV{'YPPSC_YARRG_YARRG'};
298 get_our_version($form, 'client');
299 die unless $dest =~ m,/$,;
300 return cgipostform($ua, "${dest}commod-update-receiver", $form);
303 sub cgipostform ($$$) {
304 my ($ua, $url, $form) = @_;
305 my $req= HTTP::Request::Common::POST($url,
307 Content_Type => 'form-data');
308 if ($url =~ m,^\.?/,) {
309 my $tf= pipethrough_prep();
310 print $tf $req->content() or die $!;
311 #print STDERR "[[[",$req->content(),"]]]";
312 my $out= pipethrough_run($tf, sub {
313 $ENV{'REQUEST_METHOD'}= 'POST';
314 $ENV{'QUERY_STRING'}= '';
315 $ENV{'PATH_TRANSLATED'}= $url;
316 $ENV{'PATH_INFO'}= '';
317 $ENV{'HTTP_HOST'}= 'localhost';
318 $ENV{'REMOTE_ADDR'}= '127.0.0.1';
319 $ENV{'GATEWAY_INTERFACE'}= 'CGI/1.1';
320 $ENV{'DOCUMENT_ROOT'}= '.';
321 $ENV{'SCRIPT_FILENAME'}= $url;
322 $ENV{'SCRIPT_NAME'}= $url;
323 $ENV{'HTTP_USER_AGENT'}= 'Commods.pm local test';
325 foreach my $f (qw(Content_Length Content_Type)) {
326 $ENV{uc $f}= $req->header($f);
328 #system 'printenv >&2';
331 $out =~ m,^Content-Type: text/plain.*\n\n, or die "$out ?";
334 my $resp= $ua->request($req);
335 die $resp->status_line."\n".$resp->content."\n "
336 unless $resp->is_success;
337 return $resp->content();
343 sub check_tsv_line ($$) {
344 my ($l, $bad_data_callback) = @_;
345 my $bad_data= sub { &$bad_data_callback("bad data: line $.: $_[0]"); };
347 chomp($l) or &$bad_data('missing end-of-line');
349 $l !~ m/\P{IsPrint}/ or &$bad_data('nonprinting char(s)');
350 my @v= split /\t/, $l, -1;
351 @v==6 or &$bad_data('wrong number of fields');
352 my ($commod,$stall) = @v;
355 defined $commods{$commod} or
356 &$bad_data("unknown commodity \`$commod'");
358 $stall =~ m/^\p{IsUpper}|^[0-9]/ or &$bad_data("stall not capitalised");
359 !exists $check_tsv_done{$commod,$stall} or &$bad_data("repeated data");
360 $check_tsv_done{$commod,$stall}= 1;
361 foreach my $i (2..5) {
363 $f =~ m/^(|0|[1-9][0-9]{0,5}|\>1000)$/ or &$bad_data("bad field $i");
364 ($i % 2) or ($f !~ m/\>/) or &$bad_data("> in field $i price");
367 foreach my $i (2,4) {
368 &$bad_data("price with no qty or vice versa (field $i)")
369 if length($v[$i]) xor length($v[$i+1]);
371 length($v[2]) or length($v[4]) or
372 &$bad_data("commodity entry with no buy or sell offer");
377 sub cgi_get_caller () {
378 my $caller= $ENV{'REMOTE_ADDR'};
379 $caller= 'LOCAL' unless defined $caller;
381 my $fwdf= $ENV{'HTTP_X_FORWARDED_FOR'};
384 $fwdf =~ s/[^0-9.,]/?/g;
390 sub set_ctype_utf8 () {
391 setlocale(LC_CTYPE, "en.UTF-8");
394 sub http_useragent_string_map ($$) {
395 my ($caller_lib_agent, $reason_style_or_caller) = @_;
396 $caller_lib_agent =~ y/A-Za-z/N-ZA-Mn-za-m/;
397 $caller_lib_agent =~ s/\s/_/g;
398 my $version= version_core();
399 return "yarrg/$version ($reason_style_or_caller)".
400 " $caller_lib_agent".
401 " (http://yarrg.chiark.net/intro)";
404 sub http_useragent ($) {
406 my $ua= LWP::UserAgent->new;
407 my $base= $ua->_agent();
408 $ua->agent(http_useragent_string_map($base, $who));