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