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