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 answer($c,$ciccontent,"text/xml","x-gzip");
158 } elsif ($http_method eq 'GET' and $http_path eq "/resolve") {
159 my $outputurl = $map{$inputuri};
160 $outputurl = "" if (not defined($outputurl));
161 $cont = "<?xml version=\"1.0\" ?>\n\n";
162 if ($outputurl eq "") {
163 $cont .= "<unresolved />\n";
165 $cont .= "<url value=\"$outputurl\" />\n";
167 answer($c,$cont,"text/xml","");
168 } elsif ($http_method eq 'GET' and $http_path eq "/getdtd") {
169 my $filename = $inputuri;
170 $filename = $dtd_dir."/".$filename;
171 print "DTD: $inputuri ==> ($filename)\n";
172 if (stat($filename)) {
173 print "Using local copy\n";
174 open(FD, $filename) or die "Cannot open $filename\n";
177 # Vary bad heuristic for substituion of absolute URLs
179 s/ENTITY (.*) SYSTEM\s+"/ENTITY $1 SYSTEM "$myownurl\/getdtd?uri=/g;
183 answer($c,$cont,"text/xml","");
185 die "Could not find DTD!";
187 } elsif ($http_method eq 'GET' and $http_path eq "/getstyleconf") {
188 my $filename = $inputuri;
189 $filename = $style_dir."/config/".$filename;
190 if (stat($filename)) {
191 open(FD, $filename) or die "Cannot open $filename\n";
194 s/DOCTYPE (.*) SYSTEM\s+"/DOCTYPE $1 SYSTEM "$myownurl\/getstyleconf?uri=/g;
198 answer($c,$cont,"text/plain","");
200 die "Could not find Style Configuration File!";
202 } elsif ($http_method eq 'GET' and $http_path eq "/getxslt") {
203 my $filename = $inputuri;
204 $filename = $style_dir."/".$filename;
205 print "XSLT: $inputuri ==> ($filename)\n";
206 if (stat($filename)) {
207 print "Using local copy\n";
208 open(FD, $filename) or die "Cannot open $filename\n";
211 # Vary bad heuristic for substituion of absolute URLs
213 s/xsl:import\s+href="/xsl:import href="$myownurl\/getxslt?uri=/g ;
214 s/xsl:include\s+href="/xsl:include href="$myownurl\/getxslt?uri=/g ;
218 answer($c,$cont,"text/xml","");
220 die "Could not find XSLT!";
222 } elsif ($http_method eq 'GET' and $http_path eq "/update") {
223 # rebuild urls_of_uris.db
224 print "Update requested...\n";
226 kill(USR1,getppid()); # signal changes to parent
228 html_nice_answer($c,"Update done");
229 } elsif ($http_method eq 'GET' and $http_path eq "/ls") {
230 # send back keys that begin with a given uri
231 my ($uritype,$uripattern,$uriprefix);
232 my $baseuri = $cgi->param('baseuri');
233 chop $baseuri if ($baseuri =~ /.*\/$/); # remove trailing "/"
234 my $outype = $cgi->param('format'); # output type, might be 'txt' or 'xml'
235 $uripattern = $baseuri;
236 $uripattern =~ s/^.*:(.*)/$1/;
237 if ($baseuri =~ /^cic:/) {
239 } elsif ($baseuri =~ /^theory:/) {
242 $uritype = "invalid";
244 if ($uritype ne "invalid") { # uri is valid
245 if (($outype ne 'txt') and ($outype ne 'xml')) { # invalid out type
246 print "Invalid output type specified: $outype\n";
247 html_nice_answer($c,"Invalid output type, must be ".
249 } else { # valid output
250 print "BASEURI $baseuri, FORMAT $outype\n";
251 $cont = finduris($uritype,$uripattern,$outype);
252 if ($outype eq 'txt') {
253 answer($c,$cont,"text/plain","");
254 } elsif ($outype eq 'xml') {
255 answer($c,$cont,"text/xml","");
257 die "Internal error, exiting!";
260 } else { # invalid uri
261 print "Invalid uri: $baseuri, may begin with 'cic:', ".
262 "'theory:' or '*:'\n";
263 html_nice_answer($c,"Invalid uri , must begin with ".
264 "'cic:' or 'theory:'");
266 } elsif ($http_method eq 'GET' and $http_path eq "/help") {
267 print "Help requested!\n";
268 html_nice_answer($c,"HTTP Getter Version: $VERSION");
269 } elsif ($http_method eq 'GET' and $http_path =~ /\.cgi$/) {
270 print "CGI requested!\n";
271 if ($http_path !~ /^\/[^\/]*\.cgi$/) {
272 html_nice_answer($c,"Invalid CGI name: $http_path, ".
273 "you can't request CGI that contain a slash in the name\n");
274 } elsif (stat "$cgi_dir"."$http_path") {
275 if (not -x "$cgi_dir/$http_path") {
276 html_nice_answer($c,"CGI $http_path found but not ".
278 } else { # exec CGI and anser back its output
281 $ENV{'QUERY_STRING'} = $http_query;
282 my $cgi_output = `$cgi_dir/$http_path`;
283 answer($c,$cgi_output,"","");
287 html_nice_answer($c,"CGI '$http_path' not found ".
288 "in CGI dir '$cgi_dir'");
292 print "INVALID REQUEST!!!!!\n";
293 print "(PATH: ",$http_path,", ";
294 print "QUERY: ",$http_query,")\n";
295 $c->send_error(RC_FORBIDDEN)
297 print "\nRequest solved: ".$r->url."\n\n";
301 print "\nCONNECTION CLOSED\n\n";
306 #================================
308 sub finduris { # find uris for cic and theory trees generation
309 my ($uritype,$uripattern,$format) = @_;
311 my ($uri,$localpart,$basepart,$dirname,$suffix,$flags,$key);
312 my (@itemz,@already_pushed_dir);
313 my (%objects,%dirs); # map uris to suffixes' flags
314 #my $debug=1; # for debug
316 print "FINDURIS, uritype: $uritype, uripattern: $uripattern, ".
317 "format: $format\n\n" if defined($debug);
319 if (($uritype eq "cic") or ($uritype eq "theory")) {
320 # get info only of one type: cic or theory
321 foreach (keys(%map)) { # select matching uris
323 if ($uri =~ /^$uritype:$uripattern(\/|$|\.)/) {
324 if ($uri =~ /^$uritype:$uripattern\//) { # directory match
326 $localpart =~ s/^$uritype:$uripattern\/(.*)/$1/;
327 } elsif ($uri =~ /^$uritype:$uripattern($|\.)/) { # file match
329 $localpart =~ s/^.*\/([^\/]*)/$1/;
331 die "Internal error, seems that requested match is none of ".
332 "directory match or file match";
334 print "LOCALPART: $localpart\n" if defined($debug);
336 if ($localpart =~ /^[^\/]*$/) { # no slash, an OBJECT
337 $basepart = $localpart;
338 $basepart =~ s/^([^.]*\.[^.]*)(\.types)?(\.ann)?/$1/;
339 # remove exts .types or
341 $flags = $objects{$basepart}; # get old flags
342 if ($localpart =~ /\.ann$/) {
343 $flags = add_flag("ann","YES",$flags);
345 $flags = add_flag("ann","NO",$flags);
347 if ($localpart =~ /\.types$/) {
348 $flags = add_flag("types","YES",$flags);
349 } elsif ($localpart =~ /\.types\.ann$/) {
350 $flags = add_flag("types","ANN",$flags);
352 $flags = add_flag("types","NO",$flags);
354 $objects{$basepart} = $flags; # save new flags
355 } else { # exists at least one slash, a DIR
356 ($dirname) = split (/\//, $localpart);
357 $dirs{$dirname} = ""; # no flags requirement for dir
362 die "getter internal error: unsupported uritype: \"$uritype\"";
364 # now generate OUTPUT:
365 # output will be saved in $content
366 if ($format eq "txt") { # TXT output
367 foreach $key (sort(keys %dirs)) {
368 $content .= "dir, " . $key . "\n";
370 foreach $key (sort(keys %objects)) {
371 $content .= "object, $key, " . $objects{$key} . "\n";
373 } elsif ($format eq "xml") { # XML output
374 $content .= '<?xml version="1.0" encoding="ISO-8859-1"?>' . "\n";
375 $content .= "<!DOCTYPE ls SYSTEM ";
376 $content .= "\"$myownurl/getdtd?uri=ls.dtd\">" . "\n\n";
377 $content .= "<ls>\n";
378 foreach $key (sort(keys %dirs)) {
379 $content .= "\t<section>$key</section>\n";
381 foreach $key (sort(keys %objects)) {
382 $content .= "\t<object name=\"$key\">\n";
383 $flags = $objects{$key};
384 $flags =~ s/^<(.*)>$/$1/;
385 my ($annflag,$typesflag) = split /,/,$flags;
386 $content .= "\t\t<ann value=\"$annflag\" />\n";
387 $content .= "\t\t<types value=\"$typesflag\" />\n";
388 $content .= "\t</object>\n";
390 $content .= "</ls>\n";
391 } else { # may not enter this branch
392 die "Getter internal error: invalid format received by finduris sub";
398 # manage string like: "<ann_flag,type_flag>"
399 # "ann_flag" may be one of "ann_YES", "ann_NO"
400 # "type_flag" may be one of "types_NO", "types_YES", "types_ANN"
401 # when adding a flag the max between the current flag and the new flag
402 # is taken, the orders are ann_NO < ann_YES and types_NO < types_YES <
404 my ($flagtype,$newflag,$str) = @_;
405 $str = "<,>" if ($str eq "");
406 ($str =~ s/^<(.*,.*)>$/$1/) or die "Internal error: ".
407 "wrong string format for flag adding in $str";
408 my ($annflag,$typeflag) = split /,/,$str;
409 if ($flagtype eq "ann") { # ANN flag handling
410 if ($newflag eq "YES") {
412 } elsif ($newflag eq "NO") {
413 $annflag = "NO" unless ($annflag eq "YES");
415 die "Internal error: annflag must be \"YES\" or \"NO\"";
417 } elsif ($flagtype eq "types") { # TYPES flag handling
418 if ($newflag eq "ANN") {
420 } elsif ($newflag eq "YES") {
421 $typeflag = "YES" unless ($typeflag eq "ANN");
422 } elsif ($newflag eq "NO") {
424 unless (($typeflag eq "ANN") or ($typeflag eq "YES"));
426 die "Internal error: typeflag must be \"YES\", \"NO\" or \"ANN\"";
429 die "Internal error: unsupported flagtype \"$flagtype\"";
431 $str = "<$annflag,$typeflag>";
434 #CSC: Too much powerful: creates even /home, /home/users/, ...
435 #CSC: Does not raise errors if could not create dirs/files
439 my @dirs = split /\//,$pathname;
441 foreach $dir (@dirs) {
442 $tmp = ((defined($tmp)) ? $tmp."\/".$dir : "");
450 my ($str,$uri,$url,$filename) = @_;
451 print $str."uri: $uri\n";
452 print $str."url: $url\n";
453 print $str."filename: $filename\n\n";
462 sub gunzip { # gunzip a file and return the deflated content
465 my ($gz, $buffer, $cont);
467 print "deflating $filename ...\n";
468 $gz = gzopen($filename, "r")
469 or die "Cannot open gzip'ed file $filename: $gzerrno";
471 while ( $gz->gzread($buffer) > 0 ) {
474 die "Error while reading : $gzerrno\n" if $gzerrno != Z_STREAM_END ;
480 sub gzip { # gzip the content argument and save it to filename argument
481 my ($cont, $filename) = @_;
482 #my $debug=1; # debug only
484 print "gzopening $filename ...\n" if (defined($debug));
485 my $gz = gzopen($filename, "w")
486 or die "Cannot gzopen for writing file $filename: $gzerrno";
487 print "gzwriting ...\n" if (defined($debug));
488 $gz->gzwrite($cont) or die "error writing: $gzerrno, exiting!\n";
489 print "gzclosing ...\n" if (defined($debug));
494 my ($patch_dtd,$str,$url,$filename,$format) = @_;
497 #my $debug=1; # for DEBUG only
499 my $resourcetype; # retrieve mode: "normal" (.xml) or "gzipped" (.xml.gz)
500 if ($filename =~ /\.xml$/) { # set retrieve mode
501 $resourcetype = "normal";
502 } elsif ($filename =~ /\.xml\.gz$/) {
503 $resourcetype = "gzipped";
505 die "Unsupported download extension, might be '.gz' or '.xml'\n";
507 my $basefname = $filename;
508 $basefname =~ s/\.gz$//; # get base resource name removing trailing .gz
509 $cont = ""; # modified by side-effect by the callback function
512 if (stat($basefname)) {
513 $localfname=$basefname;
514 } elsif (stat($basefname.".gz")) {
515 $localfname=$basefname.".gz";
517 if ($localfname ne "") { # we already have local copy of requested file
518 # check both possible cache entry: gzipped or normal
519 print "Using local copy for the $str file\n";
520 if ($localfname =~ /\.xml\.gz$/) { # deflating cached file and return it
521 $cont = gunzip($localfname);
522 } elsif ($localfname =~ /\.xml$/) { # just return cached file
523 open(FD, $localfname) or die "Cannot open $localfname";
524 while(<FD>) { $cont .= $_; }
527 die "Internal error: unexpected file name $localfname,"
528 ."must end with '.gz' or '.xml.gz'\n";
530 } else { # download file from net
531 print "Downloading the $str file\n"; # download file
532 my $ua = LWP::UserAgent->new;
533 my $request = HTTP::Request->new(GET => "$url");
534 my $response = $ua->request($request, \&callback);
536 # cache retrieved file to disk
537 # <ZACK/> TODO: inefficent, I haven't yet undestood how to deflate
538 # in memory gzipped file, without call "gzopen"
539 print "Storing the $str file\n";
540 print "Making dirs ...\n" if (defined($debug));
542 print "Opening tmp file for writing ...\n" if (defined($debug));
543 open(FD, ">".$filename.".tmp") or die "Cannot open $filename.tmp\n";
544 print "Writing on tmp file ...\n" if (defined($debug));
546 print "Closing tmp file ...\n" if (defined($debug));
549 # handle cache conversion normal->gzipped or gzipped->normal as user choice
550 print "cachemode:$cachemode, resourcetype:$resourcetype\n" if (defined($debug));
551 if (($cachemode eq 'normal') and ($resourcetype eq 'normal')) {
552 # cache the file as is
553 rename "$filename.tmp", $filename;
554 } elsif (($cachemode eq 'gzipped') and ($resourcetype eq 'gzipped')) {
555 # cache the file as is
556 # and update the $cont variabile with deflated content
557 rename "$filename.tmp", $filename;
558 $cont = gunzip($filename);
559 } elsif (($cachemode eq 'normal') and ($resourcetype eq 'gzipped')) {
560 # deflate cache entry
562 open(FD, "> $basefname") or die "cannot open $basefname\n";
563 $cont = gunzip($filename.".tmp");
566 unlink "$filename.tmp"; # delete old gzipped file
567 } elsif (($cachemode eq 'gzipped') and ($resourcetype eq 'normal')) {
568 # compress cache entry
569 print "gzipping ...\n" if (defined($debug));
570 gzip($cont, $basefname.".gz");
571 unlink "$filename.tmp"; # delete old uncompressed file
573 die "Internal error, unsopported cachemode, resourcetype couple\n";
575 # $cont now contained uncompressed data
577 if ($patch_dtd eq "yes") {
578 $cont =~ s/DOCTYPE (.*) SYSTEM\s+"http:\/\/www.cs.unibo.it\/helm\/dtd\//DOCTYPE $1 SYSTEM "$myownurl\/getdtd?uri=/g;
580 if ($format eq "gz") {
581 gzip($cont,"$basefname.tmp");
582 open (TMP, "< $basefname.tmp")
583 or die "Can't open tempfile: $filename.tmp, exiting!\n";
589 unlink ($basefname . ".tmp") or
590 die "cannot unlink temporary file: $basefname.tmp\n";
597 # answer the client setting content, Content-Type and Content-Enconding
599 my ($c,$cont,$contype,$contenc) = @_;
600 my $res = new HTTP::Response;
601 $res->content($cont);
602 $res->push_header("Content-Type" => $contype)
603 unless ($contype eq "");
604 $res->push_header("Content-Encoding" => $contenc)
605 unless ($contenc eq "");
606 $c->send_response($res);
609 sub html_nice_answer {
610 # answer the client whith a nice html document
611 my ($c,$content) = @_;
612 $content = "<html><body><h1>$content</h1></body></html>";
613 answer($c,$content,"text/html","");
617 #retrieve a file from an url and write it to a temp dir
618 #used for retrieve resource index from servers
620 my ($prefix, $URL) = @_;
621 my $ua = LWP::UserAgent->new;
622 my $request = HTTP::Request->new(GET => "$URL");
623 my $response = $ua->request($request, \&callback);
624 my ($filename) = reverse (split "/", $URL); # get filename part of the URL
625 open (TEMP, "> $prefix/$filename")
626 || die "Cannot open temporary file: $prefix/$filename\n";
633 tie(%map, 'DB_File', $uris_dbm.".db", O_RDONLY, 0664);
636 sub mk_urls_of_uris {
637 #rebuild $uris_dbm.db fetching resource indexes from servers
639 $server, $idxfile, $uri, $url, $comp, $line,
645 if (stat $uris_dbm.".db") { # remove old db file
646 unlink($uris_dbm.".db") or
647 die "cannot unlink old db file: $uris_dbm.db\n";
649 tie(%urls_of_uris, 'DB_File', $uris_dbm.".db", O_RDWR|O_CREAT, 0664);
651 open (SRVS, "< $servers_file") or
652 die "cannot open servers file: $servers_file\n";
655 while ($server = pop @servers) { #cicle on servers in reverse order
656 print "processing server: $server ...\n";
658 helm_wget($tmp_dir, $server."/".$indexname); #get index
659 $idxfile = $tmp_dir."/".$indexname;
660 open (INDEX, "< $idxfile") or
661 die "cannot open temporary index file: $idxfile\n";
662 while ($line = <INDEX>) { #parse index and add entry to urls_of_uris
664 ($uri,$comp) = split /[ \t]+/, $line;
667 $url = $uri . ".xml" . ".gz";
669 $url = $uri . ".xml";
671 $url =~ s/cic:/$server/;
672 $url =~ s/theory:/$server/;
673 $urls_of_uris{$uri} = $url;
676 die "cannot unlink temporary file: $idxfile\n"
677 if (unlink $idxfile) != 1;
680 untie(%urls_of_uris);
681 tie(%map, 'DB_File', $uris_dbm.".db", O_RDONLY, 0664);