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