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