]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/getter/http_getter.ml
a wrong exception was raised
[helm.git] / helm / ocaml / getter / http_getter.ml
1 (* Copyright (C) 2005, HELM Team.
2  * 
3  * This file is part of HELM, an Hypertextual, Electronic
4  * Library of Mathematics, developed at the Computer Science
5  * Department, University of Bologna, Italy.
6  * 
7  * HELM is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  * 
12  * HELM is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with HELM; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://helm.cs.unibo.it/
24  *)
25
26 open Printf
27
28 open Http_getter_common
29 open Http_getter_misc
30 open Http_getter_types
31
32 exception Not_implemented of string
33 exception UnexpectedGetterOutput
34
35 type resolve_result =
36   | Unknown
37   | Exception of exn
38   | Resolved of string
39
40 type logger_callback = HelmLogger.html_tag -> unit
41
42 let stdout_logger tag = print_string (HelmLogger.string_of_html_tag tag)
43
44 let not_implemented s = raise (Not_implemented ("Http_getter." ^ s))
45
46 let index_line_sep_RE     = Pcre.regexp "[ \t]+"
47 let index_sep_RE          = Pcre.regexp "\r\n|\r|\n"
48 let trailing_types_RE     = Pcre.regexp "\\.types$"
49 let heading_cic_RE        = Pcre.regexp "^cic:"
50 let heading_theory_RE     = Pcre.regexp "^theory:"
51 let heading_nuprl_RE      = Pcre.regexp "^nuprl:"
52 let types_RE              = Pcre.regexp "\\.types$"
53 let types_ann_RE          = Pcre.regexp "\\.types\\.ann$"
54 let body_RE               = Pcre.regexp "\\.body$"
55 let body_ann_RE           = Pcre.regexp "\\.body\\.ann$"
56 let proof_tree_RE         = Pcre.regexp "\\.proof_tree$"
57 let proof_tree_ann_RE     = Pcre.regexp "\\.proof_tree\\.ann$"
58 let theory_RE             = Pcre.regexp "\\.theory$"
59 let basepart_RE           = Pcre.regexp
60   "^([^.]*\\.[^.]*)((\\.body)|(\\.proof_tree)|(\\.types))?(\\.ann)?$"
61 let slash_RE              = Pcre.regexp "/"
62 let pipe_RE               = Pcre.regexp "\\|"
63 let til_slash_RE          = Pcre.regexp "^.*/"
64 let no_slashes_RE         = Pcre.regexp "^[^/]*$"
65 let fix_regexp_RE         = Pcre.regexp ("^" ^ (Pcre.quote "(cic|theory)"))
66 let showable_file_RE      =
67   Pcre.regexp "(\\.con|\\.ind|\\.var|\\.body|\\.types|\\.proof_tree)$"
68
69 let xml_suffix = ".xml"
70 let theory_suffix = ".theory"
71
72   (* global maps, shared by all threads *)
73
74 let ends_with_slash s =
75   try
76     s.[String.length s - 1] = '/'
77   with Invalid_argument _ -> false
78
79   (* should we use a remote getter or not *)
80 let remote () =
81   try
82     Helm_registry.get "getter.mode" = "remote"
83   with Helm_registry.Key_not_found _ -> false
84
85 let getter_url () = Helm_registry.get "getter.url"
86
87 (* Remote interface: getter methods implemented using a remote getter *)
88
89   (* <TODO> *)
90 let getxml_remote uri = not_implemented "getxml_remote"
91 let getxslt_remote uri = not_implemented "getxslt_remote"
92 let getdtd_remote uri = not_implemented "getdtd_remote"
93 let clean_cache_remote () = not_implemented "clean_cache_remote"
94 let list_servers_remote () = not_implemented "list_servers_remote"
95 let add_server_remote ~logger ~position name =
96   not_implemented "add_server_remote"
97 let remove_server_remote ~logger position =
98   not_implemented "remove_server_remote"
99 let getalluris_remote () = not_implemented "getalluris_remote"
100 let ls_remote lsuri = not_implemented "ls_remote"
101 let exists_remote uri = not_implemented "exists_remote"
102   (* </TODO> *)
103
104 let resolve_remote uri =
105   (* deliver resolve request to http_getter *)
106   let doc =
107     Http_getter_wget.get (sprintf "%sresolve?uri=%s" (getter_url ()) uri)
108   in
109   let res = ref Unknown in
110   let start_element tag attrs =
111     match tag with
112     | "url" ->
113         (try
114           res := Resolved (List.assoc "value" attrs)
115         with Not_found -> ())
116     | "unresolvable" -> res := Exception (Unresolvable_URI uri)
117     | "not_found" -> res := Exception (Key_not_found uri)
118     | _ -> ()
119   in
120   let callbacks = {
121     XmlPushParser.default_callbacks with
122       XmlPushParser.start_element = Some start_element
123   } in
124   let xml_parser = XmlPushParser.create_parser callbacks in
125   XmlPushParser.parse xml_parser (`String doc);
126   XmlPushParser.final xml_parser;
127   match !res with
128   | Unknown -> raise UnexpectedGetterOutput
129   | Exception e -> raise e
130   | Resolved url -> url
131
132 (* API *)
133
134 let help () = Http_getter_const.usage_string (Http_getter_env.env_to_string ())
135
136 let exists uri =
137 (*   prerr_endline ("Http_getter.exists " ^ uri); *)
138   if remote () then
139     exists_remote uri
140   else
141     Http_getter_storage.exists (uri ^ xml_suffix)
142         
143 let resolve uri =
144   if remote () then
145     resolve_remote uri
146   else
147     try
148       Http_getter_storage.resolve (uri ^ xml_suffix)
149     with Http_getter_storage.Resource_not_found _ -> raise (Key_not_found uri)
150
151 let deref_index_theory uri =
152   if is_theory_uri uri && Filename.basename uri = "index.theory" then
153     strip_trailing_slash (Filename.dirname uri) ^ theory_suffix
154   else
155     uri
156
157 let getxml uri =
158   if remote () then getxml_remote uri
159   else begin
160     let uri' = deref_index_theory uri in
161     (try
162       try
163         Http_getter_storage.filename (uri' ^ xml_suffix)
164       with Http_getter_storage.Resource_not_found _ as exn ->
165         if uri <> uri' then Http_getter_storage.filename (uri ^ xml_suffix)
166         else raise (Key_not_found uri)
167     with Http_getter_storage.Resource_not_found _ -> raise (Key_not_found uri))
168   end
169
170 let getxslt uri =
171   if remote () then getxslt_remote uri
172   else Http_getter_storage.filename ~find:true ("xslt:/" ^ uri)
173
174 let getdtd uri =
175   if remote () then
176     getdtd_remote uri
177   else begin
178     let fname = Lazy.force Http_getter_env.dtd_dir ^ "/" ^ uri in
179     if not (Sys.file_exists fname) then raise (Dtd_not_found uri);
180     fname
181   end
182
183 let clean_cache () =
184   if remote () then
185     clean_cache_remote ()
186   else
187     Http_getter_storage.clean_cache ()
188
189 let (++) (oldann, oldtypes, oldbody, oldtree)
190          (newann, newtypes, newbody, newtree) =
191   ((if newann   > oldann    then newann   else oldann),
192    (if newtypes > oldtypes  then newtypes else oldtypes),
193    (if newbody  > oldbody   then newbody  else oldbody),
194    (if newtree  > oldtree   then newtree  else oldtree))
195     
196 let store_obj tbl o =
197 (*   prerr_endline ("Http_getter.store_obj " ^ o); *)
198   if Pcre.pmatch ~rex:showable_file_RE o then begin
199     let basepart = Pcre.replace ~rex:basepart_RE ~templ:"$1" o in
200     let no_flags = false, No, No, No in
201     let oldflags =
202       try
203         Hashtbl.find tbl basepart
204       with Not_found -> (* no ann, no types, no body, no proof tree *)
205         no_flags
206     in
207     let newflags =
208       match o with
209       | s when Pcre.pmatch ~rex:types_RE s          -> (false, Yes, No, No)
210       | s when Pcre.pmatch ~rex:types_ann_RE s      -> (true,  Ann, No, No)
211       | s when Pcre.pmatch ~rex:body_RE s           -> (false, No, Yes, No)
212       | s when Pcre.pmatch ~rex:body_ann_RE s       -> (true,  No, Ann, No)
213       | s when Pcre.pmatch ~rex:proof_tree_RE s     -> (false, No, No, Yes)
214       | s when Pcre.pmatch ~rex:proof_tree_ann_RE s -> (true,  No, No, Ann)
215       | s -> no_flags
216     in
217     Hashtbl.replace tbl basepart (oldflags ++ newflags)
218   end
219   
220 let store_dir set_ref d =
221   set_ref := StringSet.add (List.hd (Pcre.split ~rex:slash_RE d)) !set_ref
222
223 let collect_ls_items dirs_set objs_tbl =
224   let items = ref [] in
225   StringSet.iter (fun dir -> items := Ls_section dir :: !items) dirs_set;
226   Http_getter_misc.hashtbl_sorted_iter
227     (fun uri (annflag, typesflag, bodyflag, treeflag) ->
228       items :=
229         Ls_object {
230           uri = uri; ann = annflag;
231           types = typesflag; body = bodyflag; proof_tree = treeflag
232         } :: !items)
233     objs_tbl;
234   List.rev !items
235
236 let contains_object = (<>) []
237
238   (** non regexp-aware version of ls *)
239 let rec dumb_ls uri_prefix =
240 (*   prerr_endline ("Http_getter.dumb_ls " ^ uri_prefix); *)
241   if is_cic_obj_uri uri_prefix then begin
242     let dirs = ref StringSet.empty in
243     let objs = Hashtbl.create 17 in
244     List.iter
245       (fun fname ->
246         if ends_with_slash fname then
247           store_dir dirs fname
248         else
249           try
250             store_obj objs (strip_suffix ~suffix:xml_suffix fname)
251           with Invalid_argument _ -> ())
252       (Http_getter_storage.ls uri_prefix);
253     collect_ls_items !dirs objs
254   end else if is_theory_uri uri_prefix then begin
255     let items = ref [] in
256     let add_theory fname =
257       items :=
258         Ls_object {
259           uri = fname; ann = false; types = No; body = No; proof_tree = No }
260         :: !items
261     in
262     let cic_uri_prefix =
263       Pcre.replace_first ~rex:heading_theory_RE ~templ:"cic:" uri_prefix
264     in
265     List.iter
266       (fun fname ->
267         if ends_with_slash fname then
268           items := Ls_section (strip_trailing_slash fname) :: !items
269         else
270           try
271             let fname = strip_suffix ~suffix:xml_suffix fname in
272             let theory_name = strip_suffix ~suffix:theory_suffix fname in
273             let sub_theory = normalize_dir cic_uri_prefix ^ theory_name ^ "/" in
274             if is_empty_theory sub_theory then add_theory fname
275           with Invalid_argument _ -> ())
276       (Http_getter_storage.ls uri_prefix);
277     (try
278       if contains_object (dumb_ls cic_uri_prefix)
279         && exists (strip_trailing_slash uri_prefix ^ theory_suffix)
280       then
281         add_theory "index.theory";
282     with Unresolvable_URI _ -> ());
283     !items
284   end else
285     raise (Invalid_URI uri_prefix)
286
287 and is_empty_theory uri_prefix =
288 (*   prerr_endline ("is_empty_theory " ^ uri_prefix); *)
289   not (contains_object (dumb_ls uri_prefix))
290
291   (* handle simple regular expressions of the form "...(..|..|..)..." on cic
292    * uris, not meant to be a real implementation of regexp. The only we use is
293    * "(cic|theory):/..." *)
294 let explode_ls_regexp regexp =
295   try
296     let len = String.length regexp in
297     let lparen_idx = String.index regexp '(' in
298     let rparen_idx = String.index_from regexp lparen_idx ')' in
299     let choices_str = (* substring between parens, parens excluded *)
300       String.sub regexp (lparen_idx + 1) (rparen_idx - lparen_idx - 1)
301     in
302     let choices = Pcre.split ~rex:pipe_RE choices_str in
303     let prefix = String.sub regexp 0 lparen_idx in
304     let suffix = String.sub regexp (rparen_idx + 1) (len - (rparen_idx + 1)) in
305     List.map (fun choice -> prefix ^ choice ^ suffix) choices
306   with Not_found -> [regexp]
307
308 let merge_results results =
309   let rec aux objects_acc dirs_acc = function
310     | [] -> dirs_acc @ objects_acc
311     | Ls_object _ as obj :: tl -> aux (obj :: objects_acc) dirs_acc tl
312     | Ls_section _ as dir :: tl ->
313         if List.mem dir dirs_acc then (* filters out dir duplicates *)
314           aux objects_acc dirs_acc tl
315         else
316           aux objects_acc (dir :: dirs_acc) tl
317   in
318   aux [] [] (List.concat results)
319
320 let ls regexp =
321   if remote () then
322     ls_remote regexp
323   else
324     let prefixes = explode_ls_regexp regexp in
325     merge_results (List.map dumb_ls prefixes)
326
327 let getalluris () =
328   let rec aux acc = function
329     | [] -> acc
330     | dir :: todo ->
331         let acc', todo' =
332           List.fold_left
333             (fun (acc, subdirs) result ->
334               match result with
335               | Ls_object obj -> (dir ^ obj.uri) :: acc, subdirs
336               | Ls_section sect -> acc, (dir ^ sect ^ "/") :: subdirs)
337             (acc, todo)
338             (dumb_ls dir)
339         in
340         aux acc' todo'
341   in
342   aux [] ["cic:/"] (* trailing slash required *)
343
344 (* Shorthands from now on *)
345
346 let getxml' uri = getxml (UriManager.string_of_uri uri)
347 let resolve' uri = resolve (UriManager.string_of_uri uri)
348 let exists' uri = exists (UriManager.string_of_uri uri)
349
350 let init () =
351   Http_getter_logger.set_log_level
352     (Helm_registry.get_opt_default Helm_registry.int ~default:1
353       "getter.log_level");
354   Http_getter_logger.set_log_file
355     (Helm_registry.get_opt Helm_registry.string "getter.log_file")
356