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