]> matita.cs.unibo.it Git - helm.git/blob - helm/http_getter/http_getter.pl.in
HELM_DTD_DIR now also used
[helm.git] / helm / http_getter / http_getter.pl.in
1 #!@PERL_BINARY@
2
3 # Copyright (C) 2000, HELM Team.
4
5 # This file is part of HELM, an Hypertextual, Electronic
6 # Library of Mathematics, developed at the Computer Science
7 # Department, University of Bologna, Italy.
8
9 # HELM is free software; you can redistribute it and/or
10 # modify it under the terms of the GNU General Public License
11 # as published by the Free Software Foundation; either version 2
12 # of the License, or (at your option) any later version.
13
14 # HELM is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 # GNU General Public License for more details.
18
19 # You should have received a copy of the GNU General Public License
20 # along with HELM; if not, write to the Free Software
21 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22
23 # For details, see the HELM World-Wide-Web page,
24 # http://cs.unibo.it/helm/.
25
26 # First of all, let's load HELM configuration
27 use Env;
28 my $HELM_LIB_DIR = $ENV{"HELM_LIB_DIR"};
29 # this should be the only fixed constant
30 my $DEFAULT_HELM_LIB_DIR = "@HELM_LIB_DIR@";
31 if (defined ($HELM_LIB_DIR)) {
32    $HELM_LIB_PATH = $HELM_LIB_DIR."/configuration.pl";
33 } else {
34    $HELM_LIB_PATH = $DEFAULT_HELM_LIB_DIR."/configuration.pl";
35 }
36
37 # Let's override the configuration file
38 $styles_dir = $ENV{"HELM_STYLE_DIR"} if (defined ($ENV{"HELM_STYLE_DIR"}));
39 $dtd_dir = $ENV{"HELM_DTD_DIR"} if (defined ($ENV{"HELM_DTD_DIR"}));
40
41 # <ZACK>: TODO temporary, move this setting to configuration file
42 # set the cache mode, may be "gzipped" or "normal"
43 my $cachemode = $ENV{'HTTP_GETTER_CACHE_MODE'} || 'gzipped';
44 if (($cachemode ne 'gzipped') and ($cachemode ne 'normal')) {
45         die "Invalid HTTP_GETTER_CACHE_MODE environment variable, must be 'normal' or 'gzipped'\n";
46 }
47 # </ZACK>
48
49 # next require defines: $helm_dir, $html_link, $dtd_dir, $uris_dbm
50 require $HELM_LIB_PATH;
51
52 use HTTP::Daemon;
53 use HTTP::Status;
54 use HTTP::Request;
55 use LWP::UserAgent;
56 use DB_File;
57 use Compress::Zlib;
58
59 #CSC: mancano i controlli sulle condizioni di errore di molte funzioni
60 #CSC: ==> non e' robusto
61 #CSC: altra roba da sistemare segnata con CSC
62
63 my $d = new HTTP::Daemon LocalPort => 8081;
64 tie(%map, 'DB_File', $uris_dbm.".db", O_RDONLY, 0664);
65 print "Please contact me at: <URL:", $d->url, ">\n";
66 print "helm_dir: $helm_dir\n";
67 print "dtd_dir: $dtd_dir\n";
68 print "urls_of_uris.db: $uris_dbm.db\n";
69 print "cache mode: $cachemode\n";
70
71 $SIG{CHLD} = "IGNORE"; # do not accumulate defunct processes
72 $SIG{USR1} = \&update; # sent by the child to make the parent update
73 while (my $c = $d->accept) {
74  if (fork() == 0) {
75     while (my $r = $c->get_request) {
76         #CSC: mancano i controlli di sicurezza
77         
78         my $inputuri = $r->url; 
79         $inputuri =~ s/^[^?]*\?uri=(.*)/$1/;
80         print "\nRequest: ".$r->url."\n\n";
81         my $http_method = $r->method;
82         my $http_path = $r->url->path;
83
84         if ($http_method eq 'GET' and $http_path eq "/getciconly") {
85             # finds the uri, url and filename
86             my $cicuri = $inputuri;
87
88             my $cicfilename = $cicuri;
89             $cicfilename =~ s/cic:(.*)/$1/;
90             $cicfilename =~ s/theory:(.*)/$1/;
91 #            $cicfilename = $helm_dir.$cicfilename.".xml";
92 # <gzip>
93             my $cicurl   = $map{$cicuri};
94                         my $extension;
95                         if ($cicurl =~ /\.xml$/) {      # non gzipped file
96                                         $extension = ".xml";
97                         } elsif ($cicurl =~ /\.xml\.gz$/) {     # gzipped file
98                                         $extension = ".xml.gz";
99                         } else {        # error: unknown extension
100                                 die "unexpected extension in url: $cicurl, might be '.xml' or '.xml.gz'";
101                         }
102             $cicfilename = $helm_dir.$cicfilename.$extension;
103
104             #my $cicurl   = $map{$cicuri};
105 # </gzip>
106             if (!defined($cicurl)) {
107              print "\nNOT FOUND!!!!!\n";
108              $c->send_error(RC_NOT_FOUND)
109             } else {
110                print_request("cic",$cicuri,$cicurl,$cicfilename);
111
112                # Retrieves the file
113                my $ciccontent = download(0,"cic",$cicurl,$cicfilename);
114
115                # Answering the client
116                answer($c,$ciccontent);
117             }
118         } elsif ($http_method eq 'GET' and $http_path eq "/get") {
119             # finds the uris, urls and filenames
120             my $cicuri = $inputuri,
121                $typesuri = $inputuri,
122                $annuri = $inputuri;
123             my $annsuffix;
124             if ($inputuri =~ /\.types$/) {
125                $cicuri    =~ s/(.*)\.types$/$1/;
126                undef($annuri);
127             } elsif ($inputuri =~ /\.types\.ann$/) {
128                $cicuri    =~ s/(.*)\.types\.ann$/$1/;
129                $typesuri  =~ s/(.*)\.ann$/$1/;
130                $annsuffix = ".types.ann";
131             } elsif ($inputuri =~ /\.ann$/) {
132                $cicuri  =~ s/(.*)\.ann$/$1/;
133                undef($typesuri);
134                $annsuffix = ".ann";
135             } else {
136                undef($typesuri);
137                undef($annuri);
138             }
139
140             my $cicfilename = $cicuri;
141             $cicfilename =~ s/cic:(.*)/$1/;
142             $cicfilename =~ s/theory:(.*)/$1/;
143             $cicfilename = $helm_dir.$cicfilename;
144
145 #            my $typesfilename = $cicfilename.".types.xml"     if $typesuri;
146 #            my $annfilename  = $cicfilename.$annsuffix.".xml" if $annuri;
147 #            $cicfilename .= ".xml";
148
149 # <gzip>
150             my $cicurl   = $map{$cicuri};
151             my $typesurl = $map{$typesuri} if (defined($typesuri));
152             my $annurl   = $map{$annuri}  if (defined($annuri));
153                         my ($cicext, $typesext, $annext);
154                         if ($cicurl =~ /\.xml$/) {      # normal file
155                                 $cicext = ".xml";
156                         } elsif ($cicurl =~ /\.xml\.gz$/) {     # gzipped file
157                                 $cicext = ".xml.gz";
158                         } else {
159                                 die "unexpected extension in url: $cicurl; might be '.xml' or '.xml.gz'";
160                         }
161                         if (defined($typesuri)) {       # extension selection for types file
162                                 if ($typesurl =~ /\.xml$/) {    # normal file
163                                         $typesext = ".types.xml";
164                                 } elsif ($typesurl =~ /\.xml\.gz$/) {   # gzipped file
165                                         $typesext = ".types.xml.gz";
166                                 } else {
167                                         die "unexpected extension in url: $typesurl; might be '.xml' or '.xml.gz'";
168                                 }
169                         }
170                         if (defined($annuri)) { # extension selection for annotation file
171                                 if ($annurl =~ /\.xml$/) {      # normal file
172                                         $annext = ".xml";
173                                 } elsif ($annurl =~ /\.xml\.gz$/) {     # gzipped file
174                                         $annext = ".xml.gz";
175                                 } else {
176                                         die "unexpected extension in url: $annurl might be '.xml' or '.xml.gz'";
177                                 }
178                         }
179             my $typesfilename = $cicfilename.$typesext if $typesuri;
180             my $annfilename  = $cicfilename.$annsuffix.$annext if $annuri;
181             $cicfilename .= $cicext;
182 # </gzip>
183
184
185             if (!defined($cicurl) ||
186                (!defined($typesurl) && $typesuri) ||
187                (!defined($annuri) && $annuri))
188             {
189              print "\nNOT FOUND!!!!!\n";
190              $c->send_error(RC_NOT_FOUND)
191             } else {
192                print_request("cic",$cicuri,$cicurl,$cicfilename);
193                print_request("types",$typesuri,$typesurl,$typesfilename)
194                 if ($typesuri);
195                print_request("ann",$annuri,$annurl,$annfilename)
196                 if ($annuri);
197  
198                # Retrieves the files
199
200                my $ciccontent = download(1,"cic",$cicurl,$cicfilename);
201                my $typescontent =
202                 download(1,"types",$typesurl,$typesfilename) if ($typesuri);
203                my $anncontent =
204                 download(1,"ann",$annurl,$annfilename) if ($annuri);
205  
206                # Merging the files together
207  
208                my $merged = <<EOT;
209 <?xml version="1.0" encoding="UTF-8"?>
210 <cicxml uri="$cicuri">
211 $ciccontent
212 $typescontent
213 $anncontent
214 </cicxml>
215 EOT
216
217                # Answering the client
218                answer($c,$merged);
219             }
220          } elsif ($http_method eq 'GET' and $http_path eq "/getdtd") {
221             my $filename = $inputuri;
222             $filename = $dtd_dir."/".$filename;
223             print "DTD: $inputuri ==> ($filename)\n";
224             if (stat($filename)) {
225                print "Using local copy\n";
226                open(FD, $filename) or die "Cannot open $filename\n";
227                $cont = "";
228                while(<FD>) { $cont .= $_; }
229                close(FD);
230                answer($c,$cont);
231             } else {
232                die "Could not find DTD!";
233             }
234          } elsif ($http_method eq 'GET' and $http_path eq "/getxslt") {
235             my $filename = $inputuri;
236             $filename = $styles_dir."/".$filename;
237             print "XSLT: $inputuri ==> ($filename)\n";
238             if (stat($filename)) {
239                print "Using local copy\n";
240                open(FD, $filename) or die "Cannot open $filename\n";
241                $cont = "";
242                while(<FD>) { $cont .= $_; }
243                close(FD);
244                answer($c,$cont);
245             } else {
246                die "Could not find XSLT!";
247             }
248         } elsif ($http_method eq 'GET' and $http_path eq "/conf") {
249             my $quoted_html_link = $html_link;
250             $quoted_html_link =~ s/&/&amp;/g;
251             $quoted_html_link =~ s/</&lt;/g;
252             $quoted_html_link =~ s/>/&gt;/g;
253             $quoted_html_link =~ s/'/&apos;/g;
254             $quoted_html_link =~ s/"/&quot;/g;
255             print "\nConfiguration requested, returned #$quoted_html_link#\n";
256             $cont = "<?xml version=\"1.0\"?><html_link>$quoted_html_link</html_link>";
257             answer($c,$cont);
258         } elsif ($http_method eq 'GET' and $http_path eq "/update") {
259            print "Update requested...";
260            update();
261            kill(USR1,getppid());
262            print " done\n";
263            answer($c,"<html><body><h1>Update done</h1></body></html>");
264         } else {
265             print "\nINVALID REQUEST!!!!!\n";
266             $c->send_error(RC_FORBIDDEN)
267         }
268         print "\nRequest solved: ".$r->url."\n\n";
269     }
270     $c->close;
271     undef($c);
272     print "\nCONNECTION CLOSED\n\n";
273     exit;
274   } # fork
275 }
276
277 #================================
278
279
280 #CSC: Too much powerful: creates even /home, /home/users/, ...
281 #CSC: Does not raise errors if could not create dirs/files
282 sub mkdirs
283 {
284  my ($pathname) = @_;
285  my @dirs = split /\//,$pathname;
286  my $tmp;
287  foreach $dir (@dirs) {
288   $tmp = ((defined($tmp)) ?  $tmp."\/".$dir : "");
289   mkdir($tmp,0777);
290  }
291  rmdir($tmp);
292 }
293
294 sub print_request
295 {
296  my ($str,$uri,$url,$filename) = @_;
297  print $str."uri: $uri\n";
298  print $str."url: $url\n";
299  print $str."filename: $filename\n\n";
300 }
301
302 sub callback
303 {
304  my ($data) = @_;
305  $cont .= $data;
306 }
307
308 sub gunzip { # gunzip a file and return the deflated content
309         my ($filename) = @_;
310
311         my ($gz, $buffer, $cont);
312
313         print "deflating $filename ...\n";
314         $gz = gzopen($filename, "r") or die "Cannot open gzip'ed file $filename: $gzerrno";
315         $cont = "";
316         while ( $gz->gzread($buffer) > 0 ) {
317                 $cont .= $buffer;
318         }
319         die "Error while reading : $gzerrno\n" if $gzerrno != Z_STREAM_END ;
320         $gz->gzclose();
321
322         return $cont;
323 }
324
325 sub gzip {      # gzip the content argument and save it to filename argument
326         my ($cont, $filename) = @_;
327
328         my ($gz, $cont);
329
330         $gz = gzopen($filename, "w") or die "Cannot gzopen for writing file $filename: $gzerrno";
331         $gz->gzwrite($cont) or die "error writing: $gzerrno\n" ;
332         $gz->gzclose();
333 }
334
335 sub download
336 {
337  my ($remove_headers,$str,$url,$filename) = @_;
338 # <gzip>
339  my ($gz, $buffer);
340
341  my $resourcetype;      # retrieve mode: "normal" (.xml) or "gzipped" (.xml.gz)
342  if ($filename =~ /\.xml$/) {   # set retrieve mode
343          $resourcetype = "normal";
344  } elsif ($filename =~ /\.xml\.gz$/) {
345          $resourcetype = "gzipped";
346  } else {
347          die "Unsupported download extension, might be '.gz' or '.xml'\n";
348  }
349  my $basefname = $filename;
350  $basefname =~ s/\.gz$//;               # get base resource name removing trailing .gz
351 # </gzip>
352  $cont = ""; # modified by side-effect by the callback function
353
354  my $localfname="";
355  if (stat($basefname)) {
356         $localfname=$basefname;
357  } elsif (stat($basefname.".gz")) {
358         $localfname=$basefname.".gz";
359  }
360  if ($localfname ne "") {               # we already have local copy of requested file
361                                                                 # check both possible cache entry: gzipped or normal
362     print "Using local copy for the $str file\n";
363 # <gzip>
364         if ($localfname =~ /\.xml\.gz$/) {      # deflating cached file and return it
365                 $cont = gunzip($localfname);
366         } elsif ($localfname =~ /\.xml$/) {     # just return cached file
367                 open(FD, $localfname) or die "Cannot open $localfname";
368                 while(<FD>) { $cont .= $_; }
369                 close(FD);
370         } else {        # error
371                 die "Internal error: unexpected file name $localfname, must end with '.gz' or '.xml.gz'\n";
372         }
373 # </gzip>
374  } else {       # download file from net
375     print "Downloading the $str file\n";        # download file
376     $ua = LWP::UserAgent->new;
377     $request = HTTP::Request->new(GET => "$url");
378     $response = $ua->request($request, \&callback);
379                
380                                 # cache retrieved file to disk
381 # <ZACK/> TODO: inefficent, I haven't yet undestood how to deflate in memory gzipped file,
382 #                               without call "gzopen"
383 # <gzip>
384         print "Storing the $str file\n";
385         mkdirs($filename);
386         open(FD, ">".$filename.".tmp") or die "Cannot open $filename.tmp\n";
387         print FD $cont;
388         close(FD);
389
390         # handle cache conversion normal->gzipped or gzipped->normal as user choice
391         if (($cachemode eq 'normal') and ($resourcetype eq 'normal')) { # cache the file as is
392                 rename "$filename.tmp", $filename;      
393         } elsif (($cachemode eq 'gzipped') and ($resourcetype eq 'gzipped')) {  # cache the file as is
394                                                                                         # and update the $cont variabile with deflated content
395                 rename "$filename.tmp", $filename;      
396                 $cont = gunzip($filename);
397         } elsif (($cachemode eq 'normal') and ($resourcetype eq 'gzipped')) {   # deflate cache entry
398                                                                                                                                                         # and update $cont
399                 open(FD, "> $basefname") or die "cannot open $basefname\n";
400                 $cont = gunzip($filename.".tmp");
401                 print FD $cont;
402                 close(FD);
403                 unlink "$filename.tmp"; # delete old gzipped file
404         } elsif (($cachemode eq 'gzipped') and ($resourcetype eq 'normal')) {   # compress cache entry
405                 gzip($cont, $basefname.".gz");
406                 unlink "$filename.tmp"; # delete old uncompressed file
407         } else {
408                 die "Internal error, unsopported cachemode, resourcetype couple\n";
409         }
410         # $cont now contained uncompressed data
411
412 # </gzip>
413  }
414  if ($remove_headers) {
415     $cont =~ s/<\?xml [^?]*\?>//sg;
416     $cont =~ s/<!DOCTYPE [^>]*>//sg;
417  }
418  return $cont;
419 }
420
421 sub answer
422 {
423  my ($c,$cont) = @_;
424  my $res = new HTTP::Response;
425  $res->content($cont);
426  $c->send_response($res);
427 }
428
429 sub update {
430  untie %map;
431  tie(%map, 'DB_File', $uris_dbm.".db", O_RDONLY, 0664);
432 }