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