]> matita.cs.unibo.it Git - helm.git/blob - helm/http_getter/http_getter.pl.in
Done for URLs for DTDs the same thing previously done for stylesheets
[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>) {
227                 # Vary bad heuristic for substituion of absolute URLs
228                 # for relative ones
229                 s/ENTITY (.*) SYSTEM\s+"/ENTITY $1 SYSTEM "$myownurl\/getdtd?uri=/g;
230                 $cont .= $_;
231                }
232                close(FD);
233                answer($c,$cont);
234             } else {
235                die "Could not find DTD!";
236             }
237          } elsif ($http_method eq 'GET' and $http_path eq "/getxslt") {
238             my $filename = $inputuri;
239             $filename = $styles_dir."/".$filename;
240             print "XSLT: $inputuri ==> ($filename)\n";
241             if (stat($filename)) {
242                print "Using local copy\n";
243                open(FD, $filename) or die "Cannot open $filename\n";
244                $cont = "";
245                while(<FD>) {
246                 # Vary bad heuristic for substituion of absolute URLs
247                 # for relative ones
248                 s/xsl:import\s+href="/xsl:import href="$myownurl\/getxslt?uri=/g ;
249                 s/xsl:include\s+href="/xsl:include href="$myownurl\/getxslt?uri=/g ;
250                 $cont .= $_;
251                }
252                close(FD);
253                answer($c,$cont);
254             } else {
255                die "Could not find XSLT!";
256             }
257         } elsif ($http_method eq 'GET' and $http_path eq "/conf") {
258             my $quoted_html_link = $html_link;
259             $quoted_html_link =~ s/&/&amp;/g;
260             $quoted_html_link =~ s/</&lt;/g;
261             $quoted_html_link =~ s/>/&gt;/g;
262             $quoted_html_link =~ s/'/&apos;/g;
263             $quoted_html_link =~ s/"/&quot;/g;
264             print "\nConfiguration requested, returned #$quoted_html_link#\n";
265             $cont = "<?xml version=\"1.0\"?><html_link>$quoted_html_link</html_link>";
266             answer($c,$cont);
267         } elsif ($http_method eq 'GET' and $http_path eq "/update") {
268            print "Update requested...";
269            update();
270            kill(USR1,getppid());
271            print " done\n";
272            answer($c,"<html><body><h1>Update done</h1></body></html>");
273         } else {
274             print "\nINVALID REQUEST!!!!!\n";
275             $c->send_error(RC_FORBIDDEN)
276         }
277         print "\nRequest solved: ".$r->url."\n\n";
278     }
279     $c->close;
280     undef($c);
281     print "\nCONNECTION CLOSED\n\n";
282     exit;
283   } # fork
284 }
285
286 #================================
287
288
289 #CSC: Too much powerful: creates even /home, /home/users/, ...
290 #CSC: Does not raise errors if could not create dirs/files
291 sub mkdirs
292 {
293  my ($pathname) = @_;
294  my @dirs = split /\//,$pathname;
295  my $tmp;
296  foreach $dir (@dirs) {
297   $tmp = ((defined($tmp)) ?  $tmp."\/".$dir : "");
298   mkdir($tmp,0777);
299  }
300  rmdir($tmp);
301 }
302
303 sub print_request
304 {
305  my ($str,$uri,$url,$filename) = @_;
306  print $str."uri: $uri\n";
307  print $str."url: $url\n";
308  print $str."filename: $filename\n\n";
309 }
310
311 sub callback
312 {
313  my ($data) = @_;
314  $cont .= $data;
315 }
316
317 sub gunzip { # gunzip a file and return the deflated content
318         my ($filename) = @_;
319
320         my ($gz, $buffer, $cont);
321
322         print "deflating $filename ...\n";
323         $gz = gzopen($filename, "r")
324                 or die "Cannot open gzip'ed file $filename: $gzerrno";
325         $cont = "";
326         while ( $gz->gzread($buffer) > 0 ) {
327                 $cont .= $buffer;
328         }
329         die "Error while reading : $gzerrno\n" if $gzerrno != Z_STREAM_END ;
330         $gz->gzclose();
331
332         return $cont;
333 }
334
335 sub gzip {      # gzip the content argument and save it to filename argument
336         my ($cont, $filename) = @_;
337
338         my ($gz, $cont);
339
340         $gz = gzopen($filename, "w")
341                 or die "Cannot gzopen for writing file $filename: $gzerrno";
342         $gz->gzwrite($cont) or die "error writing: $gzerrno\n" ;
343         $gz->gzclose();
344 }
345
346 sub download
347 {
348  my ($remove_headers,$str,$url,$filename) = @_;
349  my ($gz, $buffer);
350
351  my $resourcetype;      # retrieve mode: "normal" (.xml) or "gzipped" (.xml.gz)
352  if ($filename =~ /\.xml$/) {   # set retrieve mode
353          $resourcetype = "normal";
354  } elsif ($filename =~ /\.xml\.gz$/) {
355          $resourcetype = "gzipped";
356  } else {
357          die "Unsupported download extension, might be '.gz' or '.xml'\n";
358  }
359  my $basefname = $filename;
360  $basefname =~ s/\.gz$//;       # get base resource name removing trailing .gz
361  $cont = ""; # modified by side-effect by the callback function
362
363  my $localfname="";
364  if (stat($basefname)) {
365         $localfname=$basefname;
366  } elsif (stat($basefname.".gz")) {
367         $localfname=$basefname.".gz";
368  }
369  if ($localfname ne "") { # we already have local copy of requested file
370       # check both possible cache entry: gzipped or normal
371   print "Using local copy for the $str file\n";
372   if ($localfname =~ /\.xml\.gz$/) { # deflating cached file and return it
373    $cont = gunzip($localfname);
374   } elsif ($localfname =~ /\.xml$/) { # just return cached file
375    open(FD, $localfname) or die "Cannot open $localfname";
376    while(<FD>) { $cont .= $_; }
377    close(FD);
378   } else { # error
379    die "Internal error: unexpected file name $localfname,"
380    ."must end with '.gz' or '.xml.gz'\n";
381   }
382  } else { # download file from net
383     print "Downloading the $str file\n"; # download file
384     $ua = LWP::UserAgent->new;
385     $request = HTTP::Request->new(GET => "$url");
386     $response = $ua->request($request, \&callback);
387                
388     # cache retrieved file to disk
389 # <ZACK/> TODO: inefficent, I haven't yet undestood how to deflate
390 #    in memory gzipped file, without call "gzopen"
391  print "Storing the $str file\n";
392  mkdirs($filename);
393  open(FD, ">".$filename.".tmp") or die "Cannot open $filename.tmp\n";
394  print FD $cont;
395  close(FD);
396
397  # handle cache conversion normal->gzipped or gzipped->normal as user choice
398  if (($cachemode eq 'normal') and ($resourcetype eq 'normal')) {
399    # cache the file as is
400   rename "$filename.tmp", $filename; 
401  } elsif (($cachemode eq 'gzipped') and ($resourcetype eq 'gzipped')) {
402    # cache the file as is
403    # and update the $cont variabile with deflated content
404   rename "$filename.tmp", $filename; 
405   $cont = gunzip($filename);
406  } elsif (($cachemode eq 'normal') and ($resourcetype eq 'gzipped')) {
407    # deflate cache entry
408    # and update $cont
409   open(FD, "> $basefname") or die "cannot open $basefname\n";
410   $cont = gunzip($filename.".tmp");
411   print FD $cont;
412   close(FD);
413   unlink "$filename.tmp"; # delete old gzipped file
414  } elsif (($cachemode eq 'gzipped') and ($resourcetype eq 'normal')) {
415    # compress cache entry
416   gzip($cont, $basefname.".gz");
417   unlink "$filename.tmp"; # delete old uncompressed file
418  } else {
419   die "Internal error, unsopported cachemode, resourcetype couple\n";
420  }
421  # $cont now contained uncompressed data
422
423  }
424  if ($remove_headers) {
425     $cont =~ s/<\?xml [^?]*\?>//sg;
426     $cont =~ s/<!DOCTYPE [^>]*>//sg;
427  }
428  return $cont;
429 }
430
431 sub answer
432 {
433  my ($c,$cont) = @_;
434  my $res = new HTTP::Response;
435  $res->content($cont);
436  $c->send_response($res);
437 }
438
439 sub update {
440  untie %map;
441  tie(%map, 'DB_File', $uris_dbm.".db", O_RDONLY, 0664);
442 }