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