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/.
26 my $VERSION = "@VERSION@";
28 # First of all, let's load HELM configuration
30 my $HELM_LIB_DIR = $ENV{"HELM_LIB_DIR"};
31 # this should be the only fixed constant
32 my $DEFAULT_HELM_LIB_DIR = "@HELM_LIB_DIR@";
33 if (defined ($HELM_LIB_DIR)) {
34 $HELM_LIB_PATH = $HELM_LIB_DIR."/configuration.pl";
36 $HELM_LIB_PATH = $DEFAULT_HELM_LIB_DIR."/configuration.pl";
39 # <ZACK>: TODO temporary, move this setting to configuration file
40 # set the cache mode, may be "gzipped" or "normal"
41 my $cachemode = $ENV{'HTTP_GETTER_CACHE_MODE'} || 'gzipped';
42 if (($cachemode ne 'gzipped') and ($cachemode ne 'normal')) {
43 die "Invalid HTTP_GETTER_CACHE_MODE environment variable, must be".
44 "'normal' or 'gzipped'\n";
48 # next require defines: $helm_dir, $html_link, $dtd_dir, $uris_dbm
49 require $HELM_LIB_PATH;
51 # Let's override the configuration file
52 $style_dir = $ENV{"HELM_STYLE_DIR"} if (defined ($ENV{"HELM_STYLE_DIR"}));
53 $dtd_dir = $ENV{"HELM_DTD_DIR"} if (defined ($ENV{"HELM_DTD_DIR"}));
64 #CSC: mancano i controlli sulle condizioni di errore di molte funzioni
65 #CSC: ==> non e' robusto
66 #CSC: altra roba da sistemare segnata con CSC
68 my $d = new HTTP::Daemon LocalPort => 8081;
69 my $myownurl = $d->url;
71 # Let's patch the returned URL
72 $myownurl =~ s/\/$//; # chop the final slash
73 my $myownport = $myownurl;
74 $myownport =~ s/http:\/\/(.*):(.*)/$2/;
75 $myownurl =~ s/http:\/\/(.*):(.*)/$1/;
76 ($myownurl) = gethostbyname($myownurl);
77 $myownurl = "http://".$myownurl.":".$myownport;
79 tie(%map, 'DB_File', $uris_dbm.".db", O_RDONLY, 0664);
80 print "Please contact me at: <URL:", $myownurl."/", ">\n";
81 print "helm_dir: $helm_dir\n";
82 print "style_dir: $style_dir\n";
83 print "dtd_dir: $dtd_dir\n";
84 print "urls_of_uris.db: $uris_dbm.db\n";
85 print "cache mode: $cachemode\n";
87 $SIG{CHLD} = "IGNORE"; # do not accumulate defunct processes
88 $SIG{USR1} = \&update; # sent by the child to make the parent update
89 while (my $c = $d->accept) {
91 while (my $r = $c->get_request) {
92 #CSC: mancano i controlli di sicurezza
94 my $inputuri = uri_unescape($r->url);
95 $inputuri =~ s/^[^?]*\?uri=(.*)/$1/;
96 print "\nRequest: ".$r->url."\n\n";
97 my $http_method = $r->method;
98 my $http_path = $r->url->path;
99 my $http_query = uri_unescape($r->url->query);
100 my $cgi = new CGI("$http_query");
102 print "\nUnescaped query: ".$http_query."\n";
104 if ($http_method eq 'GET' and $http_path eq "/getciconly") {
105 # finds the uri, url and filename
106 my $cicuri = $inputuri;
108 my $cicfilename = $cicuri;
109 $cicfilename =~ s/cic:(.*)/$1/;
110 $cicfilename =~ s/theory:(.*)/$1/;
112 my $cicurl = $map{$cicuri};
114 if ($cicurl =~ /\.xml$/) { # non gzipped file
116 } elsif ($cicurl =~ /\.xml\.gz$/) { # gzipped file
117 $extension = ".xml.gz";
118 } else { # error: unknown extension
119 die "unexpected extension in url: $cicurl, might be '.xml'".
122 $cicfilename = $helm_dir.$cicfilename.$extension;
124 if (!defined($cicurl)) {
125 print "\nNOT FOUND!!!!!\n";
126 $c->send_error(RC_NOT_FOUND)
128 print_request("cic",$cicuri,$cicurl,$cicfilename);
131 my $ciccontent = download(0,"cic",$cicurl,$cicfilename);
133 # Answering the client
134 answer($c,$ciccontent);
136 } elsif ($http_method eq 'GET' and $http_path eq "/get") {
137 # finds the uris, urls and filenames
138 my $cicuri = $inputuri,
139 $typesuri = $inputuri,
142 if ($inputuri =~ /\.types$/) {
143 $cicuri =~ s/(.*)\.types$/$1/;
145 } elsif ($inputuri =~ /\.types\.ann$/) {
146 $cicuri =~ s/(.*)\.types\.ann$/$1/;
147 $typesuri =~ s/(.*)\.ann$/$1/;
148 $annsuffix = ".types.ann";
149 } elsif ($inputuri =~ /\.ann$/) {
150 $cicuri =~ s/(.*)\.ann$/$1/;
158 my $cicfilename = $cicuri;
159 $cicfilename =~ s/cic:(.*)/$1/;
160 $cicfilename =~ s/theory:(.*)/$1/;
161 $cicfilename = $helm_dir.$cicfilename;
163 my $cicurl = $map{$cicuri};
164 my $typesurl = $map{$typesuri} if (defined($typesuri));
165 my $annurl = $map{$annuri} if (defined($annuri));
166 my ($cicext, $typesext, $annext);
167 if ($cicurl =~ /\.xml$/) { # normal file
169 } elsif ($cicurl =~ /\.xml\.gz$/) { # gzipped file
172 die "unexpected extension in url: $cicurl;".
173 "might be '.xml' or '.xml.gz'";
175 if (defined($typesuri)) { # extension selection for types file
176 if ($typesurl =~ /\.xml$/) { # normal file
177 $typesext = ".types.xml";
178 } elsif ($typesurl =~ /\.xml\.gz$/) { # gzipped file
179 $typesext = ".types.xml.gz";
181 die "unexpected extension in url: $typesurl;".
182 "might be '.xml' or '.xml.gz'";
185 if (defined($annuri)) { # extension selection for annotation file
186 if ($annurl =~ /\.xml$/) { # normal file
188 } elsif ($annurl =~ /\.xml\.gz$/) { # gzipped file
191 die "unexpected extension in url: $annurl".
192 "might be '.xml' or '.xml.gz'";
195 my $typesfilename = $cicfilename.$typesext if $typesuri;
196 my $annfilename = $cicfilename.$annsuffix.$annext if $annuri;
197 $cicfilename .= $cicext;
199 if (!defined($cicurl) ||
200 (!defined($typesurl) && $typesuri) ||
201 (!defined($annuri) && $annuri))
203 print "\nNOT FOUND!!!!!\n";
204 $c->send_error(RC_NOT_FOUND)
206 print_request("cic",$cicuri,$cicurl,$cicfilename);
207 print_request("types",$typesuri,$typesurl,$typesfilename)
209 print_request("ann",$annuri,$annurl,$annfilename)
212 # Retrieves the files
214 my $ciccontent = download(1,"cic",$cicurl,$cicfilename);
216 download(1,"types",$typesurl,$typesfilename) if ($typesuri);
218 download(1,"ann",$annurl,$annfilename) if ($annuri);
220 # Merging the files together
223 <?xml version="1.0" encoding="UTF-8"?>
224 <cicxml uri="$cicuri">
231 # Answering the client
234 } elsif ($http_method eq 'GET' and $http_path eq "/getdtd") {
235 my $filename = $inputuri;
236 $filename = $dtd_dir."/".$filename;
237 print "DTD: $inputuri ==> ($filename)\n";
238 if (stat($filename)) {
239 print "Using local copy\n";
240 open(FD, $filename) or die "Cannot open $filename\n";
243 # Vary bad heuristic for substituion of absolute URLs
245 s/ENTITY (.*) SYSTEM\s+"/ENTITY $1 SYSTEM "$myownurl\/getdtd?uri=/g;
251 die "Could not find DTD!";
253 } elsif ($http_method eq 'GET' and $http_path eq "/getstyleconf") {
254 my $filename = $inputuri;
255 $filename = $style_dir."/config/".$filename;
256 if (stat($filename)) {
257 open(FD, $filename) or die "Cannot open $filename\n";
260 s/DOCTYPE (.*) SYSTEM\s+"/DOCTYPE $1 SYSTEM "$myownurl\/getstyleconf?uri=/g;
266 die "Could not find Style Configuration File!";
268 } elsif ($http_method eq 'GET' and $http_path eq "/getxslt") {
269 my $filename = $inputuri;
270 $filename = $style_dir."/".$filename;
271 print "XSLT: $inputuri ==> ($filename)\n";
272 if (stat($filename)) {
273 print "Using local copy\n";
274 open(FD, $filename) or die "Cannot open $filename\n";
277 # Vary bad heuristic for substituion of absolute URLs
279 s/xsl:import\s+href="/xsl:import href="$myownurl\/getxslt?uri=/g ;
280 s/xsl:include\s+href="/xsl:include href="$myownurl\/getxslt?uri=/g ;
286 die "Could not find XSLT!";
288 } elsif ($http_method eq 'GET' and $http_path eq "/conf") {
289 my $quoted_html_link = $html_link;
290 $quoted_html_link =~ s/&/&/g;
291 $quoted_html_link =~ s/</</g;
292 $quoted_html_link =~ s/>/>/g;
293 $quoted_html_link =~ s/'/'/g;
294 $quoted_html_link =~ s/"/"/g;
295 print "\nConfiguration requested, returned #$quoted_html_link#\n";
296 $cont = "<?xml version=\"1.0\"?><html_link>$quoted_html_link</html_link>";
298 } elsif ($http_method eq 'GET' and $http_path eq "/update") {
299 # rebuild urls_of_uris.db
300 print "Update requested...\n";
302 kill(USR1,getppid()); # signal changes to parent
304 answer($c,"<html><body><h1>Update done</h1></body></html>");
305 } elsif ($http_method eq 'GET' and $http_path eq "/ls") {
306 # send back keys that begin with a given uri
307 my ($uritype,$uripattern,$uriprefix);
308 my $baseuri = $cgi->param('baseuri');
309 chop $baseuri if ($baseuri =~ /.*\/$/); # remove trailing "/"
310 my $outype = $cgi->param('format'); # output type, might be 'txt' or 'xml'
311 $uripattern = $baseuri;
312 $uripattern =~ s/^.*:(.*)/$1/;
313 if ($baseuri =~ /^cic:/) {
315 } elsif ($baseuri =~ /^theory:/) {
317 } elsif ($baseuri =~ /^\*:/) {
320 $uritype = "invalid";
322 if ($uritype ne "invalid") { # uri is valid
323 if (($outype ne 'txt') and ($outype ne 'xml')) { # invalid out type
324 print "Invalid output type specified: $outype\n";
325 answer($c,"<html><body><h1>Invalid output type, may be ".
326 "\"txt\" or \"xml\"</h1></body></html>");
327 } else { # valid output
328 print "BASEURI $baseuri, FORMAT $outype\n";
329 $cont = finduris($uritype,$uripattern,$outype);
332 } else { # invalid uri
333 print "Invalid uri: $baseuri, may begin with 'cic:', ".
334 "'theory:' or '*:'\n";
335 answer($c,"<html><body><h1>Invalid uri , may begin with ".
336 "\"cic:\", \"theory:\" or \"*:\"</h1></body></html>");
338 } elsif ($http_method eq 'GET' and $http_path eq "/version") {
339 print "Version requested!";
340 answer($c,"<html><body><h1>HTTP Getter Version ".
341 $VERSION."</h1></body></html>");
344 print "INVALID REQUEST!!!!!\n";
345 print "(PATH: ",$http_path,", ";
346 print "QUERY: ",$http_query,")\n";
347 $c->send_error(RC_FORBIDDEN)
349 print "\nRequest solved: ".$r->url."\n\n";
353 print "\nCONNECTION CLOSED\n\n";
358 #================================
360 sub finduris { # find uris for cic and theory trees generation
361 my ($uritype,$uripattern,$format) = @_;
363 my ($uri,$localpart,$dirname);
364 my (@itemz,@already_pushed_dir);
366 print "FINDURIS, uritype: $uritype, uripattern: $uripattern, ".
367 "format: $format\n\n";
369 if (($uritype eq "cic") or ($uritype eq "theory")) {
370 # get info only of one type: cic or theory
371 foreach (keys(%map)) { # select matching uris
373 if ($uri =~ /^$uritype:$uripattern\//) {
375 $localpart =~ s/^$uritype:$uripattern\/(.*)/$1/;
376 if ($localpart =~ /^[^\/]*$/) { # no slash, i.e. no dir
377 push @itemz, "object," . $localpart;
378 } else { # exists at least one slash, i.e. a dir
379 ($dirname) = split (/\//, $localpart);
380 push @itemz, "dir," . $dirname;
381 #print "LOCALPART $localpart, DIRNAME $dirname\n"; #DEBUG
385 } elsif ($uritype eq "any") { # get info for both cic and theory
386 foreach (keys(%map)) {
390 die "getter internal error: unsupported uritype: \"$uritype\"";
392 @itemz = sort @itemz; # sort itemz and remove duplicates
394 if ($format eq "txt") { #now generate output
396 next if ($_ eq $last);
397 $content .= ($_ . "\n");
400 } elsif ($format eq "xml") {
401 $content .= "<ls>\n";
403 next if ($_ eq $last);
405 ($itemtype,$itemdata) = split(/,/, $_);
406 if ($itemtype eq "object") {
407 $content .= "<object type=\"$uritype\">$itemdata</object>\n";
408 } elsif ($itemtype eq "dir") {
409 $content .= "<section>$itemdata</section>\n";
412 $content .= "</ls>\n"
413 } else { # may not enter this branch
414 die "Getter internal error: invalid format received by finduris sub";
419 #CSC: Too much powerful: creates even /home, /home/users/, ...
420 #CSC: Does not raise errors if could not create dirs/files
424 my @dirs = split /\//,$pathname;
426 foreach $dir (@dirs) {
427 $tmp = ((defined($tmp)) ? $tmp."\/".$dir : "");
435 my ($str,$uri,$url,$filename) = @_;
436 print $str."uri: $uri\n";
437 print $str."url: $url\n";
438 print $str."filename: $filename\n\n";
447 sub gunzip { # gunzip a file and return the deflated content
450 my ($gz, $buffer, $cont);
452 print "deflating $filename ...\n";
453 $gz = gzopen($filename, "r")
454 or die "Cannot open gzip'ed file $filename: $gzerrno";
456 while ( $gz->gzread($buffer) > 0 ) {
459 die "Error while reading : $gzerrno\n" if $gzerrno != Z_STREAM_END ;
465 sub gzip { # gzip the content argument and save it to filename argument
466 my ($cont, $filename) = @_;
470 $gz = gzopen($filename, "w")
471 or die "Cannot gzopen for writing file $filename: $gzerrno";
472 $gz->gzwrite($cont) or die "error writing: $gzerrno\n" ;
478 my ($remove_headers,$str,$url,$filename) = @_;
481 my $resourcetype; # retrieve mode: "normal" (.xml) or "gzipped" (.xml.gz)
482 if ($filename =~ /\.xml$/) { # set retrieve mode
483 $resourcetype = "normal";
484 } elsif ($filename =~ /\.xml\.gz$/) {
485 $resourcetype = "gzipped";
487 die "Unsupported download extension, might be '.gz' or '.xml'\n";
489 my $basefname = $filename;
490 $basefname =~ s/\.gz$//; # get base resource name removing trailing .gz
491 $cont = ""; # modified by side-effect by the callback function
494 if (stat($basefname)) {
495 $localfname=$basefname;
496 } elsif (stat($basefname.".gz")) {
497 $localfname=$basefname.".gz";
499 if ($localfname ne "") { # we already have local copy of requested file
500 # check both possible cache entry: gzipped or normal
501 print "Using local copy for the $str file\n";
502 if ($localfname =~ /\.xml\.gz$/) { # deflating cached file and return it
503 $cont = gunzip($localfname);
504 } elsif ($localfname =~ /\.xml$/) { # just return cached file
505 open(FD, $localfname) or die "Cannot open $localfname";
506 while(<FD>) { $cont .= $_; }
509 die "Internal error: unexpected file name $localfname,"
510 ."must end with '.gz' or '.xml.gz'\n";
512 } else { # download file from net
513 print "Downloading the $str file\n"; # download file
514 my $ua = LWP::UserAgent->new;
515 my $request = HTTP::Request->new(GET => "$url");
516 my $response = $ua->request($request, \&callback);
518 # cache retrieved file to disk
519 # <ZACK/> TODO: inefficent, I haven't yet undestood how to deflate
520 # in memory gzipped file, without call "gzopen"
521 print "Storing the $str file\n";
523 open(FD, ">".$filename.".tmp") or die "Cannot open $filename.tmp\n";
527 # handle cache conversion normal->gzipped or gzipped->normal as user choice
528 if (($cachemode eq 'normal') and ($resourcetype eq 'normal')) {
529 # cache the file as is
530 rename "$filename.tmp", $filename;
531 } elsif (($cachemode eq 'gzipped') and ($resourcetype eq 'gzipped')) {
532 # cache the file as is
533 # and update the $cont variabile with deflated content
534 rename "$filename.tmp", $filename;
535 $cont = gunzip($filename);
536 } elsif (($cachemode eq 'normal') and ($resourcetype eq 'gzipped')) {
537 # deflate cache entry
539 open(FD, "> $basefname") or die "cannot open $basefname\n";
540 $cont = gunzip($filename.".tmp");
543 unlink "$filename.tmp"; # delete old gzipped file
544 } elsif (($cachemode eq 'gzipped') and ($resourcetype eq 'normal')) {
545 # compress cache entry
546 gzip($cont, $basefname.".gz");
547 unlink "$filename.tmp"; # delete old uncompressed file
549 die "Internal error, unsopported cachemode, resourcetype couple\n";
551 # $cont now contained uncompressed data
554 if ($remove_headers) {
555 $cont =~ s/<\?xml [^?]*\?>//sg;
556 $cont =~ s/<!DOCTYPE [^>]*>//sg;
558 $cont =~ s/DOCTYPE (.*) SYSTEM\s+"http:\/\/www.cs.unibo.it\/helm\/dtd\//DOCTYPE $1 SYSTEM "$myownurl\/getdtd?uri=/g;
566 my $res = new HTTP::Response;
567 $res->content($cont);
568 $c->send_response($res);
572 #retrieve a file from an url and write it to a temp dir
573 #used for retrieve resource index from servers
575 my ($prefix, $URL) = @_;
576 my $ua = LWP::UserAgent->new;
577 my $request = HTTP::Request->new(GET => "$URL");
578 my $response = $ua->request($request, \&callback);
579 my ($filename) = reverse (split "/", $URL); # get filename part of the URL
580 open (TEMP, "> $prefix/$filename")
581 || die "Cannot open temporary file: $prefix/$filename\n";
588 tie(%map, 'DB_File', $uris_dbm.".db", O_RDONLY, 0664);
591 sub mk_urls_of_uris {
592 #rebuild $uris_dbm.db fetching resource indexes from servers
594 $server, $idxfile, $uri, $url, $comp, $line,
600 if (stat $uris_dbm.".db") { # remove old db file
601 unlink($uris_dbm.".db") or
602 die "cannot unlink old db file: $uris_dbm.db\n";
604 tie(%urls_of_uris, 'DB_File', $uris_dbm.".db", O_RDWR|O_CREAT, 0664);
606 open (SRVS, "< $servers_file") or
607 die "cannot open servers file: $servers_file\n";
610 while ($server = pop @servers) { #cicle on servers in reverse order
611 print "processing server: $server ...\n";
613 helm_wget($tmp_dir, $server."/".$indexname); #get index
614 $idxfile = $tmp_dir."/".$indexname;
615 open (INDEX, "< $idxfile") or
616 die "cannot open temporary index file: $idxfile\n";
617 while ($line = <INDEX>) { #parse index and add entry to urls_of_uris
619 ($uri,$comp) = split /[ \t]+/, $line;
622 $url = $uri . ".xml" . ".gz";
624 $url = $uri . ".xml";
626 $url =~ s/cic:/$server/;
627 $url =~ s/theory:/$server/;
628 $urls_of_uris{$uri} = $url;
631 die "cannot unlink temporary file: $idxfile\n"
632 if (unlink $idxfile) != 1;
635 untie(%urls_of_uris);
636 tie(%map, 'DB_File', $uris_dbm.".db", O_RDONLY, 0664);