]> matita.cs.unibo.it Git - helm.git/blob - helm/http_getter/http_getter.pl.in
cf2052a0236c345db549da9762485735c411657c
[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 #use strict;
27
28 my $VERSION = "@VERSION@";
29
30 # various variables
31 my ($HELM_LIB_PATH);
32 my $cgi_dir = "@HELM_CGI_DIR@";
33 my (%map, %rdf_map);
34
35 # First of all, let's load HELM configuration
36 use Env;
37 my $HELM_LIB_DIR = $ENV{"HELM_LIB_DIR"};
38 # this should be the only fixed constant
39 my $DEFAULT_HELM_LIB_DIR = "@HELM_LIB_DIR@";
40 if (defined ($HELM_LIB_DIR)) {
41    $HELM_LIB_PATH = $HELM_LIB_DIR."/configuration.pl";
42 } else {
43    $HELM_LIB_PATH = $DEFAULT_HELM_LIB_DIR."/configuration.pl";
44 }
45
46 # next require defines: $helm_dir, $html_link, $dtd_dir, $uris_dbm, $indexname
47 require $HELM_LIB_PATH;
48
49 # TEMP: TODO put these vars in configuration file configuration.xml
50 # <move_to_conf_file>
51 my $cachemode = $ENV{'HTTP_GETTER_CACHE_MODE'} ||
52     'gzipped';
53 if (($cachemode ne 'gzipped') and ($cachemode ne 'normal')) {
54  die "Invalid HTTP_GETTER_CACHE_MODE environment variable, must be".
55  "'normal' or 'gzipped'\n";
56 }
57 my $helm_rdf_dir = $ENV{'HTTP_GETTER_RDF_DIR'} ||
58     "/usr/local/helm/rdf_library";
59 my $rdf_dbm = $ENV{'HTTP_GETTER_RDF_DBM'} ||
60     "/usr/local/helm/rdf_urls_of_uris";
61 my $rdf_indexname = $ENV{'HTTP_GETTER_RDF_INDEXNAME'} ||
62     "rdf_index.txt";
63 # </move_to_conf_file>
64
65 # Let's override the configuration file
66 $style_dir = $ENV{"HELM_STYLE_DIR"} if (defined ($ENV{"HELM_STYLE_DIR"}));
67 $dtd_dir = $ENV{"HELM_DTD_DIR"} if (defined ($ENV{"HELM_DTD_DIR"}));
68
69 use HTTP::Daemon;
70 use HTTP::Status;
71 use HTTP::Request;
72 use LWP::UserAgent;
73 use DB_File;
74 use Compress::Zlib;
75 use CGI;
76 use URI::Escape;
77
78 #CSC: mancano i controlli sulle condizioni di errore di molte funzioni
79 #CSC: ==> non e' robusto
80 #CSC: altra roba da sistemare segnata con CSC
81
82 my $d = new HTTP::Daemon LocalPort => 8081
83  or die "Error: port 8081 not available.";
84 my $myownurl = $d->url;
85
86 # Let's patch the returned URL
87 $myownurl =~ s/\/$//; # chop the final slash
88 my $myownport = $myownurl;
89 $myownport =~ s/http:\/\/(.*):(.*)/$2/;
90 $myownurl  =~ s/http:\/\/(.*):(.*)/$1/;
91 ($myownurl) = gethostbyname($myownurl);
92 $myownurl = "http://".$myownurl.":".$myownport;
93
94 tie(%map, 'DB_File', $uris_dbm.".db", O_RDWR, 0664); # open dbs
95 tie(%rdf_map, 'DB_File', $rdf_dbm.".db", O_RDWR, 0664);
96
97 print "\n";
98 print "HTTP Getter $VERSION\n"; # print hello information
99 print "Please contact me at: <URL:", $myownurl."/", ">\n";
100 print "\n";
101 print "helm_dir: $helm_dir\n";
102 print "helm_rdf_dir: $helm_rdf_dir\n";
103 print "style_dir: $style_dir\n";
104 print "dtd_dir: $dtd_dir\n";
105 print "urls_of_uris db: $uris_dbm.db\n";
106 print "rdf db: $rdf_dbm.db\n";
107 print "cache mode: $cachemode\n";
108 print "indexname: $indexname\n";
109 print "rdf_indexname: $rdf_indexname\n";
110 print "\n";
111
112 $SIG{CHLD} = "IGNORE"; # do not accumulate defunct processes
113 $SIG{USR1} = \&update; # sent by the child to make the parent update
114
115 while (my $c = $d->accept) {
116  if (fork() == 0) {
117     while (my $r = $c->get_request) {
118         #CSC: mancano i controlli di sicurezza
119         
120         my $http_method = $r->method;
121         my $http_path = $r->url->path;
122         my $http_query = uri_unescape($r->url->query);
123         my $cgi = new CGI("$http_query");
124         my $inputuri = $cgi->param('uri');
125         print "\nRequest: ".$r->url."\n\n";
126
127         print "\nUnescaped query: ".$http_query."\n";
128
129          # "getxml" works with rdf uris
130         if ($http_method eq 'GET' and $http_path eq "/getxml") {
131             # finds the uri, url and filename
132
133             my $answerformat = $cgi->param('format');
134             my $patch_dtd = $cgi->param('patch_dtd');
135             $answerformat = "" if (not defined($answerformat));
136             $patch_dtd = "yes" if (not defined($patch_dtd));
137             if (($answerformat ne "gz") and ($answerformat ne "normal")
138                and ($answerformat ne "")) {
139              die "Wrong output format: $answerformat, must be 'normal' ".
140                  "or 'gz'\n";
141             }
142             if (($patch_dtd ne "yes") and ($patch_dtd ne "no")
143                and ($patch_dtd ne "")) {
144              die "Wrong param, patch_dtd must be 'yes' or 'no'\n";
145             }
146
147             my $filename = $inputuri;
148             my $prefix;
149             if (not isRdfUri($inputuri)) { # standad cic: or theory: uri
150              $filename =~ s/^cic:(.*)/$1/;
151              $filename =~ s/^theory:(.*)/$1/;
152             } else { # rdf uri
153              # The "helm:rdf/<<...>>//cic:" prefix is kept, but quoted
154              # (so that a "helm:rdf/<<...>>//cic:" dir is created
155              $prefix = $filename;
156              $filename =~ s/^(.*)\/\/cic:(.*)/$2/;
157              $filename =~ s/^(.*)\/\/theory:(.*)/$2/;
158              $prefix =~ s/\Q$filename\E//;
159              $prefix =~ s/_/__/g;
160              $prefix =~ s/\//_/g;
161              $filename = $prefix.$filename;
162             }
163
164             my $url = resolve ($inputuri); # resolve uri in url
165             if (not defined($url)) { # uri not found in uri2url map
166              die "NOT FOUND: uri \"$inputuri\" can't be resolved\n";
167              $c->send_error(RC_NOT_FOUND)
168             } else { # uri found and mapped to url
169               my $extension; # file extension
170               if ($url =~ /\.xml$/) { # non gzipped file
171                 $extension = ".xml";
172               } elsif ($url =~ /\.xml\.gz$/) { # gzipped file
173                 $extension = ".xml.gz";
174               } else { # error: unknown extension
175                die "unexpected extension in url: $url, might be '.xml'".
176                 "or '.xml.gz'";
177               }
178
179               if (not isRdfUri ($inputuri)) { # save in uri std cache dir
180                $filename = $helm_dir.$filename.$extension;
181               } else { # save in rdf metadata cache dir
182                $filename = $helm_rdf_dir."/".$filename.$extension;
183               }
184
185               print_request($inputuri,$url,$filename);
186
187               # Retrieves the file
188               my $ciccontent = download($patch_dtd,$url,$filename,$answerformat);
189
190               if ($answerformat eq "normal") { # answer the client in text/xml
191                answer($c,$ciccontent,"text/xml","");
192               } else { # answer the client in text/xml, gzip encoding
193                answer($c,$ciccontent,"text/xml","x-gzip");
194               }
195             }
196             
197                            # "/register" does not work with rdf uris
198         } elsif ($http_method eq 'GET' and $http_path eq "/register") {
199           my $inputurl = $cgi->param('url');
200           print "Register requested...\n";
201           $map{$inputuri}=$inputurl;
202
203           # Now let's clean the cache
204           my $cicfilename = $inputuri;
205           $cicfilename =~ s/cic:(.*)/$1/;
206           $cicfilename =~ s/theory:(.*)/$1/;
207
208           print "Unlinking ".$helm_dir.$cicfilename.".xml[.gz]\n";
209           unlink ($helm_dir.$cicfilename.".xml");
210           unlink ($helm_dir.$cicfilename.".xml.gz");
211
212           kill(USR1,getppid()); # signal changes to parent
213           untie %map;
214           print "done.\n";
215           html_nice_answer($c,"Register done");
216
217                                   # "/resolve" works with rdf uri
218         } elsif ($http_method eq 'GET' and $http_path eq "/resolve") {
219           #my $outputurl = $map{$inputuri};
220           my $outputurl = resolve($inputuri);
221           $outputurl = "" if (not defined($outputurl));
222           $cont = "<?xml version=\"1.0\" ?>\n\n";
223           if ($outputurl eq "") {
224            $cont .= "<unresolved />\n";
225           } else {
226            $cont .= "<url value=\"$outputurl\" />\n";
227           }
228           answer($c,$cont,"text/xml","");
229
230         } elsif ($http_method eq 'GET' and $http_path eq "/getdtd") {
231
232 #             my $filename = $inputuri;
233 #             $filename = $dtd_dir."/".$filename;
234 #             print "DTD: $inputuri ==> ($filename)\n";
235 #             if (stat($filename)) {
236 #                print "Using local copy\n";
237 #                open(FD, $filename) or die "Cannot open $filename\n";
238 #                $cont = "";
239 #                while(<FD>) {
240 #                 # Vary bad heuristic for substituion of absolute URLs
241 #                 # for relative ones
242 #               s/ENTITY (.*) SYSTEM\s+"/ENTITY $1 SYSTEM "$myownurl\/getdtd?uri=/g;
243 #               $cont .= $_;
244 #              }
245 #                close(FD);
246 #                answer($c,$cont,"text/xml","");
247 #             } else {
248 #                die "Could not find DTD!";
249 #             }
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,"text/plain","");
263             } else {
264                die "Could not find Style Configuration File!";
265             }
266
267         } elsif ($http_method eq 'GET' and $http_path eq "/getxslt") {
268             my $filename = $inputuri;
269             $filename = $style_dir."/".$filename;
270             print "XSLT: $inputuri ==> ($filename)\n";
271             if (stat($filename)) {
272                print "Using local copy\n";
273                open(FD, $filename) or die "Cannot open $filename\n";
274                $cont = "";
275                while(<FD>) {
276                 # Vary bad heuristic for substituion of absolute URLs
277                 # for relative ones
278                 s/xsl:import\s+href="/xsl:import href="$myownurl\/getxslt?uri=/g ;
279                 s/xsl:include\s+href="/xsl:include href="$myownurl\/getxslt?uri=/g ;
280                 $cont .= $_;
281                }
282                close(FD);
283                answer($c,$cont,"text/xml","");
284             } else {
285                die "Could not find XSLT!";
286             }
287
288                                     # "/update" works with rdf uri
289         } elsif ($http_method eq 'GET' and $http_path eq "/update") {
290             # rebuild urls_of_uris db and rdf uris db
291            print "Update requested...\n";
292            update_dbs();
293            kill(USR1,getppid()); # signal changes to parent
294            print " done\n";
295            html_nice_answer($c,"Update done");
296
297                                  # "/ls" does not work with rdf uris
298         } elsif ($http_method eq 'GET' and $http_path eq "/ls") {
299             # send back keys that begin with a given uri
300            my ($uritype,$uripattern,$uriprefix);
301            my $baseuri = $cgi->param('baseuri');
302            chop $baseuri if ($baseuri =~ /.*\/$/); # remove trailing "/"
303                          # output type, might be 'txt' or 'xml':
304            my $outype = $cgi->param('format');
305            $uripattern = $baseuri;
306            $uripattern =~ s/^.*:(.*)/$1/;
307            if ($baseuri =~ /^cic:/) {
308             $uritype = "cic";
309            } elsif ($baseuri =~ /^theory:/) {
310             $uritype = "theory";
311            } else {
312             $uritype = "invalid";
313            }
314            if ($uritype ne "invalid") { # uri is valid
315             if (($outype ne 'txt') and ($outype ne 'xml')) { # invalid out type
316              print "Invalid output type specified: $outype\n";
317              html_nice_answer($c,"Invalid output type, must be ".
318               "'txt' or 'xml'");
319             } else { # valid output
320              print "BASEURI $baseuri, FORMAT $outype\n";
321              $cont = finduris($uritype,$uripattern,$outype);
322              if ($outype eq 'txt') {
323               answer($c,$cont,"text/plain","");
324              } elsif ($outype eq 'xml') {
325               answer($c,$cont,"text/xml","");
326              } else {
327               die "Internal error, exiting!";
328              }
329             }
330            } else { # invalid uri
331             print "Invalid uri: $baseuri, may begin with 'cic:', ".
332              "'theory:' or '*:'\n";
333             html_nice_answer($c,"Invalid uri , must begin with ".
334              "'cic:' or 'theory:'");
335            }
336
337         } elsif ($http_method eq 'GET' and $http_path eq "/help") {
338           # help request
339            print "Help requested!\n";
340            html_nice_answer($c,"HTTP Getter Version: $VERSION");
341
342         } elsif ($http_method eq 'GET' and $http_path eq "/getempty") {
343           # return an empty, but valid, xml document
344           my $emptyxml = <<EOXML;
345 <?xml version="1.0"?>
346 <!DOCTYPE empty [
347   <!ELEMENT empty EMPTY>
348 ]>
349 <empty />
350 EOXML
351           answer($c, $emptyxml, "", "");
352
353         } elsif ($http_method eq 'GET' and $http_path =~ /\.cgi$/) {
354           # cgi handling
355            print "CGI requested!\n";
356            if ($http_path !~ /^\/[^\/]*\.cgi$/) {
357             html_nice_answer($c,"Invalid CGI name: $http_path, ".
358             "you can't request CGI that contain a slash in the name\n");
359            } elsif (stat "$cgi_dir"."$http_path") {
360             if (not -x "$cgi_dir/$http_path") {
361              html_nice_answer($c,"CGI $http_path found but not ".
362               "executable\n");
363             } else { # exec CGI and anser back its output
364              my %old_ENV = %ENV;
365              %ENV = ();
366              $ENV{'QUERY_STRING'} = $http_query;
367              my $cgi_output = `$cgi_dir/$http_path`;
368              answer($c,$cgi_output,"","");
369              %ENV = %old_ENV;
370             }
371            } else {
372             html_nice_answer($c,"CGI '$http_path' not found ".
373              "in CGI dir '$cgi_dir'");
374            }
375
376         } else { # unsupported request
377             print "\n";
378             print "INVALID REQUEST!!!!!\n";
379             print "(PATH: ",$http_path,", ";
380             print "QUERY: ",$http_query,")\n";
381             $c->send_error(RC_FORBIDDEN)
382         }
383
384         print "\nRequest solved: ".$r->url."\n\n";
385     }
386
387     $c->close;
388     undef($c);
389     print "\nCONNECTION CLOSED\n\n";
390     exit;
391   } # fork
392 }
393
394 #================================
395
396 sub isRdfUri { # return true if the uri is an rdf uri, false otherwise
397 # typycal rdf uri:
398 # helm:rdf/cic:www.cs.unibo.it/helm/rdf/foo_schema//cic:\
399 #  /Coq/Init/Logic/True_rec.con.types
400 #
401 # the format is "helm:rdf/<metadata_tree>:<metadata_scheme>//<xml_file_uri>"
402 #
403  my ($uri) = @_;
404  if ($uri =~ /^helm:rdf(.*):(.*)\/\/(.*)/) {
405   return 1;
406  } else {
407   return 0;
408  }
409 }
410
411 sub resolve { # resolve an uri in a url, work both with standard cic: or theory:
412               # uris and rdf uris
413  print "RESOLVE subroutine\n";
414  my ($uri) = @_;
415  print "GIVEN URI: \"$uri\"\n";
416  if (isRdfUri ($uri)) { # rdf uri, resolve using rdf db
417   print "IS A RDF URI\n";
418   print "I WILL RETURN '$rdf_map{$uri}'\n";
419   return ($rdf_map{$uri});
420  } else { # standard cic: or theory: uri, resolve using std uri db
421   print "IS NOT A RDF URI\n";
422   print "I WILL RETURN '$map{$uri}'\n";
423   return ($map{$uri});
424  }
425 }
426
427 sub finduris { # find uris for cic and theory trees generation
428  my ($uritype,$uripattern,$format) = @_;
429  my $content = "";
430  my ($uri,$localpart,$basepart,$dirname,$suffix,$flags,$key);
431  my (@itemz,@already_pushed_dir);
432  my (%objects,%dirs); # map uris to suffixes' flags
433  my $debug=1; # for debug
434
435  print "FINDURIS, uritype: $uritype, uripattern: $uripattern, ".
436   "format: $format\n\n" if defined($debug);
437  
438  if (($uritype eq "cic") or ($uritype eq "theory")) {
439    # get info only of one type: cic or theory
440   foreach (keys(%map)) { # select matching uris
441    $uri = $_;
442    if ($uri =~ /^$uritype:$uripattern(\/|$|\.)/) {
443     if ($uri =~ /^$uritype:$uripattern\//) { # directory match
444      $localpart = $uri;
445      $localpart =~ s/^$uritype:$uripattern\/(.*)/$1/;
446     } elsif ($uri =~ /^$uritype:$uripattern($|\.)/) { # file match
447      $localpart = $uri;
448      $localpart =~ s/^.*\/([^\/]*)/$1/;
449     } else {
450      die "Internal error, seems that requested match is none of ".
451       "directory match or file match";
452     }
453     print "LOCALPART: $localpart\n" if defined($debug);
454
455     if ($localpart =~ /^[^\/]*$/) { # no slash, an OBJECT
456      $basepart = $localpart;
457      $basepart =~ s/^([^.]*\.[^.]*)(\.types)?(\.ann)?/$1/;
458                                               # remove exts .types or
459                                               # .types.ann
460      $flags = $objects{$basepart}; # get old flags
461      if ($localpart =~ /\.ann$/) {
462       $flags = add_flag("ann","YES",$flags);
463      } else {
464       $flags = add_flag("ann","NO",$flags);
465      }
466      if ($localpart =~ /\.types$/) {
467       $flags = add_flag("types","YES",$flags);
468      } elsif ($localpart =~ /\.types\.ann$/) {
469       $flags = add_flag("types","ANN",$flags);
470      } else {
471       $flags = add_flag("types","NO",$flags);
472      }
473      $objects{$basepart} = $flags; # save new flags
474     } else { # exists at least one slash, a DIR
475      ($dirname) = split (/\//, $localpart);
476      $dirs{$dirname} = ""; # no flags requirement for dir
477     }
478    }
479   }
480  } else {
481   die "getter internal error: unsupported uritype: \"$uritype\"";
482  }
483                             # now generate OUTPUT:
484                             # output will be saved in $content
485  if ($format eq "txt") { # TXT output
486   foreach $key (sort(keys %dirs)) {
487    $content .= "dir, " . $key . "\n";
488   }
489   foreach $key (sort(keys %objects)) {
490    $content .= "object, $key, " . $objects{$key} . "\n";
491   }
492  } elsif ($format eq "xml") { # XML output
493   $content .= '<?xml version="1.0" encoding="ISO-8859-1"?>' . "\n";
494   $content .= "<!DOCTYPE ls SYSTEM ";
495   $content .= "\"$myownurl/getdtd?uri=ls.dtd\">" . "\n\n";
496   $content .= "<ls>\n";
497   foreach $key (sort(keys %dirs)) {
498    $content .= "\t<section>$key</section>\n";
499   }
500   foreach $key (sort(keys %objects)) {
501    $content .= "\t<object name=\"$key\">\n";
502    $flags = $objects{$key};
503    $flags =~ s/^<(.*)>$/$1/;
504    my ($annflag,$typesflag) = split /,/,$flags;
505    $content .= "\t\t<ann value=\"$annflag\" />\n";
506    $content .= "\t\t<types value=\"$typesflag\" />\n";
507    $content .= "\t</object>\n";
508   }
509   $content .= "</ls>\n";
510  } else { # may not enter this branch
511   die "Getter internal error: invalid format received by finduris sub";
512  }
513  return $content;
514 }
515
516 sub add_flag {
517 # manage string like: "<ann_flag,type_flag>"
518 # "ann_flag" may be one of "ann_YES", "ann_NO"
519 # "type_flag" may be one of "types_NO", "types_YES", "types_ANN"
520 # when adding a flag the max between the current flag and the new flag
521 # is taken, the orders are ann_NO < ann_YES and types_NO < types_YES <
522 # types_ANN
523  my ($flagtype,$newflag,$str) = @_;
524  $str = "<,>" if ($str eq "");
525  ($str =~ s/^<(.*,.*)>$/$1/) or die "Internal error: ".
526    "wrong string format for flag adding in $str";
527  my ($annflag,$typeflag) = split /,/,$str;
528  if ($flagtype eq "ann") { # ANN flag handling
529   if ($newflag eq "YES") {
530    $annflag = "YES";
531   } elsif ($newflag eq "NO") {
532    $annflag = "NO" unless ($annflag eq "YES");
533   } else {
534    die "Internal error: annflag must be \"YES\" or \"NO\"";
535   }
536  } elsif ($flagtype eq "types") { # TYPES flag handling
537   if ($newflag eq "ANN") {
538    $typeflag = "ANN";
539   } elsif ($newflag eq "YES") {
540    $typeflag = "YES" unless ($typeflag eq "ANN");
541   } elsif ($newflag eq "NO") {
542    $typeflag = "NO"
543      unless (($typeflag eq "ANN") or ($typeflag eq "YES"));
544   } else {
545    die "Internal error: typeflag must be \"YES\", \"NO\" or \"ANN\"";
546   }
547  } else {
548   die "Internal error: unsupported flagtype \"$flagtype\"";
549  }
550  $str = "<$annflag,$typeflag>";
551 }
552
553 #CSC: Too much powerful: creates even /home, /home/users/, ...
554 #CSC: Does not raise errors if could not create dirs/files
555 sub mkdirs
556 {
557  my ($pathname) = @_;
558  my @dirs = split /\//,$pathname;
559  my $tmp;
560  foreach $dir (@dirs) {
561   $tmp = ((defined($tmp)) ?  $tmp."\/".$dir : "");
562   mkdir($tmp,0777);
563  }
564  rmdir($tmp);
565 }
566
567 sub print_request
568 {
569  my ($uri,$url,$filename) = @_;
570  print "<download_request>\n";
571  print "uri: $uri\n";
572  print "url: $url\n";
573  print "filename: $filename\n\n";
574  print "</download_request>\n";
575 }
576
577 sub callback
578 {
579  my ($data) = @_;
580  $cont .= $data;
581 }
582
583 sub gunzip { # gunzip a file and return the deflated content
584         my ($filename) = @_;
585
586         my ($gz, $buffer, $cont);
587
588         print "deflating $filename ...\n";
589         $gz = gzopen($filename, "r")
590                 or die "Cannot open gzip'ed file $filename: $gzerrno";
591         $cont = "";
592         while ( $gz->gzread($buffer) > 0 ) {
593                 $cont .= $buffer;
594         }
595         die "Error while reading : $gzerrno\n" if $gzerrno != Z_STREAM_END ;
596         $gz->gzclose();
597
598         return $cont;
599 }
600
601 sub gzip {      # gzip the content argument and save it to filename argument
602         my ($cont, $filename) = @_;
603  #my $debug=1; # debug only
604
605  print "gzopening $filename ...\n" if (defined($debug));
606         my $gz = gzopen($filename, "w")
607                 or die "Cannot gzopen for writing file $filename: $gzerrno";
608  print "gzwriting ...\n" if (defined($debug));
609         $gz->gzwrite($cont) or die "error writing: $gzerrno, exiting!\n";
610  print "gzclosing ...\n" if (defined($debug));
611         $gz->gzclose();
612 }
613
614 sub download {
615  my ($patch_dtd,$url,$filename,$format) = @_;
616  my ($gz, $buffer);
617
618 # print "DOWNLOAD subs receives url: \"$url\"\n";
619 # print "DOWNLOAD subs receives filename: \"$filename\"\n";
620
621  my $resourcetype;      # retrieve mode: "normal" (.xml) or "gzipped" (.xml.gz)
622  if ($filename =~ /\.xml$/) {   # set retrieve mode
623          $resourcetype = "normal";
624  } elsif ($filename =~ /\.xml\.gz$/) {
625          $resourcetype = "gzipped";
626  } else {
627          die "Unsupported download extension, might be '.gz' or '.xml'\n";
628  }
629  my $basefname = $filename;
630  $basefname =~ s/\.gz$//;       # get base resource name removing trailing .gz
631  $cont = ""; # modified by side-effect by the callback function
632
633  my $localfname="";
634  if (stat($basefname)) {
635         $localfname=$basefname;
636  } elsif (stat($basefname.".gz")) {
637         $localfname=$basefname.".gz";
638  }
639  if ($localfname ne "") { # we already have local copy of requested file
640       # check both possible cache entry: gzipped or normal
641   print "Using local copy.\n";
642   if ($localfname =~ /\.xml\.gz$/) { # deflating cached file and return it
643    $cont = gunzip($localfname);
644   } elsif ($localfname =~ /\.xml$/) { # just return cached file
645    open(FD, $localfname) or die "Cannot open $localfname";
646    while(<FD>) { $cont .= $_; }
647    close(FD);
648   } else { # error
649    die "Internal error: unexpected file name $localfname,"
650    ."must end with '.gz' or '.xml.gz'\n";
651   }
652  } else { # download file from net
653    print "Downloading file ...\n"; # download file
654    my $ua = LWP::UserAgent->new;
655    my $request = HTTP::Request->new(GET => "$url");
656    my $response = $ua->request($request, \&callback);
657    
658    # cache retrieved file to disk
659    # <ZACK/> TODO: inefficent, I haven't yet undestood how to deflate
660    #    in memory gzipped file, without call "gzopen"
661    print "Storing file ...\n";
662 #   print "Making dirs ...\n";
663    mkdirs($filename);
664 #   print "Opening tmp file for writing ...\n";
665    open(FD, ">".$filename.".tmp") or die "Cannot open $filename.tmp\n";
666 #   print "Writing on tmp file ...\n";
667    print FD $cont;
668 #   print "Closing tmp file ...\n";
669    close(FD);
670
671    # handle cache conversion normal->gzipped or gzipped->normal as user choice
672    print "cachemode:$cachemode, resourcetype:$resourcetype\n"
673     if (defined($debug));
674    if (($cachemode eq 'normal') and ($resourcetype eq 'normal')) {
675      # cache the file as is
676     rename "$filename.tmp", $filename; 
677    } elsif (($cachemode eq 'gzipped') and ($resourcetype eq 'gzipped')) {
678      # cache the file as is
679      # and update the $cont variabile with deflated content
680     rename "$filename.tmp", $filename; 
681     $cont = gunzip($filename);
682    } elsif (($cachemode eq 'normal') and ($resourcetype eq 'gzipped')) {
683      # deflate cache entry
684      # and update $cont
685     open(FD, "> $basefname") or die "cannot open $basefname\n";
686     $cont = gunzip($filename.".tmp");
687     print FD $cont;
688     close(FD);
689     unlink "$filename.tmp"; # delete old gzipped file
690    } elsif (($cachemode eq 'gzipped') and ($resourcetype eq 'normal')) {
691      # compress cache entry
692     print "gzipping ...\n" if (defined($debug));
693     gzip($cont, $basefname.".gz");
694     unlink "$filename.tmp"; # delete old uncompressed file
695    } else {
696     die "Internal error, unsopported cachemode, resourcetype couple\n";
697    }
698    # $cont now contained uncompressed data
699  }
700  if ($patch_dtd eq "yes") {
701     $cont =~ s/DOCTYPE (.*) SYSTEM\s+"http:\/\/www.cs.unibo.it\/helm\/dtd\//DOCTYPE $1 SYSTEM "$myownurl\/getdtd?uri=/g;
702  }
703  if ($format eq "gz") {
704   gzip($cont,"$basefname.tmp");
705   open (TMP, "< $basefname.tmp")
706    or die "Can't open tempfile: $filename.tmp, exiting!\n";
707   $cont = "";
708   while(<TMP>) {
709    $cont .= $_;
710   }
711   close TMP;
712   unlink ($basefname . ".tmp") or
713    die "cannot unlink temporary file: $basefname.tmp\n";
714  }
715
716  return $cont;
717 }
718
719 sub answer {
720 # answer the client setting content, Content-Type and Content-Enconding
721 # of the answer
722  my ($c,$cont,$contype,$contenc) = @_;
723  my $res = new HTTP::Response;
724  $res->content($cont);
725  $res->push_header("Content-Type" => $contype)
726    unless ($contype eq "");
727  $res->push_header("Content-Encoding" => $contenc)
728    unless ($contenc eq "");
729  $res->push_header("Cache-Control" => "no-cache");
730  $res->push_header("Pragma" => "no-cache");
731  $res->push_header("Expires" => "0");
732  $c->send_response($res);
733 }
734
735 sub html_nice_answer {
736 # answer the client whith a nice html document
737  my ($c,$content) = @_;
738  $content = "<html><body><h1>$content</h1></body></html>";
739  answer($c,$content,"text/html","");
740 }
741
742 sub helm_wget {
743 #retrieve a file from an url and write it to a temp dir
744 #used for retrieve resource index from servers
745  $cont = "";
746  my ($prefix, $URL) = @_;
747  my $ua = LWP::UserAgent->new;
748  my $request = HTTP::Request->new(GET => "$URL");
749  my $response = $ua->request($request, \&callback);
750  my ($filename) = reverse (split "/", $URL); # get filename part of the URL
751  open (TEMP, "> $prefix/$filename")
752   || die "Cannot open temporary file: $prefix/$filename\n";
753  print TEMP $cont;
754  close TEMP;
755 }
756
757 sub update {
758 # retie dbs
759  untie %map;
760  tie(%map, 'DB_File', $uris_dbm.".db", O_RDWR, 0664);
761  untie %rdf_map;
762  tie(%rdf_map, 'DB_File', $rdf_dbm.".db", O_RDWR, 0664);
763 }
764
765 sub update_dbs {
766 # rebuild dbs fetching resource indexes from servers.
767 # Rebuild urls_of_uris db (1) and rdf db (2)
768  my (
769   $server, $idxfile, $rdf_idxfile, $uri, $url, $comp, $line,
770   @servers,
771   %urls_of_uris, %rdf # local proxy of $map and $rdf_map
772  );
773
774  untie %map;
775  untie %rdf_map;
776  foreach my $file ($uris_dbm, $rdf_dbm) { # remove old db file
777   if (stat $file.".db") { # remove if exists
778    unlink ($file.".db") or die "can't unlink old db file: $file.db\n";
779   }
780  }
781  tie(%urls_of_uris, 'DB_File', $uris_dbm.".db", O_RDWR|O_CREAT, 0664);
782  tie(%rdf, 'DB_File', $rdf_dbm.".db", O_RDWR|O_CREAT, 0664);
783
784  open (SRVS, "< $servers_file") or
785   die "cannot open servers file: $servers_file\n";
786  @servers = <SRVS>; # read all servers
787  close (SRVS);
788
789  while ($server = pop @servers) { # cicle on servers in _reverse_ order
790   print "processing server: $server ...\n";
791   chomp $server;
792   helm_wget($tmp_dir, $server."/".$indexname); # get index
793   helm_wget($tmp_dir, $server."/".$rdf_indexname); # get rdf index
794   $idxfile = $tmp_dir."/".$indexname;
795   $rdf_idxfile = $tmp_dir."/".$rdf_indexname;
796
797   open (INDEX, "< $idxfile") or # (1) REBUILD URLS_OF_URIS DB
798    die "cannot open temporary index file: $idxfile\n";
799   while ($line = <INDEX>) {  # parse index and add entry to urls_of_uris db
800    chomp $line;
801    ($uri,$comp) = split /[ \t]+/, $line;
802              # build url:
803    if ($comp =~ /gz/) { 
804     $url = $uri . ".xml" . ".gz";
805    } else {
806     $url = $uri . ".xml";
807    }
808    $url =~ s/cic:/$server/;
809    $url =~ s/theory:/$server/;
810    $urls_of_uris{$uri} = $url;
811   }
812
813   open (RDF_INDEX, "< $rdf_idxfile") or # (2) REBUILD RDF DB
814    die "cannot open temporary rdf index file: $rdf_idxfile\n";
815   while ($line = <RDF_INDEX>) {  # parse index and add entry to rdf db
816    chomp $line;
817    ($uri,$comp) = split /[ \t]+/, $line; # comp is "gz" or nothing
818              # build url:
819    if ($comp =~ /gz/) { 
820     $url = $uri . ".xml" . ".gz";
821    } else {
822     $url = $uri . ".xml";
823    }
824    $url =~ s/^helm:rdf(.*)\/\/cic:/$server/;
825    $url =~ s/^helm:rdf(.*)\/\/theory:/$server/;
826    $rdf{$uri} = $url;
827   }
828
829   close INDEX;  # close indexes
830   close RDF_INDEX;
831   die "cannot unlink temporary file: $idxfile\n"  # remove temp files
832    if (unlink $idxfile) != 1;
833   die "cannot unlink temporary file: $rdf_idxfile\n"
834    if (unlink $rdf_idxfile) != 1;
835
836  }
837
838  untie(%urls_of_uris); # untie local proxies
839  untie(%rdf);
840  tie(%map, 'DB_File', $uris_dbm.".db", O_RDWR, 0664); # retie global ones
841  tie(%rdf_map, 'DB_File', $rdf_dbm.".db", O_RDWR, 0664);
842 } # update_dbs
843
844 # vim modline: do not remove!
845 # vim: set ft=perl:
846