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