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