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