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