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