3 # Copyright (C) 2000, HELM Team.
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.
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.
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.
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.
23 # For details, see the HELM World-Wide-Web page,
24 # http://cs.unibo.it/helm/.
28 my $VERSION = "@VERSION@";
32 my $cgi_dir = "@HELM_CGI_DIR@";
33 my (%xml_map, %rdf_map, %xslt_map);
35 # First of all, let's load HELM configuration
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";
43 $HELM_LIB_PATH = $DEFAULT_HELM_LIB_DIR."/configuration.pl";
46 # next require defines: $helm_dir, $html_link, $dtd_dir, $uris_dbm, $indexname
47 require $HELM_LIB_PATH;
49 # TEMP: TODO put these vars in configuration file configuration.xml
51 my $cachemode = $ENV{'HTTP_GETTER_CACHE_MODE'} ||
53 if (($cachemode ne 'gzipped') and ($cachemode ne 'normal')) {
54 die "Invalid HTTP_GETTER_CACHE_MODE environment variable, must be".
55 "'normal' or 'gzipped'\n";
58 my $helm_rdf_dir = $ENV{'HTTP_GETTER_RDF_DIR'} ||
59 "/usr/local/helm/rdf_library";
60 my $rdf_dbm = $ENV{'HTTP_GETTER_RDF_DBM'} ||
61 "/usr/local/helm/rdf_urls_of_uris.db";
62 my $xslt_dbm = $ENV{'HTTP_GETTER_XSLT_DBM'} ||
63 "/usr/local/helm/xslt_urls_of_uris.db";
64 my $rdf_indexname = $ENV{'HTTP_GETTER_RDF_INDEXNAME'} ||
66 my $xslt_indexname = $ENV{'HTTP_GETTER_XSLT_INDEXNAME'} ||
69 # </move_to_conf_file>
71 # Let's override the configuration file
72 $style_dir = $ENV{"HELM_STYLE_DIR"} if (defined ($ENV{"HELM_STYLE_DIR"}));
73 $dtd_dir = $ENV{"HELM_DTD_DIR"} if (defined ($ENV{"HELM_DTD_DIR"}));
85 #CSC: mancano i controlli sulle condizioni di errore di molte funzioni
86 #CSC: ==> non e' robusto
87 #CSC: altra roba da sistemare segnata con CSC
89 my $d = new HTTP::Daemon LocalPort => 8081
90 or die "Error: port 8081 not available.";
91 my $myownurl = $d->url;
93 # Let's patch the returned URL
94 $myownurl =~ s/\/$//; # chop the final slash
95 my $myownport = $myownurl;
96 $myownport =~ s/http:\/\/(.*):(.*)/$2/;
97 $myownurl =~ s/http:\/\/(.*):(.*)/$1/;
98 ($myownurl) = gethostbyname($myownurl);
99 $myownurl = "http://".$myownurl.":".$myownport;
101 tie(%xml_map, 'DB_File', $uris_dbm, O_RDWR, 0664); # open dbs
102 tie(%rdf_map, 'DB_File', $rdf_dbm, O_RDWR, 0664);
103 tie(%xslt_map, 'DB_File', $xslt_dbm, O_RDWR, 0664);
106 print "HTTP Getter $VERSION\n"; # print hello information
107 print "Please contact me at: <URL:", $myownurl."/", ">\n";
109 print "helm_dir: $helm_dir\n";
110 print "helm_rdf_dir: $helm_rdf_dir\n";
111 print "style_dir: $style_dir\n";
112 print "dtd_dir: $dtd_dir\n";
113 print "urls_of_uris db: $uris_dbm\n";
114 print "rdf db: $rdf_dbm\n";
115 print "cache mode: $cachemode\n";
116 print "indexname: $indexname\n";
117 print "rdf_indexname: $rdf_indexname\n";
120 $SIG{CHLD} = "IGNORE"; # do not accumulate defunct processes
121 $SIG{USR1} = \&update; # sent by the child to make the parent update
123 while (my $c = $d->accept) {
125 while (my $r = $c->get_request) {
126 #CSC: mancano i controlli di sicurezza
128 my $http_method = $r->method;
129 my $http_path = $r->url->path;
130 my $http_query = uri_unescape($r->url->query);
131 my $cgi = new CGI("$http_query");
132 my $inputuri = $cgi->param('uri');
133 print "\nRequest: ".$r->url."\n\n";
135 print "\nUnescaped query: ".$http_query."\n";
137 # "getxml" works with rdf uris
138 if ($http_method eq 'GET' and $http_path eq "/getxml") {
139 # finds the uri, url and filename
141 my $answerformat = $cgi->param('format');
142 my $patch_dtd = $cgi->param('patch_dtd');
143 $answerformat = "" if (not defined($answerformat));
144 $patch_dtd = "yes" if (not defined($patch_dtd));
145 if (($answerformat ne "gz") and ($answerformat ne "normal")
146 and ($answerformat ne "")) {
147 die "Wrong output format: $answerformat, must be 'normal' ".
150 if (($patch_dtd ne "yes") and ($patch_dtd ne "no")
151 and ($patch_dtd ne "")) {
152 die "Wrong param, patch_dtd must be 'yes' or 'no'\n";
155 my $filename = $inputuri;
157 if (not isRdfUri($inputuri)) { # standad cic: or theory: uri
158 $filename =~ s/^cic:(.*)/$1/;
159 $filename =~ s/^theory:(.*)/$1/;
161 # The "helm:rdf/<<...>>//cic:" prefix is kept, but quoted
162 # (so that a "helm:rdf/<<...>>//cic:" dir is created
164 $filename =~ s/^(.*)\/\/cic:(.*)/$2/;
165 $filename =~ s/^(.*)\/\/theory:(.*)/$2/;
166 $prefix =~ s/\Q$filename\E//;
169 $filename = $prefix.$filename;
172 my $url = resolve ($inputuri); # resolve uri in url
173 if (not defined($url)) { # uri not found in uri2url map
174 die "NOT FOUND: uri \"$inputuri\" can't be resolved\n";
175 $c->send_error(RC_NOT_FOUND)
176 } else { # uri found and mapped to url
177 my $extension; # file extension
178 if ($url =~ /\.xml$/) { # non gzipped file
180 } elsif ($url =~ /\.xml\.gz$/) { # gzipped file
181 $extension = ".xml.gz";
182 } else { # error: unknown extension
183 die "unexpected extension in url: $url, might be '.xml'".
187 if (not isRdfUri ($inputuri)) { # save in uri std cache dir
188 $filename = $helm_dir.$filename.$extension;
189 } else { # save in rdf metadata cache dir
190 $filename = $helm_rdf_dir."/".$filename.$extension;
193 print_request($inputuri,$url,$filename);
196 my $ciccontent = download($patch_dtd,$url,$filename,$answerformat);
198 if ($answerformat eq "normal") { # answer the client in text/xml
199 answer($c,$ciccontent,"text/xml","");
200 } else { # answer the client in text/xml, gzip encoding
201 answer($c,$ciccontent,"text/xml","x-gzip");
205 # "/register" does not work with rdf uris
206 } elsif ($http_method eq 'GET' and $http_path eq "/register") {
207 my $inputurl = $cgi->param('url');
208 print "Register requested...\n";
209 $xml_map{$inputuri}=$inputurl;
211 # Now let's clean the cache
212 my $cicfilename = $inputuri;
213 $cicfilename =~ s/cic:(.*)/$1/;
214 $cicfilename =~ s/theory:(.*)/$1/;
216 print "Unlinking ".$helm_dir.$cicfilename.".xml[.gz]\n";
217 unlink ($helm_dir.$cicfilename.".xml");
218 unlink ($helm_dir.$cicfilename.".xml.gz");
220 kill(USR1,getppid()); # signal changes to parent
223 html_nice_answer($c,"Register done");
225 # "/resolve" works with rdf uri
226 } elsif ($http_method eq 'GET' and $http_path eq "/resolve") {
227 #my $outputurl = $xml_map{$inputuri};
228 my $outputurl = resolve($inputuri);
229 $outputurl = "" if (not defined($outputurl));
230 $cont = "<?xml version=\"1.0\" ?>\n\n";
231 if ($outputurl eq "") {
232 $cont .= "<unresolved />\n";
234 $cont .= "<url value=\"$outputurl\" />\n";
236 answer($c,$cont,"text/xml","");
238 } elsif ($http_method eq 'GET' and $http_path eq "/getdtd") {
240 my $filename = $inputuri;
241 $filename = $dtd_dir."/".$filename;
242 print "DTD: $inputuri ==> ($filename)\n";
243 if (stat($filename)) {
244 print "Using local copy\n";
245 open(FD, $filename) or die "Cannot open $filename\n";
248 # Vary bad heuristic for substituion of absolute URLs
250 s/ENTITY (.*) SYSTEM\s+"/ENTITY $1 SYSTEM "$myownurl\/getdtd?uri=/g;
254 answer($c,$cont,"text/xml","");
256 die "Could not find DTD!";
259 } elsif ($http_method eq 'GET' and $http_path eq "/getxslt") {
261 print "Downloading XSLT ...\n";
262 helm_wget($tmp_dir, $inputuri);
263 print "XSLT downloaded!\n";
264 $inputuri =~ s/.*\///;
265 my $filename = $tmp_dir . "/" . $inputuri;
267 die "Could not find XSLT!\n" unless stat($filename);
268 open(FD, $filename) or die "Can't open xslt local copy: '$filename'\n";
270 s/xsl:import\s+href="/xsl:import href="$myownurl\/getxslt?uri=/g;
271 s/xsl:include\s+href="/xsl:include href="$myownurl\/getxslt?uri=/g;
275 answer($c, $cont, "text/xml", "");
277 print "Can't unlink XSLT temp file '$filename'";
280 # my $filename = $inputuri;
281 # $filename = $style_dir."/".$filename;
282 # print "XSLT: $inputuri ==> ($filename)\n";
283 # if (stat($filename)) {
284 # print "Using local copy\n";
285 # open(FD, $filename) or die "Cannot open $filename\n";
288 # # Vary bad heuristic for substituion of absolute URLs
289 # # for relative ones
290 # s/xsl:import\s+href="/xsl:import href="$myownurl\/getxslt?uri=/g ;
291 # s/xsl:include\s+href="/xsl:include href="$myownurl\/getxslt?uri=/g ;
295 # answer($c,$cont,"text/xml","");
297 # die "Could not find XSLT!";
301 # "/update" works with rdf uri
302 } elsif ($http_method eq 'GET' and $http_path eq "/update") {
303 # rebuild urls_of_uris db and rdf uris db
304 print "Update requested...\n";
306 kill(USR1,getppid()); # signal changes to parent
308 html_nice_answer($c,"Update done");
310 # "/ls" does not work with rdf uris
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 # output type, might be 'txt' or 'xml':
317 my $outype = $cgi->param('format');
318 $uripattern = $baseuri;
319 $uripattern =~ s/^.*:(.*)/$1/;
320 if ($baseuri =~ /^cic:/) {
322 } elsif ($baseuri =~ /^theory:/) {
325 $uritype = "invalid";
327 if ($uritype ne "invalid") { # uri is valid
328 if (($outype ne 'txt') and ($outype ne 'xml')) { # invalid out type
329 print "Invalid output type specified: $outype\n";
330 html_nice_answer($c,"Invalid output type, must be ".
332 } else { # valid output
333 print "BASEURI $baseuri, FORMAT $outype\n";
334 $cont = finduris($uritype,$uripattern,$outype);
335 if ($outype eq 'txt') {
336 answer($c,$cont,"text/plain","");
337 } elsif ($outype eq 'xml') {
338 answer($c,$cont,"text/xml","");
340 die "Internal error, exiting!";
343 } else { # invalid uri
344 print "Invalid uri: $baseuri, may begin with 'cic:', ".
345 "'theory:' or '*:'\n";
346 html_nice_answer($c,"Invalid uri , must begin with ".
347 "'cic:' or 'theory:'");
350 } elsif ($http_method eq 'GET' and $http_path eq "/help") {
352 print "Help requested!\n";
353 html_nice_answer($c,"HTTP Getter Version: $VERSION");
355 } elsif ($http_method eq 'GET' and $http_path eq "/getempty") {
356 # return an empty, but valid, xml document
357 my $emptyxml = <<EOXML;
358 <?xml version="1.0"?>
360 <!ELEMENT empty EMPTY>
364 answer($c, $emptyxml, "", "");
366 } elsif ($http_method eq 'GET' and $http_path =~ /\.cgi$/) {
368 print "CGI requested!\n";
369 if ($http_path !~ /^\/[^\/]*\.cgi$/) {
370 html_nice_answer($c,"Invalid CGI name: $http_path, ".
371 "you can't request CGI that contain a slash in the name\n");
372 } elsif (stat "$cgi_dir"."$http_path") {
373 if (not -x "$cgi_dir/$http_path") {
374 html_nice_answer($c,"CGI $http_path found but not ".
376 } else { # exec CGI and anser back its output
379 $ENV{'QUERY_STRING'} = $http_query;
380 my $cgi_output = `$cgi_dir/$http_path`;
381 answer($c,$cgi_output,"","");
385 html_nice_answer($c,"CGI '$http_path' not found ".
386 "in CGI dir '$cgi_dir'");
389 } else { # unsupported request
391 print "INVALID REQUEST!!!!!\n";
392 print "(PATH: ",$http_path,", ";
393 print "QUERY: ",$http_query,")\n";
394 $c->send_error(RC_FORBIDDEN)
397 print "\nRequest solved: ".$r->url."\n\n";
402 print "\nCONNECTION CLOSED\n\n";
407 #================================
409 sub isRdfUri { # return true if the uri is an rdf uri, false otherwise
411 # helm:rdf/cic:www.cs.unibo.it/helm/rdf/foo_schema//cic:\
412 # /Coq/Init/Logic/True_rec.con.types
414 # the format is "helm:rdf/<metadata_tree>:<metadata_scheme>//<xml_file_uri>"
417 if ($uri =~ /^helm:rdf(.*):(.*)\/\/(.*)/) {
424 sub resolve { # resolve an uri in a url, work both with standard cic: or theory:
426 print "RESOLVE subroutine\n";
428 print "GIVEN URI: \"$uri\"\n";
429 if (isRdfUri ($uri)) { # rdf uri, resolve using rdf db
430 print "IS A RDF URI\n";
431 print "I WILL RETURN '$rdf_map{$uri}'\n";
432 return ($rdf_map{$uri});
433 } else { # standard cic: or theory: uri, resolve using std uri db
434 print "IS NOT A RDF URI\n";
435 print "I WILL RETURN '$xml_map{$uri}'\n";
436 return ($xml_map{$uri});
440 sub finduris { # find uris for cic and theory trees generation
441 my ($uritype,$uripattern,$format) = @_;
443 my ($uri,$localpart,$basepart,$dirname,$suffix,$flags,$key);
444 my (@itemz,@already_pushed_dir);
445 my (%objects,%dirs); # map uris to suffixes' flags
446 my $debug=1; # for debug
448 print "FINDURIS, uritype: $uritype, uripattern: $uripattern, ".
449 "format: $format\n\n" if defined($debug);
451 if (($uritype eq "cic") or ($uritype eq "theory")) {
452 # get info only of one type: cic or theory
453 foreach (keys(%xml_map)) { # select matching uris
455 if ($uri =~ /^$uritype:$uripattern(\/|$|\.)/) {
456 if ($uri =~ /^$uritype:$uripattern\//) { # directory match
458 $localpart =~ s/^$uritype:$uripattern\/(.*)/$1/;
459 } elsif ($uri =~ /^$uritype:$uripattern($|\.)/) { # file match
461 $localpart =~ s/^.*\/([^\/]*)/$1/;
463 die "Internal error, seems that requested match is none of ".
464 "directory match or file match";
466 print "LOCALPART: $localpart\n" if defined($debug);
468 if ($localpart =~ /^[^\/]*$/) { # no slash, an OBJECT
469 $basepart = $localpart;
470 $basepart =~ s/^([^.]*\.[^.]*)(\.types)?(\.ann)?/$1/;
471 # remove exts .types or
473 $flags = $objects{$basepart}; # get old flags
474 if ($localpart =~ /\.ann$/) {
475 $flags = add_flag("ann","YES",$flags);
477 $flags = add_flag("ann","NO",$flags);
479 if ($localpart =~ /\.types$/) {
480 $flags = add_flag("types","YES",$flags);
481 } elsif ($localpart =~ /\.types\.ann$/) {
482 $flags = add_flag("types","ANN",$flags);
484 $flags = add_flag("types","NO",$flags);
486 $objects{$basepart} = $flags; # save new flags
487 } else { # exists at least one slash, a DIR
488 ($dirname) = split (/\//, $localpart);
489 $dirs{$dirname} = ""; # no flags requirement for dir
494 die "getter internal error: unsupported uritype: \"$uritype\"";
496 # now generate OUTPUT:
497 # output will be saved in $content
498 if ($format eq "txt") { # TXT output
499 foreach $key (sort(keys %dirs)) {
500 $content .= "dir, " . $key . "\n";
502 foreach $key (sort(keys %objects)) {
503 $content .= "object, $key, " . $objects{$key} . "\n";
505 } elsif ($format eq "xml") { # XML output
506 $content .= '<?xml version="1.0" encoding="ISO-8859-1"?>' . "\n";
507 $content .= "<!DOCTYPE ls SYSTEM ";
508 $content .= "\"$myownurl/getdtd?uri=ls.dtd\">" . "\n\n";
509 $content .= "<ls>\n";
510 foreach $key (sort(keys %dirs)) {
511 $content .= "\t<section>$key</section>\n";
513 foreach $key (sort(keys %objects)) {
514 $content .= "\t<object name=\"$key\">\n";
515 $flags = $objects{$key};
516 $flags =~ s/^<(.*)>$/$1/;
517 my ($annflag,$typesflag) = split /,/,$flags;
518 $content .= "\t\t<ann value=\"$annflag\" />\n";
519 $content .= "\t\t<types value=\"$typesflag\" />\n";
520 $content .= "\t</object>\n";
522 $content .= "</ls>\n";
523 } else { # may not enter this branch
524 die "Getter internal error: invalid format received by finduris sub";
530 # manage string like: "<ann_flag,type_flag>"
531 # "ann_flag" may be one of "ann_YES", "ann_NO"
532 # "type_flag" may be one of "types_NO", "types_YES", "types_ANN"
533 # when adding a flag the max between the current flag and the new flag
534 # is taken, the orders are ann_NO < ann_YES and types_NO < types_YES <
536 my ($flagtype,$newflag,$str) = @_;
537 $str = "<,>" if ($str eq "");
538 ($str =~ s/^<(.*,.*)>$/$1/) or die "Internal error: ".
539 "wrong string format for flag adding in $str";
540 my ($annflag,$typeflag) = split /,/,$str;
541 if ($flagtype eq "ann") { # ANN flag handling
542 if ($newflag eq "YES") {
544 } elsif ($newflag eq "NO") {
545 $annflag = "NO" unless ($annflag eq "YES");
547 die "Internal error: annflag must be \"YES\" or \"NO\"";
549 } elsif ($flagtype eq "types") { # TYPES flag handling
550 if ($newflag eq "ANN") {
552 } elsif ($newflag eq "YES") {
553 $typeflag = "YES" unless ($typeflag eq "ANN");
554 } elsif ($newflag eq "NO") {
556 unless (($typeflag eq "ANN") or ($typeflag eq "YES"));
558 die "Internal error: typeflag must be \"YES\", \"NO\" or \"ANN\"";
561 die "Internal error: unsupported flagtype \"$flagtype\"";
563 $str = "<$annflag,$typeflag>";
566 #CSC: Too much powerful: creates even /home, /home/users/, ...
567 #CSC: Does not raise errors if could not create dirs/files
571 my @dirs = split /\//,$pathname;
573 foreach $dir (@dirs) {
574 $tmp = ((defined($tmp)) ? $tmp."\/".$dir : "");
582 my ($uri,$url,$filename) = @_;
583 print "<download_request>\n";
586 print "filename: $filename\n\n";
587 print "</download_request>\n";
590 sub gunzip { # gunzip a file and return the deflated content
593 my ($gz, $buffer, $cont);
595 print "deflating $filename ...\n";
596 $gz = gzopen($filename, "r")
597 or die "Cannot open gzip'ed file $filename: $gzerrno";
599 while ( $gz->gzread($buffer) > 0 ) {
602 die "Error while reading : $gzerrno\n" if $gzerrno != Z_STREAM_END ;
608 sub gzip { # gzip the content argument and save it to filename argument
609 my ($cont, $filename) = @_;
610 #my $debug=1; # debug only
612 print "gzopening $filename ...\n" if (defined($debug));
613 my $gz = gzopen($filename, "w")
614 or die "Cannot gzopen for writing file $filename: $gzerrno";
615 print "gzwriting ...\n" if (defined($debug));
616 $gz->gzwrite($cont) or die "error writing: $gzerrno, exiting!\n";
617 print "gzclosing ...\n" if (defined($debug));
622 my ($patch_dtd,$url,$filename,$format) = @_;
625 # print "DOWNLOAD subs receives url: \"$url\"\n";
626 # print "DOWNLOAD subs receives filename: \"$filename\"\n";
628 my $resourcetype; # retrieve mode: "normal" (.xml) or "gzipped" (.xml.gz)
629 if ($filename =~ /\.xml$/) { # set retrieve mode
630 $resourcetype = "normal";
631 } elsif ($filename =~ /\.xml\.gz$/) {
632 $resourcetype = "gzipped";
634 die "Unsupported download extension, might be '.gz' or '.xml'\n";
636 my $basefname = $filename;
637 $basefname =~ s/\.gz$//; # get base resource name removing trailing .gz
638 $cont = ""; # modified by side-effect by the callback function
641 if (stat($basefname)) {
642 $localfname=$basefname;
643 } elsif (stat($basefname.".gz")) {
644 $localfname=$basefname.".gz";
646 if ($localfname ne "") { # we already have local copy of requested file
647 # check both possible cache entry: gzipped or normal
648 print "Using local copy.\n";
649 if ($localfname =~ /\.xml\.gz$/) { # deflating cached file and return it
650 $cont = gunzip($localfname);
651 } elsif ($localfname =~ /\.xml$/) { # just return cached file
652 open(FD, $localfname) or die "Cannot open $localfname";
653 while(<FD>) { $cont .= $_; }
656 die "Internal error: unexpected file name $localfname,"
657 ."must end with '.gz' or '.xml.gz'\n";
659 } else { # download file from net
660 print "Downloading file ...\n"; # download file
661 my $ua = LWP::UserAgent->new;
662 my $request = HTTP::Request->new(GET => "$url");
663 my $response = $ua->request($request, \&callback);
665 # cache retrieved file to disk
666 # <ZACK/> TODO: inefficent, I haven't yet undestood how to deflate
667 # in memory gzipped file, without call "gzopen"
668 print "Storing file ...\n";
669 # print "Making dirs ...\n";
671 # print "Opening tmp file for writing ...\n";
672 open(FD, ">".$filename.".tmp") or die "Cannot open $filename.tmp\n";
673 # print "Writing on tmp file ...\n";
675 # print "Closing tmp file ...\n";
678 # handle cache conversion normal->gzipped or gzipped->normal as user choice
679 print "cachemode:$cachemode, resourcetype:$resourcetype\n"
680 if (defined($debug));
681 if (($cachemode eq 'normal') and ($resourcetype eq 'normal')) {
682 # cache the file as is
683 rename "$filename.tmp", $filename;
684 } elsif (($cachemode eq 'gzipped') and ($resourcetype eq 'gzipped')) {
685 # cache the file as is
686 # and update the $cont variabile with deflated content
687 rename "$filename.tmp", $filename;
688 $cont = gunzip($filename);
689 } elsif (($cachemode eq 'normal') and ($resourcetype eq 'gzipped')) {
690 # deflate cache entry
692 open(FD, "> $basefname") or die "cannot open $basefname\n";
693 $cont = gunzip($filename.".tmp");
696 unlink "$filename.tmp"; # delete old gzipped file
697 } elsif (($cachemode eq 'gzipped') and ($resourcetype eq 'normal')) {
698 # compress cache entry
699 print "gzipping ...\n" if (defined($debug));
700 gzip($cont, $basefname.".gz");
701 unlink "$filename.tmp"; # delete old uncompressed file
703 die "Internal error, unsopported cachemode, resourcetype couple\n";
705 # $cont now contained uncompressed data
707 if ($patch_dtd eq "yes") {
708 $cont =~ s/DOCTYPE (.*) SYSTEM\s+"http:\/\/www.cs.unibo.it\/helm\/dtd\//DOCTYPE $1 SYSTEM "$myownurl\/getdtd?uri=/g;
710 if ($format eq "gz") {
711 gzip($cont,"$basefname.tmp");
712 open (TMP, "< $basefname.tmp")
713 or die "Can't open tempfile: $filename.tmp, exiting!\n";
719 unlink ($basefname . ".tmp") or
720 die "cannot unlink temporary file: $basefname.tmp\n";
727 # answer the client setting content, Content-Type and Content-Enconding
729 my ($c,$cont,$contype,$contenc) = @_;
730 my $res = new HTTP::Response;
731 $res->content($cont);
732 $res->push_header("Content-Type" => $contype)
733 unless ($contype eq "");
734 $res->push_header("Content-Encoding" => $contenc)
735 unless ($contenc eq "");
736 $res->push_header("Cache-Control" => "no-cache");
737 $res->push_header("Pragma" => "no-cache");
738 $res->push_header("Expires" => "0");
739 $c->send_response($res);
742 sub html_nice_answer {
743 # answer the client whith a nice html document
744 my ($c,$content) = @_;
745 $content = "<html><body><h1>$content</h1></body></html>";
746 answer($c,$content,"text/html","");
755 # retrieve a file from an url and write it to a temp dir
756 # used for retrieve resource index from servers
758 my ($prefix, $URL) = @_;
759 my $ua = LWP::UserAgent->new;
760 my $request = HTTP::Request->new(GET => "$URL");
761 my $response = $ua->request($request, \&callback);
762 my ($filename) = reverse (split "/", $URL); # get filename part of the URL
763 open (TEMP, "> $prefix/$filename")
764 || die "Cannot open temporary file: $prefix/$filename\n";
772 tie(%xml_map, 'DB_File', $uris_dbm, O_RDWR, 0664);
774 tie(%rdf_map, 'DB_File', $rdf_dbm, O_RDWR, 0664);
776 tie(%xslt_map, 'DB_File', $xslt_dbm, O_RDWR, 0664);
780 # rebuild dbs fetching resource indexes from servers.
781 # Rebuild urls_of_uris db (1), rdf db (2) and xslt db (3)
783 $server, $idxfile, $rdf_idxfile, $uri, $url, $comp, $line,
785 %urls_of_uris, %rdf, %xslt # local proxy of dbs
791 foreach my $file ($uris_dbm, $rdf_dbm, $xslt_dbm) { # remove old db file
792 if (stat $file) { # remove if exists
793 unlink ($file) or die "can't unlink old db file: $file\n";
796 tie(%urls_of_uris, 'DB_File', $uris_dbm, O_RDWR|O_CREAT, 0664);
797 tie(%rdf, 'DB_File', $rdf_dbm, O_RDWR|O_CREAT, 0664);
798 tie(%xslt, 'DB_File', $xslt_dbm, O_RDWR|O_CREAT, 0664);
800 open (SRVS, "< $servers_file") or
801 die "cannot open servers file: $servers_file\n";
802 @servers = <SRVS>; # read all servers
805 while ($server = pop @servers) { # cicle on servers in _reverse_ order
806 print "processing server: $server ...\n";
808 helm_wget($tmp_dir, $server."/".$indexname); # get index
809 helm_wget($tmp_dir, $server."/".$rdf_indexname); # get rdf index
810 helm_wget($tmp_dir, $server."/".$xslt_indexname); # get xslt index
811 $idxfile = $tmp_dir."/".$indexname;
812 $rdf_idxfile = $tmp_dir."/".$rdf_indexname;
813 $xslt_idxfile = $tmp_dir . "/" . $xslt_indexname;
815 # (1) REBUILD URLS_OF_URIS DB
816 open (INDEX, "< $idxfile") or
817 die "cannot open temporary index file: $idxfile\n";
818 while (my $line = <INDEX>) { # parse index and add entry to urls_of_uris db
820 ($uri,$comp) = split /[ \t]+/, $line;
823 $url = $uri . ".xml" . ".gz";
825 $url = $uri . ".xml";
827 $url =~ s/cic:/$server/;
828 $url =~ s/theory:/$server/;
829 $urls_of_uris{$uri} = $url;
833 open (RDF_INDEX, "< $rdf_idxfile") or
834 die "cannot open temporary RDF index file: $rdf_idxfile\n";
835 while (my $line = <RDF_INDEX>) { # parse index and add entry to rdf db
837 ($uri,$comp) = split /[ \t]+/, $line; # comp is "gz" or nothing
840 $url = $uri . ".xml" . ".gz";
842 $url = $uri . ".xml";
844 $url =~ s/^helm:rdf(.*)\/\/cic:/$server/;
845 $url =~ s/^helm:rdf(.*)\/\/theory:/$server/;
849 # (3) REBUILD XSLT DB
850 open (XSLT_INDEX, "< $xslt_idxfile") or
851 die "cannot open temporary XSLT index file: $xslt_idxfile\n";
852 while (my $line = <XSLT_INDEX>) { # parse index and add entry to xslt db
854 my $stylesheet = $line;
855 my $url = $server . "/" . $stylesheet;
856 $xslt{$stylesheet} = $url;
859 close INDEX; # close indexes
864 foreach my $file in ($idxfile, $rdf_idxfile, $xslt_idxfile) {
865 print "cannot unlink temporary file: $file\n" if (unlink $file) != 1;
870 untie(%urls_of_uris); # untie local proxies
873 tie(%xml_map, 'DB_File', $uris_dbm, O_RDWR, 0664); # retie global ones
874 tie(%rdf_map, 'DB_File', $rdf_dbm, O_RDWR, 0664);
875 tie(%xslt_map, 'DB_File', $xslt_dbm, O_RDWR, 0664);
879 # vim modline: do not remove!