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