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 # To extend the source-info.txt format:
58 # * Commods.pm:parse_info1
59 # add code to parse new version
64 # If new data should NOT be in master-info.txt too:
66 # * update-master-info:process_some_info
67 # check that code for converting source-info to master-info
68 # removes the extra info; add code to remove it if necessary
70 # * db-idempotent-populate
71 # if database schema is extended, add code to copy data
73 # If new data DOES need to be in master-info.txt too:
75 # * Commods.pm:$masterinfoversion
78 # * update-master-info:process_some_info
79 # add code to convert new version to old, by removing
80 # extra info conditionally depending on version
82 our %oceans; # eg $oceans{'Midnight'}{'Ruby'}{'Eta Island'}= $sources;
83 our %clients; # eg $clients{'ypp-sc-tools'}= [ qw(last-page) ];
84 our %vessels; # eg $vessels{'War Brig'}{Shot}='medium'
85 # $vessels{'War Brig'}{Volume}= 81000
86 # $vessels{'War Brig'}{Mass}= 54000
87 our %shotname2damage; # eg $shotname2damage{'medium'}= 3;
89 # 's' = Special Circumstances; 'l' = local ; B = with Bleach
92 # eg $commods{'Fine black cloth'}{Srcs}= $sources;
93 # eg $commods{'Fine black cloth'}{Mass}= 700 [g]
94 # eg $commods{'Fine black cloth'}{Volume}= 1000 [ml]
95 # eg $commods{'Fine black cloth'}{Ordval}= 203921
97 our (%pctb_commodmap,@pctb_commodmap);
99 my %colours; # eg $colours{'c'}{'black'}= $sources
100 my (@rawcm, @nocm); # eg $rawcm[0]='fine rum'; $rawcm[1]='fine %c cloth'
102 my %colour_ordvals; # $colour_ordvals{'c'}{'green'}= '30';
103 my %commodclasses; # $commodclasses{'dye'}= '3';
106 # when extending the format of source-info in a non-backward
107 # compatible way, be sure to update update-master-info too.
109 sub parse_info1 ($$$) {
110 my ($mmfn,$src,$enoentok)= @_;
111 my $mm= new IO::File $mmfn, 'r';
113 return if $enoentok && $!==&ENOENT;
124 m/^(\S[^\t@]*\S)(?:\t+\@(\d+\+?))?$/ or die "$_ ?";
125 my ($colour,$order)=($1,$2);
126 $colours{$colourkind}{$colour} .= $src;
127 if (defined $order) {
128 $order =~ s/^(\d+)\+$/ $1 + $. * 10 /e;
129 $colour_ordvals{$colourkind}{$colour}= $order;
132 } elsif (m/^commods$/) {
133 @ctx= (sub { push @rawcm, lc $_; });
134 } elsif (m/^nocommods$/) {
135 @ctx= (sub { push @nocm, lc $_; });
136 } elsif (m/^commodclasses$/) {
138 die unless m/^\*([-a-z]+)$/;
139 $commodclasses{$1}= scalar keys %commodclasses;
141 } elsif (m/^ocean (\w+)$/) {
143 keys %{ $oceans{$ocean} };
145 $ocean or die; # ref to $ocean needed to work
148 keys %{ $oceans{$ocean}{$arch} };
150 $oceans{$ocean}{$arch}{$_} .= $src;
153 } elsif (m/^vessels$/) {
155 return if m/^[-+|]+$/;
156 m/^ \| \s* ([A-Z][a-z\ ]+[a-z]) \s*
157 \| \s* (small|medium|large) \s*
158 \| \s* ([1-9][0-9,]+) \s*
159 \| \s* ([1-9][0-9,]+) \s*
163 my $v= { Shot => $2, Volume => $3, Mass => $4 };
164 foreach my $vm (qw(Volume Mass)) { $v->{$vm} =~ s/,//g; }
167 } elsif (m/^shot$/) {
169 m/^ ([a-z]+) \s+ (\d+) $/x or die;
170 $shotname2damage{$1}= $2;
172 } elsif (m/^client (\S+.*\S)$/) {
174 $clients{$client}= [ ];
177 push @{ $clients{$client} }, $bug;
180 my $indent= length $&;
181 die "wrong indent $indent" unless defined $ctx[$indent-1];
182 &{ $ctx[$indent-1] }();
187 $mm->error and die $!;
190 #print Dumper(\%oceans);
191 #print Dumper(\@rawcm);
197 my ($s,$ss,$ordbase) = @_;
198 #print STDERR "ca($s,,".(defined $ordbase ? $ordbase : '?').")\n";
199 if ($s !~ m/\%(\w+)/) {
200 my ($name, $props) = $s =~
201 /^(\S[^\t]*\S)(?:\t+(\S.*\S))?$/
202 or die "bad commodspec $s";
203 return if grep { $name eq $_ } @nocm;
204 my $ucname= ucfirst $name;
205 $commods{$ucname}{Srcs} .= $ss;
206 my $c= $commods{$ucname};
208 my ($ordval, $ordclassval);
209 foreach my $prop (defined $props ? split /\s+/, $props : ()) {
210 if ($prop =~ m/^([1-9]\d*)(k?)g$/) {
211 $c->{Mass}= $1 * ($2 ? 1000 : 1);
212 } elsif ($prop =~ m/^([1-9]\d*)l$/) {
213 $c->{Volume}= $1 * 1000;
214 } elsif ($prop =~ m/^\*([-a-z]+)$/) {
216 die "$1" unless exists $commodclasses{$1};
217 $ordclassval= 1e7 + $commodclasses{$1} * 1e7;
218 } elsif ($prop =~ m/^\@(\d+\+?)$/) {
220 $ordval =~ s/^(\d+)\+$/ $1 + $lnoix * 10 /e;
222 die "unknown property $prop for $ucname";
225 if (defined $ordbase && defined $ordval && defined $ordclassval) {
226 my $ordvalout= $ordbase + $ordval + $ordclassval;
227 $c->{Ordval}= $ordvalout;
228 #print STDERR "ordval $ordvalout $name OV=$ordval OB=$ordbase OCV=$ordclassval\n";
230 #print STDERR "ordval NONE $name\n";
234 die "unknown $&" unless defined $colours{$1};
235 my ($lhs,$pctlet,$rhs)= ($`,$1,$');
236 foreach my $c (keys %{ $colours{$pctlet} }) {
237 my $ordcolour= $colour_ordvals{$pctlet}{$c};
239 $ss .'%'. $colours{$pctlet}{$c},
240 defined($ordbase) && defined($ordcolour)
241 ? $ordbase+$ordcolour : undef);
244 foreach (@rawcm) { $lnoix++; &$ca($_,$src,0); }
247 sub parse_info_clientside () {
248 my $master= fetch_with_rsync("info-v$masterinfoversion");
249 parse_info1($master,'s',1);
250 parse_info1('_local-info.txt','s',1);
253 sub fetch_with_rsync ($) {
256 my $rsync= $ENV{'YPPSC_YARRG_RSYNC'};
257 $rsync= 'rsync' if !defined $rsync;
259 my $local= "_master-$stem.txt";
260 my $src= $ENV{'YPPSC_YARRG_DICT_UPDATE'};
262 my $remote= "$src/master-$stem.txt";
263 $!=0; system 'rsync','-Lt','--',$remote,$local;
264 die "$? $!" if $! or $?;
269 sub parse_info_serverside () {
270 parse_info1('source-info.txt','s',0);
272 sub parse_info_serverside_ocean ($) {
273 my ($oceanname) = @_;
274 die "unknown ocean $oceanname ?" unless exists $oceans{$oceanname};
275 parse_info1("_ocean-".(lc $oceanname).".txt", 's',0);
278 sub parse_pctb_commodmap () {
279 undef %pctb_commodmap;
280 foreach my $commod (keys %commods) { $commods{$commod}{Srcs} =~ s/b//; }
282 my $c= new IO::File '_commodmap.tsv';
283 if (!$c) { $!==&ENOENT or die $!; return 0; }
286 m/^(\S.*\S)\t(\d+)\n$/ or die "$_";
287 die if defined $pctb_commodmap{$1}; $pctb_commodmap{$1}= $2;
288 die if defined $pctb_commodmap[$2]; $pctb_commodmap[$2]= $1;
289 $commods{$1}{Srcs} .= 'b';
291 $c->error and die $!;
296 sub get_our_version ($$) {
297 my ($aref,$prefix) = @_;
298 $aref->{"${prefix}name"}= 'ypp-sc-tools yarrg';
299 $aref->{"${prefix}fixes"}= 'lastpage checkpager';
300 $aref->{"${prefix}version"}= version_core();
302 # clientname "ypp-sc-tools"
303 # clientversion 2.1-g2e06a26 [from git-describe --tags HEAD]
304 # clientfixes "lastpage" [space separated list]
307 sub version_core () {
309 if type -p git-describe >/dev/null 2>&1; then
314 \$gd --tags HEAD || echo 0unknown
320 sub pipethrough_prep () {
321 my $tf= IO::File::new_tmpfile() or die $!;
325 sub pipethrough_run_along ($$$@) {
326 my ($tf, $childprep, $cmd, @a) = @_;
327 $tf->error and die $!;
328 $tf->flush or die $!;
329 $tf->seek(0,0) or die $!;
330 my $fh= new IO::File;
331 my $child= $fh->open("-|"); defined $child or die $!;
333 open STDIN, "<&", $tf;
334 &$childprep() if defined $childprep;
335 exec $cmd @a; die "@a $!";
339 sub pipethrough_run_finish ($$) {
341 $fh->error and die $!;
342 close $fh or die "$what $! $?"; die $? if $?;
345 sub pipethrough_run ($$$@) {
346 my ($tf, $childprep, $cmd, @a) = @_;
347 my $pt= pipethrough_run_along($tf,$childprep,$cmd,@a);
349 { undef $/; $!=0; $r= <$pt>; }
350 defined $r or die $!;
351 pipethrough_run_finish($pt, "@a");
354 sub pipethrough_run_gzip ($) {
355 pipethrough_run($_[0],undef,'gzip','gzip');
358 sub yarrgpostform ($$) {
359 my ($ua, $form) = @_;
360 my $dest= $ENV{'YPPSC_YARRG_YARRG'};
361 get_our_version($form, 'client');
362 die unless $dest =~ m,/$,;
363 return cgipostform($ua, "${dest}commod-update-receiver", $form);
366 sub cgipostform ($$$) {
367 my ($ua, $url, $form) = @_;
368 my $req= HTTP::Request::Common::POST($url,
370 Content_Type => 'form-data');
371 if ($url =~ m,^\.?/,) {
372 my $tf= pipethrough_prep();
373 print $tf $req->content() or die $!;
374 #print STDERR "[[[",$req->content(),"]]]";
375 my $out= pipethrough_run($tf, sub {
376 $ENV{'REQUEST_METHOD'}= 'POST';
377 $ENV{'QUERY_STRING'}= '';
378 $ENV{'PATH_TRANSLATED'}= $url;
379 $ENV{'PATH_INFO'}= '';
380 $ENV{'HTTP_HOST'}= 'localhost';
381 $ENV{'REMOTE_ADDR'}= '127.0.0.1';
382 $ENV{'GATEWAY_INTERFACE'}= 'CGI/1.1';
383 $ENV{'DOCUMENT_ROOT'}= '.';
384 $ENV{'SCRIPT_FILENAME'}= $url;
385 $ENV{'SCRIPT_NAME'}= $url;
386 $ENV{'HTTP_USER_AGENT'}= 'Commods.pm local test';
388 foreach my $f (qw(Content_Length Content_Type)) {
389 $ENV{uc $f}= $req->header($f);
391 #system 'printenv >&2';
394 $out =~ m,^Content-Type: text/plain.*\n\n, or die "$out ?";
397 my $resp= $ua->request($req);
398 die $resp->status_line."\n".$resp->content."\n "
399 unless $resp->is_success;
400 return $resp->content();
406 sub check_tsv_line ($$) {
407 my ($l, $bad_data_callback) = @_;
408 my $bad_data= sub { &$bad_data_callback("bad data: line $.: $_[0]"); };
410 chomp($l) or &$bad_data('missing end-of-line');
412 $l !~ m/\P{IsPrint}/ or &$bad_data('nonprinting char(s)');
413 my @v= split /\t/, $l, -1;
414 @v==6 or &$bad_data('wrong number of fields');
415 my ($commod,$stall) = @v;
418 defined $commods{$commod} or
419 &$bad_data("unknown commodity \`$commod'");
421 $stall =~ m/^\p{IsUpper}|^[0-9]/ or &$bad_data("stall not capitalised");
422 !exists $check_tsv_done{$commod,$stall} or &$bad_data("repeated data");
423 $check_tsv_done{$commod,$stall}= 1;
424 foreach my $i (2..5) {
426 $f =~ m/^(|0|[1-9][0-9]{0,5}|\>1000)$/ or &$bad_data("bad field $i");
427 ($i % 2) or ($f !~ m/\>/) or &$bad_data("> in field $i price");
430 foreach my $i (2,4) {
431 &$bad_data("price with no qty or vice versa (field $i)")
432 if length($v[$i]) xor length($v[$i+1]);
434 length($v[2]) or length($v[4]) or
435 &$bad_data("commodity entry with no buy or sell offer");
440 sub cgi_get_caller () {
441 my $caller= $ENV{'REMOTE_ADDR'};
442 $caller= 'LOCAL' unless defined $caller;
444 my $fwdf= $ENV{'HTTP_X_FORWARDED_FOR'};
447 $fwdf =~ s/[^0-9.,]/?/g;
453 sub set_ctype_utf8 () {
454 setlocale(LC_CTYPE, "en.UTF-8");
457 sub http_useragent_string_map ($$) {
458 my ($caller_lib_agent, $reason_style_or_caller) = @_;
459 $caller_lib_agent =~ y/A-Za-z/N-ZA-Mn-za-m/;
460 $caller_lib_agent =~ s/\s/_/g;
461 my $version= version_core();
462 return "yarrg/$version ($reason_style_or_caller)".
463 " $caller_lib_agent".
464 " (http://yarrg.chiark.net/intro)";
467 sub http_useragent ($) {
469 my $ua= LWP::UserAgent->new;
470 my $base= $ua->_agent();
471 $ua->agent(http_useragent_string_map($base, $who));