]> matita.cs.unibo.it Git - helm.git/blob - helm/http_getter/http_getter.pl.in
added support for new environment variables
[helm.git] / helm / http_getter / http_getter.pl.in
1 #!@PERL_BINARY@
2
3 # Copyright (C) 2000, HELM Team.
4
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.
8
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.
13
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.
18
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.
22
23 # For details, see the HELM World-Wide-Web page,
24 # http://cs.unibo.it/helm/.
25
26 #use strict;
27
28 my $VERSION = "@VERSION@";
29
30 # various variables
31 my ($HELM_LIB_PATH);
32 my $cgi_dir = "@HELM_CGI_DIR@";
33 my (%map, %rdf_map);
34
35 # First of all, let's load HELM configuration
36 use Env;
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";
42 } else {
43    $HELM_LIB_PATH = $DEFAULT_HELM_LIB_DIR."/configuration.pl";
44 }
45
46 # next require defines: $helm_dir, $html_link, $dtd_dir, $uris_dbm, $indexname
47 require $HELM_LIB_PATH;
48
49 # TEMP: TODO put these vars in configuration file configuration.xml
50 # <move_to_conf_file>
51 my $cachemode = $ENV{'HTTP_GETTER_CACHE_MODE'} ||
52     'gzipped';
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";
56 }
57 my $helm_rdf_dir = $ENV{'HTTP_GETTER_RDF_DIR'} ||
58     "/usr/local/helm/rdf_library";
59 my $rdf_dbm = $ENV{'HTTP_GETTER_RDF_DBM'} ||
60     "/usr/local/helm/rdf_urls_of_uris";
61 my $rdf_indexname = $ENV{'HTTP_GETTER_RDF_INDEXNAME'} ||
62     "rdf_index.txt";
63 # </move_to_conf_file>
64
65 # Let's override the configuration file
66 $style_dir = $ENV{"HELM_STYLE_DIR"} if (defined ($ENV{"HELM_STYLE_DIR"}));
67 $dtd_dir = $ENV{"HELM_DTD_DIR"} if (defined ($ENV{"HELM_DTD_DIR"}));
68
69 use HTTP::Daemon;
70 use HTTP::Status;
71 use HTTP::Request;
72 use LWP::UserAgent;
73 use DB_File;
74 use Compress::Zlib;
75 use CGI;
76 use URI::Escape;
77
78 #CSC: mancano i controlli sulle condizioni di errore di molte funzioni
79 #CSC: ==> non e' robusto
80 #CSC: altra roba da sistemare segnata con CSC
81
82 my $d = new HTTP::Daemon LocalPort => 8081;
83 my $myownurl = $d->url;
84
85 # Let's patch the returned URL
86 $myownurl =~ s/\/$//; # chop the final slash
87 my $myownport = $myownurl;
88 $myownport =~ s/http:\/\/(.*):(.*)/$2/;
89 $myownurl  =~ s/http:\/\/(.*):(.*)/$1/;
90 ($myownurl) = gethostbyname($myownurl);
91 $myownurl = "http://".$myownurl.":".$myownport;
92
93 tie(%map, 'DB_File', $uris_dbm.".db", O_RDWR, 0664); # open dbs
94 tie(%rdf_map, 'DB_File', $rdf_dbm.".db", O_RDWR, 0664);
95
96 print "\n";
97 print "HTTP Getter $VERSION\n"; # print hello information
98 print "Please contact me at: <URL:", $myownurl."/", ">\n";
99 print "\n";
100 print "helm_dir: $helm_dir\n";
101 print "helm_rdf_dir: $helm_rdf_dir\n";
102 print "style_dir: $style_dir\n";
103 print "dtd_dir: $dtd_dir\n";
104 print "urls_of_uris db: $uris_dbm.db\n";
105 print "rdf db: $rdf_dbm.db\n";
106 print "cache mode: $cachemode\n";
107 print "indexname: $indexname\n";
108 print "rdf_indexname: $rdf_indexname\n";
109 print "\n";
110
111 $SIG{CHLD} = "IGNORE"; # do not accumulate defunct processes
112 $SIG{USR1} = \&update; # sent by the child to make the parent update
113
114 while (my $c = $d->accept) {
115  if (fork() == 0) {
116     while (my $r = $c->get_request) {
117         #CSC: mancano i controlli di sicurezza
118         
119         my $http_method = $r->method;
120         my $http_path = $r->url->path;
121         my $http_query = uri_unescape($r->url->query);
122         my $cgi = new CGI("$http_query");
123         my $inputuri = $cgi->param('uri');
124         print "\nRequest: ".$r->url."\n\n";
125
126         print "\nUnescaped query: ".$http_query."\n";
127
128          # "getxml" works with rdf uris
129         if ($http_method eq 'GET' and $http_path eq "/getxml") {
130             # finds the uri, url and filename
131
132             my $answerformat = $cgi->param('format');
133             my $patch_dtd = $cgi->param('patch_dtd');
134             $answerformat = "" if (not defined($answerformat));
135             $patch_dtd = "yes" if (not defined($patch_dtd));
136             if (($answerformat ne "gz") and ($answerformat ne "normal")
137                and ($answerformat ne "")) {
138              die "Wrong output format: $answerformat, must be 'normal' ".
139                  "or 'gz'\n";
140             }
141             if (($patch_dtd ne "yes") and ($patch_dtd ne "no")
142                and ($patch_dtd ne "")) {
143              die "Wrong param, patch_dtd must be 'yes' or 'no'\n";
144             }
145
146             my $filename = $inputuri;
147             if (not isRdfUri($inputuri)) { # standad cic: or theory: uri
148              $filename =~ s/^cic:(.*)/$1/;
149              $filename =~ s/^theory:(.*)/$1/;
150             } else { # rdf uri
151              $filename =~ s/^(.*)\/\/cic:(.*)/$2/;
152              $filename =~ s/^(.*)\/\/theory:(.*)/$2/;
153             }
154
155             my $url = resolve ($inputuri); # resolve uri in url
156             if (not defined($url)) { # uri not found in uri2url map
157              die "NOT FOUND: uri \"$inputuri\" can't be resolved\n";
158              $c->send_error(RC_NOT_FOUND)
159             } else { # uri found and mapped to url
160               my $extension; # file extension
161               if ($url =~ /\.xml$/) { # non gzipped file
162                 $extension = ".xml";
163               } elsif ($url =~ /\.xml\.gz$/) { # gzipped file
164                 $extension = ".xml.gz";
165               } else { # error: unknown extension
166                die "unexpected extension in url: $url, might be '.xml'".
167                 "or '.xml.gz'";
168               }
169
170               if (not isRdfUri ($inputuri)) { # save in uri std cache dir
171                $filename = $helm_dir.$filename.$extension;
172               } else { # save in rdf metadata cache dir
173                $filename = $helm_rdf_dir.$filename.$extension;
174               }
175
176               print_request($inputuri,$url,$filename);
177
178               # Retrieves the file
179               my $ciccontent = download($patch_dtd,$url,$filename,$answerformat);
180
181               if ($answerformat eq "normal") { # answer the client in text/xml
182                answer($c,$ciccontent,"text/xml","");
183               } else { # answer the client in text/xml, gzip encoding
184                answer($c,$ciccontent,"text/xml","x-gzip");
185               }
186             }
187             
188                            # "/register" does not work with rdf uris
189         } elsif ($http_method eq 'GET' and $http_path eq "/register") {
190           my $inputurl = $cgi->param('url');
191           print "Register requested...\n";
192           $map{$inputuri}=$inputurl;
193
194           # Now let's clean the cache
195           my $cicfilename = $inputuri;
196           $cicfilename =~ s/cic:(.*)/$1/;
197           $cicfilename =~ s/theory:(.*)/$1/;
198
199           print "Unlinking ".$helm_dir.$cicfilename.".xml[.gz]\n";
200           unlink ($helm_dir.$cicfilename.".xml");
201           unlink ($helm_dir.$cicfilename.".xml.gz");
202
203           kill(USR1,getppid()); # signal changes to parent
204           untie %map;
205           print "done.\n";
206           html_nice_answer($c,"Register done");
207
208                                   # "/resolve" works with rdf uri
209         } elsif ($http_method eq 'GET' and $http_path eq "/resolve") {
210           #my $outputurl = $map{$inputuri};
211           my $outputurl = resolve($inputuri);
212           $outputurl = "" if (not defined($outputurl));
213           $cont = "<?xml version=\"1.0\" ?>\n\n";
214           if ($outputurl eq "") {
215            $cont .= "<unresolved />\n";
216           } else {
217            $cont .= "<url value=\"$outputurl\" />\n";
218           }
219           answer($c,$cont,"text/xml","");
220
221         } elsif ($http_method eq 'GET' and $http_path eq "/getdtd") {
222             my $filename = $inputuri;
223             $filename = $dtd_dir."/".$filename;
224             print "DTD: $inputuri ==> ($filename)\n";
225             if (stat($filename)) {
226                print "Using local copy\n";
227                open(FD, $filename) or die "Cannot open $filename\n";
228                $cont = "";
229                while(<FD>) {
230                 # Vary bad heuristic for substituion of absolute URLs
231                 # for relative ones
232                 s/ENTITY (.*) SYSTEM\s+"/ENTITY $1 SYSTEM "$myownurl\/getdtd?uri=/g;
233                 $cont .= $_;
234                }
235                close(FD);
236                answer($c,$cont,"text/xml","");
237             } else {
238                die "Could not find DTD!";
239             }
240
241         } elsif ($http_method eq 'GET' and $http_path eq "/getstyleconf") {
242             my $filename = $inputuri;
243             $filename = $style_dir."/config/".$filename;
244             if (stat($filename)) {
245                open(FD, $filename) or die "Cannot open $filename\n";
246                $cont = "";
247                while(<FD>) {
248                 s/DOCTYPE (.*) SYSTEM\s+"/DOCTYPE $1 SYSTEM "$myownurl\/getstyleconf?uri=/g;
249                 $cont .= $_;
250                }
251                close(FD);
252                answer($c,$cont,"text/plain","");
253             } else {
254                die "Could not find Style Configuration File!";
255             }
256
257         } elsif ($http_method eq 'GET' and $http_path eq "/getxslt") {
258             my $filename = $inputuri;
259             $filename = $style_dir."/".$filename;
260             print "XSLT: $inputuri ==> ($filename)\n";
261             if (stat($filename)) {
262                print "Using local copy\n";
263                open(FD, $filename) or die "Cannot open $filename\n";
264                $cont = "";
265                while(<FD>) {
266                 # Vary bad heuristic for substituion of absolute URLs
267                 # for relative ones
268                 s/xsl:import\s+href="/xsl:import href="$myownurl\/getxslt?uri=/g ;
269                 s/xsl:include\s+href="/xsl:include href="$myownurl\/getxslt?uri=/g ;
270                 $cont .= $_;
271                }
272                close(FD);
273                answer($c,$cont,"text/xml","");
274             } else {
275                die "Could not find XSLT!";
276             }
277
278                                     # "/update" works with rdf uri
279         } elsif ($http_method eq 'GET' and $http_path eq "/update") {
280             # rebuild urls_of_uris db and rdf uris db
281            print "Update requested...\n";
282            update_dbs();
283            kill(USR1,getppid()); # signal changes to parent
284            print " done\n";
285            html_nice_answer($c,"Update done");
286
287                                  # "/ls" does not work with rdf uris
288         } elsif ($http_method eq 'GET' and $http_path eq "/ls") {
289             # send back keys that begin with a given uri
290            my ($uritype,$uripattern,$uriprefix);
291            my $baseuri = $cgi->param('baseuri');
292            chop $baseuri if ($baseuri =~ /.*\/$/); # remove trailing "/"
293                          # output type, might be 'txt' or 'xml':
294            my $outype = $cgi->param('format');
295            $uripattern = $baseuri;
296            $uripattern =~ s/^.*:(.*)/$1/;
297            if ($baseuri =~ /^cic:/) {
298             $uritype = "cic";
299            } elsif ($baseuri =~ /^theory:/) {
300             $uritype = "theory";
301            } else {
302             $uritype = "invalid";
303            }
304            if ($uritype ne "invalid") { # uri is valid
305             if (($outype ne 'txt') and ($outype ne 'xml')) { # invalid out type
306              print "Invalid output type specified: $outype\n";
307              html_nice_answer($c,"Invalid output type, must be ".
308               "'txt' or 'xml'");
309             } else { # valid output
310              print "BASEURI $baseuri, FORMAT $outype\n";
311              $cont = finduris($uritype,$uripattern,$outype);
312              if ($outype eq 'txt') {
313               answer($c,$cont,"text/plain","");
314              } elsif ($outype eq 'xml') {
315               answer($c,$cont,"text/xml","");
316              } else {
317               die "Internal error, exiting!";
318              }
319             }
320            } else { # invalid uri
321             print "Invalid uri: $baseuri, may begin with 'cic:', ".
322              "'theory:' or '*:'\n";
323             html_nice_answer($c,"Invalid uri , must begin with ".
324              "'cic:' or 'theory:'");
325            }
326
327         } elsif ($http_method eq 'GET' and $http_path eq "/help") {
328           # help request
329            print "Help requested!\n";
330            html_nice_answer($c,"HTTP Getter Version: $VERSION");
331
332         } elsif ($http_method eq 'GET' and $http_path =~ /\.cgi$/) {
333           # cgi handling
334            print "CGI requested!\n";
335            if ($http_path !~ /^\/[^\/]*\.cgi$/) {
336             html_nice_answer($c,"Invalid CGI name: $http_path, ".
337             "you can't request CGI that contain a slash in the name\n");
338            } elsif (stat "$cgi_dir"."$http_path") {
339             if (not -x "$cgi_dir/$http_path") {
340              html_nice_answer($c,"CGI $http_path found but not ".
341               "executable\n");
342             } else { # exec CGI and anser back its output
343              my %old_ENV = %ENV;
344              %ENV = ();
345              $ENV{'QUERY_STRING'} = $http_query;
346              my $cgi_output = `$cgi_dir/$http_path`;
347              answer($c,$cgi_output,"","");
348              %ENV = %old_ENV;
349             }
350            } else {
351             html_nice_answer($c,"CGI '$http_path' not found ".
352              "in CGI dir '$cgi_dir'");
353            }
354
355         } else { # unsupported request
356             print "\n";
357             print "INVALID REQUEST!!!!!\n";
358             print "(PATH: ",$http_path,", ";
359             print "QUERY: ",$http_query,")\n";
360             $c->send_error(RC_FORBIDDEN)
361         }
362
363         print "\nRequest solved: ".$r->url."\n\n";
364     }
365
366     $c->close;
367     undef($c);
368     print "\nCONNECTION CLOSED\n\n";
369     exit;
370   } # fork
371 }
372
373 #================================
374
375 sub isRdfUri { # return true if the uri is an rdf uri, false otherwise
376 # typycal rdf uri:
377 # helm:rdf/cic:www.cs.unibo.it/helm/rdf/foo_schema//cic:\
378 #  /Coq/Init/Logic/True_rec.con.types
379 #
380 # the format is "helm:rdf/<metadata_tree>:<metadata_scheme>//<xml_file_uri>"
381 #
382  my ($uri) = @_;
383  if ($uri =~ /^helm:rdf(.*):(.*)\/\/(.*)/) {
384   return 1;
385  } else {
386   return 0;
387  }
388 }
389
390 sub resolve { # resolve an uri in a url, work both with standard cic: or theory:
391               # uris and rdf uris
392  print "RESOLVE subroutine\n";
393  my ($uri) = @_;
394  print "GIVEN URI: \"$uri\"\n";
395  if (isRdfUri ($uri)) { # rdf uri, resolve using rdf db
396   print "IS A RDF URI\n";
397   print "I WILL RETURN '$rdf_map{$uri}'\n";
398   return ($rdf_map{$uri});
399  } else { # standard cic: or theory: uri, resolve using std uri db
400   print "IS NOT A RDF URI\n";
401   print "I WILL RETURN '$map{$uri}'\n";
402   return ($map{$uri});
403  }
404 }
405
406 sub finduris { # find uris for cic and theory trees generation
407  my ($uritype,$uripattern,$format) = @_;
408  my $content = "";
409  my ($uri,$localpart,$basepart,$dirname,$suffix,$flags,$key);
410  my (@itemz,@already_pushed_dir);
411  my (%objects,%dirs); # map uris to suffixes' flags
412  my $debug=1; # for debug
413
414  print "FINDURIS, uritype: $uritype, uripattern: $uripattern, ".
415   "format: $format\n\n" if defined($debug);
416  
417  if (($uritype eq "cic") or ($uritype eq "theory")) {
418    # get info only of one type: cic or theory
419   foreach (keys(%map)) { # select matching uris
420    $uri = $_;
421    if ($uri =~ /^$uritype:$uripattern(\/|$|\.)/) {
422     if ($uri =~ /^$uritype:$uripattern\//) { # directory match
423      $localpart = $uri;
424      $localpart =~ s/^$uritype:$uripattern\/(.*)/$1/;
425     } elsif ($uri =~ /^$uritype:$uripattern($|\.)/) { # file match
426      $localpart = $uri;
427      $localpart =~ s/^.*\/([^\/]*)/$1/;
428     } else {
429      die "Internal error, seems that requested match is none of ".
430       "directory match or file match";
431     }
432     print "LOCALPART: $localpart\n" if defined($debug);
433
434     if ($localpart =~ /^[^\/]*$/) { # no slash, an OBJECT
435      $basepart = $localpart;
436      $basepart =~ s/^([^.]*\.[^.]*)(\.types)?(\.ann)?/$1/;
437                                               # remove exts .types or
438                                               # .types.ann
439      $flags = $objects{$basepart}; # get old flags
440      if ($localpart =~ /\.ann$/) {
441       $flags = add_flag("ann","YES",$flags);
442      } else {
443       $flags = add_flag("ann","NO",$flags);
444      }
445      if ($localpart =~ /\.types$/) {
446       $flags = add_flag("types","YES",$flags);
447      } elsif ($localpart =~ /\.types\.ann$/) {
448       $flags = add_flag("types","ANN",$flags);
449      } else {
450       $flags = add_flag("types","NO",$flags);
451      }
452      $objects{$basepart} = $flags; # save new flags
453     } else { # exists at least one slash, a DIR
454      ($dirname) = split (/\//, $localpart);
455      $dirs{$dirname} = ""; # no flags requirement for dir
456     }
457    }
458   }
459  } else {
460   die "getter internal error: unsupported uritype: \"$uritype\"";
461  }
462                             # now generate OUTPUT:
463                             # output will be saved in $content
464  if ($format eq "txt") { # TXT output
465   foreach $key (sort(keys %dirs)) {
466    $content .= "dir, " . $key . "\n";
467   }
468   foreach $key (sort(keys %objects)) {
469    $content .= "object, $key, " . $objects{$key} . "\n";
470   }
471  } elsif ($format eq "xml") { # XML output
472   $content .= '<?xml version="1.0" encoding="ISO-8859-1"?>' . "\n";
473   $content .= "<!DOCTYPE ls SYSTEM ";
474   $content .= "\"$myownurl/getdtd?uri=ls.dtd\">" . "\n\n";
475   $content .= "<ls>\n";
476   foreach $key (sort(keys %dirs)) {
477    $content .= "\t<section>$key</section>\n";
478   }
479   foreach $key (sort(keys %objects)) {
480    $content .= "\t<object name=\"$key\">\n";
481    $flags = $objects{$key};
482    $flags =~ s/^<(.*)>$/$1/;
483    my ($annflag,$typesflag) = split /,/,$flags;
484    $content .= "\t\t<ann value=\"$annflag\" />\n";
485    $content .= "\t\t<types value=\"$typesflag\" />\n";
486    $content .= "\t</object>\n";
487   }
488   $content .= "</ls>\n";
489  } else { # may not enter this branch
490   die "Getter internal error: invalid format received by finduris sub";
491  }
492  return $content;
493 }
494
495 sub add_flag {
496 # manage string like: "<ann_flag,type_flag>"
497 # "ann_flag" may be one of "ann_YES", "ann_NO"
498 # "type_flag" may be one of "types_NO", "types_YES", "types_ANN"
499 # when adding a flag the max between the current flag and the new flag
500 # is taken, the orders are ann_NO < ann_YES and types_NO < types_YES <
501 # types_ANN
502  my ($flagtype,$newflag,$str) = @_;
503  $str = "<,>" if ($str eq "");
504  ($str =~ s/^<(.*,.*)>$/$1/) or die "Internal error: ".
505    "wrong string format for flag adding in $str";
506  my ($annflag,$typeflag) = split /,/,$str;
507  if ($flagtype eq "ann") { # ANN flag handling
508   if ($newflag eq "YES") {
509    $annflag = "YES";
510   } elsif ($newflag eq "NO") {
511    $annflag = "NO" unless ($annflag eq "YES");
512   } else {
513    die "Internal error: annflag must be \"YES\" or \"NO\"";
514   }
515  } elsif ($flagtype eq "types") { # TYPES flag handling
516   if ($newflag eq "ANN") {
517    $typeflag = "ANN";
518   } elsif ($newflag eq "YES") {
519    $typeflag = "YES" unless ($typeflag eq "ANN");
520   } elsif ($newflag eq "NO") {
521    $typeflag = "NO"
522      unless (($typeflag eq "ANN") or ($typeflag eq "YES"));
523   } else {
524    die "Internal error: typeflag must be \"YES\", \"NO\" or \"ANN\"";
525   }
526  } else {
527   die "Internal error: unsupported flagtype \"$flagtype\"";
528  }
529  $str = "<$annflag,$typeflag>";
530 }
531
532 #CSC: Too much powerful: creates even /home, /home/users/, ...
533 #CSC: Does not raise errors if could not create dirs/files
534 sub mkdirs
535 {
536  my ($pathname) = @_;
537  my @dirs = split /\//,$pathname;
538  my $tmp;
539  foreach $dir (@dirs) {
540   $tmp = ((defined($tmp)) ?  $tmp."\/".$dir : "");
541   mkdir($tmp,0777);
542  }
543  rmdir($tmp);
544 }
545
546 sub print_request
547 {
548  my ($uri,$url,$filename) = @_;
549  print "<download_request>\n";
550  print "uri: $uri\n";
551  print "url: $url\n";
552  print "filename: $filename\n\n";
553  print "</download_request>\n";
554 }
555
556 sub callback
557 {
558  my ($data) = @_;
559  $cont .= $data;
560 }
561
562 sub gunzip { # gunzip a file and return the deflated content
563         my ($filename) = @_;
564
565         my ($gz, $buffer, $cont);
566
567         print "deflating $filename ...\n";
568         $gz = gzopen($filename, "r")
569                 or die "Cannot open gzip'ed file $filename: $gzerrno";
570         $cont = "";
571         while ( $gz->gzread($buffer) > 0 ) {
572                 $cont .= $buffer;
573         }
574         die "Error while reading : $gzerrno\n" if $gzerrno != Z_STREAM_END ;
575         $gz->gzclose();
576
577         return $cont;
578 }
579
580 sub gzip {      # gzip the content argument and save it to filename argument
581         my ($cont, $filename) = @_;
582  #my $debug=1; # debug only
583
584  print "gzopening $filename ...\n" if (defined($debug));
585         my $gz = gzopen($filename, "w")
586                 or die "Cannot gzopen for writing file $filename: $gzerrno";
587  print "gzwriting ...\n" if (defined($debug));
588         $gz->gzwrite($cont) or die "error writing: $gzerrno, exiting!\n";
589  print "gzclosing ...\n" if (defined($debug));
590         $gz->gzclose();
591 }
592
593 sub download {
594  my ($patch_dtd,$url,$filename,$format) = @_;
595  my ($gz, $buffer);
596
597 # print "DOWNLOAD subs receives url: \"$url\"\n";
598 # print "DOWNLOAD subs receives filename: \"$filename\"\n";
599
600  my $resourcetype;      # retrieve mode: "normal" (.xml) or "gzipped" (.xml.gz)
601  if ($filename =~ /\.xml$/) {   # set retrieve mode
602          $resourcetype = "normal";
603  } elsif ($filename =~ /\.xml\.gz$/) {
604          $resourcetype = "gzipped";
605  } else {
606          die "Unsupported download extension, might be '.gz' or '.xml'\n";
607  }
608  my $basefname = $filename;
609  $basefname =~ s/\.gz$//;       # get base resource name removing trailing .gz
610  $cont = ""; # modified by side-effect by the callback function
611
612  my $localfname="";
613  if (stat($basefname)) {
614         $localfname=$basefname;
615  } elsif (stat($basefname.".gz")) {
616         $localfname=$basefname.".gz";
617  }
618  if ($localfname ne "") { # we already have local copy of requested file
619       # check both possible cache entry: gzipped or normal
620   print "Using local copy.\n";
621   if ($localfname =~ /\.xml\.gz$/) { # deflating cached file and return it
622    $cont = gunzip($localfname);
623   } elsif ($localfname =~ /\.xml$/) { # just return cached file
624    open(FD, $localfname) or die "Cannot open $localfname";
625    while(<FD>) { $cont .= $_; }
626    close(FD);
627   } else { # error
628    die "Internal error: unexpected file name $localfname,"
629    ."must end with '.gz' or '.xml.gz'\n";
630   }
631  } else { # download file from net
632    print "Downloading file ...\n"; # download file
633    my $ua = LWP::UserAgent->new;
634    my $request = HTTP::Request->new(GET => "$url");
635    my $response = $ua->request($request, \&callback);
636    
637    # cache retrieved file to disk
638    # <ZACK/> TODO: inefficent, I haven't yet undestood how to deflate
639    #    in memory gzipped file, without call "gzopen"
640    print "Storing file ...\n";
641 #   print "Making dirs ...\n";
642    mkdirs($filename);
643 #   print "Opening tmp file for writing ...\n";
644    open(FD, ">".$filename.".tmp") or die "Cannot open $filename.tmp\n";
645 #   print "Writing on tmp file ...\n";
646    print FD $cont;
647 #   print "Closing tmp file ...\n";
648    close(FD);
649
650    # handle cache conversion normal->gzipped or gzipped->normal as user choice
651    print "cachemode:$cachemode, resourcetype:$resourcetype\n"
652     if (defined($debug));
653    if (($cachemode eq 'normal') and ($resourcetype eq 'normal')) {
654      # cache the file as is
655     rename "$filename.tmp", $filename; 
656    } elsif (($cachemode eq 'gzipped') and ($resourcetype eq 'gzipped')) {
657      # cache the file as is
658      # and update the $cont variabile with deflated content
659     rename "$filename.tmp", $filename; 
660     $cont = gunzip($filename);
661    } elsif (($cachemode eq 'normal') and ($resourcetype eq 'gzipped')) {
662      # deflate cache entry
663      # and update $cont
664     open(FD, "> $basefname") or die "cannot open $basefname\n";
665     $cont = gunzip($filename.".tmp");
666     print FD $cont;
667     close(FD);
668     unlink "$filename.tmp"; # delete old gzipped file
669    } elsif (($cachemode eq 'gzipped') and ($resourcetype eq 'normal')) {
670      # compress cache entry
671     print "gzipping ...\n" if (defined($debug));
672     gzip($cont, $basefname.".gz");
673     unlink "$filename.tmp"; # delete old uncompressed file
674    } else {
675     die "Internal error, unsopported cachemode, resourcetype couple\n";
676    }
677    # $cont now contained uncompressed data
678  }
679  if ($patch_dtd eq "yes") {
680     $cont =~ s/DOCTYPE (.*) SYSTEM\s+"http:\/\/www.cs.unibo.it\/helm\/dtd\//DOCTYPE $1 SYSTEM "$myownurl\/getdtd?uri=/g;
681  }
682  if ($format eq "gz") {
683   gzip($cont,"$basefname.tmp");
684   open (TMP, "< $basefname.tmp")
685    or die "Can't open tempfile: $filename.tmp, exiting!\n";
686   $cont = "";
687   while(<TMP>) {
688    $cont .= $_;
689   }
690   close TMP;
691   unlink ($basefname . ".tmp") or
692    die "cannot unlink temporary file: $basefname.tmp\n";
693  }
694
695  return $cont;
696 }
697
698 sub answer {
699 # answer the client setting content, Content-Type and Content-Enconding
700 # of the answer
701  my ($c,$cont,$contype,$contenc) = @_;
702  my $res = new HTTP::Response;
703  $res->content($cont);
704  $res->push_header("Content-Type" => $contype)
705    unless ($contype eq "");
706  $res->push_header("Content-Encoding" => $contenc)
707    unless ($contenc eq "");
708  $res->push_header("Cache-Control" => "no-cache");
709  $res->push_header("Pragma" => "no-cache");
710  $res->push_header("Expires" => "0");
711  $c->send_response($res);
712 }
713
714 sub html_nice_answer {
715 # answer the client whith a nice html document
716  my ($c,$content) = @_;
717  $content = "<html><body><h1>$content</h1></body></html>";
718  answer($c,$content,"text/html","");
719 }
720
721 sub helm_wget {
722 #retrieve a file from an url and write it to a temp dir
723 #used for retrieve resource index from servers
724  $cont = "";
725  my ($prefix, $URL) = @_;
726  my $ua = LWP::UserAgent->new;
727  my $request = HTTP::Request->new(GET => "$URL");
728  my $response = $ua->request($request, \&callback);
729  my ($filename) = reverse (split "/", $URL); # get filename part of the URL
730  open (TEMP, "> $prefix/$filename")
731   || die "Cannot open temporary file: $prefix/$filename\n";
732  print TEMP $cont;
733  close TEMP;
734 }
735
736 sub update {
737  untie %map;
738  tie(%map, 'DB_File', $uris_dbm.".db", O_RDWR, 0664);
739  untie %rdf_map;
740  tie(%rdf_map, 'DB_File', $rdf_dbm.".db", O_RDWR, 0664);
741 }
742
743 sub update_dbs {
744 # rebuild dbs fetching resource indexes from servers.
745 # Rebuild urls_of_uris db (1) and rdf db (2)
746  my (
747   $server, $idxfile, $rdf_idxfile, $uri, $url, $comp, $line,
748   @servers,
749   %urls_of_uris, %rdf # local proxy of $map and $rdf_map
750  );
751
752  untie %map;
753  untie %rdf_map;
754  foreach my $file ($uris_dbm, $rdf_dbm) { # remove old db file
755   if (stat $file.".db") { # remove if exists
756    unlink ($file.".db") or die "can't unlink old db file: $file.db\n";
757   }
758  }
759  tie(%urls_of_uris, 'DB_File', $uris_dbm.".db", O_RDWR|O_CREAT, 0664);
760  tie(%rdf, 'DB_File', $rdf_dbm.".db", O_RDWR|O_CREAT, 0664);
761
762  open (SRVS, "< $servers_file") or
763   die "cannot open servers file: $servers_file\n";
764  @servers = <SRVS>; # read all servers
765  close (SRVS);
766
767  while ($server = pop @servers) { # cicle on servers in _reverse_ order
768   print "processing server: $server ...\n";
769   chomp $server;
770   helm_wget($tmp_dir, $server."/".$indexname); # get index
771   helm_wget($tmp_dir, $server."/".$rdf_indexname); # get rdf index
772   $idxfile = $tmp_dir."/".$indexname;
773   $rdf_idxfile = $tmp_dir."/".$rdf_indexname;
774
775   open (INDEX, "< $idxfile") or # (1) REBUILD URLS_OF_URIS DB
776    die "cannot open temporary index file: $idxfile\n";
777   while ($line = <INDEX>) {  # parse index and add entry to urls_of_uris db
778    chomp $line;
779    ($uri,$comp) = split /[ \t]+/, $line;
780              # build url:
781    if ($comp =~ /gz/) { 
782     $url = $uri . ".xml" . ".gz";
783    } else {
784     $url = $uri . ".xml";
785    }
786    $url =~ s/cic:/$server/;
787    $url =~ s/theory:/$server/;
788    $urls_of_uris{$uri} = $url;
789   }
790
791   open (RDF_INDEX, "< $rdf_idxfile") or # (2) REBUILD RDF DB
792    die "cannot open temporary rdf index file: $rdf_idxfile\n";
793   while ($line = <RDF_INDEX>) {  # parse index and add entry to rdf db
794    chomp $line;
795    ($uri,$comp) = split /[ \t]+/, $line; # comp is "gz" or nothing
796              # build url:
797    if ($comp =~ /gz/) { 
798     $url = $uri . ".xml" . ".gz";
799    } else {
800     $url = $uri . ".xml";
801    }
802    $url =~ s/^helm:rdf(.*)\/\/cic:/$server/;
803    $url =~ s/^helm:rdf(.*)\/\/theory:/$server/;
804    $rdf{$uri} = $url;
805   }
806
807   close INDEX;  # close indexes
808   close RDF_INDEX;
809   die "cannot unlink temporary file: $idxfile\n"  # remove temp files
810    if (unlink $idxfile) != 1;
811   die "cannot unlink temporary file: $rdf_idxfile\n"
812    if (unlink $rdf_idxfile) != 1;
813
814  }
815
816  untie(%urls_of_uris); # untie local proxies
817  untie(%rdf);
818  tie(%map, 'DB_File', $uris_dbm.".db", O_RDWR, 0664); # retie global ones
819  tie(%rdf_map, 'DB_File', $rdf_dbm.".db", O_RDWR, 0664);
820 } # update_dbs
821