]> matita.cs.unibo.it Git - helm.git/blob - helm/http_getter/http_getter.ml
deefa047e51a7bc43069526dab8fddcc57acf01a
[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 (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 =
92   try
93     (map_of_uri uri)#resolve uri
94   with Http_getter_map.Key_not_found _ ->
95     raise (Http_getter_unresolvable_URI uri)
96 in
97 let register uri =  (map_of_uri uri )#add uri in
98 let return_all_foo_uris map doctype filter outchan =
99   (** return all URIs contained in 'map' which satisfy predicate 'filter'; URIs
100   are written in an XMLish format ('doctype' is the XML doctype) onto 'outchan'
101   *)
102   Http_daemon.send_basic_headers ~code:200 outchan;
103   Http_daemon.send_header "Content-Type" "text/xml" outchan;
104   Http_daemon.send_headers common_headers outchan;
105   Http_daemon.send_CRLF outchan;
106   output_string
107     outchan
108     (sprintf
109 "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>
110 <!DOCTYPE %s SYSTEM \"%s/getdtd?uri=%s.dtd\">
111
112 <%s>
113 "
114       doctype
115       Http_getter_env.my_own_url
116       doctype
117       doctype);
118   map#iter
119     (fun uri _ ->
120       if filter uri then
121         output_string outchan (sprintf "\t<uri value=\"%s\" />\n" uri));
122   output_string outchan (sprintf "</%s>\n" doctype)
123 in
124 let return_all_xml_uris = return_all_foo_uris xml_map "alluris" in
125 let return_all_rdf_uris = return_all_foo_uris rdf_map "allrdfuris" in
126 let return_ls =
127   let (++) (oldann, oldtypes, oldbody) (newann, newtypes, newbody) =
128     ((if newann   > oldann    then newann   else oldann),
129      (if newtypes > oldtypes  then newtypes else oldtypes),
130      (if newbody > oldbody    then newbody  else oldbody))
131    in
132   let basepart_RE =
133     Pcre.regexp "^([^.]*\\.[^.]*)((\\.body)|(\\.types))?(\\.ann)?"
134   in
135   let (types_RE, types_ann_RE, body_RE, body_ann_RE) =
136     (Pcre.regexp "\\.types", Pcre.regexp "\\.types.ann",
137      Pcre.regexp "\\.body", Pcre.regexp "\\.body.ann")
138   in
139   let (slash_RE, til_slash_RE, no_slashes_RE) =
140     (Pcre.regexp "/", Pcre.regexp "^.*/", Pcre.regexp "^[^/]*$")
141   in
142   fun lsuri fmt outchan ->
143     let pat =
144       "^" ^
145       (match lsuri with Cic p -> ("cic:" ^ p) | Theory p -> ("theory:" ^ p))
146     in
147     let (dir_RE, obj_RE) =
148       (Pcre.regexp (pat ^ "/"), Pcre.regexp (pat ^ "(\\.|$)"))
149     in
150     let dirs = ref StringSet.empty in
151     let objs = Hashtbl.create 17 in
152     let store_dir d =
153       dirs := StringSet.add (List.hd (Pcre.split ~rex:slash_RE d)) !dirs
154     in
155     let store_obj o =
156       let basepart = Pcre.replace ~rex:basepart_RE ~templ:"$1" o in
157       let oldflags =
158         try
159           Hashtbl.find objs basepart
160         with Not_found -> (false, No, No) (* no ann, no types no body *)
161       in
162       let newflags =
163         match o with
164         | s when Pcre.pmatch ~rex:types_RE s     -> (false, Yes, No)
165         | s when Pcre.pmatch ~rex:types_ann_RE s -> (true,  Ann, No)
166         | s when Pcre.pmatch ~rex:body_RE s      -> (false, No,  Yes)
167         | s when Pcre.pmatch ~rex:body_ann_RE s  -> (true,  No,  Ann)
168         | s -> (false, No, No)
169       in
170       Hashtbl.replace objs basepart (oldflags ++ newflags)
171     in
172     xml_map#iter  (* BLEARGH Dbm module lacks support for fold-like functions *)
173       (fun key _ ->
174         match key with
175         | uri when Pcre.pmatch ~rex:dir_RE uri ->  (* directory hit *)
176             let localpart = Pcre.replace ~rex:dir_RE uri in
177             if Pcre.pmatch ~rex:no_slashes_RE localpart then
178               store_obj localpart
179             else
180               store_dir localpart
181         | uri when Pcre.pmatch ~rex:obj_RE  uri ->  (* file hit *)
182             store_obj (Pcre.replace ~rex:til_slash_RE uri)
183         | uri -> () (* miss *));
184     match fmt with
185     | Fmt_text ->
186         let body =
187           (List.fold_left
188             (fun s d -> sprintf "%sdir, %s\n" s d) ""
189             (StringSet.elements !dirs)) ^
190           (Http_getter_misc.hashtbl_sorted_fold
191             (fun uri (annflag, typesflag, bodyflag) cont ->
192               sprintf "%sobject, %s, <%s,%s,%s>\n"
193                 cont uri (if annflag then "YES" else "NO")
194                 (string_of_ls_flag typesflag) (string_of_ls_flag bodyflag))
195             objs "")
196         in
197         Http_daemon.respond
198           ~headers:(("Content-Type", "text/plain") :: common_headers)
199           ~body outchan
200     | Fmt_xml ->
201         let body =
202           sprintf
203 "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>
204 <!DOCTYPE ls SYSTEM \"%s/getdtd?uri=ls.dtd\">
205
206 <ls>
207 %s
208 </ls>
209 "
210             Http_getter_env.my_own_url
211             ("\n" ^
212             (String.concat
213               "\n"
214               (List.map
215                 (fun d -> "<section>" ^ d ^ "</section>")
216                 (StringSet.elements !dirs))) ^ "\n" ^
217             (Http_getter_misc.hashtbl_sorted_fold
218               (fun uri (annflag, typesflag, bodyflag) cont ->
219                 sprintf
220 "%s<object name=\"%s\">
221 \t<ann value=\"%s\" />
222 \t<types value=\"%s\" />
223 \t<body value=\"%s\" />
224 </object>
225 "
226                   cont uri (if annflag then "YES" else "NO")
227                   (string_of_ls_flag typesflag)
228                   (string_of_ls_flag bodyflag))
229               objs ""))
230         in
231         Http_daemon.respond
232           ~headers:(("Content-Type", "text/xml") :: common_headers)
233           ~body outchan
234 in
235 let (index_line_sep_RE, index_sep_RE, trailing_types_RE,
236     heading_cic_RE, heading_theory_RE,
237     heading_rdf_cic_RE, heading_rdf_theory_RE) =
238   (Pcre.regexp "[ \t]+", Pcre.regexp "\n+", Pcre.regexp "\\.types$",
239   Pcre.regexp "^cic:", Pcre.regexp "^theory:",
240   Pcre.regexp "^helm:rdf.*//cic:", Pcre.regexp "^helm:rdf.*//theory:")
241 in
242 let update_from_server logmsg server_url = (* use global maps *)
243   debug_print ("Updating information from " ^ server_url);
244   let xml_url_of_uri = function
245       (* TODO missing sanity checks on server_url, e.g. it can contains $1 *)
246     | uri when (Pcre.pmatch ~rex:heading_cic_RE uri) ->
247         Pcre.replace ~rex:heading_cic_RE ~templ:server_url uri
248     | uri when (Pcre.pmatch ~rex:heading_theory_RE uri) ->
249         Pcre.replace ~rex:heading_theory_RE ~templ:server_url uri
250     | uri -> raise (Http_getter_invalid_URI uri)
251   in
252   let rdf_url_of_uri = function (* TODO as above *)
253     | uri when (Pcre.pmatch ~rex:heading_rdf_cic_RE uri) ->
254         Pcre.replace ~rex:heading_rdf_cic_RE ~templ:server_url uri
255     | uri when (Pcre.pmatch ~rex:heading_rdf_theory_RE uri) ->
256         Pcre.replace ~rex:heading_rdf_theory_RE ~templ:server_url uri
257     | uri -> raise (Http_getter_invalid_URI uri)
258   in
259   let log = ref (logmsg ^ "Processing server: " ^ server_url ^ "<br />\n") in
260   let (xml_index, rdf_index, xsl_index) =
261     (* TODO keeps index in memory, is better to keep them on temp files? *)
262     (http_get (server_url ^ "/" ^ Http_getter_env.xml_index),
263      http_get (server_url ^ "/" ^ Http_getter_env.rdf_index),
264      http_get (server_url ^ "/" ^ Http_getter_env.xsl_index))
265   in
266   if (xml_index = None && rdf_index = None && xsl_index = None) then
267     debug_print (sprintf "Warning: useless server %s" server_url);
268   (match xml_index with
269   | Some xml_index ->
270       (log := !log ^ "Updating XML db ...<br />\n";
271       List.iter
272         (fun l ->
273           try
274             (match Pcre.split ~rex:index_line_sep_RE l with
275             | [uri; "gz"] -> xml_map#add uri ((xml_url_of_uri uri) ^ ".xml.gz")
276             | [uri] -> xml_map#add uri ((xml_url_of_uri uri) ^ ".xml")
277             | _ -> log := !log ^ "Ignoring invalid line: " ^ l ^ "<br />\n")
278           with Http_getter_invalid_URI uri ->
279             log := !log ^ "Ignoring invalid XML URI: " ^ uri ^ "<br />\n")
280         (Pcre.split ~rex:index_sep_RE xml_index)) (* xml_index lines *)
281   | None -> ());
282   (match rdf_index with
283   | Some rdf_index ->
284       (log := !log ^ "Updating RDF db ...<br />\n";
285       List.iter
286         (fun l ->
287           try
288             (match Pcre.split ~rex:index_line_sep_RE l with
289             | [uri; "gz"] -> rdf_map#add uri ((rdf_url_of_uri uri) ^ ".xml.gz")
290             | [uri] -> rdf_map#add uri ((rdf_url_of_uri uri) ^ ".xml")
291             | _ -> log := !log ^ "Ignoring invalid line: " ^ l ^ "<br />\n")
292           with Http_getter_invalid_URI uri ->
293             log := !log ^ "Ignoring invalid RDF URI: " ^ uri ^ "<br />\n")
294         (Pcre.split ~rex:index_sep_RE rdf_index)) (* rdf_index lines *)
295   | None -> ());
296   (match xsl_index with
297   | Some xsl_index ->
298       (log := !log ^ "Updating XSLT db ...<br />\n";
299       List.iter
300         (fun l -> xsl_map#add l (server_url ^ "/" ^ l))
301         (Pcre.split ~rex:index_sep_RE xsl_index);
302       log := !log ^ "All done!<br />\n")
303   | None -> ());
304   debug_print "done with this server";
305   !log
306 in
307
308   (* thread action *)
309
310 let callback (req: Http_types.request) outchan =
311   try
312     debug_print ("Connection from " ^ req#clientAddr);
313     debug_print ("Received request: " ^ req#path);
314     (match req#path with
315     | "/help" -> return_html_msg Http_getter_const.usage_string outchan
316     | "/getxml" | "/getxslt" | "/getdtd" | "/resolve" | "/register" ->
317         (let uri = req#param "uri" in  (* common parameter *)
318         match req#path with
319         | "/getxml" ->
320             let enc = parse_enc req in
321             let patch =
322               try parse_patch req with Http_types.Param_not_found _ -> true
323             in
324             Http_getter_cache.respond_xml
325               ~url:(resolve uri) ~uri ~enc ~patch outchan
326         | "/getxslt" ->
327             let patch =
328               try parse_patch req with Http_types.Param_not_found _ -> true
329             in
330             Http_getter_cache.respond_xsl ~url:(resolve uri) ~patch outchan
331         | "/getdtd" ->
332             let patch =
333               try parse_patch req with Http_types.Param_not_found _ -> true
334             in
335             Http_getter_cache.respond_dtd
336               ~patch ~url:(Http_getter_env.dtd_dir ^ "/" ^ uri) outchan
337         | "/resolve" ->
338             (try
339               return_xml_msg
340                 (sprintf "<url value=\"%s\" />\n" (resolve uri))
341                 outchan
342             with Http_getter_unresolvable_URI uri ->
343               return_xml_msg "<unresolved />\n" outchan)
344         | "/register" ->
345             let url = req#param "url" in
346             register uri url;
347             return_html_msg "Register done" outchan
348         | _ -> assert false)
349     | "/update" ->
350         (Http_getter_env.reload (); (* reload servers list from servers file *)
351         xml_map#clear; rdf_map#clear; xsl_map#clear;
352         let log =
353           List.fold_left
354             update_from_server
355             ""  (* initial logmsg: empty *)
356               (* reverse order: 1st server is the most important one *)
357             (List.rev !Http_getter_env.servers)
358         in
359         xml_map#sync; rdf_map#sync; xsl_map#sync;
360         return_html_msg log outchan)
361     | "/getalluris" ->
362         return_all_xml_uris
363           (fun uri ->
364             (Pcre.pmatch ~rex:heading_cic_RE uri) &&
365             not (Pcre.pmatch ~rex:trailing_types_RE uri))
366           outchan
367     | "/getallrdfuris" ->
368         (let classs = req#param "class" in
369         try
370           let filter =
371             let base = "^helm:rdf:www\\.cs\\.unibo\\.it/helm/rdf/" in
372             match classs with
373             | ("forward" as c) | ("backward" as c) ->
374                 (fun uri -> Pcre.pmatch ~pat:(base ^ c) uri)
375             | c -> raise (Http_getter_invalid_RDF_class c)
376           in
377           return_all_rdf_uris filter outchan
378         with Http_getter_invalid_RDF_class c ->
379           raise (Http_getter_bad_request ("Invalid RDF class: " ^ c)))
380     | "/ls" -> return_ls (parse_ls_uri req) (parse_output_format req) outchan
381     | "/getempty" ->
382         Http_daemon.respond ~body:Http_getter_const.empty_xml outchan
383     | invalid_request ->
384         Http_daemon.respond_error ~status:(`Client_error `Bad_request) outchan);
385     debug_print "Done!\n"
386   with
387   | Http_types.Param_not_found attr_name ->
388       return_400 (sprintf "Parameter '%s' is missing" attr_name) outchan
389   | Http_getter_bad_request msg -> return_html_error msg outchan
390   | Http_getter_internal_error msg -> return_html_internal_error msg outchan
391   | Shell.Subprocess_error l ->
392       return_html_internal_error
393         (String.concat "<br />\n"
394           (List.map
395             (fun (cmd, code) ->
396               sprintf "Command '%s' returned %s"
397                 cmd (string_of_proc_status code))
398             l))
399         outchan
400   | exc ->
401       return_html_error
402         ("Uncaught exception: " ^ (Printexc.to_string exc))
403         outchan
404 in
405
406     (* daemon initialization *)
407
408 let main () =
409   Http_getter_env.dump_env ();
410   Unix.putenv "http_proxy" "";
411   at_exit save_maps;
412   Sys.catch_break true;
413   try
414     Http_daemon.start'
415       ~timeout:(Some 600) ~port:Http_getter_env.port ~mode:`Thread callback
416   with Sys.Break -> ()  (* 'save_maps' already registered with 'at_exit' *)
417 in
418
419 main ()
420