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