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