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