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