]> matita.cs.unibo.it Git - helm.git/blob - helm/http_getter/http_getter.ml
- added some cache-control header telling not to cache some responses
[helm.git] / helm / http_getter / http_getter.ml
1 (*
2  *  Copyright (C) 2003, HELM Team.
3  *
4  *  This file is part of HELM, an Hypertextual, Electronic
5  *  Library of Mathematics, developed at the Computer Science
6  *  Department, University of Bologna, Italy.
7  *
8  *  HELM is free software; you can redistribute it and/or
9  *  modify it under the terms of the GNU General Public License
10  *  as published by the Free Software Foundation; either version 2
11  *  of the License, or (at your option) any later version.
12  *
13  *  HELM is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with HELM; if not, write to the Free Software
20  *  Foundation, Inc., 59 Temple Place - Suite 330, Boston,
21  *  MA  02111-1307, USA.
22  *
23  *  For details, see the HELM World-Wide-Web page,
24  *  http://cs.unibo.it/helm/.
25  *)
26
27 open Http_getter_common;;
28 open Http_getter_misc;;
29 open Http_getter_types;;
30 open Http_getter_debugger;;
31 open Printf;;
32
33   (* constants *)
34
35 let common_headers = [
36   "Cache-Control", "no-cache";
37   "Pragma", "no-cache";
38   "Expires", "0"
39 ]
40
41   (* HTTP queries argument parsing *)
42
43 let parse_enc (req: Http_types.request) =
44   try
45     (match req#param "format" with
46     | "normal" -> Enc_normal
47     | "gz" -> Enc_gzipped
48     | s -> raise (Http_getter_bad_request ("Invalid format: " ^ s)))
49   with Http_types.Param_not_found _ -> Enc_normal
50 ;;
51 let parse_patch_dtd (req: Http_types.request) =
52   match req#param "patch_dtd" with
53   | s when String.lowercase s = "yes" -> true
54   | s when String.lowercase s = "no" -> false
55   | s -> raise (Http_getter_bad_request ("Invalid patch_dtd value: " ^ s))
56 ;;
57 let parse_output_format (req: Http_types.request) =
58   match req#param "format" with
59   | s when String.lowercase s = "txt" -> Fmt_text
60   | s when String.lowercase s = "xml" -> Fmt_xml
61   | s -> raise (Http_getter_bad_request ("Invalid /ls format: " ^ s))
62 ;;
63 let parse_ls_uri =
64   let parse_ls_RE = Pcre.regexp "^(\\w+):(.*)$" in
65   let trailing_slash_RE = Pcre.regexp "/+$" in
66   fun (req: Http_types.request) ->
67     let baseuri = req#param "baseuri" in
68     let subs =
69       Pcre.extract ~rex:parse_ls_RE
70         (Pcre.replace ~rex:trailing_slash_RE  baseuri)
71     in
72     match (subs.(1), subs.(2)) with
73     | "cic", uri -> Cic uri
74     | "theory", uri -> Theory uri
75     | _ -> raise (Http_getter_bad_request ("Invalid /ls baseuri: " ^ baseuri))
76 ;;
77
78   (* global maps, shared by all threads *)
79
80 let xml_map = new Http_getter_map.map Http_getter_env.xml_dbm in
81 let rdf_map = new Http_getter_map.map Http_getter_env.rdf_dbm in
82 let xsl_map = new Http_getter_map.map Http_getter_env.xsl_dbm in
83
84 let save_maps () = xml_map#close; rdf_map#close; xsl_map#close in
85 let map_of_uri = function
86   | uri when is_xml_uri uri -> xml_map
87   | uri when is_rdf_uri uri -> rdf_map
88   | uri when is_xsl_uri uri -> xsl_map
89   | uri -> raise (Http_getter_unresolvable_URI uri)
90 in
91 let resolve uri = (map_of_uri uri)#resolve uri in
92 let register uri =  (map_of_uri uri )#add uri in
93 let return_all_foo_uris map doctype filter outchan =
94   (** return all URIs contained in 'map' which satisfy predicate 'filter'; URIs
95   are written in an XMLish format ('doctype' is the XML doctype) onto 'outchan'
96   *)
97   Http_daemon.send_basic_headers ~code:200 outchan;
98   Http_daemon.send_header "Content-Type" "text/xml" outchan;
99   Http_daemon.send_headers common_headers outchan;
100   Http_daemon.send_CRLF outchan;
101   output_string
102     outchan
103     (sprintf
104 "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>
105 <!DOCTYPE %s SYSTEM \"%s/getdtd?uri=%s.dtd\">
106
107 <%s>
108 "
109       doctype
110       Http_getter_env.my_own_url
111       doctype
112       doctype);
113   map#iter
114     (fun uri _ ->
115       if filter uri then
116         output_string outchan (sprintf "\t<uri value=\"%s\" />\n" uri));
117   output_string outchan (sprintf "</%s>\n" doctype)
118 in
119 let return_all_xml_uris = return_all_foo_uris xml_map "alluris" in
120 let return_all_rdf_uris = return_all_foo_uris rdf_map "allrdfuris" in
121 let return_ls =
122   let (++) (oldann, oldtypes, oldbody) (newann, newtypes, newbody) =
123     ((if newann   > oldann    then newann   else oldann),
124      (if newtypes > oldtypes  then newtypes else oldtypes),
125      (if newbody > oldbody    then newbody  else oldbody))
126    in
127   let basepart_RE =
128     Pcre.regexp "^([^.]*\\.[^.]*)((\\.body)|(\\.types))?(\\.ann)?"
129   in
130   let (types_RE, types_ann_RE, body_RE, body_ann_RE) =
131     (Pcre.regexp "\\.types", Pcre.regexp "\\.types.ann",
132      Pcre.regexp "\\.body", Pcre.regexp "\\.body.ann")
133   in
134   let (slash_RE, til_slash_RE, no_slashes_RE) =
135     (Pcre.regexp "/", Pcre.regexp "^.*/", Pcre.regexp "^[^/]*$")
136   in
137   fun lsuri fmt outchan ->
138     let pat =
139       "^" ^
140       (match lsuri with Cic p -> ("cic:" ^ p) | Theory p -> ("theory:" ^ p))
141     in
142     let (dir_RE, obj_RE) =
143       (Pcre.regexp (pat ^ "/"), Pcre.regexp (pat ^ "(\\.|$)"))
144     in
145     let dirs = ref StringSet.empty in
146     let objs = Hashtbl.create 17 in
147     let store_dir d =
148       dirs := StringSet.add (List.hd (Pcre.split ~rex:slash_RE d)) !dirs
149     in
150     let store_obj o =
151       let basepart = Pcre.replace ~rex:basepart_RE ~templ:"$1" o in
152       let oldflags =
153         try
154           Hashtbl.find objs basepart
155         with Not_found -> (false, No, No) (* no ann, no types no body *)
156       in
157       let newflags =
158         match o with
159         | s when Pcre.pmatch ~rex:types_RE s     -> (false, Yes, No)
160         | s when Pcre.pmatch ~rex:types_ann_RE s -> (true,  Ann, No)
161         | s when Pcre.pmatch ~rex:body_RE s      -> (false, No,  Yes)
162         | s when Pcre.pmatch ~rex:body_ann_RE s  -> (true,  No,  Ann)
163         | s -> (false, No, No)
164       in
165       Hashtbl.replace objs basepart (oldflags ++ newflags)
166     in
167     xml_map#iter  (* BLEARGH Dbm module lacks support for fold-like functions *)
168       (fun key _ ->
169         match key with
170         | uri when Pcre.pmatch ~rex:dir_RE uri ->  (* directory hit *)
171             let localpart = Pcre.replace ~rex:dir_RE uri in
172             if Pcre.pmatch ~rex:no_slashes_RE localpart then
173               store_obj localpart
174             else
175               store_dir localpart
176         | uri when Pcre.pmatch ~rex:obj_RE  uri ->  (* file hit *)
177             store_obj (Pcre.replace ~rex:til_slash_RE uri)
178         | uri -> () (* miss *));
179     match fmt with
180     | Fmt_text ->
181         let body =
182           (List.fold_left
183             (fun s d -> sprintf "%sdir, %s\n" s d) ""
184             (StringSet.elements !dirs)) ^
185           (Http_getter_misc.hashtbl_sorted_fold
186             (fun uri (annflag, typesflag, bodyflag) cont ->
187               sprintf "%sobject, %s, <%s,%s,%s>\n"
188                 cont uri (if annflag then "YES" else "NO")
189                 (string_of_ls_flag typesflag) (string_of_ls_flag bodyflag))
190             objs "")
191         in
192         Http_daemon.respond
193           ~headers:(("Content-Type", "text/plain") :: common_headers)
194           ~body outchan
195     | Fmt_xml ->
196         let body =
197           sprintf
198 "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>
199 <!DOCTYPE ls SYSTEM \"%s/getdtd?uri=ls.dtd\">
200
201 <ls>
202 %s
203 </ls>
204 "
205             Http_getter_env.my_own_url
206             ("\n" ^
207             (String.concat
208               "\n"
209               (List.map
210                 (fun d -> "<section>" ^ d ^ "</section>")
211                 (StringSet.elements !dirs))) ^ "\n" ^
212             (Http_getter_misc.hashtbl_sorted_fold
213               (fun uri (annflag, typesflag, bodyflag) cont ->
214                 sprintf
215 "%s<object name=\"%s\">
216 \t<ann value=\"%s\" />
217 \t<types value=\"%s\" />
218 \t<body value=\"%s\" />
219 </object>
220 "
221                   cont uri (if annflag then "YES" else "NO")
222                   (string_of_ls_flag typesflag)
223                   (string_of_ls_flag bodyflag))
224               objs ""))
225         in
226         Http_daemon.respond
227           ~headers:(("Content-Type", "text/xml") :: common_headers)
228           ~body outchan
229 in
230 let (index_line_sep_RE, index_sep_RE, trailing_types_RE,
231     heading_cic_RE, heading_theory_RE,
232     heading_rdf_cic_RE, heading_rdf_theory_RE) =
233   (Pcre.regexp "[ \t]+", Pcre.regexp "\n+", Pcre.regexp "\\.types$",
234   Pcre.regexp "^cic:", Pcre.regexp "^theory:",
235   Pcre.regexp "^helm:rdf.*//cic:", Pcre.regexp "^helm:rdf.*//theory:")
236 in
237 let update_from_server logmsg server_url = (* use global maps *)
238   debug_print ("Updating information from " ^ server_url);
239   let xml_url_of_uri = function
240       (* TODO missing sanity checks on server_url, e.g. it can contains $1 *)
241     | uri when (Pcre.pmatch ~rex:heading_cic_RE uri) ->
242         Pcre.replace ~rex:heading_cic_RE ~templ:server_url uri
243     | uri when (Pcre.pmatch ~rex:heading_theory_RE uri) ->
244         Pcre.replace ~rex:heading_theory_RE ~templ:server_url uri
245     | uri -> raise (Http_getter_invalid_URI uri)
246   in
247   let rdf_url_of_uri = function (* TODO as above *)
248     | uri when (Pcre.pmatch ~rex:heading_rdf_cic_RE uri) ->
249         Pcre.replace ~rex:heading_rdf_cic_RE ~templ:server_url uri
250     | uri when (Pcre.pmatch ~rex:heading_rdf_theory_RE uri) ->
251         Pcre.replace ~rex:heading_rdf_theory_RE ~templ:server_url uri
252     | uri -> raise (Http_getter_invalid_URI uri)
253   in
254   let log = ref (logmsg ^ "Processing server: " ^ server_url ^ "<br />\n") in
255   let (xml_index, rdf_index, xsl_index) =
256     (* TODO keeps index in memory, is better to keep them on temp files? *)
257     (http_get (server_url ^ "/" ^ Http_getter_env.xml_index),
258      http_get (server_url ^ "/" ^ Http_getter_env.rdf_index),
259      http_get (server_url ^ "/" ^ Http_getter_env.xsl_index))
260   in
261   if (xml_index = None && rdf_index = None && xsl_index = None) then
262     debug_print (sprintf "Warning: useless server %s" server_url);
263   (match xml_index with
264   | Some xml_index ->
265       (log := !log ^ "Updating XML db ...<br />\n";
266       List.iter
267         (fun l ->
268           try
269             (match Pcre.split ~rex:index_line_sep_RE l with
270             | [uri; "gz"] -> xml_map#add uri ((xml_url_of_uri uri) ^ ".xml.gz")
271             | [uri] -> xml_map#add uri ((xml_url_of_uri uri) ^ ".xml")
272             | _ -> log := !log ^ "Ignoring invalid line: " ^ l ^ "<br />\n")
273           with Http_getter_invalid_URI uri ->
274             log := !log ^ "Ignoring invalid XML URI: " ^ uri ^ "<br />\n")
275         (Pcre.split ~rex:index_sep_RE xml_index)) (* xml_index lines *)
276   | None -> ());
277   (match rdf_index with
278   | Some rdf_index ->
279       (log := !log ^ "Updating RDF db ...<br />\n";
280       List.iter
281         (fun l ->
282           try
283             (match Pcre.split ~rex:index_line_sep_RE l with
284             | [uri; "gz"] -> rdf_map#add uri ((rdf_url_of_uri uri) ^ ".xml.gz")
285             | [uri] -> rdf_map#add uri ((rdf_url_of_uri uri) ^ ".xml")
286             | _ -> log := !log ^ "Ignoring invalid line: " ^ l ^ "<br />\n")
287           with Http_getter_invalid_URI uri ->
288             log := !log ^ "Ignoring invalid RDF URI: " ^ uri ^ "<br />\n")
289         (Pcre.split ~rex:index_sep_RE rdf_index)) (* rdf_index lines *)
290   | None -> ());
291   (match xsl_index with
292   | Some xsl_index ->
293       (log := !log ^ "Updating XSLT db ...<br />\n";
294       List.iter
295         (fun l -> xsl_map#add l (server_url ^ "/" ^ l))
296         (Pcre.split ~rex:index_sep_RE xsl_index);
297       log := !log ^ "All done!<br />\n")
298   | None -> ());
299   debug_print "done with this server";
300   !log
301 in
302
303   (* thread action *)
304
305 let callback (req: Http_types.request) outchan =
306   try
307     debug_print ("Connection from " ^ req#clientAddr);
308     debug_print ("Received request: " ^ req#path);
309     (match req#path with
310     | "/help" -> return_html_msg Http_getter_const.usage_string outchan
311     | "/getxml" | "/getxslt" | "/getdtd" | "/resolve" | "/register" ->
312         (let uri = req#param "uri" in  (* common parameter *)
313         match req#path with
314         | "/getxml" ->
315             let enc = parse_enc req in
316             let patch_dtd =
317               try parse_patch_dtd req with Http_types.Param_not_found _ -> true
318             in
319             Http_getter_cache.respond_xml
320               ~url:(resolve uri) ~uri ~enc ~patch_dtd outchan
321         | "/getxslt" ->
322             let patch_dtd =
323               try parse_patch_dtd req with Http_types.Param_not_found _ -> true
324             in
325             Http_getter_cache.respond_xsl ~url:(resolve uri) ~patch_dtd outchan
326         | "/getdtd" ->
327             let patch_dtd =
328               try parse_patch_dtd req with Http_types.Param_not_found _ -> true
329             in
330             Http_getter_cache.respond_dtd
331               ~patch_dtd ~url:(Http_getter_env.dtd_dir ^ "/" ^ uri) outchan
332         | "/resolve" ->
333             (try
334               return_xml_msg
335                 (sprintf "<url value=\"%s\" />\n" (resolve uri))
336                 outchan
337             with Http_getter_unresolvable_URI uri ->
338               return_xml_msg "<unresolved />\n" outchan)
339         | "/register" ->
340             let url = req#param "url" in
341             register uri url;
342             return_html_msg "Register done" outchan
343         | _ -> assert false)
344     | "/update" ->
345         (xml_map#clear; rdf_map#clear; xsl_map#clear;
346         let log =
347           List.fold_left
348             update_from_server
349             ""  (* initial logmsg: empty *)
350               (* reverse order: 1st server is the most important one *)
351             (List.rev Http_getter_env.servers)
352         in
353         xml_map#sync; rdf_map#sync; xsl_map#sync;
354         return_html_msg log outchan)
355     | "/getalluris" ->
356         return_all_xml_uris
357           (fun uri ->
358             (Pcre.pmatch ~rex:heading_cic_RE uri) &&
359             not (Pcre.pmatch ~rex:trailing_types_RE uri))
360           outchan
361     | "/getallrdfuris" ->
362         (let classs = req#param "class" in
363         try
364           let filter =
365             let base = "^helm:rdf:www\\.cs\\.unibo\\.it/helm/rdf/" in
366             match classs with
367             | ("forward" as c) | ("backward" as c) ->
368                 (fun uri -> Pcre.pmatch ~pat:(base ^ c) uri)
369             | c -> raise (Http_getter_invalid_RDF_class c)
370           in
371           return_all_rdf_uris filter outchan
372         with Http_getter_invalid_RDF_class c ->
373           raise (Http_getter_bad_request ("Invalid RDF class: " ^ c)))
374     | "/ls" -> return_ls (parse_ls_uri req) (parse_output_format req) outchan
375     | "/getempty" ->
376         Http_daemon.respond ~body:Http_getter_const.empty_xml outchan
377     | invalid_request ->
378         Http_daemon.respond_error ~status:(`Client_error `Bad_request) outchan);
379     debug_print "Done!\n"
380   with
381   | Http_types.Param_not_found attr_name ->
382       return_400 (sprintf "Parameter '%s' is missing" attr_name) outchan
383   | Http_getter_bad_request msg -> return_html_error msg outchan
384   | Http_getter_internal_error msg -> return_html_internal_error msg outchan
385   | Shell.Subprocess_error l ->
386       return_html_internal_error
387         (String.concat "<br />\n"
388           (List.map
389             (fun (cmd, code) ->
390               sprintf "Command '%s' returned %s"
391                 cmd (string_of_proc_status code))
392             l))
393         outchan
394   | exc ->
395       return_html_error
396         ("Uncaught exception: " ^ (Printexc.to_string exc))
397         outchan
398 in
399
400     (* daemon initialization *)
401
402 let main () =
403   Http_getter_env.dump_env ();
404   Unix.putenv "http_proxy" "";
405   at_exit save_maps;
406   Sys.catch_break true;
407   try
408     Http_daemon.start'
409       ~timeout:(Some 600) ~port:Http_getter_env.port ~mode:`Thread callback
410   with Sys.Break -> ()  (* 'save_maps' already registered with 'at_exit' *)
411 in
412
413 main ()
414