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
315 print "FINDURIS, uritype: $uritype, uripattern: $uripattern, ".
316 "format: $format\n\n";
318 if (($uritype eq "cic") or ($uritype eq "theory")) {
319 # get info only of one type: cic or theory
320 foreach (keys(%map)) { # select matching uris
322 if ($uri =~ /^$uritype:$uripattern\//) {
324 $localpart =~ s/^$uritype:$uripattern\/(.*)/$1/;
326 if ($localpart =~ /^[^\/]*$/) { # no slash, an OBJECT
327 $basepart = $localpart;
328 $basepart =~ s/^([^.]*\.[^.]*)(\.types)?(\.ann)?/$1/; # remove exts .types or
330 $flags = $objects{$basepart}; # get old flags
331 if ($localpart =~ /\.ann$/) {
332 $flags = add_flag("ann","YES",$flags);
334 $flags = add_flag("ann","NO",$flags);
336 if ($localpart =~ /\.types$/) {
337 $flags = add_flag("types","YES",$flags);
338 } elsif ($localpart =~ /\.types\.ann$/) {
339 $flags = add_flag("types","ANN",$flags);
341 $flags = add_flag("types","NO",$flags);
343 $objects{$basepart} = $flags; # save new flags
344 } else { # exists at least one slash, a DIR
345 ($dirname) = split (/\//, $localpart);
346 $dirs{$dirname} = ""; # no flags requirement for dir
351 die "getter internal error: unsupported uritype: \"$uritype\"";
353 # now generate OUTPUT:
354 # output will be saved in $content
355 if ($format eq "txt") { # TXT output
356 foreach $key (sort(keys %dirs)) {
357 $content .= "dir, " . $key . "\n";
359 foreach $key (sort(keys %objects)) {
360 $content .= "object, $key, " . $objects{$key} . "\n";
362 } elsif ($format eq "xml") { # XML output
363 $content .= '<?xml version="1.0" encoding="ISO-8859-1"?>' . "\n";
364 $content .= "<!DOCTYPE ls SYSTEM ";
365 $content .= "\"$myownurl/getdtd?uri=ls.dtd\">" . "\n\n";
366 $content .= "<ls>\n";
367 foreach $key (sort(keys %dirs)) {
368 $content .= "\t<section>$key</section>\n";
370 foreach $key (sort(keys %objects)) {
371 $content .= "\t<object name=\"$key\">\n";
372 $flags = $objects{$key};
373 $flags =~ s/^<(.*)>$/$1/;
374 my ($annflag,$typesflag) = split /,/,$flags;
375 $content .= "\t\t<ann value=\"$annflag\" />\n";
376 $content .= "\t\t<types value=\"$typesflag\" />\n";
377 $content .= "\t</object>\n";
379 $content .= "</ls>\n";
380 } else { # may not enter this branch
381 die "Getter internal error: invalid format received by finduris sub";
387 # manage string like: "<ann_flag,type_flag>"
388 # "ann_flag" may be one of "ann_YES", "ann_NO"
389 # "type_flag" may be one of "types_NO", "types_YES", "types_ANN"
390 # when adding a flag the max between the current flag and the new flag
391 # is taken, the orders are ann_NO < ann_YES and types_NO < types_YES <
393 my ($flagtype,$newflag,$str) = @_;
394 $str = "<,>" if ($str eq "");
395 ($str =~ s/^<(.*,.*)>$/$1/) or die "Internal error: ".
396 "wrong string format for flag adding in $str";
397 my ($annflag,$typeflag) = split /,/,$str;
398 if ($flagtype eq "ann") { # ANN flag handling
399 if ($newflag eq "YES") {
401 } elsif ($newflag eq "NO") {
402 $annflag = "NO" unless ($annflag eq "YES");
404 die "Internal error: annflag must be \"YES\" or \"NO\"";
406 } elsif ($flagtype eq "types") { # TYPES flag handling
407 if ($newflag eq "ANN") {
409 } elsif ($newflag eq "YES") {
410 $typeflag = "YES" unless ($typeflag eq "ANN");
411 } elsif ($newflag eq "NO") {
413 unless (($typeflag eq "ANN") or ($typeflag eq "YES"));
415 die "Internal error: typeflag must be \"YES\", \"NO\" or \"ANN\"";
418 die "Internal error: unsupported flagtype \"$flagtype\"";
420 $str = "<$annflag,$typeflag>";
423 #CSC: Too much powerful: creates even /home, /home/users/, ...
424 #CSC: Does not raise errors if could not create dirs/files
428 my @dirs = split /\//,$pathname;
430 foreach $dir (@dirs) {
431 $tmp = ((defined($tmp)) ? $tmp."\/".$dir : "");
439 my ($str,$uri,$url,$filename) = @_;
440 print $str."uri: $uri\n";
441 print $str."url: $url\n";
442 print $str."filename: $filename\n\n";
451 sub gunzip { # gunzip a file and return the deflated content
454 my ($gz, $buffer, $cont);
456 print "deflating $filename ...\n";
457 $gz = gzopen($filename, "r")
458 or die "Cannot open gzip'ed file $filename: $gzerrno";
460 while ( $gz->gzread($buffer) > 0 ) {
463 die "Error while reading : $gzerrno\n" if $gzerrno != Z_STREAM_END ;
469 sub gzip { # gzip the content argument and save it to filename argument
470 my ($cont, $filename) = @_;
471 #my $debug=1; # debug only
473 print "gzopening $filename ...\n" if (defined($debug));
474 my $gz = gzopen($filename, "w")
475 or die "Cannot gzopen for writing file $filename: $gzerrno";
476 print "gzwriting ...\n" if (defined($debug));
477 $gz->gzwrite($cont) or die "error writing: $gzerrno, exiting!\n";
478 print "gzclosing ...\n" if (defined($debug));
483 my ($patch_dtd,$str,$url,$filename,$format) = @_;
486 #my $debug=1; # for DEBUG only
488 my $resourcetype; # retrieve mode: "normal" (.xml) or "gzipped" (.xml.gz)
489 if ($filename =~ /\.xml$/) { # set retrieve mode
490 $resourcetype = "normal";
491 } elsif ($filename =~ /\.xml\.gz$/) {
492 $resourcetype = "gzipped";
494 die "Unsupported download extension, might be '.gz' or '.xml'\n";
496 my $basefname = $filename;
497 $basefname =~ s/\.gz$//; # get base resource name removing trailing .gz
498 $cont = ""; # modified by side-effect by the callback function
501 if (stat($basefname)) {
502 $localfname=$basefname;
503 } elsif (stat($basefname.".gz")) {
504 $localfname=$basefname.".gz";
506 if ($localfname ne "") { # we already have local copy of requested file
507 # check both possible cache entry: gzipped or normal
508 print "Using local copy for the $str file\n";
509 if ($localfname =~ /\.xml\.gz$/) { # deflating cached file and return it
510 $cont = gunzip($localfname);
511 } elsif ($localfname =~ /\.xml$/) { # just return cached file
512 open(FD, $localfname) or die "Cannot open $localfname";
513 while(<FD>) { $cont .= $_; }
516 die "Internal error: unexpected file name $localfname,"
517 ."must end with '.gz' or '.xml.gz'\n";
519 } else { # download file from net
520 print "Downloading the $str file\n"; # download file
521 my $ua = LWP::UserAgent->new;
522 my $request = HTTP::Request->new(GET => "$url");
523 my $response = $ua->request($request, \&callback);
525 # cache retrieved file to disk
526 # <ZACK/> TODO: inefficent, I haven't yet undestood how to deflate
527 # in memory gzipped file, without call "gzopen"
528 print "Storing the $str file\n";
529 print "Making dirs ...\n" if (defined($debug));
531 print "Opening tmp file for writing ...\n" if (defined($debug));
532 open(FD, ">".$filename.".tmp") or die "Cannot open $filename.tmp\n";
533 print "Writing on tmp file ...\n" if (defined($debug));
535 print "Closing tmp file ...\n" if (defined($debug));
538 # handle cache conversion normal->gzipped or gzipped->normal as user choice
539 print "cachemode:$cachemode, resourcetype:$resourcetype\n" if (defined($debug));
540 if (($cachemode eq 'normal') and ($resourcetype eq 'normal')) {
541 # cache the file as is
542 rename "$filename.tmp", $filename;
543 } elsif (($cachemode eq 'gzipped') and ($resourcetype eq 'gzipped')) {
544 # cache the file as is
545 # and update the $cont variabile with deflated content
546 rename "$filename.tmp", $filename;
547 $cont = gunzip($filename);
548 } elsif (($cachemode eq 'normal') and ($resourcetype eq 'gzipped')) {
549 # deflate cache entry
551 open(FD, "> $basefname") or die "cannot open $basefname\n";
552 $cont = gunzip($filename.".tmp");
555 unlink "$filename.tmp"; # delete old gzipped file
556 } elsif (($cachemode eq 'gzipped') and ($resourcetype eq 'normal')) {
557 # compress cache entry
558 print "gzipping ...\n" if (defined($debug));
559 gzip($cont, $basefname.".gz");
560 unlink "$filename.tmp"; # delete old uncompressed file
562 die "Internal error, unsopported cachemode, resourcetype couple\n";
564 # $cont now contained uncompressed data
566 if ($patch_dtd eq "yes") {
567 $cont =~ s/DOCTYPE (.*) SYSTEM\s+"http:\/\/www.cs.unibo.it\/helm\/dtd\//DOCTYPE $1 SYSTEM "$myownurl\/getdtd?uri=/g;
569 if ($format eq "gz") {
570 gzip($cont,"$basefname.tmp");
571 open (TMP, "< $basefname.tmp")
572 or die "Can't open tempfile: $filename.tmp, exiting!\n";
578 unlink ($basefname . ".tmp") or
579 die "cannot unlink temporary file: $basefname.tmp\n";
586 # answer the client setting content, Content-Type and Content-Enconding
588 my ($c,$cont,$contype,$contenc) = @_;
589 my $res = new HTTP::Response;
590 $res->content($cont);
591 $res->push_header("Content-Type" => $contype)
592 unless ($contype eq "");
593 $res->push_header("Content-Encoding" => $contenc)
594 unless ($contenc eq "");
595 $c->send_response($res);
598 sub html_nice_answer {
599 # answer the client whith a nice html document
600 my ($c,$content) = @_;
601 $content = "<html><body><h1>$content</h1></body></html>";
602 answer($c,$content,"text/html","");
606 #retrieve a file from an url and write it to a temp dir
607 #used for retrieve resource index from servers
609 my ($prefix, $URL) = @_;
610 my $ua = LWP::UserAgent->new;
611 my $request = HTTP::Request->new(GET => "$URL");
612 my $response = $ua->request($request, \&callback);
613 my ($filename) = reverse (split "/", $URL); # get filename part of the URL
614 open (TEMP, "> $prefix/$filename")
615 || die "Cannot open temporary file: $prefix/$filename\n";
622 tie(%map, 'DB_File', $uris_dbm.".db", O_RDONLY, 0664);
625 sub mk_urls_of_uris {
626 #rebuild $uris_dbm.db fetching resource indexes from servers
628 $server, $idxfile, $uri, $url, $comp, $line,
634 if (stat $uris_dbm.".db") { # remove old db file
635 unlink($uris_dbm.".db") or
636 die "cannot unlink old db file: $uris_dbm.db\n";
638 tie(%urls_of_uris, 'DB_File', $uris_dbm.".db", O_RDWR|O_CREAT, 0664);
640 open (SRVS, "< $servers_file") or
641 die "cannot open servers file: $servers_file\n";
644 while ($server = pop @servers) { #cicle on servers in reverse order
645 print "processing server: $server ...\n";
647 helm_wget($tmp_dir, $server."/".$indexname); #get index
648 $idxfile = $tmp_dir."/".$indexname;
649 open (INDEX, "< $idxfile") or
650 die "cannot open temporary index file: $idxfile\n";
651 while ($line = <INDEX>) { #parse index and add entry to urls_of_uris
653 ($uri,$comp) = split /[ \t]+/, $line;
656 $url = $uri . ".xml" . ".gz";
658 $url = $uri . ".xml";
660 $url =~ s/cic:/$server/;
661 $url =~ s/theory:/$server/;
662 $urls_of_uris{$uri} = $url;
665 die "cannot unlink temporary file: $idxfile\n"
666 if (unlink $idxfile) != 1;
669 untie(%urls_of_uris);
670 tie(%map, 'DB_File', $uris_dbm.".db", O_RDONLY, 0664);