]> matita.cs.unibo.it Git - helm.git/blob - helm/http_getter/http_getter.pl.in
Experimental commit that implements the getalluris method, that gives back in
[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         } elsif ($http_method eq 'GET' and $http_path eq "/ls") {
324             # send back keys that begin with a given uri
325            my ($uritype,$uripattern,$uriprefix);
326            my $baseuri = $cgi->param('baseuri');
327            chop $baseuri if ($baseuri =~ /.*\/$/); # remove trailing "/"
328                          # output type, might be 'txt' or 'xml':
329            my $outype = $cgi->param('format');
330            $uripattern = $baseuri;
331            $uripattern =~ s/^.*:(.*)/$1/;
332            if ($baseuri =~ /^cic:/) {
333             $uritype = "cic";
334            } elsif ($baseuri =~ /^theory:/) {
335             $uritype = "theory";
336            } else {
337             $uritype = "invalid";
338            }
339            if ($uritype ne "invalid") { # uri is valid
340             if (($outype ne 'txt') and ($outype ne 'xml')) { # invalid out type
341              print "Invalid output type specified: $outype\n";
342              html_nice_answer($c,"Invalid output type, must be ".
343               "'txt' or 'xml'");
344             } else { # valid output
345              print "BASEURI $baseuri, FORMAT $outype\n";
346              $cont = finduris($uritype,$uripattern,$outype);
347              if ($outype eq 'txt') {
348               answer($c,$cont,"text/plain","");
349              } elsif ($outype eq 'xml') {
350               answer($c,$cont,"text/xml","");
351              } else {
352               die "Internal error, exiting!";
353              }
354             }
355            } else { # invalid uri
356             print "Invalid uri: $baseuri, may begin with 'cic:', ".
357              "'theory:' or '*:'\n";
358             html_nice_answer($c,"Invalid uri , must begin with ".
359              "'cic:' or 'theory:'");
360            }
361
362         } elsif ($http_method eq 'GET' and $http_path eq "/help") {
363           # help request
364            print "Help requested!\n";
365            html_nice_answer($c,"HTTP Getter Version: $VERSION");
366
367         } elsif ($http_method eq 'GET' and $http_path eq "/getempty") {
368           # return an empty, but valid, xml document
369           my $emptyxml = <<EOXML;
370 <?xml version="1.0"?>
371 <!DOCTYPE empty [
372   <!ELEMENT empty EMPTY>
373 ]>
374 <empty />
375 EOXML
376           answer($c, $emptyxml, "", "");
377
378         } elsif ($http_method eq 'GET' and $http_path =~ /\.cgi$/) {
379           # cgi handling
380            print "CGI requested!\n";
381            if ($http_path !~ /^\/[^\/]*\.cgi$/) {
382             html_nice_answer($c,"Invalid CGI name: $http_path, ".
383             "you can't request CGI that contain a slash in the name\n");
384            } elsif (stat "$cgi_dir"."$http_path") {
385             if (not -x "$cgi_dir/$http_path") {
386              html_nice_answer($c,"CGI $http_path found but not ".
387               "executable\n");
388             } else { # exec CGI and anser back its output
389              my %old_ENV = %ENV;
390              %ENV = ();
391              $ENV{'QUERY_STRING'} = $http_query;
392              my $cgi_output = `$cgi_dir/$http_path`;
393              answer($c,$cgi_output,"","");
394              %ENV = %old_ENV;
395             }
396            } else {
397             html_nice_answer($c,"CGI '$http_path' not found ".
398              "in CGI dir '$cgi_dir'");
399            }
400
401         } else { # unsupported request
402             print "\n";
403             print "INVALID REQUEST!!!!!\n";
404             print "(PATH: ",$http_path,", ";
405             print "QUERY: ",$http_query,")\n";
406             $c->send_error(RC_FORBIDDEN)
407         }
408
409         print "\nRequest solved: ".$r->url."\n\n";
410     }
411
412     $c->close;
413     undef($c);
414     print "\nCONNECTION CLOSED\n\n";
415     exit;
416   } # fork
417 }
418
419 #================================
420
421 sub isRdfUri { # return true if the uri is an rdf uri, false otherwise
422 # typycal rdf uri:
423 # helm:rdf/cic:www.cs.unibo.it/helm/rdf/foo_schema//cic:\
424 #  /Coq/Init/Logic/True_rec.con.types
425 #
426 # the format is "helm:rdf/<metadata_tree>:<metadata_scheme>//<xml_file_uri>"
427 #
428  my ($uri) = @_;
429  if ($uri =~ /^helm:rdf(.*):(.*)\/\/(.*)/) {
430   return 1;
431  } else {
432   return 0;
433  }
434 }
435
436 sub resolve { # resolve an uri in a url, work both with standard cic: or theory:
437               # uris and rdf uris
438  print "RESOLVE subroutine\n";
439  my ($uri) = @_;
440  print "GIVEN URI: \"$uri\"\n";
441  if (isRdfUri ($uri)) { # rdf uri, resolve using rdf db
442   print "IS A RDF URI\n";
443   print "I WILL RETURN '$rdf_map{$uri}'\n";
444   return ($rdf_map{$uri});
445  } else { # standard cic: or theory: uri, resolve using std uri db
446   print "IS NOT A RDF URI\n";
447   print "I WILL RETURN '$xml_map{$uri}'\n";
448   return ($xml_map{$uri});
449  }
450 }
451
452 sub getalluris { # get all the keys whose prefix is cic
453  my $content = "";
454  my ($uri);
455  my $debug=1; # for debug
456
457   $content .= '<?xml version="1.0" encoding="ISO-8859-1"?>' . "\n";
458   $content .= "<!DOCTYPE alluris SYSTEM ";
459   $content .= "\"$myownurl/getdtd?uri=alluris.dtd\">" . "\n\n";
460   $content .= "<alluris>\n";
461   foreach $uri (sort (keys(%xml_map))) { # select matching uris
462    if ($uri =~ /^cic:/ && not $uri =~ /.types$/) {
463     print "GETALLURI: $uri\n" if defined($debug);
464     $content .= "\t<uri value=\"$uri\"/>\n";
465    }
466   }
467   $content .= "</alluris>\n";
468  return $content;
469 }
470
471 sub finduris { # find uris for cic and theory trees generation
472  my ($uritype,$uripattern,$format) = @_;
473  my $content = "";
474  my ($uri,$localpart,$basepart,$dirname,$suffix,$flags,$key);
475  my (@itemz,@already_pushed_dir);
476  my (%objects,%dirs); # map uris to suffixes' flags
477  my $debug=1; # for debug
478
479  print "FINDURIS, uritype: $uritype, uripattern: $uripattern, ".
480   "format: $format\n\n" if defined($debug);
481  
482  if (($uritype eq "cic") or ($uritype eq "theory")) {
483    # get info only of one type: cic or theory
484   foreach (keys(%xml_map)) { # select matching uris
485    $uri = $_;
486    if ($uri =~ /^$uritype:$uripattern(\/|$|\.)/) {
487     if ($uri =~ /^$uritype:$uripattern\//) { # directory match
488      $localpart = $uri;
489      $localpart =~ s/^$uritype:$uripattern\/(.*)/$1/;
490     } elsif ($uri =~ /^$uritype:$uripattern($|\.)/) { # file match
491      $localpart = $uri;
492      $localpart =~ s/^.*\/([^\/]*)/$1/;
493     } else {
494      die "Internal error, seems that requested match is none of ".
495       "directory match or file match";
496     }
497     print "LOCALPART: $localpart\n" if defined($debug);
498
499     if ($localpart =~ /^[^\/]*$/) { # no slash, an OBJECT
500      $basepart = $localpart;
501      $basepart =~ s/^([^.]*\.[^.]*)(\.types)?(\.ann)?/$1/;
502                                               # remove exts .types or
503                                               # .types.ann
504      $flags = $objects{$basepart}; # get old flags
505      if ($localpart =~ /\.ann$/) {
506       $flags = add_flag("ann","YES",$flags);
507      } else {
508       $flags = add_flag("ann","NO",$flags);
509      }
510      if ($localpart =~ /\.types$/) {
511       $flags = add_flag("types","YES",$flags);
512      } elsif ($localpart =~ /\.types\.ann$/) {
513       $flags = add_flag("types","ANN",$flags);
514      } else {
515       $flags = add_flag("types","NO",$flags);
516      }
517      $objects{$basepart} = $flags; # save new flags
518     } else { # exists at least one slash, a DIR
519      ($dirname) = split (/\//, $localpart);
520      $dirs{$dirname} = ""; # no flags requirement for dir
521     }
522    }
523   }
524  } else {
525   die "getter internal error: unsupported uritype: \"$uritype\"";
526  }
527                             # now generate OUTPUT:
528                             # output will be saved in $content
529  if ($format eq "txt") { # TXT output
530   foreach $key (sort(keys %dirs)) {
531    $content .= "dir, " . $key . "\n";
532   }
533   foreach $key (sort(keys %objects)) {
534    $content .= "object, $key, " . $objects{$key} . "\n";
535   }
536  } elsif ($format eq "xml") { # XML output
537   $content .= '<?xml version="1.0" encoding="ISO-8859-1"?>' . "\n";
538   $content .= "<!DOCTYPE ls SYSTEM ";
539   $content .= "\"$myownurl/getdtd?uri=ls.dtd\">" . "\n\n";
540   $content .= "<ls>\n";
541   foreach $key (sort(keys %dirs)) {
542    $content .= "\t<section>$key</section>\n";
543   }
544   foreach $key (sort(keys %objects)) {
545    $content .= "\t<object name=\"$key\">\n";
546    $flags = $objects{$key};
547    $flags =~ s/^<(.*)>$/$1/;
548    my ($annflag,$typesflag) = split /,/,$flags;
549    $content .= "\t\t<ann value=\"$annflag\" />\n";
550    $content .= "\t\t<types value=\"$typesflag\" />\n";
551    $content .= "\t</object>\n";
552   }
553   $content .= "</ls>\n";
554  } else { # may not enter this branch
555   die "Getter internal error: invalid format received by finduris sub";
556  }
557  return $content;
558 }
559
560 sub add_flag {
561 # manage string like: "<ann_flag,type_flag>"
562 # "ann_flag" may be one of "ann_YES", "ann_NO"
563 # "type_flag" may be one of "types_NO", "types_YES", "types_ANN"
564 # when adding a flag the max between the current flag and the new flag
565 # is taken, the orders are ann_NO < ann_YES and types_NO < types_YES <
566 # types_ANN
567  my ($flagtype,$newflag,$str) = @_;
568  $str = "<,>" if ($str eq "");
569  ($str =~ s/^<(.*,.*)>$/$1/) or die "Internal error: ".
570    "wrong string format for flag adding in $str";
571  my ($annflag,$typeflag) = split /,/,$str;
572  if ($flagtype eq "ann") { # ANN flag handling
573   if ($newflag eq "YES") {
574    $annflag = "YES";
575   } elsif ($newflag eq "NO") {
576    $annflag = "NO" unless ($annflag eq "YES");
577   } else {
578    die "Internal error: annflag must be \"YES\" or \"NO\"";
579   }
580  } elsif ($flagtype eq "types") { # TYPES flag handling
581   if ($newflag eq "ANN") {
582    $typeflag = "ANN";
583   } elsif ($newflag eq "YES") {
584    $typeflag = "YES" unless ($typeflag eq "ANN");
585   } elsif ($newflag eq "NO") {
586    $typeflag = "NO"
587      unless (($typeflag eq "ANN") or ($typeflag eq "YES"));
588   } else {
589    die "Internal error: typeflag must be \"YES\", \"NO\" or \"ANN\"";
590   }
591  } else {
592   die "Internal error: unsupported flagtype \"$flagtype\"";
593  }
594  $str = "<$annflag,$typeflag>";
595 }
596
597 #CSC: Too much powerful: creates even /home, /home/users/, ...
598 #CSC: Does not raise errors if could not create dirs/files
599 sub mkdirs
600 {
601  my ($pathname) = @_;
602  my @dirs = split /\//,$pathname;
603  my $tmp;
604  foreach $dir (@dirs) {
605   $tmp = ((defined($tmp)) ?  $tmp."\/".$dir : "");
606   mkdir($tmp,0777);
607  }
608  rmdir($tmp);
609 }
610
611 sub print_request
612 {
613  my ($uri,$url,$filename) = @_;
614  print "<download_request>\n";
615  print "uri: $uri\n";
616  print "url: $url\n";
617  print "filename: $filename\n\n";
618  print "</download_request>\n";
619 }
620
621 sub gunzip { # gunzip a file and return the deflated content
622         my ($filename) = @_;
623
624         my ($gz, $buffer, $cont);
625
626         print "deflating $filename ...\n";
627         $gz = gzopen($filename, "r")
628                 or die "Cannot open gzip'ed file $filename: $gzerrno";
629         $cont = "";
630         while ( $gz->gzread($buffer) > 0 ) {
631                 $cont .= $buffer;
632         }
633         die "Error while reading : $gzerrno\n" if $gzerrno != Z_STREAM_END ;
634         $gz->gzclose();
635
636         return $cont;
637 }
638
639 sub gzip {      # gzip the content argument and save it to filename argument
640         my ($cont, $filename) = @_;
641  #my $debug=1; # debug only
642
643  print "gzopening $filename ...\n" if (defined($debug));
644         my $gz = gzopen($filename, "w")
645                 or die "Cannot gzopen for writing file $filename: $gzerrno";
646  print "gzwriting ...\n" if (defined($debug));
647         $gz->gzwrite($cont) or die "error writing: $gzerrno, exiting!\n";
648  print "gzclosing ...\n" if (defined($debug));
649         $gz->gzclose();
650 }
651
652 sub download {
653  my ($patch_dtd,$url,$filename,$format) = @_;
654  my ($gz, $buffer);
655
656 # print "DOWNLOAD subs receives url: \"$url\"\n";
657 # print "DOWNLOAD subs receives filename: \"$filename\"\n";
658
659  my $resourcetype;      # retrieve mode: "normal" (.xml) or "gzipped" (.xml.gz)
660  if ($filename =~ /\.xml$/) {   # set retrieve mode
661          $resourcetype = "normal";
662  } elsif ($filename =~ /\.xml\.gz$/) {
663          $resourcetype = "gzipped";
664  } else {
665          die "Unsupported download extension, might be '.gz' or '.xml'\n";
666  }
667  my $basefname = $filename;
668  $basefname =~ s/\.gz$//;       # get base resource name removing trailing .gz
669  $cont = ""; # modified by side-effect by the callback function
670
671  my $localfname="";
672  if (stat($basefname)) {
673         $localfname=$basefname;
674  } elsif (stat($basefname.".gz")) {
675         $localfname=$basefname.".gz";
676  }
677  if ($localfname ne "") { # we already have local copy of requested file
678       # check both possible cache entry: gzipped or normal
679   print "Using local copy.\n";
680   if ($localfname =~ /\.xml\.gz$/) { # deflating cached file and return it
681    $cont = gunzip($localfname);
682   } elsif ($localfname =~ /\.xml$/) { # just return cached file
683    open(FD, $localfname) or die "Cannot open $localfname";
684    while(<FD>) { $cont .= $_; }
685    close(FD);
686   } else { # error
687    die "Internal error: unexpected file name $localfname,"
688    ."must end with '.gz' or '.xml.gz'\n";
689   }
690  } else { # download file from net
691    print "Downloading file ...\n"; # download file
692    my $ua = LWP::UserAgent->new;
693    my $request = HTTP::Request->new(GET => "$url");
694    my $response = $ua->request($request, \&callback);
695    
696    # cache retrieved file to disk
697    # <ZACK/> TODO: inefficent, I haven't yet undestood how to deflate
698    #    in memory gzipped file, without call "gzopen"
699    print "Storing file ...\n";
700 #   print "Making dirs ...\n";
701    mkdirs($filename);
702 #   print "Opening tmp file for writing ...\n";
703    open(FD, ">".$filename.".tmp") or die "Cannot open $filename.tmp\n";
704 #   print "Writing on tmp file ...\n";
705    print FD $cont;
706 #   print "Closing tmp file ...\n";
707    close(FD);
708
709    # handle cache conversion normal->gzipped or gzipped->normal as user choice
710    print "cachemode:$cachemode, resourcetype:$resourcetype\n"
711     if (defined($debug));
712    if (($cachemode eq 'normal') and ($resourcetype eq 'normal')) {
713      # cache the file as is
714     rename "$filename.tmp", $filename; 
715    } elsif (($cachemode eq 'gzipped') and ($resourcetype eq 'gzipped')) {
716      # cache the file as is
717      # and update the $cont variabile with deflated content
718     rename "$filename.tmp", $filename; 
719     $cont = gunzip($filename);
720    } elsif (($cachemode eq 'normal') and ($resourcetype eq 'gzipped')) {
721      # deflate cache entry
722      # and update $cont
723     open(FD, "> $basefname") or die "cannot open $basefname\n";
724     $cont = gunzip($filename.".tmp");
725     print FD $cont;
726     close(FD);
727     unlink "$filename.tmp"; # delete old gzipped file
728    } elsif (($cachemode eq 'gzipped') and ($resourcetype eq 'normal')) {
729      # compress cache entry
730     print "gzipping ...\n" if (defined($debug));
731     gzip($cont, $basefname.".gz");
732     unlink "$filename.tmp"; # delete old uncompressed file
733    } else {
734     die "Internal error, unsopported cachemode, resourcetype couple\n";
735    }
736    # $cont now contained uncompressed data
737  }
738  if ($patch_dtd eq "yes") {
739     $cont =~ s/DOCTYPE (.*) SYSTEM\s+"http:\/\/www.cs.unibo.it\/helm\/dtd\//DOCTYPE $1 SYSTEM "$myownurl\/getdtd?uri=/g;
740  }
741  if ($format eq "gz") {
742   gzip($cont,"$basefname.tmp");
743   open (TMP, "< $basefname.tmp")
744    or die "Can't open tempfile: $filename.tmp, exiting!\n";
745   $cont = "";
746   while(<TMP>) {
747    $cont .= $_;
748   }
749   close TMP;
750   unlink ($basefname . ".tmp") or
751    die "cannot unlink temporary file: $basefname.tmp\n";
752  }
753
754  return $cont;
755 }
756
757 sub answer {
758 # answer the client setting content, Content-Type and Content-Enconding
759 # of the answer
760  my ($c,$cont,$contype,$contenc) = @_;
761  my $res = new HTTP::Response;
762  $res->content($cont);
763  $res->push_header("Content-Type" => $contype)
764    unless ($contype eq "");
765  $res->push_header("Content-Encoding" => $contenc)
766    unless ($contenc eq "");
767  $res->push_header("Cache-Control" => "no-cache");
768  $res->push_header("Pragma" => "no-cache");
769  $res->push_header("Expires" => "0");
770  $c->send_response($res);
771 }
772
773 sub html_nice_answer {
774 # answer the client whith a nice html document
775  my ($c,$content) = @_;
776  $content = "<html><body><h1>$content</h1></body></html>";
777  answer($c,$content,"text/html","");
778 }
779
780 sub callback {
781  my ($data) = @_;
782  $cont .= $data;
783 }
784
785 sub helm_wget {
786 # retrieve a file from an url and write it to a temp dir
787 # used for retrieve resource index from servers
788  $cont = "";
789  my ($prefix, $URL) = @_;
790  my $ua = LWP::UserAgent->new;
791  my $request = HTTP::Request->new(GET => "$URL");
792  my $response = $ua->request($request, \&callback);
793  my ($filename) = reverse (split "/", $URL); # get filename part of the URL
794  open (TEMP, "> $prefix/$filename")
795   || die "Cannot open temporary file: $prefix/$filename\n";
796  print TEMP $cont;
797  close TEMP;
798 }
799
800 sub update {
801 # retie dbs
802  untie %xml_map;
803  tie(%xml_map, 'DB_File', $uris_dbm, O_RDWR, 0664);
804  untie %rdf_map;
805  tie(%rdf_map, 'DB_File', $rdf_dbm, O_RDWR, 0664);
806  untie %xslt_map;
807  tie(%xslt_map, 'DB_File', $xslt_dbm, O_RDWR, 0664);
808 }
809
810 sub update_dbs {
811 # rebuild dbs fetching resource indexes from servers.
812 # Rebuild urls_of_uris db (1), rdf db (2) and xslt db (3)
813  my (
814   $server, $idxfile, $rdf_idxfile, $uri, $url, $comp, $line,
815   @servers,
816   %urls_of_uris, %rdf, %xslt # local proxy of dbs
817  );
818
819  untie %xml_map;
820  untie %rdf_map;
821  untie %xslt_map;
822  foreach my $file ($uris_dbm, $rdf_dbm, $xslt_dbm) { # remove old db file
823   if (stat $file) { # remove if exists
824    unlink ($file) or die "can't unlink old db file: $file\n";
825   }
826  }
827  tie(%urls_of_uris, 'DB_File', $uris_dbm, O_RDWR|O_CREAT, 0664);
828  tie(%rdf, 'DB_File', $rdf_dbm, O_RDWR|O_CREAT, 0664);
829  tie(%xslt, 'DB_File', $xslt_dbm, O_RDWR|O_CREAT, 0664);
830
831  open (SRVS, "< $servers_file") or
832   die "cannot open servers file: $servers_file\n";
833  @servers = <SRVS>; # read all servers
834  close (SRVS);
835
836  while ($server = pop @servers) { # cicle on servers in _reverse_ order
837   print "processing server: $server ...\n";
838   chomp $server;
839   helm_wget($tmp_dir, $server."/".$indexname); # get index
840   helm_wget($tmp_dir, $server."/".$rdf_indexname); # get rdf index
841   helm_wget($tmp_dir, $server."/".$xslt_indexname); # get xslt index
842   $idxfile = $tmp_dir."/".$indexname;
843   $rdf_idxfile = $tmp_dir."/".$rdf_indexname;
844   $xslt_idxfile = $tmp_dir . "/" . $xslt_indexname;
845
846                   # (1) REBUILD URLS_OF_URIS DB
847   open (INDEX, "< $idxfile") or
848    die "cannot open temporary index file: $idxfile\n";
849   while (my $line = <INDEX>) {  # parse index and add entry to urls_of_uris db
850    chomp $line;
851    ($uri,$comp) = split /[ \t]+/, $line;
852              # build url:
853    if ($comp =~ /gz/) { 
854     $url = $uri . ".xml" . ".gz";
855    } else {
856     $url = $uri . ".xml";
857    }
858    $url =~ s/cic:/$server/;
859    $url =~ s/theory:/$server/;
860    $urls_of_uris{$uri} = $url;
861   }
862
863                   # (2) REBUILD RDF DB
864   open (RDF_INDEX, "< $rdf_idxfile") or
865    die "cannot open temporary RDF index file: $rdf_idxfile\n";
866   while (my $line = <RDF_INDEX>) {  # parse index and add entry to rdf db
867    chomp $line;
868    ($uri,$comp) = split /[ \t]+/, $line; # comp is "gz" or nothing
869              # build url:
870    if ($comp =~ /gz/) { 
871     $url = $uri . ".xml" . ".gz";
872    } else {
873     $url = $uri . ".xml";
874    }
875    $url =~ s/^helm:rdf(.*)\/\/cic:/$server/;
876    $url =~ s/^helm:rdf(.*)\/\/theory:/$server/;
877    $rdf{$uri} = $url;
878   }
879
880                   # (3) REBUILD XSLT DB
881   open (XSLT_INDEX, "< $xslt_idxfile") or
882     die "cannot open temporary XSLT index file: $xslt_idxfile\n";
883   while (my $line = <XSLT_INDEX>) { # parse index and add entry to xslt db
884     chomp $line;
885     my $stylesheet = $line;
886     my $url = $server . "/" . $stylesheet;
887     $xslt{$stylesheet} = $url;
888   }
889
890   close INDEX;  # close indexes
891   close RDF_INDEX;
892   close XSLT_INDEX;
893
894                   # remove temp files
895   foreach my $file ($idxfile, $rdf_idxfile, $xslt_idxfile) {
896     print "cannot unlink temporary file: $file\n" if (unlink $file) != 1;
897   }
898
899  }
900
901  untie(%urls_of_uris); # untie local proxies
902  untie(%rdf);
903  untie(%xslt);
904  tie(%xml_map, 'DB_File', $uris_dbm, O_RDWR, 0664); # retie global ones
905  tie(%rdf_map, 'DB_File', $rdf_dbm, O_RDWR, 0664);
906  tie(%xslt_map, 'DB_File', $xslt_dbm, O_RDWR, 0664);
907
908 } # update_dbs
909
910 # vim modline: do not remove!
911 # vim: set ft=perl:
912