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@";
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 # <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";
55 # next require defines: $helm_dir, $html_link, $dtd_dir, $uris_dbm
56 require $HELM_LIB_PATH;
58 # Let's override the configuration file
59 $style_dir = $ENV{"HELM_STYLE_DIR"} if (defined ($ENV{"HELM_STYLE_DIR"}));
60 $dtd_dir = $ENV{"HELM_DTD_DIR"} if (defined ($ENV{"HELM_DTD_DIR"}));
71 #CSC: mancano i controlli sulle condizioni di errore di molte funzioni
72 #CSC: ==> non e' robusto
73 #CSC: altra roba da sistemare segnata con CSC
75 my $d = new HTTP::Daemon LocalPort => 8081;
76 my $myownurl = $d->url;
78 # Let's patch the returned URL
79 $myownurl =~ s/\/$//; # chop the final slash
80 my $myownport = $myownurl;
81 $myownport =~ s/http:\/\/(.*):(.*)/$2/;
82 $myownurl =~ s/http:\/\/(.*):(.*)/$1/;
83 ($myownurl) = gethostbyname($myownurl);
84 $myownurl = "http://".$myownurl.":".$myownport;
86 tie(%map, 'DB_File', $uris_dbm.".db", O_RDONLY, 0664);
87 print "Please contact me at: <URL:", $myownurl."/", ">\n";
88 print "helm_dir: $helm_dir\n";
89 print "style_dir: $style_dir\n";
90 print "dtd_dir: $dtd_dir\n";
91 print "urls_of_uris.db: $uris_dbm.db\n";
92 print "cache mode: $cachemode\n";
94 $SIG{CHLD} = "IGNORE"; # do not accumulate defunct processes
95 $SIG{USR1} = \&update; # sent by the child to make the parent update
96 while (my $c = $d->accept) {
98 while (my $r = $c->get_request) {
99 #CSC: mancano i controlli di sicurezza
101 my $http_method = $r->method;
102 my $http_path = $r->url->path;
103 my $http_query = uri_unescape($r->url->query);
104 my $cgi = new CGI("$http_query");
105 my $inputuri = $cgi->param('uri');
106 print "\nRequest: ".$r->url."\n\n";
108 print "\nUnescaped query: ".$http_query."\n";
110 if ($http_method eq 'GET' and $http_path eq "/getxml") {
111 # finds the uri, url and filename
112 my $cicuri = $inputuri;
113 my $answerformat = $cgi->param('format');
114 my $patch_dtd = $cgi->param('patch_dtd');
115 $answerformat = "" if (not defined($answerformat));
116 $patch_dtd = "" if (not defined($patch_dtd));
117 if (($answerformat ne "gz") and ($answerformat ne "normal")
118 and ($answerformat ne "")) {
119 die "Wrong output format: $answerformat, must be 'normal' ".
122 if (($patch_dtd ne "yes") and ($patch_dtd ne "no")
123 and ($patch_dtd ne "")) {
124 die "Wrong param, patch_dtd must be 'yes' or 'no'\n";
127 my $cicfilename = $cicuri;
128 $cicfilename =~ s/cic:(.*)/$1/;
129 $cicfilename =~ s/theory:(.*)/$1/;
131 my $cicurl = $map{$cicuri};
132 if (not defined($cicurl)) {
133 die "uri \"$cicuri\" can't be resolved\n";
136 if ($cicurl =~ /\.xml$/) { # non gzipped file
138 } elsif ($cicurl =~ /\.xml\.gz$/) { # gzipped file
139 $extension = ".xml.gz";
140 } else { # error: unknown extension
141 die "unexpected extension in url: $cicurl, might be '.xml'".
144 $cicfilename = $helm_dir.$cicfilename.$extension;
146 if (!defined($cicurl)) {
147 print "\nNOT FOUND!!!!!\n";
148 $c->send_error(RC_NOT_FOUND)
150 print_request("cic",$cicuri,$cicurl,$cicfilename);
153 my $ciccontent = download($patch_dtd,"cic",$cicurl,$cicfilename,$answerformat);
155 # Answering the client
156 if ($answerformat eq "normal") {
157 answer($c,$ciccontent,"text/xml","");
159 answer($c,$ciccontent,"text/xml","x-gzip");
162 } elsif ($http_method eq 'GET' and $http_path eq "/resolve") {
163 my $outputurl = $map{$inputuri};
164 $outputurl = "" if (not defined($outputurl));
165 $cont = "<?xml version=\"1.0\" ?>\n\n";
166 if ($outputurl eq "") {
167 $cont .= "<unresolved />\n";
169 $cont .= "<url value=\"$outputurl\" />\n";
171 answer($c,$cont,"text/xml","");
172 } elsif ($http_method eq 'GET' and $http_path eq "/getdtd") {
173 my $filename = $inputuri;
174 $filename = $dtd_dir."/".$filename;
175 print "DTD: $inputuri ==> ($filename)\n";
176 if (stat($filename)) {
177 print "Using local copy\n";
178 open(FD, $filename) or die "Cannot open $filename\n";
181 # Vary bad heuristic for substituion of absolute URLs
183 s/ENTITY (.*) SYSTEM\s+"/ENTITY $1 SYSTEM "$myownurl\/getdtd?uri=/g;
187 answer($c,$cont,"text/xml","");
189 die "Could not find DTD!";
191 } elsif ($http_method eq 'GET' and $http_path eq "/getstyleconf") {
192 my $filename = $inputuri;
193 $filename = $style_dir."/config/".$filename;
194 if (stat($filename)) {
195 open(FD, $filename) or die "Cannot open $filename\n";
198 s/DOCTYPE (.*) SYSTEM\s+"/DOCTYPE $1 SYSTEM "$myownurl\/getstyleconf?uri=/g;
202 answer($c,$cont,"text/plain","");
204 die "Could not find Style Configuration File!";
206 } elsif ($http_method eq 'GET' and $http_path eq "/getxslt") {
207 my $filename = $inputuri;
208 $filename = $style_dir."/".$filename;
209 print "XSLT: $inputuri ==> ($filename)\n";
210 if (stat($filename)) {
211 print "Using local copy\n";
212 open(FD, $filename) or die "Cannot open $filename\n";
215 # Vary bad heuristic for substituion of absolute URLs
217 s/xsl:import\s+href="/xsl:import href="$myownurl\/getxslt?uri=/g ;
218 s/xsl:include\s+href="/xsl:include href="$myownurl\/getxslt?uri=/g ;
222 answer($c,$cont,"text/xml","");
224 die "Could not find XSLT!";
226 } elsif ($http_method eq 'GET' and $http_path eq "/update") {
227 # rebuild urls_of_uris.db
228 print "Update requested...\n";
230 kill(USR1,getppid()); # signal changes to parent
232 html_nice_answer($c,"Update done");
233 } elsif ($http_method eq 'GET' and $http_path eq "/ls") {
234 # send back keys that begin with a given uri
235 my ($uritype,$uripattern,$uriprefix);
236 my $baseuri = $cgi->param('baseuri');
237 chop $baseuri if ($baseuri =~ /.*\/$/); # remove trailing "/"
238 my $outype = $cgi->param('format'); # output type, might be 'txt' or 'xml'
239 $uripattern = $baseuri;
240 $uripattern =~ s/^.*:(.*)/$1/;
241 if ($baseuri =~ /^cic:/) {
243 } elsif ($baseuri =~ /^theory:/) {
246 $uritype = "invalid";
248 if ($uritype ne "invalid") { # uri is valid
249 if (($outype ne 'txt') and ($outype ne 'xml')) { # invalid out type
250 print "Invalid output type specified: $outype\n";
251 html_nice_answer($c,"Invalid output type, must be ".
253 } else { # valid output
254 print "BASEURI $baseuri, FORMAT $outype\n";
255 $cont = finduris($uritype,$uripattern,$outype);
256 if ($outype eq 'txt') {
257 answer($c,$cont,"text/plain","");
258 } elsif ($outype eq 'xml') {
259 answer($c,$cont,"text/xml","");
261 die "Internal error, exiting!";
264 } else { # invalid uri
265 print "Invalid uri: $baseuri, may begin with 'cic:', ".
266 "'theory:' or '*:'\n";
267 html_nice_answer($c,"Invalid uri , must begin with ".
268 "'cic:' or 'theory:'");
270 } elsif ($http_method eq 'GET' and $http_path eq "/help") {
271 print "Help requested!\n";
272 html_nice_answer($c,"HTTP Getter Version: $VERSION");
273 } elsif ($http_method eq 'GET' and $http_path =~ /\.cgi$/) {
274 print "CGI requested!\n";
275 if ($http_path !~ /^\/[^\/]*\.cgi$/) {
276 html_nice_answer($c,"Invalid CGI name: $http_path, ".
277 "you can't request CGI that contain a slash in the name\n");
278 } elsif (stat "$cgi_dir"."$http_path") {
279 if (not -x "$cgi_dir/$http_path") {
280 html_nice_answer($c,"CGI $http_path found but not ".
282 } else { # exec CGI and anser back its output
285 $ENV{'QUERY_STRING'} = $http_query;
286 my $cgi_output = `$cgi_dir/$http_path`;
287 answer($c,$cgi_output,"","");
291 html_nice_answer($c,"CGI '$http_path' not found ".
292 "in CGI dir '$cgi_dir'");
296 print "INVALID REQUEST!!!!!\n";
297 print "(PATH: ",$http_path,", ";
298 print "QUERY: ",$http_query,")\n";
299 $c->send_error(RC_FORBIDDEN)
301 print "\nRequest solved: ".$r->url."\n\n";
305 print "\nCONNECTION CLOSED\n\n";
310 #================================
312 sub finduris { # find uris for cic and theory trees generation
313 my ($uritype,$uripattern,$format) = @_;
315 my ($uri,$localpart,$basepart,$dirname,$suffix,$flags,$key);
316 my (@itemz,@already_pushed_dir);
317 my (%objects,%dirs); # map uris to suffixes' flags
318 #my $debug=1; # for debug
320 print "FINDURIS, uritype: $uritype, uripattern: $uripattern, ".
321 "format: $format\n\n" if defined($debug);
323 if (($uritype eq "cic") or ($uritype eq "theory")) {
324 # get info only of one type: cic or theory
325 foreach (keys(%map)) { # select matching uris
327 if ($uri =~ /^$uritype:$uripattern(\/|$|\.)/) {
328 if ($uri =~ /^$uritype:$uripattern\//) { # directory match
330 $localpart =~ s/^$uritype:$uripattern\/(.*)/$1/;
331 } elsif ($uri =~ /^$uritype:$uripattern($|\.)/) { # file match
333 $localpart =~ s/^.*\/([^\/]*)/$1/;
335 die "Internal error, seems that requested match is none of ".
336 "directory match or file match";
338 print "LOCALPART: $localpart\n" if defined($debug);
340 if ($localpart =~ /^[^\/]*$/) { # no slash, an OBJECT
341 $basepart = $localpart;
342 $basepart =~ s/^([^.]*\.[^.]*)(\.types)?(\.ann)?/$1/;
343 # remove exts .types or
345 $flags = $objects{$basepart}; # get old flags
346 if ($localpart =~ /\.ann$/) {
347 $flags = add_flag("ann","YES",$flags);
349 $flags = add_flag("ann","NO",$flags);
351 if ($localpart =~ /\.types$/) {
352 $flags = add_flag("types","YES",$flags);
353 } elsif ($localpart =~ /\.types\.ann$/) {
354 $flags = add_flag("types","ANN",$flags);
356 $flags = add_flag("types","NO",$flags);
358 $objects{$basepart} = $flags; # save new flags
359 } else { # exists at least one slash, a DIR
360 ($dirname) = split (/\//, $localpart);
361 $dirs{$dirname} = ""; # no flags requirement for dir
366 die "getter internal error: unsupported uritype: \"$uritype\"";
368 # now generate OUTPUT:
369 # output will be saved in $content
370 if ($format eq "txt") { # TXT output
371 foreach $key (sort(keys %dirs)) {
372 $content .= "dir, " . $key . "\n";
374 foreach $key (sort(keys %objects)) {
375 $content .= "object, $key, " . $objects{$key} . "\n";
377 } elsif ($format eq "xml") { # XML output
378 $content .= '<?xml version="1.0" encoding="ISO-8859-1"?>' . "\n";
379 $content .= "<!DOCTYPE ls SYSTEM ";
380 $content .= "\"$myownurl/getdtd?uri=ls.dtd\">" . "\n\n";
381 $content .= "<ls>\n";
382 foreach $key (sort(keys %dirs)) {
383 $content .= "\t<section>$key</section>\n";
385 foreach $key (sort(keys %objects)) {
386 $content .= "\t<object name=\"$key\">\n";
387 $flags = $objects{$key};
388 $flags =~ s/^<(.*)>$/$1/;
389 my ($annflag,$typesflag) = split /,/,$flags;
390 $content .= "\t\t<ann value=\"$annflag\" />\n";
391 $content .= "\t\t<types value=\"$typesflag\" />\n";
392 $content .= "\t</object>\n";
394 $content .= "</ls>\n";
395 } else { # may not enter this branch
396 die "Getter internal error: invalid format received by finduris sub";
402 # manage string like: "<ann_flag,type_flag>"
403 # "ann_flag" may be one of "ann_YES", "ann_NO"
404 # "type_flag" may be one of "types_NO", "types_YES", "types_ANN"
405 # when adding a flag the max between the current flag and the new flag
406 # is taken, the orders are ann_NO < ann_YES and types_NO < types_YES <
408 my ($flagtype,$newflag,$str) = @_;
409 $str = "<,>" if ($str eq "");
410 ($str =~ s/^<(.*,.*)>$/$1/) or die "Internal error: ".
411 "wrong string format for flag adding in $str";
412 my ($annflag,$typeflag) = split /,/,$str;
413 if ($flagtype eq "ann") { # ANN flag handling
414 if ($newflag eq "YES") {
416 } elsif ($newflag eq "NO") {
417 $annflag = "NO" unless ($annflag eq "YES");
419 die "Internal error: annflag must be \"YES\" or \"NO\"";
421 } elsif ($flagtype eq "types") { # TYPES flag handling
422 if ($newflag eq "ANN") {
424 } elsif ($newflag eq "YES") {
425 $typeflag = "YES" unless ($typeflag eq "ANN");
426 } elsif ($newflag eq "NO") {
428 unless (($typeflag eq "ANN") or ($typeflag eq "YES"));
430 die "Internal error: typeflag must be \"YES\", \"NO\" or \"ANN\"";
433 die "Internal error: unsupported flagtype \"$flagtype\"";
435 $str = "<$annflag,$typeflag>";
438 #CSC: Too much powerful: creates even /home, /home/users/, ...
439 #CSC: Does not raise errors if could not create dirs/files
443 my @dirs = split /\//,$pathname;
445 foreach $dir (@dirs) {
446 $tmp = ((defined($tmp)) ? $tmp."\/".$dir : "");
454 my ($str,$uri,$url,$filename) = @_;
455 print $str."uri: $uri\n";
456 print $str."url: $url\n";
457 print $str."filename: $filename\n\n";
466 sub gunzip { # gunzip a file and return the deflated content
469 my ($gz, $buffer, $cont);
471 print "deflating $filename ...\n";
472 $gz = gzopen($filename, "r")
473 or die "Cannot open gzip'ed file $filename: $gzerrno";
475 while ( $gz->gzread($buffer) > 0 ) {
478 die "Error while reading : $gzerrno\n" if $gzerrno != Z_STREAM_END ;
484 sub gzip { # gzip the content argument and save it to filename argument
485 my ($cont, $filename) = @_;
486 #my $debug=1; # debug only
488 print "gzopening $filename ...\n" if (defined($debug));
489 my $gz = gzopen($filename, "w")
490 or die "Cannot gzopen for writing file $filename: $gzerrno";
491 print "gzwriting ...\n" if (defined($debug));
492 $gz->gzwrite($cont) or die "error writing: $gzerrno, exiting!\n";
493 print "gzclosing ...\n" if (defined($debug));
498 my ($patch_dtd,$str,$url,$filename,$format) = @_;
501 #my $debug=1; # for DEBUG only
503 my $resourcetype; # retrieve mode: "normal" (.xml) or "gzipped" (.xml.gz)
504 if ($filename =~ /\.xml$/) { # set retrieve mode
505 $resourcetype = "normal";
506 } elsif ($filename =~ /\.xml\.gz$/) {
507 $resourcetype = "gzipped";
509 die "Unsupported download extension, might be '.gz' or '.xml'\n";
511 my $basefname = $filename;
512 $basefname =~ s/\.gz$//; # get base resource name removing trailing .gz
513 $cont = ""; # modified by side-effect by the callback function
516 if (stat($basefname)) {
517 $localfname=$basefname;
518 } elsif (stat($basefname.".gz")) {
519 $localfname=$basefname.".gz";
521 if ($localfname ne "") { # we already have local copy of requested file
522 # check both possible cache entry: gzipped or normal
523 print "Using local copy for the $str file\n";
524 if ($localfname =~ /\.xml\.gz$/) { # deflating cached file and return it
525 $cont = gunzip($localfname);
526 } elsif ($localfname =~ /\.xml$/) { # just return cached file
527 open(FD, $localfname) or die "Cannot open $localfname";
528 while(<FD>) { $cont .= $_; }
531 die "Internal error: unexpected file name $localfname,"
532 ."must end with '.gz' or '.xml.gz'\n";
534 } else { # download file from net
535 print "Downloading the $str file\n"; # download file
536 my $ua = LWP::UserAgent->new;
537 my $request = HTTP::Request->new(GET => "$url");
538 my $response = $ua->request($request, \&callback);
540 # cache retrieved file to disk
541 # <ZACK/> TODO: inefficent, I haven't yet undestood how to deflate
542 # in memory gzipped file, without call "gzopen"
543 print "Storing the $str file\n";
544 print "Making dirs ...\n" if (defined($debug));
546 print "Opening tmp file for writing ...\n" if (defined($debug));
547 open(FD, ">".$filename.".tmp") or die "Cannot open $filename.tmp\n";
548 print "Writing on tmp file ...\n" if (defined($debug));
550 print "Closing tmp file ...\n" if (defined($debug));
553 # handle cache conversion normal->gzipped or gzipped->normal as user choice
554 print "cachemode:$cachemode, resourcetype:$resourcetype\n" if (defined($debug));
555 if (($cachemode eq 'normal') and ($resourcetype eq 'normal')) {
556 # cache the file as is
557 rename "$filename.tmp", $filename;
558 } elsif (($cachemode eq 'gzipped') and ($resourcetype eq 'gzipped')) {
559 # cache the file as is
560 # and update the $cont variabile with deflated content
561 rename "$filename.tmp", $filename;
562 $cont = gunzip($filename);
563 } elsif (($cachemode eq 'normal') and ($resourcetype eq 'gzipped')) {
564 # deflate cache entry
566 open(FD, "> $basefname") or die "cannot open $basefname\n";
567 $cont = gunzip($filename.".tmp");
570 unlink "$filename.tmp"; # delete old gzipped file
571 } elsif (($cachemode eq 'gzipped') and ($resourcetype eq 'normal')) {
572 # compress cache entry
573 print "gzipping ...\n" if (defined($debug));
574 gzip($cont, $basefname.".gz");
575 unlink "$filename.tmp"; # delete old uncompressed file
577 die "Internal error, unsopported cachemode, resourcetype couple\n";
579 # $cont now contained uncompressed data
581 if ($patch_dtd eq "yes") {
582 $cont =~ s/DOCTYPE (.*) SYSTEM\s+"http:\/\/www.cs.unibo.it\/helm\/dtd\//DOCTYPE $1 SYSTEM "$myownurl\/getdtd?uri=/g;
584 if ($format eq "gz") {
585 gzip($cont,"$basefname.tmp");
586 open (TMP, "< $basefname.tmp")
587 or die "Can't open tempfile: $filename.tmp, exiting!\n";
593 unlink ($basefname . ".tmp") or
594 die "cannot unlink temporary file: $basefname.tmp\n";
601 # answer the client setting content, Content-Type and Content-Enconding
603 my ($c,$cont,$contype,$contenc) = @_;
604 my $res = new HTTP::Response;
605 $res->content($cont);
606 $res->push_header("Content-Type" => $contype)
607 unless ($contype eq "");
608 $res->push_header("Content-Encoding" => $contenc)
609 unless ($contenc eq "");
610 $c->send_response($res);
613 sub html_nice_answer {
614 # answer the client whith a nice html document
615 my ($c,$content) = @_;
616 $content = "<html><body><h1>$content</h1></body></html>";
617 answer($c,$content,"text/html","");
621 #retrieve a file from an url and write it to a temp dir
622 #used for retrieve resource index from servers
624 my ($prefix, $URL) = @_;
625 my $ua = LWP::UserAgent->new;
626 my $request = HTTP::Request->new(GET => "$URL");
627 my $response = $ua->request($request, \&callback);
628 my ($filename) = reverse (split "/", $URL); # get filename part of the URL
629 open (TEMP, "> $prefix/$filename")
630 || die "Cannot open temporary file: $prefix/$filename\n";
637 tie(%map, 'DB_File', $uris_dbm.".db", O_RDONLY, 0664);
640 sub mk_urls_of_uris {
641 #rebuild $uris_dbm.db fetching resource indexes from servers
643 $server, $idxfile, $uri, $url, $comp, $line,
649 if (stat $uris_dbm.".db") { # remove old db file
650 unlink($uris_dbm.".db") or
651 die "cannot unlink old db file: $uris_dbm.db\n";
653 tie(%urls_of_uris, 'DB_File', $uris_dbm.".db", O_RDWR|O_CREAT, 0664);
655 open (SRVS, "< $servers_file") or
656 die "cannot open servers file: $servers_file\n";
659 while ($server = pop @servers) { #cicle on servers in reverse order
660 print "processing server: $server ...\n";
662 helm_wget($tmp_dir, $server."/".$indexname); #get index
663 $idxfile = $tmp_dir."/".$indexname;
664 open (INDEX, "< $idxfile") or
665 die "cannot open temporary index file: $idxfile\n";
666 while ($line = <INDEX>) { #parse index and add entry to urls_of_uris
668 ($uri,$comp) = split /[ \t]+/, $line;
671 $url = $uri . ".xml" . ".gz";
673 $url = $uri . ".xml";
675 $url =~ s/cic:/$server/;
676 $url =~ s/theory:/$server/;
677 $urls_of_uris{$uri} = $url;
680 die "cannot unlink temporary file: $idxfile\n"
681 if (unlink $idxfile) != 1;
684 untie(%urls_of_uris);
685 tie(%map, 'DB_File', $uris_dbm.".db", O_RDONLY, 0664);