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