]> matita.cs.unibo.it Git - helm.git/blob - helm/http_getter/http_getter.pl.in
83c8382a7cad2183953a6b39b4a77badd480bea2
[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 # <ZACK>: TODO temporary, move this setting to configuration file
40 # set the cache mode, may be "gzipped" or "normal"
41 my $cachemode = $ENV{'HTTP_GETTER_CACHE_MODE'} || 'gzipped';
42 if (($cachemode ne 'gzipped') and ($cachemode ne 'normal')) {
43  die "Invalid HTTP_GETTER_CACHE_MODE environment variable, must be".
44  "'normal' or 'gzipped'\n";
45 }
46 # </ZACK>
47
48 # next require defines: $helm_dir, $html_link, $dtd_dir, $uris_dbm
49 require $HELM_LIB_PATH;
50
51 # Let's override the configuration file
52 $style_dir = $ENV{"HELM_STYLE_DIR"} if (defined ($ENV{"HELM_STYLE_DIR"}));
53 $dtd_dir = $ENV{"HELM_DTD_DIR"} if (defined ($ENV{"HELM_DTD_DIR"}));
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 use URI::Escape;
62
63 #CSC: mancano i controlli sulle condizioni di errore di molte funzioni
64 #CSC: ==> non e' robusto
65 #CSC: altra roba da sistemare segnata con CSC
66
67 my $d = new HTTP::Daemon LocalPort => 8081;
68 my $myownurl = $d->url;
69
70 # Let's patch the returned URL
71 $myownurl =~ s/\/$//; # chop the final slash
72 my $myownport = $myownurl;
73 $myownport =~ s/http:\/\/(.*):(.*)/$2/;
74 $myownurl  =~ s/http:\/\/(.*):(.*)/$1/;
75 ($myownurl) = gethostbyname($myownurl);
76 $myownurl = "http://".$myownurl.":".$myownport;
77
78 tie(%map, 'DB_File', $uris_dbm.".db", O_RDONLY, 0664);
79 print "Please contact me at: <URL:", $myownurl."/", ">\n";
80 print "helm_dir: $helm_dir\n";
81 print "style_dir: $style_dir\n";
82 print "dtd_dir: $dtd_dir\n";
83 print "urls_of_uris.db: $uris_dbm.db\n";
84 print "cache mode: $cachemode\n";
85
86 $SIG{CHLD} = "IGNORE"; # do not accumulate defunct processes
87 $SIG{USR1} = \&update; # sent by the child to make the parent update
88 while (my $c = $d->accept) {
89  if (fork() == 0) {
90     while (my $r = $c->get_request) {
91         #CSC: mancano i controlli di sicurezza
92         
93         my $inputuri = uri_unescape($r->url); 
94         $inputuri =~ s/^[^?]*\?uri=(.*)/$1/;
95         print "\nRequest: ".$r->url."\n\n";
96         my $http_method = $r->method;
97         my $http_path = $r->url->path;
98         my $http_query = uri_unescape($r->url->query);
99
100         print "\nUnescaped query: ".$http_query."\n";
101
102         if ($http_method eq 'GET' and $http_path eq "/getciconly") {
103             # finds the uri, url and filename
104             my $cicuri = $inputuri;
105
106             my $cicfilename = $cicuri;
107             $cicfilename =~ s/cic:(.*)/$1/;
108             $cicfilename =~ s/theory:(.*)/$1/;
109
110             my $cicurl   = $map{$cicuri};
111             my $extension;
112             if ($cicurl =~ /\.xml$/) { # non gzipped file
113               $extension = ".xml";
114             } elsif ($cicurl =~ /\.xml\.gz$/) { # gzipped file
115               $extension = ".xml.gz";
116             } else { # error: unknown extension
117              die "unexpected extension in url: $cicurl, might be '.xml'".
118               "or '.xml.gz'";
119             }
120             $cicfilename = $helm_dir.$cicfilename.$extension;
121
122             if (!defined($cicurl)) {
123              print "\nNOT FOUND!!!!!\n";
124              $c->send_error(RC_NOT_FOUND)
125             } else {
126                print_request("cic",$cicuri,$cicurl,$cicfilename);
127
128                # Retrieves the file
129                my $ciccontent = download(0,"cic",$cicurl,$cicfilename);
130
131                # Answering the client
132                answer($c,$ciccontent);
133             }
134         } elsif ($http_method eq 'GET' and $http_path eq "/get") {
135             # finds the uris, urls and filenames
136             my $cicuri = $inputuri,
137                $typesuri = $inputuri,
138                $annuri = $inputuri;
139             my $annsuffix;
140             if ($inputuri =~ /\.types$/) {
141                $cicuri    =~ s/(.*)\.types$/$1/;
142                undef($annuri);
143             } elsif ($inputuri =~ /\.types\.ann$/) {
144                $cicuri    =~ s/(.*)\.types\.ann$/$1/;
145                $typesuri  =~ s/(.*)\.ann$/$1/;
146                $annsuffix = ".types.ann";
147             } elsif ($inputuri =~ /\.ann$/) {
148                $cicuri  =~ s/(.*)\.ann$/$1/;
149                undef($typesuri);
150                $annsuffix = ".ann";
151             } else {
152                undef($typesuri);
153                undef($annuri);
154             }
155
156             my $cicfilename = $cicuri;
157             $cicfilename =~ s/cic:(.*)/$1/;
158             $cicfilename =~ s/theory:(.*)/$1/;
159             $cicfilename = $helm_dir.$cicfilename;
160
161             my $cicurl   = $map{$cicuri};
162             my $typesurl = $map{$typesuri} if (defined($typesuri));
163             my $annurl   = $map{$annuri}  if (defined($annuri));
164             my ($cicext, $typesext, $annext);
165             if ($cicurl =~ /\.xml$/) { # normal file
166              $cicext = ".xml";
167             } elsif ($cicurl =~ /\.xml\.gz$/) { # gzipped file
168              $cicext = ".xml.gz";
169             } else {
170              die "unexpected extension in url: $cicurl;".
171              "might be '.xml' or '.xml.gz'";
172             }
173             if (defined($typesuri)) { # extension selection for types file
174              if ($typesurl =~ /\.xml$/) { # normal file
175               $typesext = ".types.xml";
176              } elsif ($typesurl =~ /\.xml\.gz$/) { # gzipped file
177               $typesext = ".types.xml.gz";
178              } else {
179               die "unexpected extension in url: $typesurl;".
180               "might be '.xml' or '.xml.gz'";
181              }
182             }
183             if (defined($annuri)) { # extension selection for annotation file
184              if ($annurl =~ /\.xml$/) { # normal file
185               $annext = ".xml";
186              } elsif ($annurl =~ /\.xml\.gz$/) { # gzipped file
187               $annext = ".xml.gz";
188              } else {
189               die "unexpected extension in url: $annurl".
190               "might be '.xml' or '.xml.gz'";
191              }
192             }
193             my $typesfilename = $cicfilename.$typesext if $typesuri;
194             my $annfilename  = $cicfilename.$annsuffix.$annext if $annuri;
195             $cicfilename .= $cicext;
196
197             if (!defined($cicurl) ||
198                (!defined($typesurl) && $typesuri) ||
199                (!defined($annuri) && $annuri))
200             {
201              print "\nNOT FOUND!!!!!\n";
202              $c->send_error(RC_NOT_FOUND)
203             } else {
204                print_request("cic",$cicuri,$cicurl,$cicfilename);
205                print_request("types",$typesuri,$typesurl,$typesfilename)
206                 if ($typesuri);
207                print_request("ann",$annuri,$annurl,$annfilename)
208                 if ($annuri);
209  
210                # Retrieves the files
211
212                my $ciccontent = download(1,"cic",$cicurl,$cicfilename);
213                my $typescontent =
214                 download(1,"types",$typesurl,$typesfilename) if ($typesuri);
215                my $anncontent =
216                 download(1,"ann",$annurl,$annfilename) if ($annuri);
217  
218                # Merging the files together
219  
220                my $merged = <<EOT;
221 <?xml version="1.0" encoding="UTF-8"?>
222 <cicxml uri="$cicuri">
223 $ciccontent
224 $typescontent
225 $anncontent
226 </cicxml>
227 EOT
228
229                # Answering the client
230                answer($c,$merged);
231             }
232          } elsif ($http_method eq 'GET' and $http_path eq "/getdtd") {
233             my $filename = $inputuri;
234             $filename = $dtd_dir."/".$filename;
235             print "DTD: $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/ENTITY (.*) SYSTEM\s+"/ENTITY $1 SYSTEM "$myownurl\/getdtd?uri=/g;
244                 $cont .= $_;
245                }
246                close(FD);
247                answer($c,$cont);
248             } else {
249                die "Could not find DTD!";
250             }
251         } elsif ($http_method eq 'GET' and $http_path eq "/getstyleconf") {
252             my $filename = $inputuri;
253             $filename = $style_dir."/config/".$filename;
254             if (stat($filename)) {
255                open(FD, $filename) or die "Cannot open $filename\n";
256                $cont = "";
257                while(<FD>) {
258                 s/DOCTYPE (.*) SYSTEM\s+"/DOCTYPE $1 SYSTEM "$myownurl\/getstyleconf?uri=/g;
259                 $cont .= $_;
260                }
261                close(FD);
262                answer($c,$cont);
263             } else {
264                die "Could not find Style Configuration File!";
265             }
266         } elsif ($http_method eq 'GET' and $http_path eq "/getxslt") {
267             my $filename = $inputuri;
268             $filename = $style_dir."/".$filename;
269             print "XSLT: $inputuri ==> ($filename)\n";
270             if (stat($filename)) {
271                print "Using local copy\n";
272                open(FD, $filename) or die "Cannot open $filename\n";
273                $cont = "";
274                while(<FD>) {
275                 # Vary bad heuristic for substituion of absolute URLs
276                 # for relative ones
277                 s/xsl:import\s+href="/xsl:import href="$myownurl\/getxslt?uri=/g ;
278                 s/xsl:include\s+href="/xsl:include href="$myownurl\/getxslt?uri=/g ;
279                 $cont .= $_;
280                }
281                close(FD);
282                answer($c,$cont);
283             } else {
284                die "Could not find XSLT!";
285             }
286         } elsif ($http_method eq 'GET' and $http_path eq "/conf") {
287             my $quoted_html_link = $html_link;
288             $quoted_html_link =~ s/&/&amp;/g;
289             $quoted_html_link =~ s/</&lt;/g;
290             $quoted_html_link =~ s/>/&gt;/g;
291             $quoted_html_link =~ s/'/&apos;/g;
292             $quoted_html_link =~ s/"/&quot;/g;
293             print "\nConfiguration requested, returned #$quoted_html_link#\n";
294             $cont = "<?xml version=\"1.0\"?><html_link>$quoted_html_link</html_link>";
295             answer($c,$cont);
296         } elsif ($http_method eq 'GET' and $http_path eq "/update") {
297             # rebuild urls_of_uris.db
298            print "Update requested...\n";
299            mk_urls_of_uris();
300            kill(USR1,getppid()); # signal changes to parent
301            print " done\n";
302            answer($c,"<html><body><h1>Update done</h1></body></html>");
303         } elsif ($http_method eq 'GET' and $http_path eq "/ls") {
304             # send back keys that begin with a given uri
305            my $baseuri = $http_query;
306            $baseuri =~ s/^.*baseuri=(.*)&.*$/$1/;
307            chop $baseuri if ($baseuri =~ /.*\/$/); # remove trailing "/"
308            my $outype = $http_query; # output type, might be 'txt' or 'xml'
309            $outype =~ s/^.*&type=(.*)$/$1/;
310            if (($outype ne 'txt') and ($outype ne 'xml')) { # invalid out type
311             print "Invalid output type specified: $outype\n";
312             answer($c,"<html><body><h1>Invalid output type, may be ".
313              "\"txt\" or \"xml\"</h1></body></html>");
314            } else { # valid output type
315             print "BASEURI $baseuri, TYPE $outype\n";
316             my $key;
317             $cont = "";
318             $cont .= "<urilist>\n" if ($outype eq "xml");
319             foreach (keys(%map)) { # search for uri that begin with $baseuri
320              if ($_ =~ /^$baseuri\//) {
321               $cont .= "<uri>" if ($outype eq "xml");
322               $cont .= $_;
323               $cont .= "\n" if ($outype eq "txt");
324               $cont .= "</uri>\n" if ($outype eq "xml");
325              }
326             }
327             $cont .= "</urilist>" if ($outype eq "xml");
328             answer($c,$cont);
329            }
330         } elsif ($http_method eq 'GET' and $http_path eq "/version") {
331            print "Version requested!";
332            answer($c,"<html><body><h1>HTTP Getter Version ".
333             $VERSION."</h1></body></html>");
334         } else {
335             print "\n";
336             print "INVALID REQUEST!!!!!\n";
337             print "(PATH: ",$http_path,", ";
338             print "QUERY: ",$http_query,")\n";
339             $c->send_error(RC_FORBIDDEN)
340         }
341         print "\nRequest solved: ".$r->url."\n\n";
342     }
343     $c->close;
344     undef($c);
345     print "\nCONNECTION CLOSED\n\n";
346     exit;
347   } # fork
348 }
349
350 #================================
351
352
353 #CSC: Too much powerful: creates even /home, /home/users/, ...
354 #CSC: Does not raise errors if could not create dirs/files
355 sub mkdirs
356 {
357  my ($pathname) = @_;
358  my @dirs = split /\//,$pathname;
359  my $tmp;
360  foreach $dir (@dirs) {
361   $tmp = ((defined($tmp)) ?  $tmp."\/".$dir : "");
362   mkdir($tmp,0777);
363  }
364  rmdir($tmp);
365 }
366
367 sub print_request
368 {
369  my ($str,$uri,$url,$filename) = @_;
370  print $str."uri: $uri\n";
371  print $str."url: $url\n";
372  print $str."filename: $filename\n\n";
373 }
374
375 sub callback
376 {
377  my ($data) = @_;
378  $cont .= $data;
379 }
380
381 sub gunzip { # gunzip a file and return the deflated content
382         my ($filename) = @_;
383
384         my ($gz, $buffer, $cont);
385
386         print "deflating $filename ...\n";
387         $gz = gzopen($filename, "r")
388                 or die "Cannot open gzip'ed file $filename: $gzerrno";
389         $cont = "";
390         while ( $gz->gzread($buffer) > 0 ) {
391                 $cont .= $buffer;
392         }
393         die "Error while reading : $gzerrno\n" if $gzerrno != Z_STREAM_END ;
394         $gz->gzclose();
395
396         return $cont;
397 }
398
399 sub gzip {      # gzip the content argument and save it to filename argument
400         my ($cont, $filename) = @_;
401
402         my ($gz, $cont);
403
404         $gz = gzopen($filename, "w")
405                 or die "Cannot gzopen for writing file $filename: $gzerrno";
406         $gz->gzwrite($cont) or die "error writing: $gzerrno\n" ;
407         $gz->gzclose();
408 }
409
410 sub download
411 {
412  my ($remove_headers,$str,$url,$filename) = @_;
413  my ($gz, $buffer);
414
415  my $resourcetype;      # retrieve mode: "normal" (.xml) or "gzipped" (.xml.gz)
416  if ($filename =~ /\.xml$/) {   # set retrieve mode
417          $resourcetype = "normal";
418  } elsif ($filename =~ /\.xml\.gz$/) {
419          $resourcetype = "gzipped";
420  } else {
421          die "Unsupported download extension, might be '.gz' or '.xml'\n";
422  }
423  my $basefname = $filename;
424  $basefname =~ s/\.gz$//;       # get base resource name removing trailing .gz
425  $cont = ""; # modified by side-effect by the callback function
426
427  my $localfname="";
428  if (stat($basefname)) {
429         $localfname=$basefname;
430  } elsif (stat($basefname.".gz")) {
431         $localfname=$basefname.".gz";
432  }
433  if ($localfname ne "") { # we already have local copy of requested file
434       # check both possible cache entry: gzipped or normal
435   print "Using local copy for the $str file\n";
436   if ($localfname =~ /\.xml\.gz$/) { # deflating cached file and return it
437    $cont = gunzip($localfname);
438   } elsif ($localfname =~ /\.xml$/) { # just return cached file
439    open(FD, $localfname) or die "Cannot open $localfname";
440    while(<FD>) { $cont .= $_; }
441    close(FD);
442   } else { # error
443    die "Internal error: unexpected file name $localfname,"
444    ."must end with '.gz' or '.xml.gz'\n";
445   }
446  } else { # download file from net
447     print "Downloading the $str file\n"; # download file
448     my $ua = LWP::UserAgent->new;
449     my $request = HTTP::Request->new(GET => "$url");
450     my $response = $ua->request($request, \&callback);
451                
452     # cache retrieved file to disk
453 # <ZACK/> TODO: inefficent, I haven't yet undestood how to deflate
454 #    in memory gzipped file, without call "gzopen"
455  print "Storing the $str file\n";
456  mkdirs($filename);
457  open(FD, ">".$filename.".tmp") or die "Cannot open $filename.tmp\n";
458  print FD $cont;
459  close(FD);
460
461  # handle cache conversion normal->gzipped or gzipped->normal as user choice
462  if (($cachemode eq 'normal') and ($resourcetype eq 'normal')) {
463    # cache the file as is
464   rename "$filename.tmp", $filename; 
465  } elsif (($cachemode eq 'gzipped') and ($resourcetype eq 'gzipped')) {
466    # cache the file as is
467    # and update the $cont variabile with deflated content
468   rename "$filename.tmp", $filename; 
469   $cont = gunzip($filename);
470  } elsif (($cachemode eq 'normal') and ($resourcetype eq 'gzipped')) {
471    # deflate cache entry
472    # and update $cont
473   open(FD, "> $basefname") or die "cannot open $basefname\n";
474   $cont = gunzip($filename.".tmp");
475   print FD $cont;
476   close(FD);
477   unlink "$filename.tmp"; # delete old gzipped file
478  } elsif (($cachemode eq 'gzipped') and ($resourcetype eq 'normal')) {
479    # compress cache entry
480   gzip($cont, $basefname.".gz");
481   unlink "$filename.tmp"; # delete old uncompressed file
482  } else {
483   die "Internal error, unsopported cachemode, resourcetype couple\n";
484  }
485  # $cont now contained uncompressed data
486
487  }
488  if ($remove_headers) {
489     $cont =~ s/<\?xml [^?]*\?>//sg;
490     $cont =~ s/<!DOCTYPE [^>]*>//sg;
491  } else {
492     $cont =~ s/DOCTYPE (.*) SYSTEM\s+"http:\/\/www.cs.unibo.it\/helm\/dtd\//DOCTYPE $1 SYSTEM "$myownurl\/getdtd?uri=/g;
493  }
494  return $cont;
495 }
496
497 sub answer
498 {
499  my ($c,$cont) = @_;
500  my $res = new HTTP::Response;
501  $res->content($cont);
502  $c->send_response($res);
503 }
504
505 sub helm_wget {
506 #retrieve a file from an url and write it to a temp dir
507 #used for retrieve resource index from servers
508  $cont = "";
509  my ($prefix, $URL) = @_;
510  my $ua = LWP::UserAgent->new;
511  my $request = HTTP::Request->new(GET => "$URL");
512  my $response = $ua->request($request, \&callback);
513  my ($filename) = reverse (split "/", $URL); # get filename part of the URL
514  open (TEMP, "> $prefix/$filename")
515   || die "Cannot open temporary file: $prefix/$filename\n";
516  print TEMP $cont;
517  close TEMP;
518 }
519
520 sub update {
521  untie %map;
522  tie(%map, 'DB_File', $uris_dbm.".db", O_RDONLY, 0664);
523 }
524
525 sub mk_urls_of_uris {
526 #rebuild $uris_dbm.db fetching resource indexes from servers
527  my (
528   $server, $idxfile, $uri, $url, $comp, $line,
529   @servers,
530   %urls_of_uris
531  );
532
533  untie %map;
534  if (stat $uris_dbm.".db") { # remove old db file
535   unlink($uris_dbm.".db") or
536    die "cannot unlink old db file: $uris_dbm.db\n";
537  }
538  tie(%urls_of_uris, 'DB_File', $uris_dbm.".db", O_RDWR|O_CREAT, 0664);
539
540  open (SRVS, "< $servers_file") or
541   die "cannot open servers file: $servers_file\n";
542  @servers = <SRVS>;
543  close (SRVS);
544  while ($server = pop @servers) { #cicle on servers in reverse order
545   print "processing server: $server ...\n";
546   chomp $server;
547   helm_wget($tmp_dir, $server."/".$indexname); #get index
548   $idxfile = $tmp_dir."/".$indexname;
549   open (INDEX, "< $idxfile") or
550    die "cannot open temporary index file: $idxfile\n";
551   while ($line = <INDEX>) { #parse index and add entry to urls_of_uris
552    chomp $line;
553    ($uri,$comp) = split /[ \t]+/, $line;
554              # build url:
555    if ($comp =~ /gz/) { 
556     $url = $uri . ".xml" . ".gz";
557    } else {
558     $url = $uri . ".xml";
559    }
560    $url =~ s/cic:/$server/;
561    $url =~ s/theory:/$server/;
562    $urls_of_uris{$uri} = $url;
563   }
564   close INDEX;
565   die "cannot unlink temporary file: $idxfile\n"
566    if (unlink $idxfile) != 1;
567  }
568
569  untie(%urls_of_uris);
570  tie(%map, 'DB_File', $uris_dbm.".db", O_RDONLY, 0664);
571 }
572