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