chiark / gitweb /
Fix spelling error in intro
[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 IO::Pipe;
26 use HTTP::Request::Common ();
27 use POSIX;
28 use LWP::UserAgent;
29
30 use strict;
31 use warnings;
32
33 BEGIN {
34     use Exporter ();
35     our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
36     $VERSION     = 1.00;
37     @ISA         = qw(Exporter);
38     @EXPORT      = qw(&parse_info_clientside &fetch_with_rsync
39                       &parse_info_serverside &parse_info_serverside_ocean
40                       %oceans %commods %clients
41                       %vessels %shotname2damage
42                       &parse_pctb_commodmap %pctb_commodmap @pctb_commodmap
43                       &get_our_version &check_tsv_line
44                       &pipethrough_prep &pipethrough_run
45                       &pipethrough_run_along &pipethrough_run_finish
46                       &pipethrough_run_gzip &http_useragent &version_core
47                       &http_useragent_string_map
48                       &cgipostform &yarrgpostform &cgi_get_caller
49                       &set_ctype_utf8 $masterinfoversion
50                       &source_tarball);
51     %EXPORT_TAGS = ( );
52
53     @EXPORT_OK   = qw();
54 }
55
56 our $masterinfoversion= 2; # version we understand.
57 #
58 # To extend the source-info.txt format:
59 #
60 #    * Commods.pm:parse_info1
61 #       add code to parse new version
62 #
63 #    * source-info.txt
64 #       add new information
65 #
66 # If new data should NOT be in master-info.txt too:
67 #
68 #    * update-master-info:process_some_info
69 #       check that code for converting source-info to master-info
70 #       removes the extra info; add code to remove it if necessary
71 #
72 #    * db-idempotent-populate
73 #       if database schema is extended, add code to copy data
74 #
75 # If new data DOES need to be in master-info.txt too:
76 #
77 #    * Commods.pm:$masterinfoversion
78 #       increment
79 #
80 #    * update-master-info:process_some_info
81 #       add code to convert new version to old, by removing
82 #       extra info conditionally depending on version
83
84 our %oceans; # eg $oceans{'Midnight'}{'Ruby'}{'Eta Island'}= $sources;
85 our %clients; # eg $clients{'ypp-sc-tools'}= [ qw(last-page) ];
86 our %vessels; # eg $vessels{'War Brig'}{Shot}='medium'
87               #    $vessels{'War Brig'}{Volume}= 81000
88               #    $vessels{'War Brig'}{Mass}= 54000
89 our %shotname2damage; # eg $shotname2damage{'medium'}= 3;
90 # $sources = 's[l]b';
91 #       's' = Special Circumstances; 'l' = local ; B = with Bleach
92
93 our %commods;
94 # eg $commods{'Fine black cloth'}{Srcs}= $sources;
95 # eg $commods{'Fine black cloth'}{Mass}= 700 [g]
96 # eg $commods{'Fine black cloth'}{Volume}= 1000 [ml]
97
98 our (%pctb_commodmap,@pctb_commodmap);
99
100 my %colours; # eg $colours{'c'}{'black'}= $sources
101 my (@rawcm, @nocm); # eg $rawcm[0]='fine rum'; $rawcm[1]='fine %c cloth'
102
103 # IMPORTANT
104 #  when extending the format of source-info in a non-backward
105 #  compatible way, be sure to update update-master-info too.
106
107 sub parse_info1 ($$$) {
108     my ($mmfn,$src,$enoentok)= @_;
109     my $mm= new IO::File $mmfn, 'r';
110     if (!$mm) {
111         return if $enoentok && $!==&ENOENT;
112         die "$mmfn $!";
113     }
114     my @ctx= ();
115     while (<$mm>) {
116         next if m/^\s*\#/;
117         next unless m/\S/;
118         s/\s+$//;
119         if (m/^\%(\w+)$/) {
120             my $colourkind= $1;
121             @ctx= (sub { $colours{$colourkind}{lc $_} .= $src; });
122         } elsif (m/^commods$/) {
123             @ctx= (sub { push @rawcm, lc $_; });
124         } elsif (m/^nocommods$/) {
125             @ctx= (sub { push @nocm, lc $_; });
126         } elsif (m/^ocean (\w+)$/) {
127             my $ocean= $1;
128             keys %{ $oceans{$ocean} };
129             @ctx= (sub {
130                 $ocean or die; # ref to $ocean needed to work
131                                # around a perl bug
132                 my $arch= $_;
133                 keys %{ $oceans{$ocean}{$arch} };
134                 $ctx[1]= sub {
135                     $oceans{$ocean}{$arch}{$_} .= $src;
136                 };
137             });
138         } elsif (m/^vessels$/) {
139             @ctx= (sub {
140                 return if m/^[-+|]+$/;
141                 m/^ \| \s* ([A-Z][a-z\ ]+[a-z]) \s*
142                     \| \s* (small|medium|large) \s*
143                     \| \s* ([1-9][0-9,]+) \s*
144                     \| \s* ([1-9][0-9,]+) \s*
145                     \| $/x
146                     or die;
147                 my $name= $1;
148                 my $v= { Shot => $2, Volume => $3, Mass => $4 };
149                 foreach my $vm (qw(Volume Mass)) { $v->{$vm} =~ s/,//g; }
150                 $vessels{$name}= $v;
151             });
152         } elsif (m/^shot$/) {
153             @ctx= (sub {
154                 m/^ ([a-z]+) \s+ (\d+) $/x or die;
155                 $shotname2damage{$1}= $2;
156             });
157         } elsif (m/^client (\S+.*\S)$/) {
158             my $client= $1;
159             $clients{$client}= [ ];
160             @ctx= (sub {
161                 my $bug= $_;
162                 push @{ $clients{$client} }, $bug;
163             });
164         } elsif (s/^ +//) {
165             my $indent= length $&;
166             die "wrong indent $indent" unless defined $ctx[$indent-1];
167             &{ $ctx[$indent-1] }();
168         } else {
169             die "bad syntax";
170         }
171     }
172     $mm->error and die $!;
173     close $mm or die $!;
174
175 #print Dumper(\%oceans);
176 #print Dumper(\@rawcm);
177         
178     %commods= ();
179     my $ca;
180     $ca= sub {
181         my ($s,$ss) = @_;
182 #print "ca($s)\n";
183         if ($s !~ m/\%(\w+)/) {
184             my ($name, $props) = $s =~
185                 /^(\S[^\t]*\S)(?:\t+(\S[^\t]*\S))?$/
186                 or die "bad commodspec $s";
187             return if grep { $name eq $_ } @nocm;
188             my $ucname= ucfirst $name;
189             $commods{$ucname}{Srcs} .= $ss;
190             my $c= $commods{$ucname};
191             $c->{Volume}= 1000;
192             foreach my $prop (defined $props ? split /\s+/, $props : ()) {
193                 if ($prop =~ m/^([1-9]\d*)(k?)g$/) {
194                     $c->{Mass}= $1 * ($2 ? 1000 : 1);
195                 } elsif ($prop =~m/^([1-9]\d*)l$/) {
196                     $c->{Volume}= $1 * 1000;
197                 } else {
198                     die "unknown property $prop for $ucname";
199                 }
200             }
201             return;
202         }
203         die "unknown $&" unless defined $colours{$1};
204         my ($lhs,$pctlet,$rhs)= ($`,$1,$');
205         foreach my $c (keys %{ $colours{$pctlet} }) {
206             &$ca($lhs.$c.$rhs, $ss .'%'. $colours{$pctlet}{$c});
207         }
208     };
209     foreach (@rawcm) { &$ca($_,$src); }
210 }
211
212 sub parse_info_clientside () {
213     my $master= fetch_with_rsync("info-v$masterinfoversion");
214     parse_info1($master,'s',1);
215     parse_info1('_local-info.txt','s',1);
216 }
217
218 sub fetch_with_rsync ($) {
219     my ($stem) = @_;
220
221     my $rsync= $ENV{'YPPSC_YARRG_RSYNC'};
222     $rsync= 'rsync' if !defined $rsync;
223
224     my $local= "_master-$stem.txt";
225     my $src= $ENV{'YPPSC_YARRG_DICT_UPDATE'};
226     if ($src) {
227         my $remote= "$src/master-$stem.txt";
228         $!=0; system 'rsync','-Lt','--',$remote,$local;
229         die "$? $!" if $! or $?;
230     }
231     return $local;
232 }
233
234 sub parse_info_serverside () {
235     parse_info1('source-info.txt','s',0);
236     parse_info1('tree-info.txt','t',1);
237 }
238 sub parse_info_serverside_ocean ($) {
239     my ($oceanname) = @_;
240     die "unknown ocean $oceanname ?" unless exists $oceans{$oceanname};
241     parse_info1("_ocean-".(lc $oceanname).".txt", 's',0);
242 }
243
244 sub parse_pctb_commodmap () {
245     undef %pctb_commodmap;
246     foreach my $commod (keys %commods) { $commods{$commod}{Srcs} =~ s/b//; }
247
248     my $c= new IO::File '_commodmap.tsv';
249     if (!$c) { $!==&ENOENT or die $!; return 0; }
250
251     while (<$c>) {
252         m/^(\S.*\S)\t(\d+)\n$/ or die "$_";
253         die if defined $pctb_commodmap{$1};  $pctb_commodmap{$1}= $2;
254         die if defined $pctb_commodmap[$2];  $pctb_commodmap[$2]= $1;
255         $commods{$1}{Srcs} .= 'b';
256     }
257     $c->error and die $!;
258     close $c or die $!;
259     return 1;
260 }
261
262 sub get_our_version ($$) {
263     my ($aref,$prefix) = @_;
264     $aref->{"${prefix}name"}= 'ypp-sc-tools yarrg';
265     $aref->{"${prefix}fixes"}= 'lastpage checkpager';
266     $aref->{"${prefix}version"}= version_core();
267     return $aref;
268     # clientname        "ypp-sc-tools"
269     # clientversion     2.1-g2e06a26  [from git-describe --tags HEAD]
270     # clientfixes       "lastpage"  [space separated list]
271 }
272
273 sub version_core () {
274     my $version= `
275         if type -p git-describe >/dev/null 2>&1; then
276                 gd=git-describe
277         else
278                 gd="git describe"
279         fi
280         \$gd --tags HEAD || echo 0unknown
281     `; $? and die $?;
282     chomp($version);
283     return $version;
284 }
285
286 sub pipethrough_prep () {
287     my $tf= IO::File::new_tmpfile() or die $!;
288     return $tf;
289 }
290
291 sub pipethrough_run_along ($$$@) {
292     my ($tf, $childprep, $cmd, @a) = @_;
293     $tf->error and die $!;
294     $tf->flush or die $!;
295     $tf->seek(0,0) or die $!;
296     my $fh= new IO::File;
297     my $child= $fh->open("-|"); defined $child or die $!;
298     if (!$child) {
299         open STDIN, "<&", $tf;
300         &$childprep() if defined $childprep;
301         exec $cmd @a; die "@a $!";
302     }
303     return $fh;
304 }
305 sub pipethrough_run_finish ($$) {
306     my ($fh, $what)= @_;
307     $fh->error and die $!;
308     close $fh or die "$what $! $?";  die $? if $?;
309 }
310
311 sub pipethrough_run ($$$@) {
312     my ($tf, $childprep, $cmd, @a) = @_;
313     my $pt= pipethrough_run_along($tf,$childprep,$cmd,@a);
314     my $r;
315     { undef $/; $!=0; $r= <$pt>; }
316     defined $r or die $!;
317     pipethrough_run_finish($pt, "@a");
318     return $r;
319 }
320 sub pipethrough_run_gzip ($) {
321     pipethrough_run($_[0],undef,'gzip','gzip');
322 }
323
324 sub yarrgpostform ($$) {
325     my ($ua, $form) = @_;
326     my $dest= $ENV{'YPPSC_YARRG_YARRG'};
327     get_our_version($form, 'client');
328     die unless $dest =~ m,/$,;
329     return cgipostform($ua, "${dest}commod-update-receiver", $form);
330 }    
331
332 sub cgipostform ($$$) {
333     my ($ua, $url, $form) = @_;
334     my $req= HTTP::Request::Common::POST($url,
335                                          Content => $form,
336                                          Content_Type => 'form-data');
337     if ($url =~ m,^\.?/,) {
338         my $tf= pipethrough_prep();
339         print $tf $req->content() or die $!;
340 #print STDERR "[[[",$req->content(),"]]]";
341         my $out= pipethrough_run($tf, sub {
342             $ENV{'REQUEST_METHOD'}= 'POST';
343             $ENV{'QUERY_STRING'}= '';
344             $ENV{'PATH_TRANSLATED'}= $url;
345             $ENV{'PATH_INFO'}= '';
346             $ENV{'HTTP_HOST'}= 'localhost';
347             $ENV{'REMOTE_ADDR'}= '127.0.0.1';
348             $ENV{'GATEWAY_INTERFACE'}= 'CGI/1.1';
349             $ENV{'DOCUMENT_ROOT'}= '.';
350             $ENV{'SCRIPT_FILENAME'}= $url;
351             $ENV{'SCRIPT_NAME'}= $url;
352             $ENV{'HTTP_USER_AGENT'}= 'Commods.pm local test';
353
354             foreach my $f (qw(Content_Length Content_Type)) {
355                 $ENV{uc $f}= $req->header($f);
356             }
357 #system 'printenv >&2';
358         }, "$url", "$url");
359         $out =~ s/\r\n/\n/g;
360         $out =~ m,^Content-Type: text/plain.*\n\n, or die "$out ?";
361         return $';
362     } else {
363         my $resp= $ua->request($req);
364         die $resp->status_line."\n".$resp->content."\n "
365             unless $resp->is_success;
366         return $resp->content();
367     }
368 }
369
370 our %check_tsv_done;
371
372 sub check_tsv_line ($$) {
373     my ($l, $bad_data_callback) = @_;
374     my $bad_data= sub { &$bad_data_callback("bad data: line $.: $_[0]"); };
375     
376     chomp($l) or &$bad_data('missing end-of-line');
377
378     $l !~ m/\P{IsPrint}/ or &$bad_data('nonprinting char(s)');
379     my @v= split /\t/, $l, -1;
380     @v==6 or &$bad_data('wrong number of fields');
381     my ($commod,$stall) = @v;
382
383     !keys %commods or
384         defined $commods{$commod} or
385         &$bad_data("unknown commodity \`$commod'");
386     
387     $stall =~ m/^\p{IsUpper}|^[0-9]/ or &$bad_data("stall not capitalised");
388     !exists $check_tsv_done{$commod,$stall} or &$bad_data("repeated data");
389     $check_tsv_done{$commod,$stall}= 1;
390     foreach my $i (2..5) {
391         my $f= $v[$i];
392         $f =~ m/^(|0|[1-9][0-9]{0,5}|\>1000)$/ or &$bad_data("bad field $i");
393         ($i % 2) or ($f !~ m/\>/) or &$bad_data("> in field $i price");
394     }
395
396     foreach my $i (2,4) {
397         &$bad_data("price with no qty or vice versa (field $i)")
398             if length($v[$i]) xor length($v[$i+1]);
399     }
400     length($v[2]) or length($v[4]) or
401         &$bad_data("commodity entry with no buy or sell offer");
402     
403     return @v;
404 }
405
406 sub cgi_get_caller () {
407     my $caller= $ENV{'REMOTE_ADDR'};
408     $caller= 'LOCAL' unless defined $caller;
409
410     my $fwdf= $ENV{'HTTP_X_FORWARDED_FOR'};
411     if (defined $fwdf) {
412         $fwdf =~ s/\s//g;
413         $fwdf =~ s/[^0-9.,]/?/g;
414         $caller= "$fwdf";
415     }
416     return $caller;
417 }
418
419 sub set_ctype_utf8 () {
420     setlocale(LC_CTYPE, "en.UTF-8");
421 }
422
423 sub http_useragent_string_map ($$) {
424     my ($caller_lib_agent, $reason_style_or_caller) = @_;
425     $caller_lib_agent =~ y/A-Za-z/N-ZA-Mn-za-m/;
426     $caller_lib_agent =~ s/\s/_/g;
427     my $version= version_core();
428     return "yarrg/$version ($reason_style_or_caller)".
429            " $caller_lib_agent".
430            " (http://yarrg.chiark.net/intro)";
431 }
432
433 sub http_useragent ($) {
434     my ($who) = @_;
435     my $ua= LWP::UserAgent->new;
436     my $base= $ua->_agent();
437     $ua->agent(http_useragent_string_map($base, $who));
438     return $ua;
439 }
440
441 sub source_tarball ($$) {
442     my ($sourcebasedir,$spitoutfn) = @_;
443
444     my $pipe= new IO::Pipe or die $!;
445     my $pid= fork();  defined $pid or die $!;
446     if (!$pid) {
447         $ENV{'YPPSC_YARRG_SRCBASE'}= $sourcebasedir;
448         $pipe->writer();
449         exec '/bin/sh','-c','
450                 cd -P "$YPPSC_YARRG_SRCBASE"
451                 (
452                  git-ls-files -z;
453                  git-ls-files -z --others --exclude-from=.gitignore;
454                  if test -d .git; then find .git -print0; fi
455                 ) | (
456                  cpio -Hustar -o --quiet -0 -R 1000:1000 || \
457                  cpio -Hustar -o --quiet -0
458                 ) | gzip
459         ';
460         die $!;
461     }
462     $pipe->reader();
463
464     my ($d, $l);
465     while ($l= read $pipe, $d, 65536) {
466         $spitoutfn->($d);
467     }
468     waitpid $pid,0;
469     defined $l or die "read pipe $!";
470     $pipe->error and die "pipe error $!";
471     close $pipe;
472     # deliberately ignore errors
473 }
474
475 1;