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