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.
26 use HTTP::Request::Common ();
35 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
38 @EXPORT = qw(&parse_info_clientside &fetch_with_rsync
39 &parse_info_serverside &parse_info_serverside_ocean
40 %oceans %commods %clients %commodclasses
41 %vessels %shotname2damage
42 &parse_pctb_commodmap %pctb_commodmap @pctb_commodmap
43 &get_our_version &check_tsv_line &errsan
44 &pipethrough_prep &pipethrough_run
45 &pipethrough_run_along &pipethrough_run_finish
46 &pipethrough_run_gzip &http_useragent &version_core
47 &http_useragent_string_map
48 &cgipostform &yarrgpostform &cgi_get_caller
49 &set_ctype_utf8 $masterinfoversion
56 our $masterinfoversion= 2; # version we understand.
58 # To extend the source-info.txt format:
60 # * Commods.pm:parse_info1
61 # add code to parse new version
66 # If new data should NOT be in master-info.txt too:
68 # * update-master-info:process_some_info
69 # check that code for converting source-info to master-info
70 # removes the extra info; add code to remove it if necessary
72 # * db-idempotent-populate
73 # if database schema is extended, add code to copy data
75 # If new data DOES need to be in master-info.txt too:
77 # * Commods.pm:$masterinfoversion
80 # * update-master-info:process_some_info
81 # add code to convert new version to old, by removing
82 # extra info conditionally depending on version
84 our %oceans; # eg $oceans{'Midnight'}{'Ruby'}{'Eta Island'}= $sources;
85 our %clients; # eg $clients{'ypp-sc-tools'}= [ qw(last-page) ];
86 our %vessels; # eg $vessels{'War Brig'}{Shot}='medium'
87 # $vessels{'War Brig'}{Volume}= 81000
88 # $vessels{'War Brig'}{Mass}= 54000
89 our %shotname2damage; # eg $shotname2damage{'medium'}= 3;
91 # 's' = Special Circumstances; 'l' = local ; B = with Bleach
94 # eg $commods{'Fine black cloth'}{Srcs}= $sources;
95 # eg $commods{'Fine black cloth'}{Mass}= 700 [g]
96 # eg $commods{'Fine black cloth'}{Volume}= 1000 [ml]
97 # eg $commods{'Fine black cloth'}{Ordval}= 203921
99 our (%pctb_commodmap,@pctb_commodmap);
101 my %colours; # eg $colours{'c'}{'black'}= $sources
102 my (@rawcm, @nocm); # eg $rawcm[0]='fine rum'; $rawcm[1]='fine %c cloth'
104 my %colour_ordvals; # $colour_ordvals{'c'}{'green'}= '30';
105 our %commodclasses; # $commodclasses{'dye'}= '3';
108 # when extending the format of source-info in a non-backward
109 # compatible way, be sure to update update-master-info too.
111 sub parse_info1 ($$$) {
112 my ($mmfn,$src,$enoentok)= @_;
113 my $mm= new IO::File $mmfn, 'r';
115 return if $enoentok && $!==&ENOENT;
126 m/^(\S[^\t@]*\S)(?:\t+\@(\d+\+?))?$/ or die "$_ ?";
127 my ($colour,$order)=($1,$2);
128 $colours{$colourkind}{$colour} .= $src;
129 if (defined $order) {
130 $order =~ s/^(\d+)\+$/ $1 + $. * 10 /e;
131 $colour_ordvals{$colourkind}{$colour}= $order;
134 } elsif (m/^commods$/) {
135 @ctx= (sub { push @rawcm, lc $_; });
136 } elsif (m/^nocommods$/) {
137 @ctx= (sub { push @nocm, lc $_; });
138 } elsif (m/^commodclasses$/) {
140 die unless m/^\*([_a-z]+)$/;
141 $commodclasses{$1}= scalar keys %commodclasses;
143 } elsif (m/^ocean (\w+)$/) {
145 keys %{ $oceans{$ocean} };
147 $ocean or die; # ref to $ocean needed to work
150 keys %{ $oceans{$ocean}{$arch} };
152 $oceans{$ocean}{$arch}{$_} .= $src;
155 } elsif (m/^vessels$/) {
157 return if m/^[-+|]+$/;
158 m/^ \| \s* ([A-Z][a-z\ ]+[a-z]) \s*
159 \| \s* (small|medium|large) \s*
160 \| \s* ([1-9][0-9,]+) \s*
161 \| \s* ([1-9][0-9,]+) \s*
165 my $v= { Shot => $2, Volume => $3, Mass => $4 };
166 foreach my $vm (qw(Volume Mass)) { $v->{$vm} =~ s/,//g; }
169 } elsif (m/^shot$/) {
171 m/^ ([a-z]+) \s+ (\d+) $/x or die;
172 $shotname2damage{$1}= $2;
174 } elsif (m/^client (\S+.*\S)$/) {
176 $clients{$client}= [ ];
179 push @{ $clients{$client} }, $bug;
182 my $indent= length $&;
183 die "wrong indent $indent" unless defined $ctx[$indent-1];
184 &{ $ctx[$indent-1] }();
189 $mm->error and die $!;
192 #print Dumper(\%oceans);
193 #print Dumper(\@rawcm);
199 my ($s,$ss,$ordbase) = @_;
200 #print STDERR "ca($s,,".(defined $ordbase ? $ordbase : '?').")\n";
201 if ($s !~ m/\%(\w+)/) {
202 my ($name, $props) = $s =~
203 /^(\S[^\t]*\S)(?:\t+(\S.*\S))?$/
204 or die "bad commodspec $s";
205 return if grep { $name eq $_ } @nocm;
206 my $ucname= ucfirst $name;
207 $commods{$ucname}{Srcs} .= $ss;
208 my $c= $commods{$ucname};
211 my ($ordval, $ordclassval);
212 foreach my $prop (defined $props ? split /\s+/, $props : ()) {
213 if ($prop =~ m/^([1-9]\d*)(k?)g$/) {
214 $c->{Mass}= $1 * ($2 ? 1000 : 1);
215 } elsif ($prop =~ m/^([1-9]\d*)l$/) {
216 $c->{Volume}= $1 * 1000;
217 } elsif ($prop =~ m/^\*([_a-z]+)$/) {
219 die "$1" unless exists $commodclasses{$1};
220 $ordclassval= 1e7 + $commodclasses{$1} * 1e7;
221 } elsif ($prop =~ m/^\@(\d+\+?)$/) {
223 $ordval =~ s/^(\d+)\+$/ $1 + $lnoix * 10 /e;
224 } elsif ($prop =~ m/^\!([a-z]+)$/) {
227 die "unknown property $prop for $ucname";
230 $c->{ClassOrdval}= $ordclassval;
231 if (defined $ordbase && defined $ordval && defined $ordclassval) {
232 my $ordvalout= $ordbase + $ordval + $ordclassval;
233 $c->{Ordval}= $ordvalout;
234 #print STDERR "ordval $ordvalout $name OV=$ordval OB=$ordbase OCV=$ordclassval\n";
236 #print STDERR "ordval NONE $name\n";
240 die "unknown $&" unless defined $colours{$1};
241 my ($lhs,$pctlet,$rhs)= ($`,$1,$');
242 foreach my $c (keys %{ $colours{$pctlet} }) {
243 my $ordcolour= $colour_ordvals{$pctlet}{$c};
245 $ss .'%'. $colours{$pctlet}{$c},
246 defined($ordbase) && defined($ordcolour)
247 ? $ordbase+$ordcolour : undef);
250 foreach (@rawcm) { $lnoix++; &$ca($_,$src,0); }
253 sub parse_info_clientside () {
254 my $master= fetch_with_rsync("info-v$masterinfoversion");
255 parse_info1($master,'s',1);
256 parse_info1('_local-info.txt','s',1);
259 sub fetch_with_rsync ($) {
262 my $rsync= $ENV{'YPPSC_YARRG_RSYNC'};
263 $rsync= 'rsync' if !defined $rsync;
265 my $local= "_master-$stem.txt";
266 my $src= $ENV{'YPPSC_YARRG_DICT_UPDATE'};
268 my $remote= "$src/master-$stem.txt";
269 $!=0; system 'rsync','-Lt','--',$remote,$local;
270 die "$? $!" if $! or $?;
275 sub parse_info_serverside () {
276 parse_info1('source-info.txt','s',0);
277 parse_info1('tree-info.txt','t',1);
279 sub parse_info_serverside_ocean ($) {
280 my ($oceanname) = @_;
281 die "unknown ocean $oceanname ?" unless exists $oceans{$oceanname};
282 parse_info1("_ocean-".(lc $oceanname).".txt", 's',0);
285 sub parse_pctb_commodmap () {
286 undef %pctb_commodmap;
287 foreach my $commod (keys %commods) { $commods{$commod}{Srcs} =~ s/b//; }
289 my $c= new IO::File '_commodmap.tsv';
290 if (!$c) { $!==&ENOENT or die $!; return 0; }
293 m/^(\S.*\S)\t(\d+)\n$/ or die "$_";
294 die if defined $pctb_commodmap{$1}; $pctb_commodmap{$1}= $2;
295 die if defined $pctb_commodmap[$2]; $pctb_commodmap[$2]= $1;
296 $commods{$1}{Srcs} .= 'b';
298 $c->error and die $!;
303 sub get_our_version ($$) {
304 my ($aref,$prefix) = @_;
305 $aref->{"${prefix}name"}= 'ypp-sc-tools yarrg';
306 $aref->{"${prefix}fixes"}= 'lastpage checkpager';
307 $aref->{"${prefix}version"}= version_core();
309 # clientname "ypp-sc-tools"
310 # clientversion 2.1-g2e06a26 [from git-describe --tags HEAD]
311 # clientfixes "lastpage" [space separated list]
314 sub version_core () {
316 if type -p git-describe >/dev/null 2>&1; then
321 \$gd --tags HEAD || echo 0unknown
327 sub pipethrough_prep () {
328 my $tf= IO::File::new_tmpfile() or die $!;
332 sub pipethrough_run_along ($$$@) {
333 my ($tf, $childprep, $cmd, @a) = @_;
334 $tf->error and die $!;
335 $tf->flush or die $!;
336 $tf->seek(0,0) or die $!;
337 my $fh= new IO::File;
338 my $child= $fh->open("-|"); defined $child or die $!;
340 open STDIN, "<&", $tf;
341 &$childprep() if defined $childprep;
342 exec $cmd @a; die "@a $!";
346 sub pipethrough_run_finish ($$) {
348 $fh->error and die $!;
349 close $fh or die "$what $! $?"; die $? if $?;
352 sub pipethrough_run ($$$@) {
353 my ($tf, $childprep, $cmd, @a) = @_;
354 my $pt= pipethrough_run_along($tf,$childprep,$cmd,@a);
356 { undef $/; $!=0; $r= <$pt>; }
357 defined $r or die $!;
358 pipethrough_run_finish($pt, "@a");
361 sub pipethrough_run_gzip ($) {
362 pipethrough_run($_[0],undef,'gzip','gzip');
365 sub yarrgpostform ($$) {
366 my ($ua, $form) = @_;
367 my $dest= $ENV{'YPPSC_YARRG_YARRG'};
368 get_our_version($form, 'client');
369 die unless $dest =~ m,/$,;
370 return cgipostform($ua, "${dest}commod-update-receiver", $form);
373 sub cgipostform ($$$) {
374 my ($ua, $url, $form) = @_;
375 my $req= HTTP::Request::Common::POST($url,
377 Content_Type => 'form-data');
378 if ($url =~ m,^\.?/,) {
379 my $tf= pipethrough_prep();
380 print $tf $req->content() or die $!;
381 #print STDERR "[[[",$req->content(),"]]]";
382 my $out= pipethrough_run($tf, sub {
383 $ENV{'REQUEST_METHOD'}= 'POST';
384 $ENV{'QUERY_STRING'}= '';
385 $ENV{'PATH_TRANSLATED'}= $url;
386 $ENV{'PATH_INFO'}= '';
387 $ENV{'HTTP_HOST'}= 'localhost';
388 $ENV{'REMOTE_ADDR'}= '127.0.0.1';
389 $ENV{'GATEWAY_INTERFACE'}= 'CGI/1.1';
390 $ENV{'DOCUMENT_ROOT'}= '.';
391 $ENV{'SCRIPT_FILENAME'}= $url;
392 $ENV{'SCRIPT_NAME'}= $url;
393 $ENV{'HTTP_USER_AGENT'}= 'Commods.pm local test';
395 foreach my $f (qw(Content_Length Content_Type)) {
396 $ENV{uc $f}= $req->header($f);
398 #system 'printenv >&2';
401 $out =~ m,^Content-Type: text/plain.*\n\n, or die "$out ?";
404 my $resp= $ua->request($req);
405 die $resp->status_line."\n".$resp->content."\n "
406 unless $resp->is_success;
407 return $resp->content();
415 $value =~ s/[^-+\'. A-Za-z0-9]/ sprintf "\\x%02x",ord $& /ge;
419 sub check_tsv_line ($$) {
420 my ($l, $bad_data_callback) = @_;
421 my $bad_data= sub { &$bad_data_callback("bad data: line $.: $_[0]"); };
423 chomp($l) or &$bad_data('missing end-of-line');
425 $l !~ m/\P{IsPrint}/ or &$bad_data('nonprinting char(s)');
426 my @v= split /\t/, $l, -1;
427 @v==6 or &$bad_data('wrong number of fields');
428 my ($commod,$stall) = @v;
431 defined $commods{$commod} or
432 &$bad_data("unknown commodity ".errsan($commod));
434 $stall =~ m/^\p{IsAlnum}/ or
435 &$bad_data("stall does not start with alphanumeric ".errsan($stall));
436 !exists $check_tsv_done{$commod,$stall} or
437 &$bad_data("repeated data ".errsan($commod).",".errsan($stall));
438 $check_tsv_done{$commod,$stall}= 1;
439 foreach my $i (2..5) {
441 $f =~ m/^(|0|[1-9][0-9]{0,5}|\>1000)$/ or
442 &$bad_data("bad field $i ".errsan($f));
443 ($i % 2) or ($f !~ m/\>/) or
444 &$bad_data("> in field $i price ".errsan($f));
447 foreach my $i (2,4) {
448 &$bad_data("price with no qty or vice versa (field $i)")
449 if length($v[$i]) xor length($v[$i+1]);
451 length($v[2]) or length($v[4]) or
452 &$bad_data("commodity entry with no buy or sell offer");
457 sub cgi_get_caller () {
458 my $caller= $ENV{'REMOTE_ADDR'};
459 $caller= 'LOCAL' unless defined $caller;
461 my $fwdf= $ENV{'HTTP_X_FORWARDED_FOR'};
464 $fwdf =~ s/[^0-9.,]/?/g;
470 sub set_ctype_utf8 () {
471 setlocale(LC_CTYPE, "en.UTF-8");
474 sub http_useragent_string_map ($$) {
475 my ($caller_lib_agent, $reason_style_or_caller) = @_;
476 $caller_lib_agent =~ y/A-Za-z/N-ZA-Mn-za-m/;
477 $caller_lib_agent =~ s/\s/_/g;
478 my $version= version_core();
479 return "yarrg/$version ($reason_style_or_caller)".
480 " $caller_lib_agent".
481 " (http://yarrg.chiark.net/intro)";
484 sub http_useragent ($) {
486 my $ua= LWP::UserAgent->new;
487 my $base= $ua->_agent();
488 $ua->agent(http_useragent_string_map($base, $who));
492 sub source_tarball ($$) {
493 my ($sourcebasedir,$spitoutfn) = @_;
495 my $pipe= new IO::Pipe or die $!;
496 my $pid= fork(); defined $pid or die $!;
498 $ENV{'YPPSC_YARRG_SRCBASE'}= $sourcebasedir;
500 exec '/bin/sh','-c','
501 cd -P "$YPPSC_YARRG_SRCBASE"
504 git-ls-files -z --others --exclude-from=.gitignore;
505 if test -d .git; then find .git -print0; fi
507 cpio -Hustar -o --quiet -0 -R 1000:1000 || \
508 cpio -Hustar -o --quiet -0
516 while ($l= read $pipe, $d, 65536) {
520 defined $l or die "read pipe $!";
521 $pipe->error and die "pipe error $!";
523 # deliberately ignore errors