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