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 "xslt db: $xslt_dbm\n";
116 print "cache mode: $cachemode\n";
117 print "indexname: $indexname\n";
118 print "rdf_indexname: $rdf_indexname\n";
119 print "xslt_indexname: $xslt_indexname\n";
122 $SIG{CHLD} = "IGNORE"; # do not accumulate defunct processes
123 $SIG{USR1} = \&update; # sent by the child to make the parent update
125 while (my $c = $d->accept) {
127 while (my $r = $c->get_request) {
128 #CSC: mancano i controlli di sicurezza
130 my $http_method = $r->method;
131 my $http_path = $r->url->path;
132 my $http_query = uri_unescape($r->url->query);
133 my $cgi = new CGI("$http_query");
134 my $inputuri = $cgi->param('uri');
135 print "\nRequest: ".$r->url."\n\n";
137 print "\nUnescaped query: ".$http_query."\n";
139 # "getxml" works with rdf uris
140 if ($http_method eq 'GET' and $http_path eq "/getxml") {
141 # finds the uri, url and filename
143 my $answerformat = $cgi->param('format');
144 my $patch_dtd = $cgi->param('patch_dtd');
145 $answerformat = "" if (not defined($answerformat));
146 $patch_dtd = "yes" if (not defined($patch_dtd));
147 if (($answerformat ne "gz") and ($answerformat ne "normal")
148 and ($answerformat ne "")) {
149 die "Wrong output format: $answerformat, must be 'normal' ".
152 if (($patch_dtd ne "yes") and ($patch_dtd ne "no")
153 and ($patch_dtd ne "")) {
154 die "Wrong param, patch_dtd must be 'yes' or 'no'\n";
157 my $filename = $inputuri;
159 if (not isRdfUri($inputuri)) { # standad cic: or theory: uri
160 $filename =~ s/^cic:(.*)/$1/;
161 $filename =~ s/^theory:(.*)/$1/;
163 # The "helm:rdf/<<...>>//cic:" prefix is kept, but quoted
164 # (so that a "helm:rdf/<<...>>//cic:" dir is created
166 $filename =~ s/^(.*)\/\/cic:(.*)/$2/;
167 $filename =~ s/^(.*)\/\/theory:(.*)/$2/;
168 $prefix =~ s/\Q$filename\E//;
171 $filename = $prefix.$filename;
174 my $url = resolve ($inputuri); # resolve uri in url
175 if (not defined($url)) { # uri not found in uri2url map
176 die "NOT FOUND: uri \"$inputuri\" can't be resolved\n";
177 $c->send_error(RC_NOT_FOUND)
178 } else { # uri found and mapped to url
179 my $extension; # file extension
180 if ($url =~ /\.xml$/) { # non gzipped file
182 } elsif ($url =~ /\.xml\.gz$/) { # gzipped file
183 $extension = ".xml.gz";
184 } else { # error: unknown extension
185 die "unexpected extension in url: $url, might be '.xml'".
189 if (not isRdfUri ($inputuri)) { # save in uri std cache dir
190 $filename = $helm_dir.$filename.$extension;
191 } else { # save in rdf metadata cache dir
192 $filename = $helm_rdf_dir."/".$filename.$extension;
195 print_request($inputuri,$url,$filename);
198 my $ciccontent = download($patch_dtd,$url,$filename,$answerformat);
200 if ($answerformat eq "normal") { # answer the client in text/xml
201 answer($c,$ciccontent,"text/xml","");
202 } else { # answer the client in text/xml, gzip encoding
203 answer($c,$ciccontent,"text/xml","x-gzip");
207 # "/register" does not work with rdf uris
208 } elsif ($http_method eq 'GET' and $http_path eq "/register") {
209 my $inputurl = $cgi->param('url');
210 print "Register requested...\n";
211 $xml_map{$inputuri}=$inputurl;
213 # Now let's clean the cache
214 my $cicfilename = $inputuri;
215 $cicfilename =~ s/cic:(.*)/$1/;
216 $cicfilename =~ s/theory:(.*)/$1/;
218 print "Unlinking ".$helm_dir.$cicfilename.".xml[.gz]\n";
219 unlink ($helm_dir.$cicfilename.".xml");
220 unlink ($helm_dir.$cicfilename.".xml.gz");
222 kill(USR1,getppid()); # signal changes to parent
225 html_nice_answer($c,"Register done");
227 # "/resolve" works with rdf uri
228 } elsif ($http_method eq 'GET' and $http_path eq "/resolve") {
229 #my $outputurl = $xml_map{$inputuri};
230 my $outputurl = resolve($inputuri);
231 $outputurl = "" if (not defined($outputurl));
232 $cont = "<?xml version=\"1.0\" ?>\n\n";
233 if ($outputurl eq "") {
234 $cont .= "<unresolved />\n";
236 $cont .= "<url value=\"$outputurl\" />\n";
238 answer($c,$cont,"text/xml","");
240 } elsif ($http_method eq 'GET' and $http_path eq "/getdtd") {
242 my $filename = $inputuri;
243 $filename = $dtd_dir."/".$filename;
244 print "DTD: $inputuri ==> ($filename)\n";
245 if (stat($filename)) {
246 print "Using local copy\n";
247 open(FD, $filename) or die "Cannot open $filename\n";
250 # Vary bad heuristic for substituion of absolute URLs
252 s/ENTITY (.*) SYSTEM\s+"/ENTITY $1 SYSTEM "$myownurl\/getdtd?uri=/g;
256 answer($c,$cont,"text/xml","");
258 die "Could not find DTD!";
261 } elsif ($http_method eq 'GET' and $http_path eq "/getxslt") {
263 $url = $xslt_map{$inputuri};
264 print "Downloading XSLT ...\n";
265 helm_wget($tmp_dir, $url);
266 print "XSLT downloaded!\n";
267 $inputuri =~ s/.*\///;
268 my $filename = $tmp_dir . "/" . $inputuri;
270 die "Could not find XSLT!\n" unless stat($filename);
271 open(FD, $filename) or die "Can't open xslt local copy: '$filename'\n";
273 s/xsl:import\s+href="/xsl:import href="$myownurl\/getxslt?uri=/g;
274 s/xsl:include\s+href="/xsl:include href="$myownurl\/getxslt?uri=/g;
278 answer($c, $cont, "text/xml", "");
280 print "Can't unlink XSLT temp file '$filename'";
283 # my $filename = $inputuri;
284 # $filename = $style_dir."/".$filename;
285 # print "XSLT: $inputuri ==> ($filename)\n";
286 # if (stat($filename)) {
287 # print "Using local copy\n";
288 # open(FD, $filename) or die "Cannot open $filename\n";
291 # # Vary bad heuristic for substituion of absolute URLs
292 # # for relative ones
293 # s/xsl:import\s+href="/xsl:import href="$myownurl\/getxslt?uri=/g ;
294 # s/xsl:include\s+href="/xsl:include href="$myownurl\/getxslt?uri=/g ;
298 # answer($c,$cont,"text/xml","");
300 # die "Could not find XSLT!";
304 # "/update" works with rdf uri
305 } elsif ($http_method eq 'GET' and $http_path eq "/update") {
306 # rebuild urls_of_uris db and rdf uris db
307 print "Update requested...\n";
309 kill(USR1,getppid()); # signal changes to parent
311 html_nice_answer($c,"Update done");
313 # "/ls" does not work with rdf uris
314 } elsif ($http_method eq 'GET' and $http_path eq "/ls") {
315 # send back keys that begin with a given uri
316 my ($uritype,$uripattern,$uriprefix);
317 my $baseuri = $cgi->param('baseuri');
318 chop $baseuri if ($baseuri =~ /.*\/$/); # remove trailing "/"
319 # output type, might be 'txt' or 'xml':
320 my $outype = $cgi->param('format');
321 $uripattern = $baseuri;
322 $uripattern =~ s/^.*:(.*)/$1/;
323 if ($baseuri =~ /^cic:/) {
325 } elsif ($baseuri =~ /^theory:/) {
328 $uritype = "invalid";
330 if ($uritype ne "invalid") { # uri is valid
331 if (($outype ne 'txt') and ($outype ne 'xml')) { # invalid out type
332 print "Invalid output type specified: $outype\n";
333 html_nice_answer($c,"Invalid output type, must be ".
335 } else { # valid output
336 print "BASEURI $baseuri, FORMAT $outype\n";
337 $cont = finduris($uritype,$uripattern,$outype);
338 if ($outype eq 'txt') {
339 answer($c,$cont,"text/plain","");
340 } elsif ($outype eq 'xml') {
341 answer($c,$cont,"text/xml","");
343 die "Internal error, exiting!";
346 } else { # invalid uri
347 print "Invalid uri: $baseuri, may begin with 'cic:', ".
348 "'theory:' or '*:'\n";
349 html_nice_answer($c,"Invalid uri , must begin with ".
350 "'cic:' or 'theory:'");
353 } elsif ($http_method eq 'GET' and $http_path eq "/help") {
355 print "Help requested!\n";
356 html_nice_answer($c,"HTTP Getter Version: $VERSION");
358 } elsif ($http_method eq 'GET' and $http_path eq "/getempty") {
359 # return an empty, but valid, xml document
360 my $emptyxml = <<EOXML;
361 <?xml version="1.0"?>
363 <!ELEMENT empty EMPTY>
367 answer($c, $emptyxml, "", "");
369 } elsif ($http_method eq 'GET' and $http_path =~ /\.cgi$/) {
371 print "CGI requested!\n";
372 if ($http_path !~ /^\/[^\/]*\.cgi$/) {
373 html_nice_answer($c,"Invalid CGI name: $http_path, ".
374 "you can't request CGI that contain a slash in the name\n");
375 } elsif (stat "$cgi_dir"."$http_path") {
376 if (not -x "$cgi_dir/$http_path") {
377 html_nice_answer($c,"CGI $http_path found but not ".
379 } else { # exec CGI and anser back its output
382 $ENV{'QUERY_STRING'} = $http_query;
383 my $cgi_output = `$cgi_dir/$http_path`;
384 answer($c,$cgi_output,"","");
388 html_nice_answer($c,"CGI '$http_path' not found ".
389 "in CGI dir '$cgi_dir'");
392 } else { # unsupported request
394 print "INVALID REQUEST!!!!!\n";
395 print "(PATH: ",$http_path,", ";
396 print "QUERY: ",$http_query,")\n";
397 $c->send_error(RC_FORBIDDEN)
400 print "\nRequest solved: ".$r->url."\n\n";
405 print "\nCONNECTION CLOSED\n\n";
410 #================================
412 sub isRdfUri { # return true if the uri is an rdf uri, false otherwise
414 # helm:rdf/cic:www.cs.unibo.it/helm/rdf/foo_schema//cic:\
415 # /Coq/Init/Logic/True_rec.con.types
417 # the format is "helm:rdf/<metadata_tree>:<metadata_scheme>//<xml_file_uri>"
420 if ($uri =~ /^helm:rdf(.*):(.*)\/\/(.*)/) {
427 sub resolve { # resolve an uri in a url, work both with standard cic: or theory:
429 print "RESOLVE subroutine\n";
431 print "GIVEN URI: \"$uri\"\n";
432 if (isRdfUri ($uri)) { # rdf uri, resolve using rdf db
433 print "IS A RDF URI\n";
434 print "I WILL RETURN '$rdf_map{$uri}'\n";
435 return ($rdf_map{$uri});
436 } else { # standard cic: or theory: uri, resolve using std uri db
437 print "IS NOT A RDF URI\n";
438 print "I WILL RETURN '$xml_map{$uri}'\n";
439 return ($xml_map{$uri});
443 sub finduris { # find uris for cic and theory trees generation
444 my ($uritype,$uripattern,$format) = @_;
446 my ($uri,$localpart,$basepart,$dirname,$suffix,$flags,$key);
447 my (@itemz,@already_pushed_dir);
448 my (%objects,%dirs); # map uris to suffixes' flags
449 my $debug=1; # for debug
451 print "FINDURIS, uritype: $uritype, uripattern: $uripattern, ".
452 "format: $format\n\n" if defined($debug);
454 if (($uritype eq "cic") or ($uritype eq "theory")) {
455 # get info only of one type: cic or theory
456 foreach (keys(%xml_map)) { # select matching uris
458 if ($uri =~ /^$uritype:$uripattern(\/|$|\.)/) {
459 if ($uri =~ /^$uritype:$uripattern\//) { # directory match
461 $localpart =~ s/^$uritype:$uripattern\/(.*)/$1/;
462 } elsif ($uri =~ /^$uritype:$uripattern($|\.)/) { # file match
464 $localpart =~ s/^.*\/([^\/]*)/$1/;
466 die "Internal error, seems that requested match is none of ".
467 "directory match or file match";
469 print "LOCALPART: $localpart\n" if defined($debug);
471 if ($localpart =~ /^[^\/]*$/) { # no slash, an OBJECT
472 $basepart = $localpart;
473 $basepart =~ s/^([^.]*\.[^.]*)(\.types)?(\.ann)?/$1/;
474 # remove exts .types or
476 $flags = $objects{$basepart}; # get old flags
477 if ($localpart =~ /\.ann$/) {
478 $flags = add_flag("ann","YES",$flags);
480 $flags = add_flag("ann","NO",$flags);
482 if ($localpart =~ /\.types$/) {
483 $flags = add_flag("types","YES",$flags);
484 } elsif ($localpart =~ /\.types\.ann$/) {
485 $flags = add_flag("types","ANN",$flags);
487 $flags = add_flag("types","NO",$flags);
489 $objects{$basepart} = $flags; # save new flags
490 } else { # exists at least one slash, a DIR
491 ($dirname) = split (/\//, $localpart);
492 $dirs{$dirname} = ""; # no flags requirement for dir
497 die "getter internal error: unsupported uritype: \"$uritype\"";
499 # now generate OUTPUT:
500 # output will be saved in $content
501 if ($format eq "txt") { # TXT output
502 foreach $key (sort(keys %dirs)) {
503 $content .= "dir, " . $key . "\n";
505 foreach $key (sort(keys %objects)) {
506 $content .= "object, $key, " . $objects{$key} . "\n";
508 } elsif ($format eq "xml") { # XML output
509 $content .= '<?xml version="1.0" encoding="ISO-8859-1"?>' . "\n";
510 $content .= "<!DOCTYPE ls SYSTEM ";
511 $content .= "\"$myownurl/getdtd?uri=ls.dtd\">" . "\n\n";
512 $content .= "<ls>\n";
513 foreach $key (sort(keys %dirs)) {
514 $content .= "\t<section>$key</section>\n";
516 foreach $key (sort(keys %objects)) {
517 $content .= "\t<object name=\"$key\">\n";
518 $flags = $objects{$key};
519 $flags =~ s/^<(.*)>$/$1/;
520 my ($annflag,$typesflag) = split /,/,$flags;
521 $content .= "\t\t<ann value=\"$annflag\" />\n";
522 $content .= "\t\t<types value=\"$typesflag\" />\n";
523 $content .= "\t</object>\n";
525 $content .= "</ls>\n";
526 } else { # may not enter this branch
527 die "Getter internal error: invalid format received by finduris sub";
533 # manage string like: "<ann_flag,type_flag>"
534 # "ann_flag" may be one of "ann_YES", "ann_NO"
535 # "type_flag" may be one of "types_NO", "types_YES", "types_ANN"
536 # when adding a flag the max between the current flag and the new flag
537 # is taken, the orders are ann_NO < ann_YES and types_NO < types_YES <
539 my ($flagtype,$newflag,$str) = @_;
540 $str = "<,>" if ($str eq "");
541 ($str =~ s/^<(.*,.*)>$/$1/) or die "Internal error: ".
542 "wrong string format for flag adding in $str";
543 my ($annflag,$typeflag) = split /,/,$str;
544 if ($flagtype eq "ann") { # ANN flag handling
545 if ($newflag eq "YES") {
547 } elsif ($newflag eq "NO") {
548 $annflag = "NO" unless ($annflag eq "YES");
550 die "Internal error: annflag must be \"YES\" or \"NO\"";
552 } elsif ($flagtype eq "types") { # TYPES flag handling
553 if ($newflag eq "ANN") {
555 } elsif ($newflag eq "YES") {
556 $typeflag = "YES" unless ($typeflag eq "ANN");
557 } elsif ($newflag eq "NO") {
559 unless (($typeflag eq "ANN") or ($typeflag eq "YES"));
561 die "Internal error: typeflag must be \"YES\", \"NO\" or \"ANN\"";
564 die "Internal error: unsupported flagtype \"$flagtype\"";
566 $str = "<$annflag,$typeflag>";
569 #CSC: Too much powerful: creates even /home, /home/users/, ...
570 #CSC: Does not raise errors if could not create dirs/files
574 my @dirs = split /\//,$pathname;
576 foreach $dir (@dirs) {
577 $tmp = ((defined($tmp)) ? $tmp."\/".$dir : "");
585 my ($uri,$url,$filename) = @_;
586 print "<download_request>\n";
589 print "filename: $filename\n\n";
590 print "</download_request>\n";
593 sub gunzip { # gunzip a file and return the deflated content
596 my ($gz, $buffer, $cont);
598 print "deflating $filename ...\n";
599 $gz = gzopen($filename, "r")
600 or die "Cannot open gzip'ed file $filename: $gzerrno";
602 while ( $gz->gzread($buffer) > 0 ) {
605 die "Error while reading : $gzerrno\n" if $gzerrno != Z_STREAM_END ;
611 sub gzip { # gzip the content argument and save it to filename argument
612 my ($cont, $filename) = @_;
613 #my $debug=1; # debug only
615 print "gzopening $filename ...\n" if (defined($debug));
616 my $gz = gzopen($filename, "w")
617 or die "Cannot gzopen for writing file $filename: $gzerrno";
618 print "gzwriting ...\n" if (defined($debug));
619 $gz->gzwrite($cont) or die "error writing: $gzerrno, exiting!\n";
620 print "gzclosing ...\n" if (defined($debug));
625 my ($patch_dtd,$url,$filename,$format) = @_;
628 # print "DOWNLOAD subs receives url: \"$url\"\n";
629 # print "DOWNLOAD subs receives filename: \"$filename\"\n";
631 my $resourcetype; # retrieve mode: "normal" (.xml) or "gzipped" (.xml.gz)
632 if ($filename =~ /\.xml$/) { # set retrieve mode
633 $resourcetype = "normal";
634 } elsif ($filename =~ /\.xml\.gz$/) {
635 $resourcetype = "gzipped";
637 die "Unsupported download extension, might be '.gz' or '.xml'\n";
639 my $basefname = $filename;
640 $basefname =~ s/\.gz$//; # get base resource name removing trailing .gz
641 $cont = ""; # modified by side-effect by the callback function
644 if (stat($basefname)) {
645 $localfname=$basefname;
646 } elsif (stat($basefname.".gz")) {
647 $localfname=$basefname.".gz";
649 if ($localfname ne "") { # we already have local copy of requested file
650 # check both possible cache entry: gzipped or normal
651 print "Using local copy.\n";
652 if ($localfname =~ /\.xml\.gz$/) { # deflating cached file and return it
653 $cont = gunzip($localfname);
654 } elsif ($localfname =~ /\.xml$/) { # just return cached file
655 open(FD, $localfname) or die "Cannot open $localfname";
656 while(<FD>) { $cont .= $_; }
659 die "Internal error: unexpected file name $localfname,"
660 ."must end with '.gz' or '.xml.gz'\n";
662 } else { # download file from net
663 print "Downloading file ...\n"; # download file
664 my $ua = LWP::UserAgent->new;
665 my $request = HTTP::Request->new(GET => "$url");
666 my $response = $ua->request($request, \&callback);
668 # cache retrieved file to disk
669 # <ZACK/> TODO: inefficent, I haven't yet undestood how to deflate
670 # in memory gzipped file, without call "gzopen"
671 print "Storing file ...\n";
672 # print "Making dirs ...\n";
674 # print "Opening tmp file for writing ...\n";
675 open(FD, ">".$filename.".tmp") or die "Cannot open $filename.tmp\n";
676 # print "Writing on tmp file ...\n";
678 # print "Closing tmp file ...\n";
681 # handle cache conversion normal->gzipped or gzipped->normal as user choice
682 print "cachemode:$cachemode, resourcetype:$resourcetype\n"
683 if (defined($debug));
684 if (($cachemode eq 'normal') and ($resourcetype eq 'normal')) {
685 # cache the file as is
686 rename "$filename.tmp", $filename;
687 } elsif (($cachemode eq 'gzipped') and ($resourcetype eq 'gzipped')) {
688 # cache the file as is
689 # and update the $cont variabile with deflated content
690 rename "$filename.tmp", $filename;
691 $cont = gunzip($filename);
692 } elsif (($cachemode eq 'normal') and ($resourcetype eq 'gzipped')) {
693 # deflate cache entry
695 open(FD, "> $basefname") or die "cannot open $basefname\n";
696 $cont = gunzip($filename.".tmp");
699 unlink "$filename.tmp"; # delete old gzipped file
700 } elsif (($cachemode eq 'gzipped') and ($resourcetype eq 'normal')) {
701 # compress cache entry
702 print "gzipping ...\n" if (defined($debug));
703 gzip($cont, $basefname.".gz");
704 unlink "$filename.tmp"; # delete old uncompressed file
706 die "Internal error, unsopported cachemode, resourcetype couple\n";
708 # $cont now contained uncompressed data
710 if ($patch_dtd eq "yes") {
711 $cont =~ s/DOCTYPE (.*) SYSTEM\s+"http:\/\/www.cs.unibo.it\/helm\/dtd\//DOCTYPE $1 SYSTEM "$myownurl\/getdtd?uri=/g;
713 if ($format eq "gz") {
714 gzip($cont,"$basefname.tmp");
715 open (TMP, "< $basefname.tmp")
716 or die "Can't open tempfile: $filename.tmp, exiting!\n";
722 unlink ($basefname . ".tmp") or
723 die "cannot unlink temporary file: $basefname.tmp\n";
730 # answer the client setting content, Content-Type and Content-Enconding
732 my ($c,$cont,$contype,$contenc) = @_;
733 my $res = new HTTP::Response;
734 $res->content($cont);
735 $res->push_header("Content-Type" => $contype)
736 unless ($contype eq "");
737 $res->push_header("Content-Encoding" => $contenc)
738 unless ($contenc eq "");
739 $res->push_header("Cache-Control" => "no-cache");
740 $res->push_header("Pragma" => "no-cache");
741 $res->push_header("Expires" => "0");
742 $c->send_response($res);
745 sub html_nice_answer {
746 # answer the client whith a nice html document
747 my ($c,$content) = @_;
748 $content = "<html><body><h1>$content</h1></body></html>";
749 answer($c,$content,"text/html","");
758 # retrieve a file from an url and write it to a temp dir
759 # used for retrieve resource index from servers
761 my ($prefix, $URL) = @_;
762 my $ua = LWP::UserAgent->new;
763 my $request = HTTP::Request->new(GET => "$URL");
764 my $response = $ua->request($request, \&callback);
765 my ($filename) = reverse (split "/", $URL); # get filename part of the URL
766 open (TEMP, "> $prefix/$filename")
767 || die "Cannot open temporary file: $prefix/$filename\n";
775 tie(%xml_map, 'DB_File', $uris_dbm, O_RDWR, 0664);
777 tie(%rdf_map, 'DB_File', $rdf_dbm, O_RDWR, 0664);
779 tie(%xslt_map, 'DB_File', $xslt_dbm, O_RDWR, 0664);
783 # rebuild dbs fetching resource indexes from servers.
784 # Rebuild urls_of_uris db (1), rdf db (2) and xslt db (3)
786 $server, $idxfile, $rdf_idxfile, $uri, $url, $comp, $line,
788 %urls_of_uris, %rdf, %xslt # local proxy of dbs
794 foreach my $file ($uris_dbm, $rdf_dbm, $xslt_dbm) { # remove old db file
795 if (stat $file) { # remove if exists
796 unlink ($file) or die "can't unlink old db file: $file\n";
799 tie(%urls_of_uris, 'DB_File', $uris_dbm, O_RDWR|O_CREAT, 0664);
800 tie(%rdf, 'DB_File', $rdf_dbm, O_RDWR|O_CREAT, 0664);
801 tie(%xslt, 'DB_File', $xslt_dbm, O_RDWR|O_CREAT, 0664);
803 open (SRVS, "< $servers_file") or
804 die "cannot open servers file: $servers_file\n";
805 @servers = <SRVS>; # read all servers
808 while ($server = pop @servers) { # cicle on servers in _reverse_ order
809 print "processing server: $server ...\n";
811 helm_wget($tmp_dir, $server."/".$indexname); # get index
812 helm_wget($tmp_dir, $server."/".$rdf_indexname); # get rdf index
813 helm_wget($tmp_dir, $server."/".$xslt_indexname); # get xslt index
814 $idxfile = $tmp_dir."/".$indexname;
815 $rdf_idxfile = $tmp_dir."/".$rdf_indexname;
816 $xslt_idxfile = $tmp_dir . "/" . $xslt_indexname;
818 # (1) REBUILD URLS_OF_URIS DB
819 open (INDEX, "< $idxfile") or
820 die "cannot open temporary index file: $idxfile\n";
821 while (my $line = <INDEX>) { # parse index and add entry to urls_of_uris db
823 ($uri,$comp) = split /[ \t]+/, $line;
826 $url = $uri . ".xml" . ".gz";
828 $url = $uri . ".xml";
830 $url =~ s/cic:/$server/;
831 $url =~ s/theory:/$server/;
832 $urls_of_uris{$uri} = $url;
836 open (RDF_INDEX, "< $rdf_idxfile") or
837 die "cannot open temporary RDF index file: $rdf_idxfile\n";
838 while (my $line = <RDF_INDEX>) { # parse index and add entry to rdf db
840 ($uri,$comp) = split /[ \t]+/, $line; # comp is "gz" or nothing
843 $url = $uri . ".xml" . ".gz";
845 $url = $uri . ".xml";
847 $url =~ s/^helm:rdf(.*)\/\/cic:/$server/;
848 $url =~ s/^helm:rdf(.*)\/\/theory:/$server/;
852 # (3) REBUILD XSLT DB
853 open (XSLT_INDEX, "< $xslt_idxfile") or
854 die "cannot open temporary XSLT index file: $xslt_idxfile\n";
855 while (my $line = <XSLT_INDEX>) { # parse index and add entry to xslt db
857 my $stylesheet = $line;
858 my $url = $server . "/" . $stylesheet;
859 $xslt{$stylesheet} = $url;
862 close INDEX; # close indexes
867 foreach my $file ($idxfile, $rdf_idxfile, $xslt_idxfile) {
868 print "cannot unlink temporary file: $file\n" if (unlink $file) != 1;
873 untie(%urls_of_uris); # untie local proxies
876 tie(%xml_map, 'DB_File', $uris_dbm, O_RDWR, 0664); # retie global ones
877 tie(%rdf_map, 'DB_File', $rdf_dbm, O_RDWR, 0664);
878 tie(%xslt_map, 'DB_File', $xslt_dbm, O_RDWR, 0664);
882 # vim modline: do not remove!