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