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