]> matita.cs.unibo.it Git - helm.git/blob - helm/http_getter/http_getter.pl.in
Bug fixed: the result was declared as gzipped even when it was not so
[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);
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 # <ZACK>: TODO temporary, move this setting to configuration file
47 # set the cache mode, may be "gzipped" or "normal"
48 my $cachemode = $ENV{'HTTP_GETTER_CACHE_MODE'} || 'gzipped';
49 if (($cachemode ne 'gzipped') and ($cachemode ne 'normal')) {
50  die "Invalid HTTP_GETTER_CACHE_MODE environment variable, must be".
51  "'normal' or 'gzipped'\n";
52 }
53 # </ZACK>
54
55 # next require defines: $helm_dir, $html_link, $dtd_dir, $uris_dbm
56 require $HELM_LIB_PATH;
57
58 # Let's override the configuration file
59 $style_dir = $ENV{"HELM_STYLE_DIR"} if (defined ($ENV{"HELM_STYLE_DIR"}));
60 $dtd_dir = $ENV{"HELM_DTD_DIR"} if (defined ($ENV{"HELM_DTD_DIR"}));
61
62 use HTTP::Daemon;
63 use HTTP::Status;
64 use HTTP::Request;
65 use LWP::UserAgent;
66 use DB_File;
67 use Compress::Zlib;
68 use CGI;
69 use URI::Escape;
70
71 #CSC: mancano i controlli sulle condizioni di errore di molte funzioni
72 #CSC: ==> non e' robusto
73 #CSC: altra roba da sistemare segnata con CSC
74
75 my $d = new HTTP::Daemon LocalPort => 8081;
76 my $myownurl = $d->url;
77
78 # Let's patch the returned URL
79 $myownurl =~ s/\/$//; # chop the final slash
80 my $myownport = $myownurl;
81 $myownport =~ s/http:\/\/(.*):(.*)/$2/;
82 $myownurl  =~ s/http:\/\/(.*):(.*)/$1/;
83 ($myownurl) = gethostbyname($myownurl);
84 $myownurl = "http://".$myownurl.":".$myownport;
85
86 tie(%map, 'DB_File', $uris_dbm.".db", O_RDONLY, 0664);
87 print "Please contact me at: <URL:", $myownurl."/", ">\n";
88 print "helm_dir: $helm_dir\n";
89 print "style_dir: $style_dir\n";
90 print "dtd_dir: $dtd_dir\n";
91 print "urls_of_uris.db: $uris_dbm.db\n";
92 print "cache mode: $cachemode\n";
93
94 $SIG{CHLD} = "IGNORE"; # do not accumulate defunct processes
95 $SIG{USR1} = \&update; # sent by the child to make the parent update
96 while (my $c = $d->accept) {
97  if (fork() == 0) {
98     while (my $r = $c->get_request) {
99         #CSC: mancano i controlli di sicurezza
100         
101         my $http_method = $r->method;
102         my $http_path = $r->url->path;
103         my $http_query = uri_unescape($r->url->query);
104         my $cgi = new CGI("$http_query");
105         my $inputuri = $cgi->param('uri');
106         print "\nRequest: ".$r->url."\n\n";
107
108         print "\nUnescaped query: ".$http_query."\n";
109
110         if ($http_method eq 'GET' and $http_path eq "/getxml") {
111             # finds the uri, url and filename
112             my $cicuri = $inputuri;
113             my $answerformat = $cgi->param('format');
114             my $patch_dtd = $cgi->param('patch_dtd');
115             $answerformat = "" if (not defined($answerformat));
116             $patch_dtd = "" if (not defined($patch_dtd));
117             if (($answerformat ne "gz") and ($answerformat ne "normal")
118                and ($answerformat ne "")) {
119              die "Wrong output format: $answerformat, must be 'normal' ".
120                  "or 'gz'\n";
121             }
122             if (($patch_dtd ne "yes") and ($patch_dtd ne "no")
123                and ($patch_dtd ne "")) {
124              die "Wrong param, patch_dtd must be 'yes' or 'no'\n";
125             }
126
127             my $cicfilename = $cicuri;
128             $cicfilename =~ s/cic:(.*)/$1/;
129             $cicfilename =~ s/theory:(.*)/$1/;
130
131             my $cicurl   = $map{$cicuri};
132             if (not defined($cicurl)) {
133              die "uri \"$cicuri\" can't be resolved\n";
134             }
135             my $extension;
136             if ($cicurl =~ /\.xml$/) { # non gzipped file
137               $extension = ".xml";
138             } elsif ($cicurl =~ /\.xml\.gz$/) { # gzipped file
139               $extension = ".xml.gz";
140             } else { # error: unknown extension
141              die "unexpected extension in url: $cicurl, might be '.xml'".
142               "or '.xml.gz'";
143             }
144             $cicfilename = $helm_dir.$cicfilename.$extension;
145
146             if (!defined($cicurl)) {
147              print "\nNOT FOUND!!!!!\n";
148              $c->send_error(RC_NOT_FOUND)
149             } else {
150                print_request("cic",$cicuri,$cicurl,$cicfilename);
151
152                # Retrieves the file
153                my $ciccontent = download($patch_dtd,"cic",$cicurl,$cicfilename,$answerformat);
154
155                # Answering the client
156                if ($answerformat eq "normal") {
157                 answer($c,$ciccontent,"text/xml","");
158                } else {
159                 answer($c,$ciccontent,"text/xml","x-gzip");
160                }
161             }
162         } elsif ($http_method eq 'GET' and $http_path eq "/resolve") {
163           my $outputurl = $map{$inputuri};
164           $outputurl = "" if (not defined($outputurl));
165           $cont = "<?xml version=\"1.0\" ?>\n\n";
166           if ($outputurl eq "") {
167            $cont .= "<unresolved />\n";
168           } else {
169            $cont .= "<url value=\"$outputurl\" />\n";
170           }
171           answer($c,$cont,"text/xml","");
172         } elsif ($http_method eq 'GET' and $http_path eq "/getdtd") {
173             my $filename = $inputuri;
174             $filename = $dtd_dir."/".$filename;
175             print "DTD: $inputuri ==> ($filename)\n";
176             if (stat($filename)) {
177                print "Using local copy\n";
178                open(FD, $filename) or die "Cannot open $filename\n";
179                $cont = "";
180                while(<FD>) {
181                 # Vary bad heuristic for substituion of absolute URLs
182                 # for relative ones
183                 s/ENTITY (.*) SYSTEM\s+"/ENTITY $1 SYSTEM "$myownurl\/getdtd?uri=/g;
184                 $cont .= $_;
185                }
186                close(FD);
187                answer($c,$cont,"text/xml","");
188             } else {
189                die "Could not find DTD!";
190             }
191         } elsif ($http_method eq 'GET' and $http_path eq "/getstyleconf") {
192             my $filename = $inputuri;
193             $filename = $style_dir."/config/".$filename;
194             if (stat($filename)) {
195                open(FD, $filename) or die "Cannot open $filename\n";
196                $cont = "";
197                while(<FD>) {
198                 s/DOCTYPE (.*) SYSTEM\s+"/DOCTYPE $1 SYSTEM "$myownurl\/getstyleconf?uri=/g;
199                 $cont .= $_;
200                }
201                close(FD);
202                answer($c,$cont,"text/plain","");
203             } else {
204                die "Could not find Style Configuration File!";
205             }
206         } elsif ($http_method eq 'GET' and $http_path eq "/getxslt") {
207             my $filename = $inputuri;
208             $filename = $style_dir."/".$filename;
209             print "XSLT: $inputuri ==> ($filename)\n";
210             if (stat($filename)) {
211                print "Using local copy\n";
212                open(FD, $filename) or die "Cannot open $filename\n";
213                $cont = "";
214                while(<FD>) {
215                 # Vary bad heuristic for substituion of absolute URLs
216                 # for relative ones
217                 s/xsl:import\s+href="/xsl:import href="$myownurl\/getxslt?uri=/g ;
218                 s/xsl:include\s+href="/xsl:include href="$myownurl\/getxslt?uri=/g ;
219                 $cont .= $_;
220                }
221                close(FD);
222                answer($c,$cont,"text/xml","");
223             } else {
224                die "Could not find XSLT!";
225             }
226         } elsif ($http_method eq 'GET' and $http_path eq "/update") {
227             # rebuild urls_of_uris.db
228            print "Update requested...\n";
229            mk_urls_of_uris();
230            kill(USR1,getppid()); # signal changes to parent
231            print " done\n";
232            html_nice_answer($c,"Update done");
233         } elsif ($http_method eq 'GET' and $http_path eq "/ls") {
234             # send back keys that begin with a given uri
235            my ($uritype,$uripattern,$uriprefix);
236            my $baseuri = $cgi->param('baseuri');
237            chop $baseuri if ($baseuri =~ /.*\/$/); # remove trailing "/"
238            my $outype = $cgi->param('format'); # output type, might be 'txt' or 'xml'
239            $uripattern = $baseuri;
240            $uripattern =~ s/^.*:(.*)/$1/;
241            if ($baseuri =~ /^cic:/) {
242             $uritype = "cic";
243            } elsif ($baseuri =~ /^theory:/) {
244             $uritype = "theory";
245            } else {
246             $uritype = "invalid";
247            }
248            if ($uritype ne "invalid") { # uri is valid
249             if (($outype ne 'txt') and ($outype ne 'xml')) { # invalid out type
250              print "Invalid output type specified: $outype\n";
251              html_nice_answer($c,"Invalid output type, must be ".
252               "'txt' or 'xml'");
253             } else { # valid output
254              print "BASEURI $baseuri, FORMAT $outype\n";
255              $cont = finduris($uritype,$uripattern,$outype);
256              if ($outype eq 'txt') {
257               answer($c,$cont,"text/plain","");
258              } elsif ($outype eq 'xml') {
259               answer($c,$cont,"text/xml","");
260              } else {
261               die "Internal error, exiting!";
262              }
263             }
264            } else { # invalid uri
265             print "Invalid uri: $baseuri, may begin with 'cic:', ".
266              "'theory:' or '*:'\n";
267             html_nice_answer($c,"Invalid uri , must begin with ".
268              "'cic:' or 'theory:'");
269            }
270         } elsif ($http_method eq 'GET' and $http_path eq "/help") {
271            print "Help requested!\n";
272            html_nice_answer($c,"HTTP Getter Version: $VERSION");
273         } elsif ($http_method eq 'GET' and $http_path =~ /\.cgi$/) {
274            print "CGI requested!\n";
275            if ($http_path !~ /^\/[^\/]*\.cgi$/) {
276             html_nice_answer($c,"Invalid CGI name: $http_path, ".
277             "you can't request CGI that contain a slash in the name\n");
278            } elsif (stat "$cgi_dir"."$http_path") {
279             if (not -x "$cgi_dir/$http_path") {
280              html_nice_answer($c,"CGI $http_path found but not ".
281               "executable\n");
282             } else { # exec CGI and anser back its output
283              my %old_ENV = %ENV;
284              %ENV = ();
285              $ENV{'QUERY_STRING'} = $http_query;
286              my $cgi_output = `$cgi_dir/$http_path`;
287              answer($c,$cgi_output,"","");
288              %ENV = %old_ENV;
289             }
290            } else {
291             html_nice_answer($c,"CGI '$http_path' not found ".
292              "in CGI dir '$cgi_dir'");
293            }
294         } else {
295             print "\n";
296             print "INVALID REQUEST!!!!!\n";
297             print "(PATH: ",$http_path,", ";
298             print "QUERY: ",$http_query,")\n";
299             $c->send_error(RC_FORBIDDEN)
300         }
301         print "\nRequest solved: ".$r->url."\n\n";
302     }
303     $c->close;
304     undef($c);
305     print "\nCONNECTION CLOSED\n\n";
306     exit;
307   } # fork
308 }
309
310 #================================
311
312 sub finduris { # find uris for cic and theory trees generation
313  my ($uritype,$uripattern,$format) = @_;
314  my $content = "";
315  my ($uri,$localpart,$basepart,$dirname,$suffix,$flags,$key);
316  my (@itemz,@already_pushed_dir);
317  my (%objects,%dirs); # map uris to suffixes' flags
318  #my $debug=1; # for debug
319
320  print "FINDURIS, uritype: $uritype, uripattern: $uripattern, ".
321   "format: $format\n\n" if defined($debug);
322  
323  if (($uritype eq "cic") or ($uritype eq "theory")) {
324    # get info only of one type: cic or theory
325   foreach (keys(%map)) { # select matching uris
326    $uri = $_;
327    if ($uri =~ /^$uritype:$uripattern(\/|$|\.)/) {
328     if ($uri =~ /^$uritype:$uripattern\//) { # directory match
329      $localpart = $uri;
330      $localpart =~ s/^$uritype:$uripattern\/(.*)/$1/;
331     } elsif ($uri =~ /^$uritype:$uripattern($|\.)/) { # file match
332      $localpart = $uri;
333      $localpart =~ s/^.*\/([^\/]*)/$1/;
334     } else {
335      die "Internal error, seems that requested match is none of ".
336       "directory match or file match";
337     }
338     print "LOCALPART: $localpart\n" if defined($debug);
339
340     if ($localpart =~ /^[^\/]*$/) { # no slash, an OBJECT
341      $basepart = $localpart;
342      $basepart =~ s/^([^.]*\.[^.]*)(\.types)?(\.ann)?/$1/;
343                                               # remove exts .types or
344                                               # .types.ann
345      $flags = $objects{$basepart}; # get old flags
346      if ($localpart =~ /\.ann$/) {
347       $flags = add_flag("ann","YES",$flags);
348      } else {
349       $flags = add_flag("ann","NO",$flags);
350      }
351      if ($localpart =~ /\.types$/) {
352       $flags = add_flag("types","YES",$flags);
353      } elsif ($localpart =~ /\.types\.ann$/) {
354       $flags = add_flag("types","ANN",$flags);
355      } else {
356       $flags = add_flag("types","NO",$flags);
357      }
358      $objects{$basepart} = $flags; # save new flags
359     } else { # exists at least one slash, a DIR
360      ($dirname) = split (/\//, $localpart);
361      $dirs{$dirname} = ""; # no flags requirement for dir
362     }
363    }
364   }
365  } else {
366   die "getter internal error: unsupported uritype: \"$uritype\"";
367  }
368                             # now generate OUTPUT:
369                             # output will be saved in $content
370  if ($format eq "txt") { # TXT output
371   foreach $key (sort(keys %dirs)) {
372    $content .= "dir, " . $key . "\n";
373   }
374   foreach $key (sort(keys %objects)) {
375    $content .= "object, $key, " . $objects{$key} . "\n";
376   }
377  } elsif ($format eq "xml") { # XML output
378   $content .= '<?xml version="1.0" encoding="ISO-8859-1"?>' . "\n";
379   $content .= "<!DOCTYPE ls SYSTEM ";
380   $content .= "\"$myownurl/getdtd?uri=ls.dtd\">" . "\n\n";
381   $content .= "<ls>\n";
382   foreach $key (sort(keys %dirs)) {
383    $content .= "\t<section>$key</section>\n";
384   }
385   foreach $key (sort(keys %objects)) {
386    $content .= "\t<object name=\"$key\">\n";
387    $flags = $objects{$key};
388    $flags =~ s/^<(.*)>$/$1/;
389    my ($annflag,$typesflag) = split /,/,$flags;
390    $content .= "\t\t<ann value=\"$annflag\" />\n";
391    $content .= "\t\t<types value=\"$typesflag\" />\n";
392    $content .= "\t</object>\n";
393   }
394   $content .= "</ls>\n";
395  } else { # may not enter this branch
396   die "Getter internal error: invalid format received by finduris sub";
397  }
398  return $content;
399 }
400
401 sub add_flag {
402 # manage string like: "<ann_flag,type_flag>"
403 # "ann_flag" may be one of "ann_YES", "ann_NO"
404 # "type_flag" may be one of "types_NO", "types_YES", "types_ANN"
405 # when adding a flag the max between the current flag and the new flag
406 # is taken, the orders are ann_NO < ann_YES and types_NO < types_YES <
407 # types_ANN
408  my ($flagtype,$newflag,$str) = @_;
409  $str = "<,>" if ($str eq "");
410  ($str =~ s/^<(.*,.*)>$/$1/) or die "Internal error: ".
411    "wrong string format for flag adding in $str";
412  my ($annflag,$typeflag) = split /,/,$str;
413  if ($flagtype eq "ann") { # ANN flag handling
414   if ($newflag eq "YES") {
415    $annflag = "YES";
416   } elsif ($newflag eq "NO") {
417    $annflag = "NO" unless ($annflag eq "YES");
418   } else {
419    die "Internal error: annflag must be \"YES\" or \"NO\"";
420   }
421  } elsif ($flagtype eq "types") { # TYPES flag handling
422   if ($newflag eq "ANN") {
423    $typeflag = "ANN";
424   } elsif ($newflag eq "YES") {
425    $typeflag = "YES" unless ($typeflag eq "ANN");
426   } elsif ($newflag eq "NO") {
427    $typeflag = "NO"
428      unless (($typeflag eq "ANN") or ($typeflag eq "YES"));
429   } else {
430    die "Internal error: typeflag must be \"YES\", \"NO\" or \"ANN\"";
431   }
432  } else {
433   die "Internal error: unsupported flagtype \"$flagtype\"";
434  }
435  $str = "<$annflag,$typeflag>";
436 }
437
438 #CSC: Too much powerful: creates even /home, /home/users/, ...
439 #CSC: Does not raise errors if could not create dirs/files
440 sub mkdirs
441 {
442  my ($pathname) = @_;
443  my @dirs = split /\//,$pathname;
444  my $tmp;
445  foreach $dir (@dirs) {
446   $tmp = ((defined($tmp)) ?  $tmp."\/".$dir : "");
447   mkdir($tmp,0777);
448  }
449  rmdir($tmp);
450 }
451
452 sub print_request
453 {
454  my ($str,$uri,$url,$filename) = @_;
455  print $str."uri: $uri\n";
456  print $str."url: $url\n";
457  print $str."filename: $filename\n\n";
458 }
459
460 sub callback
461 {
462  my ($data) = @_;
463  $cont .= $data;
464 }
465
466 sub gunzip { # gunzip a file and return the deflated content
467         my ($filename) = @_;
468
469         my ($gz, $buffer, $cont);
470
471         print "deflating $filename ...\n";
472         $gz = gzopen($filename, "r")
473                 or die "Cannot open gzip'ed file $filename: $gzerrno";
474         $cont = "";
475         while ( $gz->gzread($buffer) > 0 ) {
476                 $cont .= $buffer;
477         }
478         die "Error while reading : $gzerrno\n" if $gzerrno != Z_STREAM_END ;
479         $gz->gzclose();
480
481         return $cont;
482 }
483
484 sub gzip {      # gzip the content argument and save it to filename argument
485         my ($cont, $filename) = @_;
486  #my $debug=1; # debug only
487
488  print "gzopening $filename ...\n" if (defined($debug));
489         my $gz = gzopen($filename, "w")
490                 or die "Cannot gzopen for writing file $filename: $gzerrno";
491  print "gzwriting ...\n" if (defined($debug));
492         $gz->gzwrite($cont) or die "error writing: $gzerrno, exiting!\n";
493  print "gzclosing ...\n" if (defined($debug));
494         $gz->gzclose();
495 }
496
497 sub download {
498  my ($patch_dtd,$str,$url,$filename,$format) = @_;
499  my ($gz, $buffer);
500
501  #my $debug=1; # for DEBUG only
502
503  my $resourcetype;      # retrieve mode: "normal" (.xml) or "gzipped" (.xml.gz)
504  if ($filename =~ /\.xml$/) {   # set retrieve mode
505          $resourcetype = "normal";
506  } elsif ($filename =~ /\.xml\.gz$/) {
507          $resourcetype = "gzipped";
508  } else {
509          die "Unsupported download extension, might be '.gz' or '.xml'\n";
510  }
511  my $basefname = $filename;
512  $basefname =~ s/\.gz$//;       # get base resource name removing trailing .gz
513  $cont = ""; # modified by side-effect by the callback function
514
515  my $localfname="";
516  if (stat($basefname)) {
517         $localfname=$basefname;
518  } elsif (stat($basefname.".gz")) {
519         $localfname=$basefname.".gz";
520  }
521  if ($localfname ne "") { # we already have local copy of requested file
522       # check both possible cache entry: gzipped or normal
523   print "Using local copy for the $str file\n";
524   if ($localfname =~ /\.xml\.gz$/) { # deflating cached file and return it
525    $cont = gunzip($localfname);
526   } elsif ($localfname =~ /\.xml$/) { # just return cached file
527    open(FD, $localfname) or die "Cannot open $localfname";
528    while(<FD>) { $cont .= $_; }
529    close(FD);
530   } else { # error
531    die "Internal error: unexpected file name $localfname,"
532    ."must end with '.gz' or '.xml.gz'\n";
533   }
534  } else { # download file from net
535    print "Downloading the $str file\n"; # download file
536    my $ua = LWP::UserAgent->new;
537    my $request = HTTP::Request->new(GET => "$url");
538    my $response = $ua->request($request, \&callback);
539    
540    # cache retrieved file to disk
541    # <ZACK/> TODO: inefficent, I haven't yet undestood how to deflate
542    #    in memory gzipped file, without call "gzopen"
543    print "Storing the $str file\n";
544    print "Making dirs ...\n" if (defined($debug));
545    mkdirs($filename);
546    print "Opening tmp file for writing ...\n" if (defined($debug));
547    open(FD, ">".$filename.".tmp") or die "Cannot open $filename.tmp\n";
548    print "Writing on tmp file ...\n" if (defined($debug));
549    print FD $cont;
550    print "Closing tmp file ...\n" if (defined($debug));
551    close(FD);
552
553    # handle cache conversion normal->gzipped or gzipped->normal as user choice
554    print "cachemode:$cachemode, resourcetype:$resourcetype\n" if (defined($debug));
555    if (($cachemode eq 'normal') and ($resourcetype eq 'normal')) {
556      # cache the file as is
557     rename "$filename.tmp", $filename; 
558    } elsif (($cachemode eq 'gzipped') and ($resourcetype eq 'gzipped')) {
559      # cache the file as is
560      # and update the $cont variabile with deflated content
561     rename "$filename.tmp", $filename; 
562     $cont = gunzip($filename);
563    } elsif (($cachemode eq 'normal') and ($resourcetype eq 'gzipped')) {
564      # deflate cache entry
565      # and update $cont
566     open(FD, "> $basefname") or die "cannot open $basefname\n";
567     $cont = gunzip($filename.".tmp");
568     print FD $cont;
569     close(FD);
570     unlink "$filename.tmp"; # delete old gzipped file
571    } elsif (($cachemode eq 'gzipped') and ($resourcetype eq 'normal')) {
572      # compress cache entry
573     print "gzipping ...\n" if (defined($debug));
574     gzip($cont, $basefname.".gz");
575     unlink "$filename.tmp"; # delete old uncompressed file
576    } else {
577     die "Internal error, unsopported cachemode, resourcetype couple\n";
578    }
579    # $cont now contained uncompressed data
580  }
581  if ($patch_dtd eq "yes") {
582     $cont =~ s/DOCTYPE (.*) SYSTEM\s+"http:\/\/www.cs.unibo.it\/helm\/dtd\//DOCTYPE $1 SYSTEM "$myownurl\/getdtd?uri=/g;
583  }
584  if ($format eq "gz") {
585   gzip($cont,"$basefname.tmp");
586   open (TMP, "< $basefname.tmp")
587    or die "Can't open tempfile: $filename.tmp, exiting!\n";
588   $cont = "";
589   while(<TMP>) {
590    $cont .= $_;
591   }
592   close TMP;
593   unlink ($basefname . ".tmp") or
594    die "cannot unlink temporary file: $basefname.tmp\n";
595  }
596
597  return $cont;
598 }
599
600 sub answer {
601 # answer the client setting content, Content-Type and Content-Enconding
602 # of the answer
603  my ($c,$cont,$contype,$contenc) = @_;
604  my $res = new HTTP::Response;
605  $res->content($cont);
606  $res->push_header("Content-Type" => $contype)
607    unless ($contype eq "");
608  $res->push_header("Content-Encoding" => $contenc)
609    unless ($contenc eq "");
610  $c->send_response($res);
611 }
612
613 sub html_nice_answer {
614 # answer the client whith a nice html document
615  my ($c,$content) = @_;
616  $content = "<html><body><h1>$content</h1></body></html>";
617  answer($c,$content,"text/html","");
618 }
619
620 sub helm_wget {
621 #retrieve a file from an url and write it to a temp dir
622 #used for retrieve resource index from servers
623  $cont = "";
624  my ($prefix, $URL) = @_;
625  my $ua = LWP::UserAgent->new;
626  my $request = HTTP::Request->new(GET => "$URL");
627  my $response = $ua->request($request, \&callback);
628  my ($filename) = reverse (split "/", $URL); # get filename part of the URL
629  open (TEMP, "> $prefix/$filename")
630   || die "Cannot open temporary file: $prefix/$filename\n";
631  print TEMP $cont;
632  close TEMP;
633 }
634
635 sub update {
636  untie %map;
637  tie(%map, 'DB_File', $uris_dbm.".db", O_RDONLY, 0664);
638 }
639
640 sub mk_urls_of_uris {
641 #rebuild $uris_dbm.db fetching resource indexes from servers
642  my (
643   $server, $idxfile, $uri, $url, $comp, $line,
644   @servers,
645   %urls_of_uris
646  );
647
648  untie %map;
649  if (stat $uris_dbm.".db") { # remove old db file
650   unlink($uris_dbm.".db") or
651    die "cannot unlink old db file: $uris_dbm.db\n";
652  }
653  tie(%urls_of_uris, 'DB_File', $uris_dbm.".db", O_RDWR|O_CREAT, 0664);
654
655  open (SRVS, "< $servers_file") or
656   die "cannot open servers file: $servers_file\n";
657  @servers = <SRVS>;
658  close (SRVS);
659  while ($server = pop @servers) { #cicle on servers in reverse order
660   print "processing server: $server ...\n";
661   chomp $server;
662   helm_wget($tmp_dir, $server."/".$indexname); #get index
663   $idxfile = $tmp_dir."/".$indexname;
664   open (INDEX, "< $idxfile") or
665    die "cannot open temporary index file: $idxfile\n";
666   while ($line = <INDEX>) { #parse index and add entry to urls_of_uris
667    chomp $line;
668    ($uri,$comp) = split /[ \t]+/, $line;
669              # build url:
670    if ($comp =~ /gz/) { 
671     $url = $uri . ".xml" . ".gz";
672    } else {
673     $url = $uri . ".xml";
674    }
675    $url =~ s/cic:/$server/;
676    $url =~ s/theory:/$server/;
677    $urls_of_uris{$uri} = $url;
678   }
679   close INDEX;
680   die "cannot unlink temporary file: $idxfile\n"
681    if (unlink $idxfile) != 1;
682  }
683
684  untie(%urls_of_uris);
685  tie(%map, 'DB_File', $uris_dbm.".db", O_RDONLY, 0664);
686 }
687