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