chiark / gitweb /
Do some referential integrity checking
[ypp-sc-tools.db-test.git] / yarrg / commod-update-receiver
1 #!/usr/bin/perl -w
2 #
3 # This script is invoked when the yarrg client uploads to
4 # the chiark database.
5
6 # This is part of the YARRG website.  YARRG is a tool and website
7 # for assisting players of Yohoho Puzzle Pirates.
8 #
9 # Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
10 #
11 # This program is free software: you can redistribute it and/or modify
12 # it under the terms of the GNU Affero General Public License as
13 # published by the Free Software Foundation, either version 3 of the
14 # License, or (at your option) any later version.
15 #
16 # This program is distributed in the hope that it will be useful,
17 # but WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 # GNU Affero General Public License for more details.
20 #
21 # You should have received a copy of the GNU Affero General Public License
22 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
23 #
24 # Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
25 # are used without permission.  This program is not endorsed or
26 # sponsored by Three Rings.
27
28 use strict (qw(vars));
29 use POSIX;
30 use MIME::Entity;
31
32 use Commods;
33
34 $CGI::POST_MAX= 3*1024*1024;
35
36 use CGI qw/:standard -private_tempfiles/;
37
38 set_ctype_utf8();
39
40 our $now= time;  defined $now or die $!;
41
42 my $re_any= "^(.*)\$";
43
44 sub fail ($) {
45     my ($msg) = @_;
46     addlog("failing $msg");
47     print header(-status=>'400 Bad commodity update',
48                  -type=>'text/plain',
49                  -charset=>'us-ascii');
50     print "\nError: $msg\n";
51     exit 0;
52 }
53
54 sub must_param ($$) {
55     my ($n,$re)= @_;
56     my $v= param($n);
57     fail("missing form parameter $n") unless defined $v;
58     fail("invalid form parameter $n ($re)") unless $v =~ m/$re/;
59     return $1;
60 }
61
62 my %o;
63
64 if (param('get_source')) {
65     # There's another copy of this in dictionary-update-receiver.  Sorry.
66     print header('application/octet-stream') or die $!;
67     source_tarball('..', sub { print $_[0] or die $!; });
68     exit 0;
69 }
70
71 parse_info_serverside();
72
73 my $midtmp= "_mid-pid$$.hold";
74 open MIDTMP, ">$midtmp" or die "$midtmp $!";
75 stat MIDTMP or die $!;
76 my $ino= (stat _)[1];
77 my $midino= "_mid-ino$$.hold";
78 rename $midtmp, $midino or die "$midtmp $midino $!";
79 close MIDTMP or die $!;
80
81 our $hostname= `hostname -f`; $? and die $?;  chomp $hostname or die;
82 our $mid= "<$now.$$.$ino\@$hostname>";
83 our $pwd= `pwd`; $? and die $?; chomp($pwd);
84 our $caller= cgi_get_caller;
85
86 sub addlog ($) {
87     print LOG "$mid $caller $_[0]\n" or die $!;
88     flush LOG or die $!;
89 }
90
91 open LOG, ">>_upload.log" or die $!;
92 addlog("receiving");
93
94 $o{'clientname'}= must_param('clientname',$re_any);
95 my $clientinfo= $clients{$o{'clientname'}};
96 fail('unknown client') unless defined $clientinfo;
97
98 my $clientfixes= must_param('clientfixes', "^([-0-9a-z ]*)\$");
99 my @clientfixes= sort grep { m/./ } split /\s+/, $clientfixes;
100 $o{'clientfixes'}= "@clientfixes";
101 foreach my $bug (@$clientinfo) {
102     fail("client out of date - missing bugfix \`$bug'")
103         unless grep { $_ eq $bug } @clientfixes;
104 }
105
106 $o{'clientversion'}= must_param('clientversion', "^(\\d[-+._0-9a-zA-Z]+)\$");
107
108 if (param('requesttimestamp')) {
109     my $now= time; defined $now or die;
110     print header(-type=>'text/plain', -charset=>'us-ascii'), "OK $now.\n";
111     exit(0);
112 }
113
114 $o{'ocean'}= must_param('ocean', $re_any);
115 $o{'island'}= must_param('island', $re_any);
116
117 my $arches= $oceans{$o{'ocean'}};
118 fail("unknown ocean") unless $arches;
119
120 parse_info_serverside_ocean($o{'ocean'});
121
122 my $island_found= 0;
123 foreach my $islands (values %$arches) {
124     my $sources= $islands->{$o{'island'}};
125     next unless $sources;
126     die if $island_found;
127     $island_found= $sources;
128 }
129 fail("unknown island") unless $island_found;
130
131 $o{'timestamp'}= must_param('timestamp', "^([1-9]\\d{1,20})\$");
132 fail("clock skew") if $o{'timestamp'} >= $now;
133
134 my $indatafh= upload('data');
135 defined $indatafh or fail("data is not a file");
136 my $datafile= must_param('data',"^(deduped\\.tsv\\.gz)\$");
137
138 foreach my $mid (<_mid-*.hold>) {
139     if (!stat $mid) { $!==&ENOENT or die "$mid $!"; next; }
140     my $age= (stat _)[9];
141     next if $age < 60;
142     unlink $mid or $!==&ENOENT or die "$mid $!";
143 }
144
145 $o{'instance'}= $ENV{'YARRG_INSTANCE'};
146
147 my $mcontent= MIME::Entity->build(To => 'yarrg-commod-updates',
148                                   Subject => $ENV{'YARRG_INSTANCE'},
149                                   Type => 'multipart/mixed',
150                                   Boundary => '=',
151                                   'Message-ID' => $mid,
152                                   Charset => 'utf-8');
153
154 get_our_version(\%o, 'server');
155 foreach my $cs (qw(client server)) {
156     $o{"${cs}spec"}= join "\t", map { $o{$cs.$_} } qw(name version fixes);
157 }
158
159 my $metadata= '';
160
161 sub ksmap ($) {
162     my ($v) = @_;
163     my $i=0; grep { return $i if $_ eq $v; $i++ } qw(ocean island timestamp);
164     sprintf "z %d %s", (length $v) / 8, $v;
165 }
166
167 foreach my $vn (sort { ksmap($a) cmp ksmap($b) } keys %o) {
168     my $val= $o{$vn};
169     die if $val =~ m/\n|\r/;
170     $metadata .= "$vn\t$o{$vn}\n";
171 }
172
173 my $mdpart= MIME::Entity->build(Top => 0,
174                                 Type => 'text/plain',
175                                 Charset => 'utf-8',
176                                 Disposition => 'inline',
177                                 Encoding => 'quoted-printable',
178                                 Filename => 'metadata',
179                                 Data => $metadata);
180 $mcontent->add_part($mdpart);
181
182 my $gunzchild= open(GZ, "-|"); defined $gunzchild or die $!;
183 if (!$gunzchild) {
184     open STDIN, "<&=", $indatafh or die $!;
185     exec 'gunzip'; die $!;
186 }
187
188 my $dedupedtsv= pipethrough_prep();
189
190 while (<GZ>) {
191     my @v= check_tsv_line($_,\&fail);
192     print $dedupedtsv join("\t",@v),"\n" or die $!;
193 }
194
195 GZ->error and die $!;
196 $?=0; close GZ; $? and fail("gunzip for check failed code $?");
197
198 my $launderedgz= pipethrough_run($dedupedtsv,undef,'gzip','gzip');
199
200 my $mdatafile= MIME::Entity->build(Top => 0,
201                                    Type => 'application/octet-stream',
202                                    Disposition => 'attachment',
203                                    Encoding => 'base64',
204                                    Filename => 'deduped.tsv.gz',
205                                    Data => $launderedgz);
206 $mcontent->add_part($mdatafile);
207
208 open M, "|/usr/sbin/sendmail -t -oi -oee -odb"
209     or fail("fork sendmail failed! ($!)");
210 $mcontent->print(\*M);
211
212 M->error and fail("write sendmail failed! ($!)");
213 $?=0; close M; $? and fail("sendmail failed code $?");
214
215 print header(-type=>'text/plain', -charset=>'us-ascii'),
216       "OK\nThank you for your submission to YARRG.\n"
217     or die $!;
218
219 addlog("accepted $o{'clientspec'}");
220 close LOG or die $!;