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