]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/getter/http_getter.ml
added a missing <br> tag
[helm.git] / helm / ocaml / getter / http_getter.ml
1 (*
2  * Copyright (C) 2003-2004:
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 Printf
30
31 open Http_getter_common
32 open Http_getter_misc
33 open Http_getter_debugger
34 open Http_getter_types
35
36 exception Not_implemented of string
37 exception UnexpectedGetterOutput
38
39 (* resolve_result is needed because it is not possible to raise *)
40 (* an exception in a pxp ever-processing callback. Too bad.     *)
41 type resolve_result =
42   | Unknown
43   | Exception of exn
44   | Resolved of string
45
46 type logger_callback = HelmLogger.html_tag -> unit
47
48 let not_implemented s = raise (Not_implemented ("Http_getter." ^ s))
49
50 let (index_line_sep_RE, index_sep_RE, trailing_types_RE,
51     heading_cic_RE, heading_theory_RE, heading_nuprl_RE,
52     heading_rdf_cic_RE, heading_rdf_theory_RE) =
53   (Pcre.regexp "[ \t]+", Pcre.regexp "\r\n|\r|\n",
54   Pcre.regexp "\\.types$",
55   Pcre.regexp "^cic:", Pcre.regexp "^theory:", Pcre.regexp "^nuprl:",
56   Pcre.regexp "^helm:rdf.*//cic:", Pcre.regexp "^helm:rdf.*//theory:")
57
58   (* global maps, shared by all threads *)
59
60 let cic_map =
61   lazy (new Http_getter_map.map (Lazy.force Http_getter_env.cic_dbm))
62 let nuprl_map =
63   lazy (new Http_getter_map.map (Lazy.force Http_getter_env.nuprl_dbm))
64 let rdf_map =
65   lazy (new Http_getter_map.map (Lazy.force Http_getter_env.rdf_dbm))
66 let xsl_map =
67   lazy (new Http_getter_map.map (Lazy.force Http_getter_env.xsl_dbm))
68
69 let maps = [ cic_map; nuprl_map; rdf_map; xsl_map ]
70 let close_maps () = List.iter (fun m -> (Lazy.force m) # close) maps
71 let clear_maps () = List.iter (fun m -> (Lazy.force m) # clear) maps
72 let sync_maps  () = List.iter (fun m -> (Lazy.force m) # sync) maps
73
74 let map_of_uri = function
75   | uri when is_cic_uri uri -> Lazy.force cic_map
76   | uri when is_nuprl_uri uri -> Lazy.force nuprl_map
77   | uri when is_rdf_uri uri -> Lazy.force rdf_map
78   | uri when is_xsl_uri uri -> Lazy.force xsl_map
79   | uri -> raise (Unresolvable_URI uri)
80
81 let update_from_server logger server_url = (* use global maps *)
82   debug_print ("Updating information from " ^ server_url);
83   let xml_url_of_uri = function
84       (* TODO missing sanity checks on server_url, e.g. it can contains $1 *)
85     | uri when (Pcre.pmatch ~rex:heading_cic_RE uri) ->
86         Pcre.replace ~rex:heading_cic_RE ~templ:server_url uri
87     | uri when (Pcre.pmatch ~rex:heading_theory_RE uri) ->
88         Pcre.replace ~rex:heading_theory_RE ~templ:server_url uri
89     | uri when (Pcre.pmatch ~rex:heading_nuprl_RE uri) ->
90         Pcre.replace ~rex:heading_nuprl_RE ~templ:server_url uri
91     | uri -> raise (Invalid_URI uri)
92   in
93   let rdf_url_of_uri = function (* TODO as above *)
94     | uri when (Pcre.pmatch ~rex:heading_rdf_cic_RE uri) ->
95         Pcre.replace ~rex:heading_rdf_cic_RE ~templ:server_url uri
96     | uri when (Pcre.pmatch ~rex:heading_rdf_theory_RE uri) ->
97         Pcre.replace ~rex:heading_rdf_theory_RE ~templ:server_url uri
98     | uri -> raise (Invalid_URI uri)
99   in
100   logger (`T ("Processing server: " ^ server_url));
101   logger `BR;
102   let (xml_index, rdf_index, xsl_index) =
103     (* TODO keeps index in memory, is better to keep them on temp files? *)
104     (http_get (server_url ^ "/" ^ (Lazy.force Http_getter_env.xml_index)),
105      http_get (server_url ^ "/" ^ (Lazy.force Http_getter_env.rdf_index)),
106      http_get (server_url ^ "/" ^ (Lazy.force Http_getter_env.xsl_index)))
107   in
108   if (xml_index = None && rdf_index = None && xsl_index = None) then
109     debug_print (sprintf "Warning: useless server %s" server_url);
110   (match xml_index with
111   | Some xml_index ->
112       logger (`T "Updating XML db ...");
113       logger `BR;
114       List.iter
115         (function
116           | l when is_blank_line l -> ()  (* skip blank and commented lines *)
117           | l ->
118               (try
119                 (match Pcre.split ~rex:index_line_sep_RE l with
120                 | [uri; "gz"] ->
121                    assert (is_cic_uri uri || is_nuprl_uri uri) ;
122                    (map_of_uri uri)#replace
123                     uri ((xml_url_of_uri uri) ^ ".xml.gz")
124                 | [uri] ->
125                    assert (is_cic_uri uri || is_nuprl_uri uri) ;
126                    (map_of_uri uri)#replace
127                     uri ((xml_url_of_uri uri) ^ ".xml")
128                 | _ ->
129                     logger (`T ("Ignoring invalid line: '" ^ l));
130                     logger `BR)
131               with Invalid_URI uri ->
132                 logger (`T ("Ignoring invalid XML URI: '" ^ l));
133                 logger `BR))
134         (Pcre.split ~rex:index_sep_RE xml_index); (* xml_index lines *)
135       logger (`T "All done");
136       logger `BR
137   | None -> ());
138   (match rdf_index with
139   | Some rdf_index ->
140       logger (`T "Updating RDF db ...");
141       logger `BR;
142       List.iter
143         (fun l ->
144           try
145             (match Pcre.split ~rex:index_line_sep_RE l with
146             | [uri; "gz"] ->
147                 (Lazy.force rdf_map) # replace uri
148                   ((rdf_url_of_uri uri) ^ ".xml.gz")
149             | [uri] ->
150                 (Lazy.force rdf_map) # replace uri
151                   ((rdf_url_of_uri uri) ^ ".xml")
152             | _ ->
153                 logger (`T ("Ignoring invalid line: '" ^ l));
154                 logger `BR)
155           with Invalid_URI uri ->
156             logger (`T ("Ignoring invalid RDF URI: '" ^ l));
157             logger `BR)
158         (Pcre.split ~rex:index_sep_RE rdf_index); (* rdf_index lines *)
159       logger (`T "All done");
160       logger `BR
161   | None -> ());
162   (match xsl_index with
163   | Some xsl_index ->
164       logger (`T "Updating XSLT db ...");
165       logger `BR;
166       List.iter
167         (fun l -> (Lazy.force xsl_map) # replace l (server_url ^ "/" ^ l))
168         (Pcre.split ~rex:index_sep_RE xsl_index);
169       logger (`T "All done");
170       logger `BR
171   | None -> ());
172   debug_print "done with this server"
173
174 let update_from_all_servers logger () =  (* use global maps *)
175   clear_maps ();
176   List.iter
177     (update_from_server logger)
178       (* reverse order: 1st server is the most important one *)
179     (List.map snd (List.rev (Http_getter_env.servers ())));
180   sync_maps ()
181
182 let update_from_one_server ?(logger = fun _ -> ()) server_url =
183   update_from_server logger server_url
184
185 let temp_file_of_uri uri =
186   let flat_string s s' c =
187     let cs = String.copy s in
188     for i = 0 to (String.length s) - 1 do
189       if String.contains s' s.[i] then cs.[i] <- c
190     done;
191     cs
192   in
193   let user = try Unix.getlogin () with _ -> "" in
194   Filename.open_temp_file (user ^ flat_string uri ".-=:;!?/&" '_') ""
195
196   (* should we use a remote getter or not *)
197 let remote () =
198   try
199     Helm_registry.get "getter.mode" = "remote"
200   with Helm_registry.Key_not_found _ -> false
201 let getter_url () = Helm_registry.get "getter.url"
202
203 (* Remote interface: getter methods implemented using a remote getter *)
204
205   (* <TODO> *)
206 let getxslt_remote ~patch_dtd uri = not_implemented "getxslt_remote"
207 let getdtd_remote ~patch_dtd uri = not_implemented "getdtd_remote"
208 let clean_cache_remote () = not_implemented "clean_cache_remote"
209 let list_servers_remote () = not_implemented "list_servers_remote"
210 let add_server_remote ~logger ~position name =
211   not_implemented "add_server_remote"
212 let remove_server_remote ~logger position =
213   not_implemented "remove_server_remote"
214 let getalluris_remote () = not_implemented "getalluris_remote"
215 let getallrdfuris_remote () = not_implemented "getallrdfuris_remote"
216 let ls_remote lsuri = not_implemented "ls_remote"
217   (* </TODO> *)
218
219 let resolve_remote uri =
220   (* deliver resolve request to http_getter *)
221   let doc = ClientHTTP.get (sprintf "%sresolve?uri=%s" (getter_url ()) uri) in
222   let res = ref Unknown in
223    Pxp_yacc.process_entity Pxp_yacc.default_config (`Entry_content [])
224     (Pxp_yacc.create_entity_manager ~is_document:true Pxp_yacc.default_config
225      (Pxp_yacc.from_string doc))
226     (function
227       | Pxp_yacc.E_start_tag ("url",["value",url],_) -> res := Resolved url
228       | Pxp_yacc.E_start_tag ("unresolved",[],_) ->
229           res := Exception (Unresolvable_URI uri)
230       | Pxp_yacc.E_start_tag _ -> res := Exception UnexpectedGetterOutput
231       | _ -> ());
232    match !res with
233    | Unknown -> raise UnexpectedGetterOutput
234    | Exception e -> raise e
235    | Resolved url -> url
236
237 let register_remote ~uri ~url =
238   ClientHTTP.send (sprintf "%sregister?uri=%s&url=%s" (getter_url ()) uri url)
239
240 let register_remote ~uri ~url =
241   ClientHTTP.send (sprintf "%sregister?uri=%s&url=%s" (getter_url ()) uri url)
242
243 let update_remote logger  () =
244   let answer = ClientHTTP.get (getter_url () ^ "update") in
245   logger (`T answer);
246   logger `BR
247
248 let getxml_remote ~format ~patch_dtd uri =
249   ClientHTTP.get_and_save_to_tmp
250     (sprintf "%sgetxml?uri=%s&format=%s&patch_dtd=%s"
251       (getter_url ()) uri
252       (match format with `Normal -> "normal" | `Gzipped -> "gzipped")
253       (match patch_dtd with true -> "yes" | false -> "no"))
254
255 (* API *)
256
257 let help () = Http_getter_const.usage_string (Http_getter_env.env_to_string ())
258
259 let resolve uri =
260   if remote () then
261     resolve_remote uri
262   else
263     try
264       (map_of_uri uri)#resolve uri
265     with Http_getter_map.Key_not_found _ -> raise (Unresolvable_URI uri)
266
267   (* Warning: this fail if uri is already registered *)
268 let register ~uri ~url =
269   if remote () then
270     register_remote ~uri ~url
271   else
272     (map_of_uri uri)#add uri url
273
274 let update ?(logger = fun _ -> ()) () =
275   if remote () then
276     update_remote logger ()
277   else
278     update_from_all_servers logger ()
279
280 let getxml ?(format = `Normal) ?(patch_dtd = true) uri =
281   if remote () then
282     getxml_remote ~format ~patch_dtd uri
283   else begin
284     let url = resolve uri in
285     let (fname, outchan) = temp_file_of_uri uri in
286     Http_getter_cache.respond_xml ~via_http:false ~enc:format ~patch:patch_dtd
287       ~uri ~url outchan;
288     close_out outchan;
289     fname
290   end
291
292 let getxslt ?(patch_dtd = true) uri =
293   if remote () then
294     getxslt_remote ~patch_dtd uri
295   else begin
296     let url = resolve uri in
297     let (fname, outchan) = temp_file_of_uri uri in
298     Http_getter_cache.respond_xsl ~via_http:false ~url ~patch:patch_dtd outchan;
299     close_out outchan;
300     fname
301   end
302
303 let getdtd ?(patch_dtd = true) uri =
304   if remote () then
305     getdtd_remote ~patch_dtd uri
306   else begin
307     let url = Lazy.force Http_getter_env.dtd_dir ^ "/" ^ uri in
308     let (fname, outchan) = temp_file_of_uri uri in
309     Http_getter_cache.respond_dtd ~via_http:false ~url ~patch:patch_dtd outchan;
310     close_out outchan;
311     fname
312   end
313
314 let clean_cache () =
315   if remote () then
316     clean_cache_remote ()
317   else
318     Http_getter_cache.clean ()
319
320 let list_servers () =
321   if remote () then
322     list_servers_remote ()
323   else
324     Http_getter_env.servers ()
325
326 let add_server ?(logger = fun _ -> ()) ?(position = 0) name =
327   if remote () then
328     add_server_remote ~logger ~position name
329   else begin
330     if position = 0 then begin
331       Http_getter_env.add_server ~position:0 name;
332       update_from_one_server ~logger name (* quick update (new server only) *)
333     end else if position > 0 then begin
334       Http_getter_env.add_server ~position name;
335       update ~logger ()
336     end else  (* already checked by parse_position *)
337       assert false
338   end
339
340 let has_server position = List.mem_assoc position (Http_getter_env.servers ())
341
342 let remove_server ?(logger = fun _ -> ()) position =
343   if remote () then
344     remove_server_remote ~logger ()
345   else begin
346     let server_name =
347       try
348         List.assoc position (Http_getter_env.servers ())
349       with Not_found ->
350         raise (Invalid_argument (sprintf "no server with position %d" position))
351     in
352     Http_getter_env.remove_server position;
353     update ~logger ()
354   end
355
356 let return_uris map filter =
357   let uris = ref [] in
358   map#iter (fun uri _ -> if filter uri then uris := uri :: !uris);
359   List.rev !uris
360
361 let getalluris () =
362   if remote () then
363     getalluris_remote ()
364   else
365     let filter uri =
366       (Pcre.pmatch ~rex:heading_cic_RE uri) &&
367       not (Pcre.pmatch ~rex:trailing_types_RE uri)
368     in
369     return_uris (Lazy.force cic_map) filter
370
371 let getallrdfuris classs =
372   if remote () then
373     getallrdfuris_remote ()
374   else
375     let filter =
376       let base = "^helm:rdf:www\\.cs\\.unibo\\.it/helm/rdf/" in
377       match classs with
378       | `Forward -> (fun uri -> Pcre.pmatch ~pat:(base ^ "forward") uri)
379       | `Backward -> (fun uri -> Pcre.pmatch ~pat:(base ^ "backward") uri)
380     in
381     return_uris (Lazy.force rdf_map) filter
382
383 let ls =
384   let (++) (oldann, oldtypes, oldbody, oldtree)
385            (newann, newtypes, newbody, newtree) =
386     ((if newann   > oldann    then newann   else oldann),
387      (if newtypes > oldtypes  then newtypes else oldtypes),
388      (if newbody  > oldbody   then newbody  else oldbody),
389      (if newtree  > oldtree   then newtree  else oldtree))
390   in
391   let basepart_RE =
392     Pcre.regexp
393       "^([^.]*\\.[^.]*)((\\.body)|(\\.proof_tree)|(\\.types))?(\\.ann)?$"
394   in
395   let (types_RE, types_ann_RE, body_RE, body_ann_RE,
396        proof_tree_RE, proof_tree_ann_RE) =
397     (Pcre.regexp "\\.types$", Pcre.regexp "\\.types\\.ann$",
398      Pcre.regexp "\\.body$", Pcre.regexp "\\.body\\.ann$",
399      Pcre.regexp "\\.proof_tree$", Pcre.regexp "\\.proof_tree\\.ann$")
400   in
401   let (slash_RE, til_slash_RE, no_slashes_RE) =
402     (Pcre.regexp "/", Pcre.regexp "^.*/", Pcre.regexp "^[^/]*$")
403   in
404   fun lsuri ->
405     if remote () then
406       ls_remote lsuri
407     else begin
408       let pat =
409         "^" ^
410         (match lsuri with Cic p -> ("cic:" ^ p) | Theory p -> ("theory:" ^ p))
411       in
412       let (dir_RE, obj_RE) =
413         (Pcre.regexp (pat ^ "/"), Pcre.regexp (pat ^ "(\\.|$)"))
414       in
415       let dirs = ref StringSet.empty in
416       let objs = Hashtbl.create 17 in
417       let store_dir d =
418         dirs := StringSet.add (List.hd (Pcre.split ~rex:slash_RE d)) !dirs
419       in
420       let store_obj o =
421         let basepart = Pcre.replace ~rex:basepart_RE ~templ:"$1" o in
422         let no_flags = false, No, No, No in
423         let oldflags =
424           try
425             Hashtbl.find objs basepart
426           with Not_found -> (* no ann, no types, no body, no proof tree *)
427             no_flags
428         in
429         let newflags =
430           match o with
431           | s when Pcre.pmatch ~rex:types_RE s          -> (false, Yes, No, No)
432           | s when Pcre.pmatch ~rex:types_ann_RE s      -> (true,  Ann, No, No)
433           | s when Pcre.pmatch ~rex:body_RE s           -> (false, No, Yes, No)
434           | s when Pcre.pmatch ~rex:body_ann_RE s       -> (true,  No, Ann, No)
435           | s when Pcre.pmatch ~rex:proof_tree_RE s     -> (false, No, No, Yes)
436           | s when Pcre.pmatch ~rex:proof_tree_ann_RE s -> (true,  No, No, Ann)
437           | s -> no_flags
438         in
439         Hashtbl.replace objs basepart (oldflags ++ newflags)
440       in
441       (Lazy.force cic_map) # iter
442         (* BLEARGH Dbm module lacks support for fold-like functions *)
443         (fun key _ ->
444           match key with
445           | uri when Pcre.pmatch ~rex:dir_RE uri ->  (* directory hit *)
446               let localpart = Pcre.replace ~rex:dir_RE uri in
447               if Pcre.pmatch ~rex:no_slashes_RE localpart then
448                 store_obj localpart
449               else
450                 store_dir localpart
451           | uri when Pcre.pmatch ~rex:obj_RE  uri ->  (* file hit *)
452               store_obj (Pcre.replace ~rex:til_slash_RE uri)
453           | uri -> () (* miss *));
454       let ls_items = ref [] in
455       StringSet.iter (fun dir -> ls_items := Ls_section dir :: !ls_items) !dirs;
456       Http_getter_misc.hashtbl_sorted_iter
457         (fun uri (annflag, typesflag, bodyflag, treeflag) ->
458           ls_items :=
459             Ls_object {
460               uri = uri; ann = annflag;
461               types = typesflag; body = bodyflag; proof_tree = treeflag
462             } :: !ls_items)
463         objs;
464       List.rev !ls_items
465     end
466
467   (* Shorthands from now on *)
468
469 let getxml' uri = getxml (UriManager.string_of_uri uri)
470 let resolve' uri = resolve (UriManager.string_of_uri uri)
471 let register' uri url = register ~uri:(UriManager.string_of_uri uri) ~url
472