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