chiark / gitweb /
Remove obsolete %routes and %route_mysteries - leftovers from manual routing
[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
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)= @_;
79     my $mm= new IO::File $mmfn, 'r' or die "$mmfn $!";
80     my @ctx= ();
81     while (<$mm>) {
82         next if m/^\s*\#/;
83         next unless m/\S/;
84         s/\s+$//;
85         if (m/^\%(\w+)$/) {
86             my $colourkind= $1;
87             @ctx= (sub { $colours{$colourkind}{lc $_} .= $src; });
88         } elsif (m/^commods$/) {
89             @ctx= (sub { push @rawcm, lc $_; });
90         } elsif (m/^nocommods$/) {
91             @ctx= (sub { push @nocm, lc $_; });
92         } elsif (m/^ocean (\w+)$/) {
93             my $ocean= $1;
94             keys %{ $oceans{$ocean} };
95             @ctx= (sub {
96                 $ocean or die; # ref to $ocean needed to work
97                                # around a perl bug
98                 my $arch= $_;
99                 keys %{ $oceans{$ocean}{$arch} };
100                 $ctx[1]= sub {
101                     $oceans{$ocean}{$arch}{$_} .= $src;
102                 };
103             });
104         } elsif (m/^vessels$/) {
105             @ctx= (sub {
106                 return if m/^[-+|]+$/;
107                 m/^ \| \s* ([A-Z][a-z\ ]+[a-z]) \s*
108                     \| \s* (small|medium|large) \s*
109                     \| \s* ([1-9][0-9,]+) \s*
110                     \| \s* ([1-9][0-9,]+) \s*
111                     \| $/x
112                     or die;
113                 my $name= $1;
114                 my $v= { Shot => $2, Volume => $3, Mass => $4 };
115                 foreach my $vm (qw(Volume Mass)) { $v->{$vm} =~ s/,//g; }
116                 $vessels{$name}= $v;
117             });
118         } elsif (m/^shot$/) {
119             @ctx= (sub {
120                 m/^ ([a-z]+) \s+ (\d+) $/x or die;
121                 $shotname2damage{$1}= $2;
122             });
123         } elsif (m/^client (\S+.*\S)$/) {
124             my $client= $1;
125             $clients{$client}= [ ];
126             @ctx= (sub {
127                 my $bug= $_;
128                 push @{ $clients{$client} }, $bug;
129             });
130         } elsif (s/^ +//) {
131             my $indent= length $&;
132             die "wrong indent $indent" unless defined $ctx[$indent-1];
133             &{ $ctx[$indent-1] }();
134         } else {
135             die "bad syntax";
136         }
137     }
138     $mm->error and die $!;
139     close $mm or die $!;
140
141 #print Dumper(\%oceans);
142 #print Dumper(\@rawcm);
143         
144     %commods= ();
145     my $ca;
146     $ca= sub {
147         my ($s,$ss) = @_;
148 #print "ca($s)\n";
149         if ($s !~ m/\%(\w+)/) {
150             my ($name, $props) = $s =~
151                 /^(\S[^\t]*\S)(?:\t+(\S[^\t]*\S))?$/
152                 or die "bad commodspec $s";
153             return if grep { $name eq $_ } @nocm;
154             my $ucname= ucfirst $name;
155             $commods{$ucname}{Srcs} .= $ss;
156             my $c= $commods{$ucname};
157             $c->{Volume}= 1000;
158             foreach my $prop (defined $props ? split /\s+/, $props : ()) {
159                 if ($prop =~ m/^([1-9]\d*)(k?)g$/) {
160                     $c->{Mass}= $1 * ($2 ? 1000 : 1);
161                 } elsif ($prop =~m/^([1-9]\d*)l$/) {
162                     $c->{Volume}= $1 * 1000;
163                 } else {
164                     die "unknown property $prop for $ucname";
165                 }
166             }
167             return;
168         }
169         die "unknown $&" unless defined $colours{$1};
170         my ($lhs,$pctlet,$rhs)= ($`,$1,$');
171         foreach my $c (keys %{ $colours{$pctlet} }) {
172             &$ca($lhs.$c.$rhs, $ss .'%'. $colours{$pctlet}{$c});
173         }
174     };
175     foreach (@rawcm) { &$ca($_,$src); }
176 }
177
178 sub parse_info_clientside () {
179     my $yarrg= $ENV{'YPPSC_YARRG_DICT_UPDATE'};
180     return unless $yarrg;
181     my $master= fetch_with_rsync("info-$masterinfoversion");
182     parse_info1($master,'s');
183     my $local= '_local-info.txt';
184     if (stat $local) {
185         parse_info1($local,'s');
186     } else {
187         die "$local $!" unless $! == &ENOENT;
188     }
189 }
190
191 sub fetch_with_rsync ($) {
192     my ($stem) = @_;
193
194     my $rsync= $ENV{'YPPSC_YARRG_RSYNC'};
195     $rsync= 'rsync' if !defined $rsync;
196
197     my $local= "_master-$stem.txt";
198     my $src= $ENV{'YPPSC_YARRG_DICT_UPDATE'};
199     if ($src) {
200         my $remote= "$src/master-$stem.txt";
201         $!=0; system 'rsync','-Lt','--',$remote,$local;
202         die "$? $!" if $! or $?;
203     }
204     return $local;
205 }
206
207 sub parse_info_serverside () {
208     parse_info1('source-info.txt','s');
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');
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
239     my $version= `git-describe --tags HEAD || echo 0unknown`; $? and die $?;
240     chomp($version);
241     $aref->{"${prefix}version"}= $version;
242     return $aref;
243     # clientname        "ypp-sc-tools"
244     # clientversion     2.1-g2e06a26  [from git-describe --tags HEAD]
245     # clientfixes       "lastpage"  [space separated list]
246 }
247
248 sub pipethrough_prep () {
249     my $tf= IO::File::new_tmpfile() or die $!;
250     return $tf;
251 }
252
253 sub pipethrough_run_along ($$$@) {
254     my ($tf, $childprep, $cmd, @a) = @_;
255     $tf->error and die $!;
256     $tf->flush or die $!;
257     $tf->seek(0,0) or die $!;
258     my $fh= new IO::File;
259     my $child= $fh->open("-|"); defined $child or die $!;
260     if (!$child) {
261         open STDIN, "<&", $tf;
262         &$childprep() if defined $childprep;
263         exec $cmd @a; die "@a $!";
264     }
265     return $fh;
266 }
267 sub pipethrough_run_finish ($$) {
268     my ($fh, $what)= @_;
269     $fh->error and die $!;
270     close $fh or die "$what $! $?";  die $? if $?;
271 }
272
273 sub pipethrough_run ($$$@) {
274     my ($tf, $childprep, $cmd, @a) = @_;
275     my $pt= pipethrough_run_along($tf,$childprep,$cmd,@a);
276     my $r;
277     { undef $/; $!=0; $r= <$pt>; }
278     defined $r or die $!;
279     pipethrough_run_finish($pt, "@a");
280     return $r;
281 }
282 sub pipethrough_run_gzip ($) {
283     pipethrough_run($_[0],undef,'gzip','gzip');
284 }
285
286 sub yarrgpostform ($$) {
287     my ($ua, $form) = @_;
288     my $dest= $ENV{'YPPSC_YARRG_YARRG'};
289     get_our_version($form, 'client');
290     die unless $dest =~ m,/$,;
291     return cgipostform($ua, "${dest}commod-update-receiver", $form);
292 }    
293
294 sub cgipostform ($$$) {
295     my ($ua, $url, $form) = @_;
296     my $req= HTTP::Request::Common::POST($url,
297                                          Content => $form,
298                                          Content_Type => 'form-data');
299     if ($url =~ m,^\.?/,) {
300         my $tf= pipethrough_prep();
301         print $tf $req->content() or die $!;
302 #print STDERR "[[[",$req->content(),"]]]";
303         my $out= pipethrough_run($tf, sub {
304             $ENV{'REQUEST_METHOD'}= 'POST';
305             $ENV{'QUERY_STRING'}= '';
306             $ENV{'PATH_TRANSLATED'}= $url;
307             $ENV{'PATH_INFO'}= '';
308             $ENV{'HTTP_HOST'}= 'localhost';
309             $ENV{'REMOTE_ADDR'}= '127.0.0.1';
310             $ENV{'GATEWAY_INTERFACE'}= 'CGI/1.1';
311             $ENV{'DOCUMENT_ROOT'}= '.';
312             $ENV{'SCRIPT_FILENAME'}= $url;
313             $ENV{'SCRIPT_NAME'}= $url;
314             $ENV{'HTTP_USER_AGENT'}= 'Commods.pm local test';
315
316             foreach my $f (qw(Content_Length Content_Type)) {
317                 $ENV{uc $f}= $req->header($f);
318             }
319 #system 'printenv >&2';
320         }, "$url", "$url");
321         $out =~ s/\r\n/\n/g;
322         $out =~ m,^Content-Type: text/plain.*\n\n, or die "$out ?";
323         return $';
324     } else {
325         my $resp= $ua->request($req);
326         die $resp->status_line."\n".$resp->content."\n "
327             unless $resp->is_success;
328         return $resp->content();
329     }
330 }
331
332 our %check_tsv_done;
333
334 sub check_tsv_line ($$) {
335     my ($l, $bad_data_callback) = @_;
336     my $bad_data= sub { &$bad_data_callback("bad data: line $.: $_[0]"); };
337     
338     chomp($l) or &$bad_data('missing end-of-line');
339
340     $l !~ m/\P{IsPrint}/ or &$bad_data('nonprinting char(s)');
341     my @v= split /\t/, $l, -1;
342     @v==6 or &$bad_data('wrong number of fields');
343     my ($commod,$stall) = @v;
344
345     !keys %commods or
346         defined $commods{$commod} or
347         &$bad_data("unknown commodity \`$commod'");
348     
349     $stall =~ m/^\p{IsUpper}|^[0-9]/ or &$bad_data("stall not capitalised");
350     !exists $check_tsv_done{$commod,$stall} or &$bad_data("repeated data");
351     $check_tsv_done{$commod,$stall}= 1;
352     foreach my $i (2..5) {
353         my $f= $v[$i];
354         $f =~ m/^(|0|[1-9][0-9]{0,5}|\>1000)$/ or &$bad_data("bad field $i");
355         ($i % 2) or ($f !~ m/\>/) or &$bad_data("> in field $i price");
356     }
357
358     foreach my $i (2,4) {
359         &$bad_data("price with no qty or vice versa (field $i)")
360             if length($v[$i]) xor length($v[$i+1]);
361     }
362     length($v[2]) or length($v[4]) or
363         &$bad_data("commodity entry with no buy or sell offer");
364     
365     return @v;
366 }
367
368 sub cgi_get_caller () {
369     my $caller= $ENV{'REMOTE_ADDR'};
370     $caller= 'LOCAL' unless defined $caller;
371
372     my $fwdf= $ENV{'HTTP_X_FORWARDED_FOR'};
373     if (defined $fwdf) {
374         $fwdf =~ s/\s//g;
375         $fwdf =~ s/[^0-9.,]/?/g;
376         $caller= "$fwdf";
377     }
378     return $caller;
379 }
380
381 sub set_ctype_utf8 () {
382     setlocale(LC_CTYPE, "en.UTF-8");
383 }
384
385 1;