1 # This is part of ypp-sc-tools, a set of third-party tools for assisting
2 # players of Yohoho Puzzle Pirates.
4 # Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
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.
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.
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/>.
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.
25 use HTTP::Request::Common ();
33 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
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
44 &cgipostform &yarrgpostform &cgi_get_caller
45 &set_ctype_utf8 $masterinfoversion);
51 our $masterinfoversion= 2; # version we understand
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
58 # 's' = Special Circumstances; 'l' = local ; B = with Bleach
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]
65 our (%pctb_commodmap,@pctb_commodmap);
67 my %colours; # eg $colours{'c'}{'black'}= $sources
68 my (@rawcm, @nocm); # eg $rawcm[0]='fine rum'; $rawcm[1]='fine %c cloth'
71 # when extending the format of source-info in a non-backward
72 # compatible way, be sure to update update-master-info too.
74 sub parse_info1 ($$) {
76 my $mm= new IO::File $mmfn, 'r' or die "$mmfn $!";
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+)$/) {
92 $ocean or die; # ref to $ocean needed to work
96 $oceans{$ocean}{$arch}{$_} .= $src;
99 } elsif (m/^routes (\w+)$/) {
102 m/^(\S[^\t]*\S),\s*(\S[^\t]*\S),\s*([1-9][0-9]{0,2})$/ or die;
103 $routes{$ocean}{$1}{$2}= $3;
105 } elsif (m/^client (\S+.*\S)$/) {
107 $clients{$client}= [ ];
110 push @{ $clients{$client} }, $bug;
113 my $indent= length $&;
114 die "wrong indent $indent" unless defined $ctx[$indent-1];
115 &{ $ctx[$indent-1] }();
120 $mm->error and die $!;
123 #print Dumper(\%oceans);
124 #print Dumper(\@rawcm);
131 if ($s !~ m/\%(\w+)/) {
132 my ($name, $props) = $s =~
133 /^(\S[^\t]*\S)(?:\t+(\S[^\t]*\S))?$/
134 or die "bad commodspec $s";
135 return if grep { $name eq $_ } @nocm;
136 my $ucname= ucfirst $name;
137 $commods{$ucname}{Srcs} .= $ss;
138 my $c= $commods{$ucname};
140 foreach my $prop (defined $props ? split /\s+/, $props : ()) {
141 if ($prop =~ m/^([1-9]\d*)(k?)g$/) {
142 $c->{Mass}= $1 * ($2 ? 1000 : 1);
143 } elsif ($prop =~m/^([1-9]\d*)l$/) {
144 $c->{Volume}= $1 * 1000;
146 die "unknown property $prop for $ucname";
151 die "unknown $&" unless defined $colours{$1};
152 my ($lhs,$pctlet,$rhs)= ($`,$1,$');
153 foreach my $c (keys %{ $colours{$pctlet} }) {
154 &$ca($lhs.$c.$rhs, $ss .'%'. $colours{$pctlet}{$c});
157 foreach (@rawcm) { &$ca($_,$src); }
159 foreach my $on (keys %routes) {
160 my $routes= $routes{$on};
161 my $ocean= $oceans{$on};
162 die unless defined $ocean;
165 foreach my $an (sort keys %$ocean) {
166 my $arch= $ocean->{$an};
167 push @allislands, sort keys %$arch;
169 parse_info_maproutes($on, \@allislands, $routes);
170 foreach my $route (values %$routes) {
171 parse_info_maproutes($on, \@allislands, $route);
176 sub parse_info_clientside () {
177 my $yarrg= $ENV{'YPPSC_YARRG_DICT_UPDATE'};
178 return unless $yarrg;
179 my $master= fetch_with_rsync("info-$masterinfoversion");
180 parse_info1($master,'s');
181 my $local= '_local-info.txt';
183 parse_info1($local,'s');
185 die "$local $!" unless $! == &ENOENT;
189 sub fetch_with_rsync ($) {
192 my $rsync= $ENV{'YPPSC_YARRG_RSYNC'};
193 $rsync= 'rsync' if !defined $rsync;
195 my $local= "_master-$stem.txt";
196 my $src= $ENV{'YPPSC_YARRG_DICT_UPDATE'};
198 my $remote= "$src/master-$stem.txt";
199 $!=0; system 'rsync','-Lt','--',$remote,$local;
200 die "$? $!" if $! or $?;
205 sub parse_info_maproutes ($$$) {
206 my ($on, $allislands, $routemap) = @_;;
207 foreach my $k (sort keys %$routemap) {
208 my @ok= grep { index($_,$k) >= 0 } @$allislands;
209 die "ambiguous $k" if @ok>1;
211 $route_mysteries{$on}{$k}++;
212 delete $routemap->{$k};
213 } elsif ($ok[0] ne $k) {
214 $routemap->{$ok[0]}= $routemap->{$k};
215 delete $routemap->{$k};
220 sub parse_info_serverside () {
221 parse_info1('source-info.txt','s');
223 sub parse_info_serverside_ocean ($) {
224 my ($oceanname) = @_;
225 die "unknown ocean $oceanname ?" unless exists $oceans{$oceanname};
226 parse_info1("ocean-".(lc $oceanname).".txt",'s');
229 sub parse_pctb_commodmap () {
230 undef %pctb_commodmap;
231 foreach my $commod (keys %commods) { $commods{$commod}{Srcs} =~ s/b//; }
233 my $c= new IO::File '_commodmap.tsv';
234 if (!$c) { $!==&ENOENT or die $!; return 0; }
237 m/^(\S.*\S)\t(\d+)\n$/ or die "$_";
238 die if defined $pctb_commodmap{$1}; $pctb_commodmap{$1}= $2;
239 die if defined $pctb_commodmap[$2]; $pctb_commodmap[$2]= $1;
240 $commods{$1}{Srcs} .= 'b';
242 $c->error and die $!;
247 sub get_our_version ($$) {
248 my ($aref,$prefix) = @_;
249 $aref->{"${prefix}name"}= 'ypp-sc-tools yarrg';
250 $aref->{"${prefix}fixes"}= 'lastpage checkpager';
252 my $version= `git-describe --tags HEAD || echo 0unknown`; $? and die $?;
254 $aref->{"${prefix}version"}= $version;
256 # clientname "ypp-sc-tools"
257 # clientversion 2.1-g2e06a26 [from git-describe --tags HEAD]
258 # clientfixes "lastpage" [space separated list]
261 sub pipethrough_prep () {
262 my $tf= IO::File::new_tmpfile() or die $!;
266 sub pipethrough_run_along ($$$@) {
267 my ($tf, $childprep, $cmd, @a) = @_;
268 $tf->error and die $!;
269 $tf->flush or die $!;
270 $tf->seek(0,0) or die $!;
271 my $fh= new IO::File;
272 my $child= $fh->open("-|"); defined $child or die $!;
274 open STDIN, "<&", $tf;
275 &$childprep() if defined $childprep;
276 exec $cmd @a; die "@a $!";
280 sub pipethrough_run_finish ($$) {
282 $fh->error and die $!;
283 close $fh or die "$what $! $?"; die $? if $?;
286 sub pipethrough_run ($$$@) {
287 my ($tf, $childprep, $cmd, @a) = @_;
288 my $pt= pipethrough_run_along($tf,$childprep,$cmd,@a);
290 { undef $/; $!=0; $r= <$pt>; }
291 defined $r or die $!;
292 pipethrough_run_finish($pt, "@a");
295 sub pipethrough_run_gzip ($) {
296 pipethrough_run($_[0],undef,'gzip','gzip');
299 sub yarrgpostform ($$) {
300 my ($ua, $form) = @_;
301 my $dest= $ENV{'YPPSC_YARRG_YARRG'};
302 get_our_version($form, 'client');
303 die unless $dest =~ m,/$,;
304 return cgipostform($ua, "${dest}commod-update-receiver", $form);
307 sub cgipostform ($$$) {
308 my ($ua, $url, $form) = @_;
309 my $req= HTTP::Request::Common::POST($url,
311 Content_Type => 'form-data');
312 if ($url =~ m,^\.?/,) {
313 my $tf= pipethrough_prep();
314 print $tf $req->content() or die $!;
315 #print STDERR "[[[",$req->content(),"]]]";
316 my $out= pipethrough_run($tf, sub {
317 $ENV{'REQUEST_METHOD'}= 'POST';
318 $ENV{'QUERY_STRING'}= '';
319 $ENV{'PATH_TRANSLATED'}= $url;
320 $ENV{'PATH_INFO'}= '';
321 $ENV{'HTTP_HOST'}= 'localhost';
322 $ENV{'REMOTE_ADDR'}= '127.0.0.1';
323 $ENV{'GATEWAY_INTERFACE'}= 'CGI/1.1';
324 $ENV{'DOCUMENT_ROOT'}= '.';
325 $ENV{'SCRIPT_FILENAME'}= $url;
326 $ENV{'SCRIPT_NAME'}= $url;
327 $ENV{'HTTP_USER_AGENT'}= 'Commods.pm local test';
329 foreach my $f (qw(Content_Length Content_Type)) {
330 $ENV{uc $f}= $req->header($f);
332 #system 'printenv >&2';
335 $out =~ m,^Content-Type: text/plain.*\n\n, or die "$out ?";
338 my $resp= $ua->request($req);
339 die $resp->status_line."\n".$resp->content."\n "
340 unless $resp->is_success;
341 return $resp->content();
347 sub check_tsv_line ($$) {
348 my ($l, $bad_data_callback) = @_;
349 my $bad_data= sub { &$bad_data_callback("bad data: line $.: $_[0]"); };
351 chomp($l) or &$bad_data('missing end-of-line');
353 $l !~ m/\P{IsPrint}/ or &$bad_data('nonprinting char(s)');
354 my @v= split /\t/, $l, -1;
355 @v==6 or &$bad_data('wrong number of fields');
356 my ($commod,$stall) = @v;
359 defined $commods{$commod} or
360 &$bad_data("unknown commodity \`$commod'");
362 $stall =~ m/^\p{IsUpper}|^[0-9]/ or &$bad_data("stall not capitalised");
363 !exists $check_tsv_done{$commod,$stall} or &$bad_data("repeated data");
364 $check_tsv_done{$commod,$stall}= 1;
365 foreach my $i (2..5) {
367 $f =~ m/^(|0|[1-9][0-9]{0,5}|\>1000)$/ or &$bad_data("bad field $i");
368 ($i % 2) or ($f !~ m/\>/) or &$bad_data("> in field $i price");
371 foreach my $i (2,4) {
372 &$bad_data("price with no qty or vice versa (field $i)")
373 if length($v[$i]) xor length($v[$i+1]);
375 length($v[2]) or length($v[4]) or
376 &$bad_data("commodity entry with no buy or sell offer");
381 sub cgi_get_caller () {
382 my $caller= $ENV{'REMOTE_ADDR'};
383 $caller= 'LOCAL' unless defined $caller;
385 my $fwdf= $ENV{'HTTP_X_FORWARDED_FOR'};
388 $fwdf =~ s/[^0-9.,]/?/g;
394 sub set_ctype_utf8 () {
395 setlocale(LC_CTYPE, "en.UTF-8");