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