]> matita.cs.unibo.it Git - helm.git/blob - helm/http_getter/http_getter.pl.in
Now helm:rdf:... is a valid URI.
[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, %rdf_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, $indexname
56 require $HELM_LIB_PATH;
57
58 # TEMP: TODO put these vars in configuration file configuration.xml
59 # <move_to_conf_file>
60 $helm_rdf_dir = "/usr/local/helm/rdf";
61 $rdf_dbm = "/usr/local/helm/rdf_urls";
62 $rdf_indexname = "rdf_index.txt";
63 # </move_to_conf_file>
64
65 # Let's override the configuration file
66 $style_dir = $ENV{"HELM_STYLE_DIR"} if (defined ($ENV{"HELM_STYLE_DIR"}));
67 $dtd_dir = $ENV{"HELM_DTD_DIR"} if (defined ($ENV{"HELM_DTD_DIR"}));
68
69 use HTTP::Daemon;
70 use HTTP::Status;
71 use HTTP::Request;
72 use LWP::UserAgent;
73 use DB_File;
74 use Compress::Zlib;
75 use CGI;
76 use URI::Escape;
77
78 #CSC: mancano i controlli sulle condizioni di errore di molte funzioni
79 #CSC: ==> non e' robusto
80 #CSC: altra roba da sistemare segnata con CSC
81
82 my $d = new HTTP::Daemon LocalPort => 8081;
83 my $myownurl = $d->url;
84
85 # Let's patch the returned URL
86 $myownurl =~ s/\/$//; # chop the final slash
87 my $myownport = $myownurl;
88 $myownport =~ s/http:\/\/(.*):(.*)/$2/;
89 $myownurl  =~ s/http:\/\/(.*):(.*)/$1/;
90 ($myownurl) = gethostbyname($myownurl);
91 $myownurl = "http://".$myownurl.":".$myownport;
92
93 tie(%map, 'DB_File', $uris_dbm.".db", O_RDWR, 0664); # open dbs
94 tie(%rdf_map, 'DB_File', $rdf_dbm.".db", O_RDWR, 0664);
95
96 print "\n";
97 print "HTTP Getter $VERSION\n"; # print hello information
98 print "Please contact me at: <URL:", $myownurl."/", ">\n";
99 print "\n";
100 print "helm_dir: $helm_dir\n";
101 print "helm_rdf_dir: $helm_rdf_dir\n";
102 print "style_dir: $style_dir\n";
103 print "dtd_dir: $dtd_dir\n";
104 print "urls_of_uris.db: $uris_dbm.db\n";
105 print "cache mode: $cachemode\n";
106 print "indexname: $indexname\n";
107 print "rdf_indexname: $rdf_indexname\n";
108 print "\n";
109
110 $SIG{CHLD} = "IGNORE"; # do not accumulate defunct processes
111 $SIG{USR1} = \&update; # sent by the child to make the parent update
112 while (my $c = $d->accept) {
113  if (fork() == 0) {
114     while (my $r = $c->get_request) {
115         #CSC: mancano i controlli di sicurezza
116         
117         my $http_method = $r->method;
118         my $http_path = $r->url->path;
119         my $http_query = uri_unescape($r->url->query);
120         my $cgi = new CGI("$http_query");
121         my $inputuri = $cgi->param('uri');
122         print "\nRequest: ".$r->url."\n\n";
123
124         print "\nUnescaped query: ".$http_query."\n";
125
126          # "getxml" works with rdf uris
127         if ($http_method eq 'GET' and $http_path eq "/getxml") {
128             # finds the uri, url and filename
129
130             my $answerformat = $cgi->param('format');
131             my $patch_dtd = $cgi->param('patch_dtd');
132             $answerformat = "" if (not defined($answerformat));
133             $patch_dtd = "yes" if (not defined($patch_dtd));
134             if (($answerformat ne "gz") and ($answerformat ne "normal")
135                and ($answerformat ne "")) {
136              die "Wrong output format: $answerformat, must be 'normal' ".
137                  "or 'gz'\n";
138             }
139             if (($patch_dtd ne "yes") and ($patch_dtd ne "no")
140                and ($patch_dtd ne "")) {
141              die "Wrong param, patch_dtd must be 'yes' or 'no'\n";
142             }
143
144             my $filename = $inputuri;
145             if (not isRdfUri($inputuri)) { # standad cic: or theory: uri
146              $filename =~ s/^cic:(.*)/$1/;
147              $filename =~ s/^theory:(.*)/$1/;
148             } else { # rdf uri
149              $filename =~ s/^(.*)\/\/cic:(.*)/$2/;
150              $filename =~ s/^(.*)\/\/theory:(.*)/$2/;
151             }
152
153             my $url = resolve ($inputuri); # resolve uri in url
154             if (not defined($url)) {
155              die "uri \"$inputuri\" can't be resolved\n";
156             }
157
158             my $extension; # file extension
159             if ($url =~ /\.xml$/) { # non gzipped file
160               $extension = ".xml";
161             } elsif ($url =~ /\.xml\.gz$/) { # gzipped file
162               $extension = ".xml.gz";
163             } else { # error: unknown extension
164              die "unexpected extension in url: $url, might be '.xml'".
165               "or '.xml.gz'";
166             }
167
168             if (not isRdfUri ($inputuri)) {
169              $filename = $helm_dir.$filename.$extension;
170             } else {
171              $filename = $helm_rdf_dir.$filename.$extension;
172             }
173
174             if (!defined($url)) {
175              print "\nNOT FOUND!!!!!\n";
176              $c->send_error(RC_NOT_FOUND)
177             } else {
178                print_request("cic",$inputuri,$url,$filename);
179
180                # Retrieves the file
181                my $ciccontent = download($patch_dtd,"cic",$url,$filename,$answerformat);
182
183                # Answering the client
184                if ($answerformat eq "normal") {
185                 answer($c,$ciccontent,"text/xml","");
186                } else {
187                 answer($c,$ciccontent,"text/xml","x-gzip");
188                }
189             }
190           # "/register" does not work with rdf uris
191         } elsif ($http_method eq 'GET' and $http_path eq "/register") {
192           my $inputurl = $cgi->param('url');
193           print "Register requested...\n";
194           $map{$inputuri}=$inputurl;
195
196           # Now let's clean the cache
197           my $cicfilename = $inputuri;
198           $cicfilename =~ s/cic:(.*)/$1/;
199           $cicfilename =~ s/theory:(.*)/$1/;
200
201           print "Unlinking ".$helm_dir.$cicfilename.".xml[.gz]\n";
202           unlink ($helm_dir.$cicfilename.".xml");
203           unlink ($helm_dir.$cicfilename.".xml.gz");
204
205           kill(USR1,getppid()); # signal changes to parent
206           untie %map;
207           print "done\n";
208           html_nice_answer($c,"Register done");
209           # "/resolve" works with rdf uri
210         } elsif ($http_method eq 'GET' and $http_path eq "/resolve") {
211           #my $outputurl = $map{$inputuri};
212           my $outputurl = resolve($inputuri);
213           $outputurl = "" if (not defined($outputurl));
214           $cont = "<?xml version=\"1.0\" ?>\n\n";
215           if ($outputurl eq "") {
216            $cont .= "<unresolved />\n";
217           } else {
218            $cont .= "<url value=\"$outputurl\" />\n";
219           }
220           answer($c,$cont,"text/xml","");
221         } elsif ($http_method eq 'GET' and $http_path eq "/getdtd") {
222             my $filename = $inputuri;
223             $filename = $dtd_dir."/".$filename;
224             print "DTD: $inputuri ==> ($filename)\n";
225             if (stat($filename)) {
226                print "Using local copy\n";
227                open(FD, $filename) or die "Cannot open $filename\n";
228                $cont = "";
229                while(<FD>) {
230                 # Vary bad heuristic for substituion of absolute URLs
231                 # for relative ones
232                 s/ENTITY (.*) SYSTEM\s+"/ENTITY $1 SYSTEM "$myownurl\/getdtd?uri=/g;
233                 $cont .= $_;
234                }
235                close(FD);
236                answer($c,$cont,"text/xml","");
237             } else {
238                die "Could not find DTD!";
239             }
240         } elsif ($http_method eq 'GET' and $http_path eq "/getstyleconf") {
241             my $filename = $inputuri;
242             $filename = $style_dir."/config/".$filename;
243             if (stat($filename)) {
244                open(FD, $filename) or die "Cannot open $filename\n";
245                $cont = "";
246                while(<FD>) {
247                 s/DOCTYPE (.*) SYSTEM\s+"/DOCTYPE $1 SYSTEM "$myownurl\/getstyleconf?uri=/g;
248                 $cont .= $_;
249                }
250                close(FD);
251                answer($c,$cont,"text/plain","");
252             } else {
253                die "Could not find Style Configuration File!";
254             }
255         } elsif ($http_method eq 'GET' and $http_path eq "/getxslt") {
256             my $filename = $inputuri;
257             $filename = $style_dir."/".$filename;
258             print "XSLT: $inputuri ==> ($filename)\n";
259             if (stat($filename)) {
260                print "Using local copy\n";
261                open(FD, $filename) or die "Cannot open $filename\n";
262                $cont = "";
263                while(<FD>) {
264                 # Vary bad heuristic for substituion of absolute URLs
265                 # for relative ones
266                 s/xsl:import\s+href="/xsl:import href="$myownurl\/getxslt?uri=/g ;
267                 s/xsl:include\s+href="/xsl:include href="$myownurl\/getxslt?uri=/g ;
268                 $cont .= $_;
269                }
270                close(FD);
271                answer($c,$cont,"text/xml","");
272             } else {
273                die "Could not find XSLT!";
274             }
275         } elsif ($http_method eq 'GET' and $http_path eq "/update") {
276             # rebuild urls_of_uris db and rdf uris db
277            print "Update requested...\n";
278            update_dbs();
279            kill(USR1,getppid()); # signal changes to parent
280            print " done\n";
281            html_nice_answer($c,"Update done");
282           # "/ls" does not work with rdf uris
283         } elsif ($http_method eq 'GET' and $http_path eq "/ls") {
284             # send back keys that begin with a given uri
285            my ($uritype,$uripattern,$uriprefix);
286            my $baseuri = $cgi->param('baseuri');
287            chop $baseuri if ($baseuri =~ /.*\/$/); # remove trailing "/"
288            my $outype = $cgi->param('format'); # output type, might be 'txt' or 'xml'
289            $uripattern = $baseuri;
290            $uripattern =~ s/^.*:(.*)/$1/;
291            if ($baseuri =~ /^cic:/) {
292             $uritype = "cic";
293            } elsif ($baseuri =~ /^theory:/) {
294             $uritype = "theory";
295            } else {
296             $uritype = "invalid";
297            }
298            if ($uritype ne "invalid") { # uri is valid
299             if (($outype ne 'txt') and ($outype ne 'xml')) { # invalid out type
300              print "Invalid output type specified: $outype\n";
301              html_nice_answer($c,"Invalid output type, must be ".
302               "'txt' or 'xml'");
303             } else { # valid output
304              print "BASEURI $baseuri, FORMAT $outype\n";
305              $cont = finduris($uritype,$uripattern,$outype);
306              if ($outype eq 'txt') {
307               answer($c,$cont,"text/plain","");
308              } elsif ($outype eq 'xml') {
309               answer($c,$cont,"text/xml","");
310              } else {
311               die "Internal error, exiting!";
312              }
313             }
314            } else { # invalid uri
315             print "Invalid uri: $baseuri, may begin with 'cic:', ".
316              "'theory:' or '*:'\n";
317             html_nice_answer($c,"Invalid uri , must begin with ".
318              "'cic:' or 'theory:'");
319            }
320         } elsif ($http_method eq 'GET' and $http_path eq "/help") {
321           # help request
322            print "Help requested!\n";
323            html_nice_answer($c,"HTTP Getter Version: $VERSION");
324         } elsif ($http_method eq 'GET' and $http_path =~ /\.cgi$/) {
325           # cgi handling
326            print "CGI requested!\n";
327            if ($http_path !~ /^\/[^\/]*\.cgi$/) {
328             html_nice_answer($c,"Invalid CGI name: $http_path, ".
329             "you can't request CGI that contain a slash in the name\n");
330            } elsif (stat "$cgi_dir"."$http_path") {
331             if (not -x "$cgi_dir/$http_path") {
332              html_nice_answer($c,"CGI $http_path found but not ".
333               "executable\n");
334             } else { # exec CGI and anser back its output
335              my %old_ENV = %ENV;
336              %ENV = ();
337              $ENV{'QUERY_STRING'} = $http_query;
338              my $cgi_output = `$cgi_dir/$http_path`;
339              answer($c,$cgi_output,"","");
340              %ENV = %old_ENV;
341             }
342            } else {
343             html_nice_answer($c,"CGI '$http_path' not found ".
344              "in CGI dir '$cgi_dir'");
345            }
346         } else { # unsupported request
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 isRdfUri { # return true if the uri is an rdf uri, false otherwise
365 # typycal rdf uri:
366 # helm:rdf/cic:www.cs.unibo.it/helm/rdf/foo_schema//cic:\
367 #  /Coq/Init/Logic/True_rec.con.types
368 #
369 # the format is "helm:rdf/<metadata_tree>:<metadata_scheme>//<xml_file_uri>"
370 #
371  my ($uri) = @_;
372  if ($uri =~ /^helm:rdf(.*):?(.*)\/\/(.*)/) {
373   return 1;
374  } else {
375   return 0;
376  }
377 }
378
379 sub resolve { # resolve an uri in a url, work both with standard cic: or theory:
380               # uris and rdf uris
381  my ($uri) = @_;
382  if (isRdfUri ($uri)) { # rdf uri, resolve using rdf db
383   return ($rdf_map{$uri});
384  } else { # standard cic: or theory: uri, resolve using std uri db
385   return ($map{$uri});
386  }
387 }
388
389 sub finduris { # find uris for cic and theory trees generation
390  my ($uritype,$uripattern,$format) = @_;
391  my $content = "";
392  my ($uri,$localpart,$basepart,$dirname,$suffix,$flags,$key);
393  my (@itemz,@already_pushed_dir);
394  my (%objects,%dirs); # map uris to suffixes' flags
395  #my $debug=1; # for debug
396
397  print "FINDURIS, uritype: $uritype, uripattern: $uripattern, ".
398   "format: $format\n\n" if defined($debug);
399  
400  if (($uritype eq "cic") or ($uritype eq "theory")) {
401    # get info only of one type: cic or theory
402   foreach (keys(%map)) { # select matching uris
403    $uri = $_;
404    if ($uri =~ /^$uritype:$uripattern(\/|$|\.)/) {
405     if ($uri =~ /^$uritype:$uripattern\//) { # directory match
406      $localpart = $uri;
407      $localpart =~ s/^$uritype:$uripattern\/(.*)/$1/;
408     } elsif ($uri =~ /^$uritype:$uripattern($|\.)/) { # file match
409      $localpart = $uri;
410      $localpart =~ s/^.*\/([^\/]*)/$1/;
411     } else {
412      die "Internal error, seems that requested match is none of ".
413       "directory match or file match";
414     }
415     print "LOCALPART: $localpart\n" if defined($debug);
416
417     if ($localpart =~ /^[^\/]*$/) { # no slash, an OBJECT
418      $basepart = $localpart;
419      $basepart =~ s/^([^.]*\.[^.]*)(\.types)?(\.ann)?/$1/;
420                                               # remove exts .types or
421                                               # .types.ann
422      $flags = $objects{$basepart}; # get old flags
423      if ($localpart =~ /\.ann$/) {
424       $flags = add_flag("ann","YES",$flags);
425      } else {
426       $flags = add_flag("ann","NO",$flags);
427      }
428      if ($localpart =~ /\.types$/) {
429       $flags = add_flag("types","YES",$flags);
430      } elsif ($localpart =~ /\.types\.ann$/) {
431       $flags = add_flag("types","ANN",$flags);
432      } else {
433       $flags = add_flag("types","NO",$flags);
434      }
435      $objects{$basepart} = $flags; # save new flags
436     } else { # exists at least one slash, a DIR
437      ($dirname) = split (/\//, $localpart);
438      $dirs{$dirname} = ""; # no flags requirement for dir
439     }
440    }
441   }
442  } else {
443   die "getter internal error: unsupported uritype: \"$uritype\"";
444  }
445                             # now generate OUTPUT:
446                             # output will be saved in $content
447  if ($format eq "txt") { # TXT output
448   foreach $key (sort(keys %dirs)) {
449    $content .= "dir, " . $key . "\n";
450   }
451   foreach $key (sort(keys %objects)) {
452    $content .= "object, $key, " . $objects{$key} . "\n";
453   }
454  } elsif ($format eq "xml") { # XML output
455   $content .= '<?xml version="1.0" encoding="ISO-8859-1"?>' . "\n";
456   $content .= "<!DOCTYPE ls SYSTEM ";
457   $content .= "\"$myownurl/getdtd?uri=ls.dtd\">" . "\n\n";
458   $content .= "<ls>\n";
459   foreach $key (sort(keys %dirs)) {
460    $content .= "\t<section>$key</section>\n";
461   }
462   foreach $key (sort(keys %objects)) {
463    $content .= "\t<object name=\"$key\">\n";
464    $flags = $objects{$key};
465    $flags =~ s/^<(.*)>$/$1/;
466    my ($annflag,$typesflag) = split /,/,$flags;
467    $content .= "\t\t<ann value=\"$annflag\" />\n";
468    $content .= "\t\t<types value=\"$typesflag\" />\n";
469    $content .= "\t</object>\n";
470   }
471   $content .= "</ls>\n";
472  } else { # may not enter this branch
473   die "Getter internal error: invalid format received by finduris sub";
474  }
475  return $content;
476 }
477
478 sub add_flag {
479 # manage string like: "<ann_flag,type_flag>"
480 # "ann_flag" may be one of "ann_YES", "ann_NO"
481 # "type_flag" may be one of "types_NO", "types_YES", "types_ANN"
482 # when adding a flag the max between the current flag and the new flag
483 # is taken, the orders are ann_NO < ann_YES and types_NO < types_YES <
484 # types_ANN
485  my ($flagtype,$newflag,$str) = @_;
486  $str = "<,>" if ($str eq "");
487  ($str =~ s/^<(.*,.*)>$/$1/) or die "Internal error: ".
488    "wrong string format for flag adding in $str";
489  my ($annflag,$typeflag) = split /,/,$str;
490  if ($flagtype eq "ann") { # ANN flag handling
491   if ($newflag eq "YES") {
492    $annflag = "YES";
493   } elsif ($newflag eq "NO") {
494    $annflag = "NO" unless ($annflag eq "YES");
495   } else {
496    die "Internal error: annflag must be \"YES\" or \"NO\"";
497   }
498  } elsif ($flagtype eq "types") { # TYPES flag handling
499   if ($newflag eq "ANN") {
500    $typeflag = "ANN";
501   } elsif ($newflag eq "YES") {
502    $typeflag = "YES" unless ($typeflag eq "ANN");
503   } elsif ($newflag eq "NO") {
504    $typeflag = "NO"
505      unless (($typeflag eq "ANN") or ($typeflag eq "YES"));
506   } else {
507    die "Internal error: typeflag must be \"YES\", \"NO\" or \"ANN\"";
508   }
509  } else {
510   die "Internal error: unsupported flagtype \"$flagtype\"";
511  }
512  $str = "<$annflag,$typeflag>";
513 }
514
515 #CSC: Too much powerful: creates even /home, /home/users/, ...
516 #CSC: Does not raise errors if could not create dirs/files
517 sub mkdirs
518 {
519  my ($pathname) = @_;
520  my @dirs = split /\//,$pathname;
521  my $tmp;
522  foreach $dir (@dirs) {
523   $tmp = ((defined($tmp)) ?  $tmp."\/".$dir : "");
524   mkdir($tmp,0777);
525  }
526  rmdir($tmp);
527 }
528
529 sub print_request
530 {
531  my ($str,$uri,$url,$filename) = @_;
532  print $str."uri: $uri\n";
533  print $str."url: $url\n";
534  print $str."filename: $filename\n\n";
535 }
536
537 sub callback
538 {
539  my ($data) = @_;
540  $cont .= $data;
541 }
542
543 sub gunzip { # gunzip a file and return the deflated content
544         my ($filename) = @_;
545
546         my ($gz, $buffer, $cont);
547
548         print "deflating $filename ...\n";
549         $gz = gzopen($filename, "r")
550                 or die "Cannot open gzip'ed file $filename: $gzerrno";
551         $cont = "";
552         while ( $gz->gzread($buffer) > 0 ) {
553                 $cont .= $buffer;
554         }
555         die "Error while reading : $gzerrno\n" if $gzerrno != Z_STREAM_END ;
556         $gz->gzclose();
557
558         return $cont;
559 }
560
561 sub gzip {      # gzip the content argument and save it to filename argument
562         my ($cont, $filename) = @_;
563  #my $debug=1; # debug only
564
565  print "gzopening $filename ...\n" if (defined($debug));
566         my $gz = gzopen($filename, "w")
567                 or die "Cannot gzopen for writing file $filename: $gzerrno";
568  print "gzwriting ...\n" if (defined($debug));
569         $gz->gzwrite($cont) or die "error writing: $gzerrno, exiting!\n";
570  print "gzclosing ...\n" if (defined($debug));
571         $gz->gzclose();
572 }
573
574 sub download {
575  my ($patch_dtd,$str,$url,$filename,$format) = @_;
576  my ($gz, $buffer);
577
578  #my $debug=1; # for DEBUG only
579
580  my $resourcetype;      # retrieve mode: "normal" (.xml) or "gzipped" (.xml.gz)
581  if ($filename =~ /\.xml$/) {   # set retrieve mode
582          $resourcetype = "normal";
583  } elsif ($filename =~ /\.xml\.gz$/) {
584          $resourcetype = "gzipped";
585  } else {
586          die "Unsupported download extension, might be '.gz' or '.xml'\n";
587  }
588  my $basefname = $filename;
589  $basefname =~ s/\.gz$//;       # get base resource name removing trailing .gz
590  $cont = ""; # modified by side-effect by the callback function
591
592  my $localfname="";
593  if (stat($basefname)) {
594         $localfname=$basefname;
595  } elsif (stat($basefname.".gz")) {
596         $localfname=$basefname.".gz";
597  }
598  if ($localfname ne "") { # we already have local copy of requested file
599       # check both possible cache entry: gzipped or normal
600   print "Using local copy for the $str file\n";
601   if ($localfname =~ /\.xml\.gz$/) { # deflating cached file and return it
602    $cont = gunzip($localfname);
603   } elsif ($localfname =~ /\.xml$/) { # just return cached file
604    open(FD, $localfname) or die "Cannot open $localfname";
605    while(<FD>) { $cont .= $_; }
606    close(FD);
607   } else { # error
608    die "Internal error: unexpected file name $localfname,"
609    ."must end with '.gz' or '.xml.gz'\n";
610   }
611  } else { # download file from net
612    print "Downloading the $str file\n"; # download file
613    my $ua = LWP::UserAgent->new;
614    my $request = HTTP::Request->new(GET => "$url");
615    my $response = $ua->request($request, \&callback);
616    
617    # cache retrieved file to disk
618    # <ZACK/> TODO: inefficent, I haven't yet undestood how to deflate
619    #    in memory gzipped file, without call "gzopen"
620    print "Storing the $str file\n";
621    print "Making dirs ...\n" if (defined($debug));
622    mkdirs($filename);
623    print "Opening tmp file for writing ...\n" if (defined($debug));
624    open(FD, ">".$filename.".tmp") or die "Cannot open $filename.tmp\n";
625    print "Writing on tmp file ...\n" if (defined($debug));
626    print FD $cont;
627    print "Closing tmp file ...\n" if (defined($debug));
628    close(FD);
629
630    # handle cache conversion normal->gzipped or gzipped->normal as user choice
631    print "cachemode:$cachemode, resourcetype:$resourcetype\n" if (defined($debug));
632    if (($cachemode eq 'normal') and ($resourcetype eq 'normal')) {
633      # cache the file as is
634     rename "$filename.tmp", $filename; 
635    } elsif (($cachemode eq 'gzipped') and ($resourcetype eq 'gzipped')) {
636      # cache the file as is
637      # and update the $cont variabile with deflated content
638     rename "$filename.tmp", $filename; 
639     $cont = gunzip($filename);
640    } elsif (($cachemode eq 'normal') and ($resourcetype eq 'gzipped')) {
641      # deflate cache entry
642      # and update $cont
643     open(FD, "> $basefname") or die "cannot open $basefname\n";
644     $cont = gunzip($filename.".tmp");
645     print FD $cont;
646     close(FD);
647     unlink "$filename.tmp"; # delete old gzipped file
648    } elsif (($cachemode eq 'gzipped') and ($resourcetype eq 'normal')) {
649      # compress cache entry
650     print "gzipping ...\n" if (defined($debug));
651     gzip($cont, $basefname.".gz");
652     unlink "$filename.tmp"; # delete old uncompressed file
653    } else {
654     die "Internal error, unsopported cachemode, resourcetype couple\n";
655    }
656    # $cont now contained uncompressed data
657  }
658  if ($patch_dtd eq "yes") {
659     $cont =~ s/DOCTYPE (.*) SYSTEM\s+"http:\/\/www.cs.unibo.it\/helm\/dtd\//DOCTYPE $1 SYSTEM "$myownurl\/getdtd?uri=/g;
660  }
661  if ($format eq "gz") {
662   gzip($cont,"$basefname.tmp");
663   open (TMP, "< $basefname.tmp")
664    or die "Can't open tempfile: $filename.tmp, exiting!\n";
665   $cont = "";
666   while(<TMP>) {
667    $cont .= $_;
668   }
669   close TMP;
670   unlink ($basefname . ".tmp") or
671    die "cannot unlink temporary file: $basefname.tmp\n";
672  }
673
674  return $cont;
675 }
676
677 sub answer {
678 # answer the client setting content, Content-Type and Content-Enconding
679 # of the answer
680  my ($c,$cont,$contype,$contenc) = @_;
681  my $res = new HTTP::Response;
682  $res->content($cont);
683  $res->push_header("Content-Type" => $contype)
684    unless ($contype eq "");
685  $res->push_header("Content-Encoding" => $contenc)
686    unless ($contenc eq "");
687  $res->push_header("Cache-Control" => "no-cache");
688  $res->push_header("Pragma" => "no-cache");
689  $res->push_header("Expires" => "0");
690  $c->send_response($res);
691 }
692
693 sub html_nice_answer {
694 # answer the client whith a nice html document
695  my ($c,$content) = @_;
696  $content = "<html><body><h1>$content</h1></body></html>";
697  answer($c,$content,"text/html","");
698 }
699
700 sub helm_wget {
701 #retrieve a file from an url and write it to a temp dir
702 #used for retrieve resource index from servers
703  $cont = "";
704  my ($prefix, $URL) = @_;
705  my $ua = LWP::UserAgent->new;
706  my $request = HTTP::Request->new(GET => "$URL");
707  my $response = $ua->request($request, \&callback);
708  my ($filename) = reverse (split "/", $URL); # get filename part of the URL
709  open (TEMP, "> $prefix/$filename")
710   || die "Cannot open temporary file: $prefix/$filename\n";
711  print TEMP $cont;
712  close TEMP;
713 }
714
715 sub update {
716  untie %map;
717  tie(%map, 'DB_File', $uris_dbm.".db", O_RDWR, 0664);
718  untie %rdf_map;
719  tie(%rdf_map, 'DB_File', $uris_dbm.".db", O_RDWR, 0664);
720 }
721
722 sub update_dbs {
723 # rebuild dbs fetching resource indexes from servers.
724 # Rebuild urls_of_uris db (1) and rdf db (2)
725  my (
726   $server, $idxfile, $rdf_idxfile, $uri, $url, $comp, $line,
727   @servers,
728   %urls_of_uris, %rdf # local proxy of $map and $rdf_map
729  );
730
731  untie %map;
732  untie %rdf_map;
733  foreach my $file ($uris_dbm, $rdf_dbm) { # remove old db file
734   if (stat $file.".db") { # remove if exists
735    unlink ($file.".db") or die "can't unlink old db file: $file.db\n";
736   }
737  }
738  tie(%urls_of_uris, 'DB_File', $uris_dbm.".db", O_RDWR|O_CREAT, 0664);
739  tie(%rdf, 'DB_File', $rdf_dbm.".db", O_RDWR|O_CREAT, 0664);
740
741  open (SRVS, "< $servers_file") or
742   die "cannot open servers file: $servers_file\n";
743  @servers = <SRVS>; # read all servers
744  close (SRVS);
745
746  while ($server = pop @servers) { # cicle on servers in _reverse_ order
747   print "processing server: $server ...\n";
748   chomp $server;
749   helm_wget($tmp_dir, $server."/".$indexname); # get index
750   helm_wget($tmp_dir, $server."/".$rdf_indexname); # get rdf index
751   $idxfile = $tmp_dir."/".$indexname;
752   $rdf_idxfile = $tmp_dir."/".$rdf_indexname;
753
754   open (INDEX, "< $idxfile") or # (1) REBUILD URLS_OF_URIS DB
755    die "cannot open temporary index file: $idxfile\n";
756   while ($line = <INDEX>) {  # parse index and add entry to urls_of_uris db
757    chomp $line;
758    ($uri,$comp) = split /[ \t]+/, $line;
759              # build url:
760    if ($comp =~ /gz/) { 
761     $url = $uri . ".xml" . ".gz";
762    } else {
763     $url = $uri . ".xml";
764    }
765    $url =~ s/cic:/$server/;
766    $url =~ s/theory:/$server/;
767    $urls_of_uris{$uri} = $url;
768   }
769
770   open (RDF_INDEX, "< $rdf_idxfile") or # (2) REBUILD RDF DB
771    die "cannot open temporary rdf index file: $rdf_idxfile\n";
772   while ($line = <RDF_INDEX>) {  # parse index and add entry to rdf db
773    chomp $line;
774    ($uri,$comp) = split /[ \t]+/, $line; # comp is "gz" or nothing
775              # build url:
776    if ($comp =~ /gz/) { 
777     $url = $uri . ".xml" . ".gz";
778    } else {
779     $url = $uri . ".xml";
780    }
781    $url =~ s/^helm:rdf(.*)\/\/cic:/$server/;
782    $url =~ s/^helm:rdf(.*)\/\/theory:/$server/;
783    $rdf{$uri} = $url;
784   }
785
786   close INDEX;  # close indexes
787   close RDF_INDEX;
788   die "cannot unlink temporary file: $idxfile\n"  # remove temp files
789    if (unlink $idxfile) != 1;
790   die "cannot unlink temporary file: $rdf_idxfile\n"
791    if (unlink $rdf_idxfile) != 1;
792
793  }
794
795  untie(%urls_of_uris); # untie local proxies
796  untie(%rdf);
797  tie(%map, 'DB_File', $uris_dbm.".db", O_RDWR, 0664); # retie global ones
798  tie(%rdf_map, 'DB_File', $rdf_dbm.".db", O_RDWR, 0664);
799 } # update_dbs
800