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