chiark / gitweb /
Merge branch 'stable-3.x'
[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 HTTP::Request::Common ();
26 use POSIX;
27
28 use strict;
29 use warnings;
30
31 BEGIN {
32     use Exporter ();
33     our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
34     $VERSION     = 1.00;
35     @ISA         = qw(Exporter);
36     @EXPORT      = qw(&parse_info_clientside &fetch_with_rsync
37                       &parse_info_serverside &parse_info_serverside_ocean
38                       %oceans %commods %clients
39                       %vessels %shotname2damage
40                       &parse_pctb_commodmap %pctb_commodmap @pctb_commodmap
41                       &get_our_version &check_tsv_line
42                       &pipethrough_prep &pipethrough_run
43                       &pipethrough_run_along &pipethrough_run_finish
44                       &pipethrough_run_gzip
45                       &cgipostform &yarrgpostform &cgi_get_caller
46                       &set_ctype_utf8 $masterinfoversion);
47     %EXPORT_TAGS = ( );
48
49     @EXPORT_OK   = qw();
50 }
51
52 our $masterinfoversion= 2; # version we understand
53
54 our %oceans; # eg $oceans{'Midnight'}{'Ruby'}{'Eta Island'}= $sources;
55 our %clients; # eg $clients{'ypp-sc-tools'}= [ qw(last-page) ];
56 our %vessels; # eg $vessels{'War Brig'}{Shot}='medium'
57               #    $vessels{'War Brig'}{Volume}= 81000
58               #    $vessels{'War Brig'}{Mass}= 54000
59 our %shotname2damage; # eg $shotname2damage{'medium'}= 3;
60 # $sources = 's[l]b';
61 #       's' = Special Circumstances; 'l' = local ; B = with Bleach
62
63 our %commods;
64 # eg $commods{'Fine black cloth'}{Srcs}= $sources;
65 # eg $commods{'Fine black cloth'}{Mass}= 700 [g]
66 # eg $commods{'Fine black cloth'}{Volume}= 1000 [ml]
67
68 our (%pctb_commodmap,@pctb_commodmap);
69
70 my %colours; # eg $colours{'c'}{'black'}= $sources
71 my (@rawcm, @nocm); # eg $rawcm[0]='fine rum'; $rawcm[1]='fine %c cloth'
72
73 # IMPORTANT
74 #  when extending the format of source-info in a non-backward
75 #  compatible way, be sure to update update-master-info too.
76
77 sub parse_info1 ($$$) {
78     my ($mmfn,$src,$enoentok)= @_;
79     my $mm= new IO::File $mmfn, 'r';
80     if (!$mm) {
81         return if $enoentok && $!==&ENOENT;
82         die "$mmfn $!";
83     }
84     my @ctx= ();
85     while (<$mm>) {
86         next if m/^\s*\#/;
87         next unless m/\S/;
88         s/\s+$//;
89         if (m/^\%(\w+)$/) {
90             my $colourkind= $1;
91             @ctx= (sub { $colours{$colourkind}{lc $_} .= $src; });
92         } elsif (m/^commods$/) {
93             @ctx= (sub { push @rawcm, lc $_; });
94         } elsif (m/^nocommods$/) {
95             @ctx= (sub { push @nocm, lc $_; });
96         } elsif (m/^ocean (\w+)$/) {
97             my $ocean= $1;
98             keys %{ $oceans{$ocean} };
99             @ctx= (sub {
100                 $ocean or die; # ref to $ocean needed to work
101                                # around a perl bug
102                 my $arch= $_;
103                 keys %{ $oceans{$ocean}{$arch} };
104                 $ctx[1]= sub {
105                     $oceans{$ocean}{$arch}{$_} .= $src;
106                 };
107             });
108         } elsif (m/^vessels$/) {
109             @ctx= (sub {
110                 return if m/^[-+|]+$/;
111                 m/^ \| \s* ([A-Z][a-z\ ]+[a-z]) \s*
112                     \| \s* (small|medium|large) \s*
113                     \| \s* ([1-9][0-9,]+) \s*
114                     \| \s* ([1-9][0-9,]+) \s*
115                     \| $/x
116                     or die;
117                 my $name= $1;
118                 my $v= { Shot => $2, Volume => $3, Mass => $4 };
119                 foreach my $vm (qw(Volume Mass)) { $v->{$vm} =~ s/,//g; }
120                 $vessels{$name}= $v;
121             });
122         } elsif (m/^shot$/) {
123             @ctx= (sub {
124                 m/^ ([a-z]+) \s+ (\d+) $/x or die;
125                 $shotname2damage{$1}= $2;
126             });
127         } elsif (m/^client (\S+.*\S)$/) {
128             my $client= $1;
129             $clients{$client}= [ ];
130             @ctx= (sub {
131                 my $bug= $_;
132                 push @{ $clients{$client} }, $bug;
133             });
134         } elsif (s/^ +//) {
135             my $indent= length $&;
136             die "wrong indent $indent" unless defined $ctx[$indent-1];
137             &{ $ctx[$indent-1] }();
138         } else {
139             die "bad syntax";
140         }
141     }
142     $mm->error and die $!;
143     close $mm or die $!;
144
145 #print Dumper(\%oceans);
146 #print Dumper(\@rawcm);
147         
148     %commods= ();
149     my $ca;
150     $ca= sub {
151         my ($s,$ss) = @_;
152 #print "ca($s)\n";
153         if ($s !~ m/\%(\w+)/) {
154             my ($name, $props) = $s =~
155                 /^(\S[^\t]*\S)(?:\t+(\S[^\t]*\S))?$/
156                 or die "bad commodspec $s";
157             return if grep { $name eq $_ } @nocm;
158             my $ucname= ucfirst $name;
159             $commods{$ucname}{Srcs} .= $ss;
160             my $c= $commods{$ucname};
161             $c->{Volume}= 1000;
162             foreach my $prop (defined $props ? split /\s+/, $props : ()) {
163                 if ($prop =~ m/^([1-9]\d*)(k?)g$/) {
164                     $c->{Mass}= $1 * ($2 ? 1000 : 1);
165                 } elsif ($prop =~m/^([1-9]\d*)l$/) {
166                     $c->{Volume}= $1 * 1000;
167                 } else {
168                     die "unknown property $prop for $ucname";
169                 }
170             }
171             return;
172         }
173         die "unknown $&" unless defined $colours{$1};
174         my ($lhs,$pctlet,$rhs)= ($`,$1,$');
175         foreach my $c (keys %{ $colours{$pctlet} }) {
176             &$ca($lhs.$c.$rhs, $ss .'%'. $colours{$pctlet}{$c});
177         }
178     };
179     foreach (@rawcm) { &$ca($_,$src); }
180 }
181
182 sub parse_info_clientside () {
183     my $master= fetch_with_rsync("info-v$masterinfoversion");
184     parse_info1($master,'s',1);
185     parse_info1('_local-info.txt','s',1);
186 }
187
188 sub fetch_with_rsync ($) {
189     my ($stem) = @_;
190
191     my $rsync= $ENV{'YPPSC_YARRG_RSYNC'};
192     $rsync= 'rsync' if !defined $rsync;
193
194     my $local= "_master-$stem.txt";
195     my $src= $ENV{'YPPSC_YARRG_DICT_UPDATE'};
196     if ($src) {
197         my $remote= "$src/master-$stem.txt";
198         $!=0; system 'rsync','-Lt','--',$remote,$local;
199         die "$? $!" if $! or $?;
200     }
201     return $local;
202 }
203
204 sub parse_info_serverside () {
205     parse_info1('source-info.txt','s',0);
206 }
207 sub parse_info_serverside_ocean ($) {
208     my ($oceanname) = @_;
209     die "unknown ocean $oceanname ?" unless exists $oceans{$oceanname};
210     parse_info1("_ocean-".(lc $oceanname).".txt", 's',0);
211 }
212
213 sub parse_pctb_commodmap () {
214     undef %pctb_commodmap;
215     foreach my $commod (keys %commods) { $commods{$commod}{Srcs} =~ s/b//; }
216
217     my $c= new IO::File '_commodmap.tsv';
218     if (!$c) { $!==&ENOENT or die $!; return 0; }
219
220     while (<$c>) {
221         m/^(\S.*\S)\t(\d+)\n$/ or die "$_";
222         die if defined $pctb_commodmap{$1};  $pctb_commodmap{$1}= $2;
223         die if defined $pctb_commodmap[$2];  $pctb_commodmap[$2]= $1;
224         $commods{$1}{Srcs} .= 'b';
225     }
226     $c->error and die $!;
227     close $c or die $!;
228     return 1;
229 }
230
231 sub get_our_version ($$) {
232     my ($aref,$prefix) = @_;
233     $aref->{"${prefix}name"}= 'ypp-sc-tools yarrg';
234     $aref->{"${prefix}fixes"}= 'lastpage checkpager';
235
236     my $version= `
237         if type -p git-describe >/dev/null 2>&1; then
238                 gd=git-describe
239         else
240                 gd="git describe"
241         fi
242         \$gd --tags HEAD || echo 0unknown
243     `; $? and die $?;
244     chomp($version);
245     $aref->{"${prefix}version"}= $version;
246     return $aref;
247     # clientname        "ypp-sc-tools"
248     # clientversion     2.1-g2e06a26  [from git-describe --tags HEAD]
249     # clientfixes       "lastpage"  [space separated list]
250 }
251
252 sub pipethrough_prep () {
253     my $tf= IO::File::new_tmpfile() or die $!;
254     return $tf;
255 }
256
257 sub pipethrough_run_along ($$$@) {
258     my ($tf, $childprep, $cmd, @a) = @_;
259     $tf->error and die $!;
260     $tf->flush or die $!;
261     $tf->seek(0,0) or die $!;
262     my $fh= new IO::File;
263     my $child= $fh->open("-|"); defined $child or die $!;
264     if (!$child) {
265         open STDIN, "<&", $tf;
266         &$childprep() if defined $childprep;
267         exec $cmd @a; die "@a $!";
268     }
269     return $fh;
270 }
271 sub pipethrough_run_finish ($$) {
272     my ($fh, $what)= @_;
273     $fh->error and die $!;
274     close $fh or die "$what $! $?";  die $? if $?;
275 }
276
277 sub pipethrough_run ($$$@) {
278     my ($tf, $childprep, $cmd, @a) = @_;
279     my $pt= pipethrough_run_along($tf,$childprep,$cmd,@a);
280     my $r;
281     { undef $/; $!=0; $r= <$pt>; }
282     defined $r or die $!;
283     pipethrough_run_finish($pt, "@a");
284     return $r;
285 }
286 sub pipethrough_run_gzip ($) {
287     pipethrough_run($_[0],undef,'gzip','gzip');
288 }
289
290 sub yarrgpostform ($$) {
291     my ($ua, $form) = @_;
292     my $dest= $ENV{'YPPSC_YARRG_YARRG'};
293     get_our_version($form, 'client');
294     die unless $dest =~ m,/$,;
295     return cgipostform($ua, "${dest}commod-update-receiver", $form);
296 }    
297
298 sub cgipostform ($$$) {
299     my ($ua, $url, $form) = @_;
300     my $req= HTTP::Request::Common::POST($url,
301                                          Content => $form,
302                                          Content_Type => 'form-data');
303     if ($url =~ m,^\.?/,) {
304         my $tf= pipethrough_prep();
305         print $tf $req->content() or die $!;
306 #print STDERR "[[[",$req->content(),"]]]";
307         my $out= pipethrough_run($tf, sub {
308             $ENV{'REQUEST_METHOD'}= 'POST';
309             $ENV{'QUERY_STRING'}= '';
310             $ENV{'PATH_TRANSLATED'}= $url;
311             $ENV{'PATH_INFO'}= '';
312             $ENV{'HTTP_HOST'}= 'localhost';
313             $ENV{'REMOTE_ADDR'}= '127.0.0.1';
314             $ENV{'GATEWAY_INTERFACE'}= 'CGI/1.1';
315             $ENV{'DOCUMENT_ROOT'}= '.';
316             $ENV{'SCRIPT_FILENAME'}= $url;
317             $ENV{'SCRIPT_NAME'}= $url;
318             $ENV{'HTTP_USER_AGENT'}= 'Commods.pm local test';
319
320             foreach my $f (qw(Content_Length Content_Type)) {
321                 $ENV{uc $f}= $req->header($f);
322             }
323 #system 'printenv >&2';
324         }, "$url", "$url");
325         $out =~ s/\r\n/\n/g;
326         $out =~ m,^Content-Type: text/plain.*\n\n, or die "$out ?";
327         return $';
328     } else {
329         my $resp= $ua->request($req);
330         die $resp->status_line."\n".$resp->content."\n "
331             unless $resp->is_success;
332         return $resp->content();
333     }
334 }
335
336 our %check_tsv_done;
337
338 sub check_tsv_line ($$) {
339     my ($l, $bad_data_callback) = @_;
340     my $bad_data= sub { &$bad_data_callback("bad data: line $.: $_[0]"); };
341     
342     chomp($l) or &$bad_data('missing end-of-line');
343
344     $l !~ m/\P{IsPrint}/ or &$bad_data('nonprinting char(s)');
345     my @v= split /\t/, $l, -1;
346     @v==6 or &$bad_data('wrong number of fields');
347     my ($commod,$stall) = @v;
348
349     !keys %commods or
350         defined $commods{$commod} or
351         &$bad_data("unknown commodity \`$commod'");
352     
353     $stall =~ m/^\p{IsUpper}|^[0-9]/ or &$bad_data("stall not capitalised");
354     !exists $check_tsv_done{$commod,$stall} or &$bad_data("repeated data");
355     $check_tsv_done{$commod,$stall}= 1;
356     foreach my $i (2..5) {
357         my $f= $v[$i];
358         $f =~ m/^(|0|[1-9][0-9]{0,5}|\>1000)$/ or &$bad_data("bad field $i");
359         ($i % 2) or ($f !~ m/\>/) or &$bad_data("> in field $i price");
360     }
361
362     foreach my $i (2,4) {
363         &$bad_data("price with no qty or vice versa (field $i)")
364             if length($v[$i]) xor length($v[$i+1]);
365     }
366     length($v[2]) or length($v[4]) or
367         &$bad_data("commodity entry with no buy or sell offer");
368     
369     return @v;
370 }
371
372 sub cgi_get_caller () {
373     my $caller= $ENV{'REMOTE_ADDR'};
374     $caller= 'LOCAL' unless defined $caller;
375
376     my $fwdf= $ENV{'HTTP_X_FORWARDED_FOR'};
377     if (defined $fwdf) {
378         $fwdf =~ s/\s//g;
379         $fwdf =~ s/[^0-9.,]/?/g;
380         $caller= "$fwdf";
381     }
382     return $caller;
383 }
384
385 sub set_ctype_utf8 () {
386     setlocale(LC_CTYPE, "en.UTF-8");
387 }
388
389 1;