chiark / gitweb /
where-vessels: provide feature to cut-and-paste island names
[ypp-sc-tools.db-test.git] / yarrg / Commods.pm
1 # This is part of ypp-sc-tools, a set of third-party tools for assisting
2 # players of Yohoho Puzzle Pirates.
3 #
4 # Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
5 #
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.
10 #
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.
15 #
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/>.
18 #
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.
22
23 package Commods;
24 use IO::File;
25 use IO::Pipe;
26 use HTTP::Request::Common ();
27 use POSIX;
28 use LWP::UserAgent;
29
30 use strict;
31 use warnings;
32
33 BEGIN {
34     use Exporter ();
35     our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
36     $VERSION     = 1.00;
37     @ISA         = qw(Exporter);
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
50                       &source_tarball);
51     %EXPORT_TAGS = ( );
52
53     @EXPORT_OK   = qw();
54 }
55
56 our $masterinfoversion= 2; # version we understand.
57 #
58 # To extend the source-info.txt format:
59 #
60 #    * Commods.pm:parse_info1
61 #       add code to parse new version
62 #
63 #    * source-info.txt
64 #       add new information
65 #
66 # If new data should NOT be in master-info.txt too:
67 #
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
71 #
72 #    * db-idempotent-populate
73 #       if database schema is extended, add code to copy data
74 #
75 # If new data DOES need to be in master-info.txt too:
76 #
77 #    * Commods.pm:$masterinfoversion
78 #       increment
79 #
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
83
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;
90 # $sources = 's[l]b';
91 #       's' = Special Circumstances; 'l' = local ; B = with Bleach
92
93 our %commods;
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
98
99 our (%pctb_commodmap,@pctb_commodmap);
100
101 my %colours; # eg $colours{'c'}{'black'}= $sources
102 my (@rawcm, @nocm); # eg $rawcm[0]='fine rum'; $rawcm[1]='fine %c cloth'
103
104 my %colour_ordvals; # $colour_ordvals{'c'}{'green'}= '30';
105 our %commodclasses; # $commodclasses{'dye'}= '3';
106
107 # IMPORTANT
108 #  when extending the format of source-info in a non-backward
109 #  compatible way, be sure to update update-master-info too.
110
111 sub parse_info1 ($$$) {
112     my ($mmfn,$src,$enoentok)= @_;
113     my $mm= new IO::File $mmfn, 'r';
114     if (!$mm) {
115         return if $enoentok && $!==&ENOENT;
116         die "$mmfn $!";
117     }
118     my @ctx= ();
119     while (<$mm>) {
120         next if m/^\s*\#/;
121         next unless m/\S/;
122         s/\s+$//;
123         if (m/^\%(\w+)$/) {
124             my $colourkind= $1;
125             @ctx= (sub {
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;
132                 }
133             });
134         } elsif (m/^commods$/) {
135             @ctx= (sub { push @rawcm, lc $_; });
136         } elsif (m/^nocommods$/) {
137             @ctx= (sub { push @nocm, lc $_; });
138         } elsif (m/^commodclasses$/) {
139             @ctx= (sub {
140                 die unless m/^\*([_a-z]+)$/;
141                 $commodclasses{$1}= scalar keys %commodclasses;
142             });
143         } elsif (m/^ocean (\w+)$/) {
144             my $ocean= $1;
145             keys %{ $oceans{$ocean} };
146             @ctx= (sub {
147                 $ocean or die; # ref to $ocean needed to work
148                                # around a perl bug
149                 my $arch= $_;
150                 keys %{ $oceans{$ocean}{$arch} };
151                 $ctx[1]= sub {
152                     $oceans{$ocean}{$arch}{$_} .= $src;
153                 };
154             });
155         } elsif (m/^vessels$/) {
156             @ctx= (sub {
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*
162                     \| $/x
163                     or die;
164                 my $name= $1;
165                 my $v= { Shot => $2, Volume => $3, Mass => $4 };
166                 foreach my $vm (qw(Volume Mass)) { $v->{$vm} =~ s/,//g; }
167                 $vessels{$name}= $v;
168             });
169         } elsif (m/^shot$/) {
170             @ctx= (sub {
171                 m/^ ([a-z]+) \s+ (\d+) $/x or die;
172                 $shotname2damage{$1}= $2;
173             });
174         } elsif (m/^client (\S+.*\S)$/) {
175             my $client= $1;
176             $clients{$client}= [ ];
177             @ctx= (sub {
178                 my $bug= $_;
179                 push @{ $clients{$client} }, $bug;
180             });
181         } elsif (s/^ +//) {
182             my $indent= length $&;
183             die "wrong indent $indent" unless defined $ctx[$indent-1];
184             &{ $ctx[$indent-1] }();
185         } else {
186             die "bad syntax";
187         }
188     }
189     $mm->error and die $!;
190     close $mm or die $!;
191
192 #print Dumper(\%oceans);
193 #print Dumper(\@rawcm);
194         
195     %commods= ();
196     my $ca;
197     my $lnoix=0;
198     $ca= sub {
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};
209             $c->{Volume}= 1000;
210             my ($ordval, $ordclassval);
211             foreach my $prop (defined $props ? split /\s+/, $props : ()) {
212                 if ($prop =~ m/^([1-9]\d*)(k?)g$/) {
213                     $c->{Mass}= $1 * ($2 ? 1000 : 1);
214                 } elsif ($prop =~ m/^([1-9]\d*)l$/) {
215                     $c->{Volume}= $1 * 1000;
216                 } elsif ($prop =~ m/^\*([_a-z]+)$/) {
217                     $c->{Class}= $1;
218                     die "$1" unless exists $commodclasses{$1};
219                     $ordclassval= 1e7 + $commodclasses{$1} * 1e7;
220                 } elsif ($prop =~ m/^\@(\d+\+?)$/) {
221                     $ordval= $1;
222                     $ordval =~ s/^(\d+)\+$/ $1 + $lnoix * 10 /e;
223                 } else {
224                     die "unknown property $prop for $ucname";
225                 }
226             }
227             $c->{ClassOrdval}= $ordclassval;
228             if (defined $ordbase && defined $ordval && defined $ordclassval) {
229                 my $ordvalout= $ordbase + $ordval + $ordclassval;
230                 $c->{Ordval}= $ordvalout;
231 #print STDERR "ordval $ordvalout $name OV=$ordval OB=$ordbase OCV=$ordclassval\n";
232             } else {
233 #print STDERR "ordval NONE $name\n";
234             }
235             return;
236         }
237         die "unknown $&" unless defined $colours{$1};
238         my ($lhs,$pctlet,$rhs)= ($`,$1,$');
239         foreach my $c (keys %{ $colours{$pctlet} }) {
240             my $ordcolour= $colour_ordvals{$pctlet}{$c};
241             &$ca($lhs.$c.$rhs,
242                  $ss .'%'. $colours{$pctlet}{$c},
243                  defined($ordbase) && defined($ordcolour)
244                      ? $ordbase+$ordcolour : undef);
245         }
246     };
247     foreach (@rawcm) { $lnoix++; &$ca($_,$src,0); }
248 }
249
250 sub parse_info_clientside () {
251     my $master= fetch_with_rsync("info-v$masterinfoversion");
252     parse_info1($master,'s',1);
253     parse_info1('_local-info.txt','s',1);
254 }
255
256 sub fetch_with_rsync ($) {
257     my ($stem) = @_;
258
259     my $rsync= $ENV{'YPPSC_YARRG_RSYNC'};
260     $rsync= 'rsync' if !defined $rsync;
261
262     my $local= "_master-$stem.txt";
263     my $src= $ENV{'YPPSC_YARRG_DICT_UPDATE'};
264     if ($src) {
265         my $remote= "$src/master-$stem.txt";
266         $!=0; system 'rsync','-Lt','--',$remote,$local;
267         die "$? $!" if $! or $?;
268     }
269     return $local;
270 }
271
272 sub parse_info_serverside () {
273     parse_info1('source-info.txt','s',0);
274     parse_info1('tree-info.txt','t',1);
275 }
276 sub parse_info_serverside_ocean ($) {
277     my ($oceanname) = @_;
278     die "unknown ocean $oceanname ?" unless exists $oceans{$oceanname};
279     parse_info1("_ocean-".(lc $oceanname).".txt", 's',0);
280 }
281
282 sub parse_pctb_commodmap () {
283     undef %pctb_commodmap;
284     foreach my $commod (keys %commods) { $commods{$commod}{Srcs} =~ s/b//; }
285
286     my $c= new IO::File '_commodmap.tsv';
287     if (!$c) { $!==&ENOENT or die $!; return 0; }
288
289     while (<$c>) {
290         m/^(\S.*\S)\t(\d+)\n$/ or die "$_";
291         die if defined $pctb_commodmap{$1};  $pctb_commodmap{$1}= $2;
292         die if defined $pctb_commodmap[$2];  $pctb_commodmap[$2]= $1;
293         $commods{$1}{Srcs} .= 'b';
294     }
295     $c->error and die $!;
296     close $c or die $!;
297     return 1;
298 }
299
300 sub get_our_version ($$) {
301     my ($aref,$prefix) = @_;
302     $aref->{"${prefix}name"}= 'ypp-sc-tools yarrg';
303     $aref->{"${prefix}fixes"}= 'lastpage checkpager';
304     $aref->{"${prefix}version"}= version_core();
305     return $aref;
306     # clientname        "ypp-sc-tools"
307     # clientversion     2.1-g2e06a26  [from git-describe --tags HEAD]
308     # clientfixes       "lastpage"  [space separated list]
309 }
310
311 sub version_core () {
312     my $version= `
313         if type -p git-describe >/dev/null 2>&1; then
314                 gd=git-describe
315         else
316                 gd="git describe"
317         fi
318         \$gd --tags HEAD || echo 0unknown
319     `; $? and die $?;
320     chomp($version);
321     return $version;
322 }
323
324 sub pipethrough_prep () {
325     my $tf= IO::File::new_tmpfile() or die $!;
326     return $tf;
327 }
328
329 sub pipethrough_run_along ($$$@) {
330     my ($tf, $childprep, $cmd, @a) = @_;
331     $tf->error and die $!;
332     $tf->flush or die $!;
333     $tf->seek(0,0) or die $!;
334     my $fh= new IO::File;
335     my $child= $fh->open("-|"); defined $child or die $!;
336     if (!$child) {
337         open STDIN, "<&", $tf;
338         &$childprep() if defined $childprep;
339         exec $cmd @a; die "@a $!";
340     }
341     return $fh;
342 }
343 sub pipethrough_run_finish ($$) {
344     my ($fh, $what)= @_;
345     $fh->error and die $!;
346     close $fh or die "$what $! $?";  die $? if $?;
347 }
348
349 sub pipethrough_run ($$$@) {
350     my ($tf, $childprep, $cmd, @a) = @_;
351     my $pt= pipethrough_run_along($tf,$childprep,$cmd,@a);
352     my $r;
353     { undef $/; $!=0; $r= <$pt>; }
354     defined $r or die $!;
355     pipethrough_run_finish($pt, "@a");
356     return $r;
357 }
358 sub pipethrough_run_gzip ($) {
359     pipethrough_run($_[0],undef,'gzip','gzip');
360 }
361
362 sub yarrgpostform ($$) {
363     my ($ua, $form) = @_;
364     my $dest= $ENV{'YPPSC_YARRG_YARRG'};
365     get_our_version($form, 'client');
366     die unless $dest =~ m,/$,;
367     return cgipostform($ua, "${dest}commod-update-receiver", $form);
368 }    
369
370 sub cgipostform ($$$) {
371     my ($ua, $url, $form) = @_;
372     my $req= HTTP::Request::Common::POST($url,
373                                          Content => $form,
374                                          Content_Type => 'form-data');
375     if ($url =~ m,^\.?/,) {
376         my $tf= pipethrough_prep();
377         print $tf $req->content() or die $!;
378 #print STDERR "[[[",$req->content(),"]]]";
379         my $out= pipethrough_run($tf, sub {
380             $ENV{'REQUEST_METHOD'}= 'POST';
381             $ENV{'QUERY_STRING'}= '';
382             $ENV{'PATH_TRANSLATED'}= $url;
383             $ENV{'PATH_INFO'}= '';
384             $ENV{'HTTP_HOST'}= 'localhost';
385             $ENV{'REMOTE_ADDR'}= '127.0.0.1';
386             $ENV{'GATEWAY_INTERFACE'}= 'CGI/1.1';
387             $ENV{'DOCUMENT_ROOT'}= '.';
388             $ENV{'SCRIPT_FILENAME'}= $url;
389             $ENV{'SCRIPT_NAME'}= $url;
390             $ENV{'HTTP_USER_AGENT'}= 'Commods.pm local test';
391
392             foreach my $f (qw(Content_Length Content_Type)) {
393                 $ENV{uc $f}= $req->header($f);
394             }
395 #system 'printenv >&2';
396         }, "$url", "$url");
397         $out =~ s/\r\n/\n/g;
398         $out =~ m,^Content-Type: text/plain.*\n\n, or die "$out ?";
399         return $';
400     } else {
401         my $resp= $ua->request($req);
402         die $resp->status_line."\n".$resp->content."\n "
403             unless $resp->is_success;
404         return $resp->content();
405     }
406 }
407
408 our %check_tsv_done;
409
410 sub errsan ($) {
411     my ($value) = @_;
412     $value =~ s/[^-+\'. A-Za-z0-9]/ sprintf "\\x%02x",ord $& /ge;
413     return "\"$value\"";
414 }
415
416 sub check_tsv_line ($$) {
417     my ($l, $bad_data_callback) = @_;
418     my $bad_data= sub { &$bad_data_callback("bad data: line $.: $_[0]"); };
419     
420     chomp($l) or &$bad_data('missing end-of-line');
421
422     $l !~ m/\P{IsPrint}/ or &$bad_data('nonprinting char(s)');
423     my @v= split /\t/, $l, -1;
424     @v==6 or &$bad_data('wrong number of fields');
425     my ($commod,$stall) = @v;
426
427     !keys %commods or
428         defined $commods{$commod} or
429         &$bad_data("unknown commodity ".errsan($commod));
430     
431     $stall =~ m/^\p{IsUpper}|^[0-9]/ or
432         &$bad_data("stall not capitalised ".errsan($stall));
433     !exists $check_tsv_done{$commod,$stall} or
434         &$bad_data("repeated data ".errsan($commod).",".errsan($stall));
435     $check_tsv_done{$commod,$stall}= 1;
436     foreach my $i (2..5) {
437         my $f= $v[$i];
438         $f =~ m/^(|0|[1-9][0-9]{0,5}|\>1000)$/ or
439             &$bad_data("bad field $i ".errsan($f));
440         ($i % 2) or ($f !~ m/\>/) or
441             &$bad_data("> in field $i price ".errsan($f));
442     }
443
444     foreach my $i (2,4) {
445         &$bad_data("price with no qty or vice versa (field $i)")
446             if length($v[$i]) xor length($v[$i+1]);
447     }
448     length($v[2]) or length($v[4]) or
449         &$bad_data("commodity entry with no buy or sell offer");
450     
451     return @v;
452 }
453
454 sub cgi_get_caller () {
455     my $caller= $ENV{'REMOTE_ADDR'};
456     $caller= 'LOCAL' unless defined $caller;
457
458     my $fwdf= $ENV{'HTTP_X_FORWARDED_FOR'};
459     if (defined $fwdf) {
460         $fwdf =~ s/\s//g;
461         $fwdf =~ s/[^0-9.,]/?/g;
462         $caller= "$fwdf";
463     }
464     return $caller;
465 }
466
467 sub set_ctype_utf8 () {
468     setlocale(LC_CTYPE, "en.UTF-8");
469 }
470
471 sub http_useragent_string_map ($$) {
472     my ($caller_lib_agent, $reason_style_or_caller) = @_;
473     $caller_lib_agent =~ y/A-Za-z/N-ZA-Mn-za-m/;
474     $caller_lib_agent =~ s/\s/_/g;
475     my $version= version_core();
476     return "yarrg/$version ($reason_style_or_caller)".
477            " $caller_lib_agent".
478            " (http://yarrg.chiark.net/intro)";
479 }
480
481 sub http_useragent ($) {
482     my ($who) = @_;
483     my $ua= LWP::UserAgent->new;
484     my $base= $ua->_agent();
485     $ua->agent(http_useragent_string_map($base, $who));
486     return $ua;
487 }
488
489 sub source_tarball ($$) {
490     my ($sourcebasedir,$spitoutfn) = @_;
491
492     my $pipe= new IO::Pipe or die $!;
493     my $pid= fork();  defined $pid or die $!;
494     if (!$pid) {
495         $ENV{'YPPSC_YARRG_SRCBASE'}= $sourcebasedir;
496         $pipe->writer();
497         exec '/bin/sh','-c','
498                 cd -P "$YPPSC_YARRG_SRCBASE"
499                 (
500                  git-ls-files -z;
501                  git-ls-files -z --others --exclude-from=.gitignore;
502                  if test -d .git; then find .git -print0; fi
503                 ) | (
504                  cpio -Hustar -o --quiet -0 -R 1000:1000 || \
505                  cpio -Hustar -o --quiet -0
506                 ) | gzip
507         ';
508         die $!;
509     }
510     $pipe->reader();
511
512     my ($d, $l);
513     while ($l= read $pipe, $d, 65536) {
514         $spitoutfn->($d);
515     }
516     waitpid $pid,0;
517     defined $l or die "read pipe $!";
518     $pipe->error and die "pipe error $!";
519     close $pipe;
520     # deliberately ignore errors
521 }
522
523 1;