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