]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/getter/http_getter_storage.ml
77bfe138da3450d9a484fdf2a6e8681b591d7e83
[helm.git] / helm / software / components / getter / http_getter_storage.ml
1 (* Copyright (C) 2004-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 (* $Id$ *)
27
28 open Printf
29
30 open Http_getter_misc
31 open Http_getter_types
32
33 exception Not_found'
34 exception Resource_not_found of string * string  (** method, uri *)
35
36 let index_fname = "INDEX"
37
38 (******************************* HELPERS **************************************)
39
40 let trailing_slash_RE = Pcre.regexp "/$"
41 let relative_RE_raw = "(^[^/]+(/[^/]+)*/?$)"
42 let relative_RE = Pcre.regexp relative_RE_raw
43 let file_scheme_RE_raw = "(^file://)"
44 let extended_file_scheme_RE = Pcre.regexp "(^file:/+)"
45 let file_scheme_RE = Pcre.regexp (relative_RE_raw ^ "|" ^ file_scheme_RE_raw)
46 let http_scheme_RE = Pcre.regexp "^http://"
47 let newline_RE = Pcre.regexp "\\n"
48 let cic_scheme_sep_RE = Pcre.regexp ":/"
49 let gz_suffix = ".gz"
50 let gz_suffix_len = String.length gz_suffix
51
52   (* file:///bla -> bla, bla -> bla *)
53 let path_of_file_url url =
54   assert (Pcre.pmatch ~rex:file_scheme_RE url);
55   if Pcre.pmatch ~rex:relative_RE url then
56     url
57   else  (* absolute path, add heading "/" if missing *)
58     "/" ^ (Pcre.replace ~rex:extended_file_scheme_RE url)
59
60 let strip_gz_suffix fname =
61   if extension fname = gz_suffix then
62     String.sub fname 0 (String.length fname - gz_suffix_len)
63   else
64     fname
65
66 let normalize_root uri =  (* add trailing slash to roots *)
67   try
68     if uri.[String.length uri - 1] = ':' then uri ^ "/"
69     else uri
70   with Invalid_argument _ -> uri
71
72 let remove_duplicates l =
73   Http_getter_misc.list_uniq (List.stable_sort Pervasives.compare l)
74
75 let has_rdonly l =  List.exists ((=) `Read_only) l
76 let has_legacy l =  List.exists ((=) `Legacy) l
77 let is_readwrite attrs = (not (has_legacy attrs) && not (has_rdonly attrs))
78
79 let is_file_schema url = Pcre.pmatch ~rex:file_scheme_RE url
80 let is_http_schema url = Pcre.pmatch ~rex:http_scheme_RE url
81
82 let is_empty_listing files = 
83   List.for_all
84    (fun s ->
85      let len = String.length s in
86       len < 4 || String.sub s (len - 4) 4 <> ".xml") files
87
88 (************************* GLOBALS PREFIXES **********************************)
89     
90   (** associative list regular expressions -> url prefixes
91    * sorted with longest prefixes first *)
92 let prefix_map_ref = ref (lazy (
93   List.map
94     (fun (uri_prefix, (url_prefix, attrs)) ->
95       let uri_prefix = normalize_dir uri_prefix in
96       let url_prefix = normalize_dir url_prefix in
97       let regexp = Pcre.regexp ("^(" ^ Pcre.quote uri_prefix ^ ")") in
98       regexp, strip_trailing_slash uri_prefix, url_prefix, attrs)
99     (List.rev (Lazy.force Http_getter_env.prefixes))))
100
101 let prefix_map () = !prefix_map_ref
102
103   (** given an uri returns the prefixes for it *)
104 let lookup uri =
105   let matches =
106     List.filter (fun (rex, _, l, _) -> Pcre.pmatch ~rex uri)
107       (Lazy.force (prefix_map ())) in
108   if matches = [] then raise (Unresolvable_URI uri);
109   matches
110
111 let get_attrs uri = List.map (fun (_, _, _, attrs) -> attrs) (lookup uri)
112
113 (*************************** ACTIONS ******************************************)
114   
115 let exists_http _ url =
116   Http_getter_wget.exists (url ^ gz_suffix) || Http_getter_wget.exists url
117
118 let exists_file _ fname =
119   Sys.file_exists (fname ^ gz_suffix) || Sys.file_exists fname
120
121 let resolve_http ~must_exists _ url =
122   try
123     if must_exists then
124       List.find Http_getter_wget.exists [ url ^ gz_suffix; url ]
125     else
126       url
127   with Not_found -> raise Not_found'
128
129 let resolve_file ~must_exists _ fname =
130   try
131     if must_exists then
132       List.find Sys.file_exists [ fname ^ gz_suffix; fname ]
133     else
134       fname
135   with Not_found -> raise Not_found'
136
137 let ls_file_single _ path_prefix =
138   let is_dir fname = (Unix.stat fname).Unix.st_kind = Unix.S_DIR in
139   let is_useless dir = try dir.[0] = '.' with _ -> false in
140   let entries = ref [] in
141   try
142     let dir_handle = Unix.opendir path_prefix in
143     (try
144       while true do
145         let entry = Unix.readdir dir_handle in
146         if is_useless entry then
147           ()
148         else if is_dir (path_prefix ^ "/" ^ entry) then
149           entries := normalize_dir entry :: !entries
150         else
151           entries := strip_gz_suffix entry :: !entries
152       done
153     with End_of_file -> Unix.closedir dir_handle);
154     remove_duplicates !entries
155   with Unix.Unix_error (_, "opendir", _) -> []
156
157 let ls_http_single _ url_prefix =
158   try
159     let index = Http_getter_wget.get (normalize_dir url_prefix ^ index_fname) in
160     Pcre.split ~rex:newline_RE index
161   with Http_client_error _ -> raise Not_found'
162
163 let get_file _ path =
164   if Sys.file_exists (path ^ gz_suffix) then
165     path ^ gz_suffix
166   else if Sys.file_exists path then
167     path
168   else
169     raise Not_found'
170
171 let get_http uri url =
172   let scheme, path =
173     match Pcre.split ~rex:cic_scheme_sep_RE uri with
174     | [scheme; path] -> scheme, path
175     | _ -> assert false
176   in
177   let cache_name =
178     sprintf "%s%s/%s" (Lazy.force Http_getter_env.cache_dir) scheme path
179   in
180   if Sys.file_exists (cache_name ^ gz_suffix) then
181     cache_name ^ gz_suffix
182   else if Sys.file_exists cache_name then
183     cache_name
184   else begin  (* fill cache *)
185     Http_getter_misc.mkdir ~parents:true (Filename.dirname cache_name);
186     (try
187       Http_getter_wget.get_and_save (url ^ gz_suffix) (cache_name ^ gz_suffix);
188       cache_name ^ gz_suffix
189     with Http_client_error _ ->
190       (try
191         Http_getter_wget.get_and_save url cache_name;
192         cache_name
193       with Http_client_error _ ->
194         raise Not_found'))
195   end
196
197 let remove_file _ path =
198   if Sys.file_exists (path ^ gz_suffix) then Sys.remove (path ^ gz_suffix);
199   if Sys.file_exists path then Sys.remove path
200
201 let remove_http _ _ =
202   prerr_endline "Http_getter_storage.remove: not implemented for HTTP scheme";
203   assert false
204
205 (**************************** RESOLUTION OF PREFIXES ************************)
206   
207 let resolve_prefixes write exists uri =
208   let exists_test new_uri =
209     if is_file_schema new_uri then 
210       exists_file () (path_of_file_url new_uri)
211     else if is_http_schema new_uri then
212       exists_http () new_uri
213     else false
214   in
215   let rec aux = function
216     | (rex, _, url_prefix, attrs) :: tl ->
217         (match write, is_readwrite attrs, exists with
218         | true ,false, _ -> aux tl
219         | true ,true ,true  
220         | false,_ ,true ->
221             let new_uri = (Pcre.replace_first ~rex ~templ:url_prefix uri) in
222             if exists_test new_uri then new_uri::aux tl else aux tl
223         | true ,true ,false
224         | false,_ ,false -> 
225             (Pcre.replace_first ~rex ~templ:url_prefix uri) :: (aux tl))
226     | [] -> []
227   in
228   aux (lookup uri)
229
230 let resolve_prefix w e u =
231   match resolve_prefixes w e u with
232   | hd :: _ -> hd
233   | [] -> 
234       raise 
235         (Resource_not_found 
236           (Printf.sprintf "resolve_prefix write:%b exists:%b" w e,u))
237   
238 (* uncomment to debug prefix resolution *)
239 (*
240 let resolve_prefix w e u =
241   prerr_endline 
242     ("XXX w=" ^ string_of_bool w ^ " e=" ^ string_of_bool e ^" :" ^ u);
243   let rc = resolve_prefix w e u in
244   prerr_endline ("YYY :" ^ rc ^ "\n");
245   rc 
246 *)
247
248 (************************* DISPATCHERS ***************************************)
249
250 type 'a storage_method = {
251   name: string;
252   write: bool;
253   exists: bool;
254   file: string -> string -> 'a; (* unresolved uri, resolved uri *)
255   http: string -> string -> 'a; (* unresolved uri, resolved uri *)
256 }
257
258 let invoke_method storage_method uri url =
259   try
260     if is_file_schema url then 
261       storage_method.file uri (path_of_file_url url)
262     else if is_http_schema url then
263       storage_method.http uri url
264     else
265       raise (Unsupported_scheme url)
266   with Not_found' -> raise (Resource_not_found (storage_method.name, uri))
267   
268 let dispatch_single storage_method uri =
269   assert (extension uri <> gz_suffix);
270   let uri = normalize_root uri in
271   let url = resolve_prefix storage_method.write storage_method.exists uri in
272   invoke_method storage_method uri url
273
274 let dispatch_multi storage_method uri =
275   let urls = resolve_prefixes storage_method.write storage_method.exists uri in
276   let rec aux = function
277     | [] -> raise (Resource_not_found (storage_method.name, uri))
278     | url :: tl ->
279         (try
280           invoke_method storage_method uri url
281         with Resource_not_found _ -> aux tl)
282   in
283   aux urls
284
285 let dispatch_all storage_method uri =
286   let urls = resolve_prefixes storage_method.write storage_method.exists uri in
287   List.map (fun url -> invoke_method storage_method uri url) urls
288  
289 (******************************** EXPORTED FUNCTIONS *************************)
290   
291 let exists s =
292   try 
293     dispatch_single 
294     { write = false; 
295       name = "exists"; 
296       exists = true;
297       file = exists_file; http = exists_http; } s
298   with Resource_not_found _ -> false
299
300 let resolve ?(must_exists=true) ~writable =
301   (if must_exists then
302     dispatch_multi
303   else
304     dispatch_single)
305     { write = writable;
306       name="resolve"; 
307       exists = must_exists;
308       file = resolve_file ~must_exists; 
309       http = resolve_http ~must_exists; }
310
311 let remove =
312   dispatch_single 
313     { write = false;
314       name = "remove"; 
315       exists=true;
316       file = remove_file; http = remove_http; }
317
318 let filename ?(find = false) =
319   (if find then dispatch_multi else dispatch_single)
320     { write = false;
321       name = "filename"; 
322       exists=true;
323       file = get_file; http = get_http; }
324
325 let ls uri_prefix =
326   let ls_all s =
327     try 
328       dispatch_all 
329         { write=false;
330           name = "ls"; 
331           exists=true;
332           file = ls_file_single; http = ls_http_single; } s
333     with Resource_not_found _ -> []
334   in 
335   let direct_results = List.flatten (ls_all uri_prefix) in
336   List.fold_left
337     (fun results (_, uri_prefix', _, _) ->
338       if Filename.dirname uri_prefix' = strip_trailing_slash uri_prefix then
339         (Filename.basename uri_prefix' ^ "/") :: results
340       else
341         results)
342     direct_results
343     (Lazy.force (prefix_map ()))
344
345 let clean_cache () =
346   ignore (Sys.command
347     (sprintf "rm -rf %s/" (Lazy.force Http_getter_env.cache_dir)))
348  
349 let list_writable_prefixes _ =
350   HExtlib.filter_map 
351     (fun (_,_,url,attrs) -> 
352       if is_readwrite attrs then 
353         Some url 
354       else 
355         None) 
356     (Lazy.force (prefix_map ()))
357
358 let is_legacy uri = List.for_all has_legacy (get_attrs uri)
359
360 (* implement this in a fast way! *)
361 let is_empty buri =
362   let buri = strip_trailing_slash buri ^ "/" in
363   let files = ls buri in
364   is_empty_listing files
365
366 let is_read_only uri = 
367   let is_empty_dir path =
368     let files = 
369       if is_file_schema path then 
370         ls_file_single () (path_of_file_url path)
371       else if is_http_schema path then
372         ls_http_single () path
373       else 
374         assert false
375     in
376     is_empty_listing files
377   in
378   let rec aux found_writable = function
379     | (rex, _, url_prefix, attrs)::tl -> 
380         let new_url = (Pcre.replace_first ~rex ~templ:url_prefix uri) in
381         let rdonly = has_legacy attrs || has_rdonly attrs in
382         (match rdonly, is_empty_dir new_url, found_writable with
383         | true, false, _ -> true
384         | true, true, _ -> aux found_writable tl
385         | false, _, _ -> aux true tl)
386     | [] -> not found_writable (* if found_writable then false else true *)
387   in 
388   aux false (lookup uri)
389
390 let activate_system_mode () =
391   let map = Lazy.force (prefix_map ()) in
392   let map = 
393     HExtlib.filter_map 
394       (fun ((rex, urip, urlp, attrs) as entry) -> 
395          if has_legacy attrs then
396            Some entry
397          else if has_rdonly attrs then
398            Some (rex, urip, urlp, List.filter ((<>) `Read_only) attrs)
399          else
400            None) 
401       map
402   in
403   let map = map in (* just to remember that ocamlc 'lazy' is a ... *)
404   prefix_map_ref := (lazy map)
405
406 (* eof *)