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