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