]> matita.cs.unibo.it Git - helm.git/blob - helm/http_getter/http_getter.pl.in
getxslt added
[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 # First of all, let's load HELM configuration
27 use Env;
28 my $HELM_LIB_DIR = $ENV{"HELM_LIB_DIR"};
29 # this should be the only fixed constant
30 my $DEFAULT_HELM_LIB_DIR = "@HELM_LIB_DIR@";
31 if (defined ($HELM_LIB_DIR)) {
32    $HELM_LIB_PATH = $HELM_LIB_DIR."/configuration.pl";
33 } else {
34    $HELM_LIB_PATH = $DEFAULT_HELM_LIB_DIR."/configuration.pl";
35 }
36
37 $styles_dir = $ENV{"HELM_STYLE_DIR"} if (defined ($ENV{"HELM_STYLE_DIR"}));
38
39 # <ZACK>: TODO temporary, move this setting to configuration file
40 # set the cache mode, may be "gzipped" or "normal"
41 my $cachemode = $ENV{'HTTP_GETTER_CACHE_MODE'} || 'gzipped';
42 if (($cachemode ne 'gzipped') and ($cachemode ne 'normal')) {
43         die "Invalid HTTP_GETTER_CACHE_MODE environment variable, must be 'normal' or 'gzipped'\n";
44 }
45 # </ZACK>
46
47 # next require defines: $helm_dir, $html_link, $dtd_dir, $uris_dbm
48 require $HELM_LIB_PATH;
49
50 use HTTP::Daemon;
51 use HTTP::Status;
52 use HTTP::Request;
53 use LWP::UserAgent;
54 use DB_File;
55 use Compress::Zlib;
56
57 #CSC: mancano i controlli sulle condizioni di errore di molte funzioni
58 #CSC: ==> non e' robusto
59 #CSC: altra roba da sistemare segnata con CSC
60
61 my $d = new HTTP::Daemon LocalPort => 8081;
62 tie(%map, 'DB_File', $uris_dbm.".db", O_RDONLY, 0664);
63 print "Please contact me at: <URL:", $d->url, ">\n";
64 print "helm_dir: $helm_dir\n";
65 print "dtd_dir: $dtd_dir\n";
66 print "urls_of_uris.db: $uris_dbm.db\n";
67 print "cache mode: $cachemode\n";
68
69 $SIG{CHLD} = "IGNORE"; # do not accumulate defunct processes
70 $SIG{USR1} = \&update; # sent by the child to make the parent update
71 while (my $c = $d->accept) {
72  if (fork() == 0) {
73     while (my $r = $c->get_request) {
74         #CSC: mancano i controlli di sicurezza
75         
76         my $inputuri = $r->url; 
77         $inputuri =~ s/^[^?]*\?uri=(.*)/$1/;
78         print "\nRequest: ".$r->url."\n\n";
79         my $http_method = $r->method;
80         my $http_path = $r->url->path;
81
82         if ($http_method eq 'GET' and $http_path eq "/getciconly") {
83             # finds the uri, url and filename
84             my $cicuri = $inputuri;
85
86             my $cicfilename = $cicuri;
87             $cicfilename =~ s/cic:(.*)/$1/;
88             $cicfilename =~ s/theory:(.*)/$1/;
89 #            $cicfilename = $helm_dir.$cicfilename.".xml";
90 # <gzip>
91             my $cicurl   = $map{$cicuri};
92                         my $extension;
93                         if ($cicurl =~ /\.xml$/) {      # non gzipped file
94                                         $extension = ".xml";
95                         } elsif ($cicurl =~ /\.xml\.gz$/) {     # gzipped file
96                                         $extension = ".xml.gz";
97                         } else {        # error: unknown extension
98                                 die "unexpected extension in url: $cicurl, might be '.xml' or '.xml.gz'";
99                         }
100             $cicfilename = $helm_dir.$cicfilename.$extension;
101
102             #my $cicurl   = $map{$cicuri};
103 # </gzip>
104             if (!defined($cicurl)) {
105              print "\nNOT FOUND!!!!!\n";
106              $c->send_error(RC_NOT_FOUND)
107             } else {
108                print_request("cic",$cicuri,$cicurl,$cicfilename);
109
110                # Retrieves the file
111                my $ciccontent = download(0,"cic",$cicurl,$cicfilename);
112
113                # Answering the client
114                answer($c,$ciccontent);
115             }
116         } elsif ($http_method eq 'GET' and $http_path eq "/get") {
117             # finds the uris, urls and filenames
118             my $cicuri = $inputuri,
119                $typesuri = $inputuri,
120                $annuri = $inputuri;
121             my $annsuffix;
122             if ($inputuri =~ /\.types$/) {
123                $cicuri    =~ s/(.*)\.types$/$1/;
124                undef($annuri);
125             } elsif ($inputuri =~ /\.types\.ann$/) {
126                $cicuri    =~ s/(.*)\.types\.ann$/$1/;
127                $typesuri  =~ s/(.*)\.ann$/$1/;
128                $annsuffix = ".types.ann";
129             } elsif ($inputuri =~ /\.ann$/) {
130                $cicuri  =~ s/(.*)\.ann$/$1/;
131                undef($typesuri);
132                $annsuffix = ".ann";
133             } else {
134                undef($typesuri);
135                undef($annuri);
136             }
137
138             my $cicfilename = $cicuri;
139             $cicfilename =~ s/cic:(.*)/$1/;
140             $cicfilename =~ s/theory:(.*)/$1/;
141             $cicfilename = $helm_dir.$cicfilename;
142
143 #            my $typesfilename = $cicfilename.".types.xml"     if $typesuri;
144 #            my $annfilename  = $cicfilename.$annsuffix.".xml" if $annuri;
145 #            $cicfilename .= ".xml";
146
147 # <gzip>
148             my $cicurl   = $map{$cicuri};
149             my $typesurl = $map{$typesuri} if (defined($typesuri));
150             my $annurl   = $map{$annuri}  if (defined($annuri));
151                         my ($cicext, $typesext, $annext);
152                         if ($cicurl =~ /\.xml$/) {      # normal file
153                                 $cicext = ".xml";
154                         } elsif ($cicurl =~ /\.xml\.gz$/) {     # gzipped file
155                                 $cicext = ".xml.gz";
156                         } else {
157                                 die "unexpected extension in url: $cicurl; might be '.xml' or '.xml.gz'";
158                         }
159                         if (defined($typesuri)) {       # extension selection for types file
160                                 if ($typesurl =~ /\.xml$/) {    # normal file
161                                         $typesext = ".types.xml";
162                                 } elsif ($typesurl =~ /\.xml\.gz$/) {   # gzipped file
163                                         $typesext = ".types.xml.gz";
164                                 } else {
165                                         die "unexpected extension in url: $typesurl; might be '.xml' or '.xml.gz'";
166                                 }
167                         }
168                         if (defined($annuri)) { # extension selection for annotation file
169                                 if ($annurl =~ /\.xml$/) {      # normal file
170                                         $annext = ".xml";
171                                 } elsif ($annurl =~ /\.xml\.gz$/) {     # gzipped file
172                                         $annext = ".xml.gz";
173                                 } else {
174                                         die "unexpected extension in url: $annurl might be '.xml' or '.xml.gz'";
175                                 }
176                         }
177             my $typesfilename = $cicfilename.$typesext if $typesuri;
178             my $annfilename  = $cicfilename.$annsuffix.$annext if $annuri;
179             $cicfilename .= $cicext;
180 # </gzip>
181
182
183             if (!defined($cicurl) ||
184                (!defined($typesurl) && $typesuri) ||
185                (!defined($annuri) && $annuri))
186             {
187              print "\nNOT FOUND!!!!!\n";
188              $c->send_error(RC_NOT_FOUND)
189             } else {
190                print_request("cic",$cicuri,$cicurl,$cicfilename);
191                print_request("types",$typesuri,$typesurl,$typesfilename)
192                 if ($typesuri);
193                print_request("ann",$annuri,$annurl,$annfilename)
194                 if ($annuri);
195  
196                # Retrieves the files
197
198                my $ciccontent = download(1,"cic",$cicurl,$cicfilename);
199                my $typescontent =
200                 download(1,"types",$typesurl,$typesfilename) if ($typesuri);
201                my $anncontent =
202                 download(1,"ann",$annurl,$annfilename) if ($annuri);
203  
204                # Merging the files together
205  
206                my $merged = <<EOT;
207 <?xml version="1.0" encoding="UTF-8"?>
208 <cicxml uri="$cicuri">
209 $ciccontent
210 $typescontent
211 $anncontent
212 </cicxml>
213 EOT
214
215                # Answering the client
216                answer($c,$merged);
217             }
218          } elsif ($http_method eq 'GET' and $http_path eq "/getdtd") {
219             my $filename = $inputuri;
220             $filename = $dtd_dir."/".$filename;
221             print "DTD: $inputuri ==> ($filename)\n";
222             if (stat($filename)) {
223                print "Using local copy\n";
224                open(FD, $filename) or die "Cannot open $filename\n";
225                $cont = "";
226                while(<FD>) { $cont .= $_; }
227                close(FD);
228                answer($c,$cont);
229             } else {
230                die "Could not find DTD!";
231             }
232          } elsif ($http_method eq 'GET' and $http_path eq "/getxslt") {
233             my $filename = $inputuri;
234             $filename = $styles_dir."/".$filename;
235             print "XSLT: $inputuri ==> ($filename)\n";
236             if (stat($filename)) {
237                print "Using local copy\n";
238                open(FD, $filename) or die "Cannot open $filename\n";
239                $cont = "";
240                while(<FD>) { $cont .= $_; }
241                close(FD);
242                answer($c,$cont);
243             } else {
244                die "Could not find XSLT!";
245             }
246         } elsif ($http_method eq 'GET' and $http_path eq "/conf") {
247             my $quoted_html_link = $html_link;
248             $quoted_html_link =~ s/&/&amp;/g;
249             $quoted_html_link =~ s/</&lt;/g;
250             $quoted_html_link =~ s/>/&gt;/g;
251             $quoted_html_link =~ s/'/&apos;/g;
252             $quoted_html_link =~ s/"/&quot;/g;
253             print "\nConfiguration requested, returned #$quoted_html_link#\n";
254             $cont = "<?xml version=\"1.0\"?><html_link>$quoted_html_link</html_link>";
255             answer($c,$cont);
256         } elsif ($http_method eq 'GET' and $http_path eq "/update") {
257            print "Update requested...";
258            update();
259            kill(USR1,getppid());
260            print " done\n";
261            answer($c,"<html><body><h1>Update done</h1></body></html>");
262         } else {
263             print "\nINVALID REQUEST!!!!!\n";
264             $c->send_error(RC_FORBIDDEN)
265         }
266         print "\nRequest solved: ".$r->url."\n\n";
267     }
268     $c->close;
269     undef($c);
270     print "\nCONNECTION CLOSED\n\n";
271     exit;
272   } # fork
273 }
274
275 #================================
276
277
278 #CSC: Too much powerful: creates even /home, /home/users/, ...
279 #CSC: Does not raise errors if could not create dirs/files
280 sub mkdirs
281 {
282  my ($pathname) = @_;
283  my @dirs = split /\//,$pathname;
284  my $tmp;
285  foreach $dir (@dirs) {
286   $tmp = ((defined($tmp)) ?  $tmp."\/".$dir : "");
287   mkdir($tmp,0777);
288  }
289  rmdir($tmp);
290 }
291
292 sub print_request
293 {
294  my ($str,$uri,$url,$filename) = @_;
295  print $str."uri: $uri\n";
296  print $str."url: $url\n";
297  print $str."filename: $filename\n\n";
298 }
299
300 sub callback
301 {
302  my ($data) = @_;
303  $cont .= $data;
304 }
305
306 sub gunzip { # gunzip a file and return the deflated content
307         my ($filename) = @_;
308
309         my ($gz, $buffer, $cont);
310
311         print "deflating $filename ...\n";
312         $gz = gzopen($filename, "r") or die "Cannot open gzip'ed file $filename: $gzerrno";
313         $cont = "";
314         while ( $gz->gzread($buffer) > 0 ) {
315                 $cont .= $buffer;
316         }
317         die "Error while reading : $gzerrno\n" if $gzerrno != Z_STREAM_END ;
318         $gz->gzclose();
319
320         return $cont;
321 }
322
323 sub gzip {      # gzip the content argument and save it to filename argument
324         my ($cont, $filename) = @_;
325
326         my ($gz, $cont);
327
328         $gz = gzopen($filename, "w") or die "Cannot gzopen for writing file $filename: $gzerrno";
329         $gz->gzwrite($cont) or die "error writing: $gzerrno\n" ;
330         $gz->gzclose();
331 }
332
333 sub download
334 {
335  my ($remove_headers,$str,$url,$filename) = @_;
336 # <gzip>
337  my ($gz, $buffer);
338
339  my $resourcetype;      # retrieve mode: "normal" (.xml) or "gzipped" (.xml.gz)
340  if ($filename =~ /\.xml$/) {   # set retrieve mode
341          $resourcetype = "normal";
342  } elsif ($filename =~ /\.xml\.gz$/) {
343          $resourcetype = "gzipped";
344  } else {
345          die "Unsupported download extension, might be '.gz' or '.xml'\n";
346  }
347  my $basefname = $filename;
348  $basefname =~ s/\.gz$//;               # get base resource name removing trailing .gz
349 # </gzip>
350  $cont = ""; # modified by side-effect by the callback function
351
352  my $localfname="";
353  if (stat($basefname)) {
354         $localfname=$basefname;
355  } elsif (stat($basefname.".gz")) {
356         $localfname=$basefname.".gz";
357  }
358  if ($localfname ne "") {               # we already have local copy of requested file
359                                                                 # check both possible cache entry: gzipped or normal
360     print "Using local copy for the $str file\n";
361 # <gzip>
362         if ($localfname =~ /\.xml\.gz$/) {      # deflating cached file and return it
363                 $cont = gunzip($localfname);
364         } elsif ($localfname =~ /\.xml$/) {     # just return cached file
365                 open(FD, $localfname) or die "Cannot open $localfname";
366                 while(<FD>) { $cont .= $_; }
367                 close(FD);
368         } else {        # error
369                 die "Internal error: unexpected file name $localfname, must end with '.gz' or '.xml.gz'\n";
370         }
371 # </gzip>
372  } else {       # download file from net
373     print "Downloading the $str file\n";        # download file
374     $ua = LWP::UserAgent->new;
375     $request = HTTP::Request->new(GET => "$url");
376     $response = $ua->request($request, \&callback);
377                
378                                 # cache retrieved file to disk
379 # <ZACK/> TODO: inefficent, I haven't yet undestood how to deflate in memory gzipped file,
380 #                               without call "gzopen"
381 # <gzip>
382         print "Storing the $str file\n";
383         mkdirs($filename);
384         open(FD, ">".$filename.".tmp") or die "Cannot open $filename.tmp\n";
385         print FD $cont;
386         close(FD);
387
388         # handle cache conversion normal->gzipped or gzipped->normal as user choice
389         if (($cachemode eq 'normal') and ($resourcetype eq 'normal')) { # cache the file as is
390                 rename "$filename.tmp", $filename;      
391         } elsif (($cachemode eq 'gzipped') and ($resourcetype eq 'gzipped')) {  # cache the file as is
392                                                                                         # and update the $cont variabile with deflated content
393                 rename "$filename.tmp", $filename;      
394                 $cont = gunzip($filename);
395         } elsif (($cachemode eq 'normal') and ($resourcetype eq 'gzipped')) {   # deflate cache entry
396                                                                                                                                                         # and update $cont
397                 open(FD, "> $basefname") or die "cannot open $basefname\n";
398                 $cont = gunzip($filename.".tmp");
399                 print FD $cont;
400                 close(FD);
401                 unlink "$filename.tmp"; # delete old gzipped file
402         } elsif (($cachemode eq 'gzipped') and ($resourcetype eq 'normal')) {   # compress cache entry
403                 gzip($cont, $basefname.".gz");
404                 unlink "$filename.tmp"; # delete old uncompressed file
405         } else {
406                 die "Internal error, unsopported cachemode, resourcetype couple\n";
407         }
408         # $cont now contained uncompressed data
409
410 # </gzip>
411  }
412  if ($remove_headers) {
413     $cont =~ s/<\?xml [^?]*\?>//sg;
414     $cont =~ s/<!DOCTYPE [^>]*>//sg;
415  }
416  return $cont;
417 }
418
419 sub answer
420 {
421  my ($c,$cont) = @_;
422  my $res = new HTTP::Response;
423  $res->content($cont);
424  $c->send_response($res);
425 }
426
427 sub update {
428  untie %map;
429  tie(%map, 'DB_File', $uris_dbm.".db", O_RDONLY, 0664);
430 }