1 (* Copyright (C) 2004-2005, HELM Team.
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.
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.
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.
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,
22 * For details, see the HELM World-Wide-Web page,
23 * http://helm.cs.unibo.it/
31 open Http_getter_types
34 exception Resource_not_found of string * string (** method, uri *)
36 let index_fname = "INDEX"
38 (******************************* HELPERS **************************************)
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 ":/"
50 let gz_suffix_len = String.length gz_suffix
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
57 else (* absolute path, add heading "/" if missing *)
58 "/" ^ (Pcre.replace ~rex:extended_file_scheme_RE url)
60 let strip_gz_suffix fname =
61 if extension fname = gz_suffix then
62 String.sub fname 0 (String.length fname - gz_suffix_len)
66 let normalize_root uri = (* add trailing slash to roots *)
68 if uri.[String.length uri - 1] = ':' then uri ^ "/"
70 with Invalid_argument _ -> uri
72 let remove_duplicates l =
73 Http_getter_misc.list_uniq (List.stable_sort Pervasives.compare l)
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))
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
82 let is_empty_listing files =
83 List.for_all (fun s -> s.[String.length s - 1] = '/') files
85 (************************* GLOBALS PREFIXES **********************************)
87 (** associative list regular expressions -> url prefixes
88 * sorted with longest prefixes first *)
89 let prefix_map_ref = ref (lazy (
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))))
98 let prefix_map () = !prefix_map_ref
100 (** given an uri returns the prefixes for it *)
103 List.filter (fun (rex, _, l, _) -> Pcre.pmatch ~rex uri)
104 (Lazy.force (prefix_map ())) in
105 if matches = [] then raise (Unresolvable_URI uri);
108 let get_attrs uri = List.map (fun (_, _, _, attrs) -> attrs) (lookup uri)
110 (*************************** ACTIONS ******************************************)
112 let exists_http _ url =
113 Http_getter_wget.exists (url ^ gz_suffix) || Http_getter_wget.exists url
115 let exists_file _ fname =
116 Sys.file_exists (fname ^ gz_suffix) || Sys.file_exists fname
118 let resolve_http ~must_exists _ url =
121 List.find Http_getter_wget.exists [ url ^ gz_suffix; url ]
124 with Not_found -> raise Not_found'
126 let resolve_file ~must_exists _ fname =
129 List.find Sys.file_exists [ fname ^ gz_suffix; fname ]
132 with Not_found -> raise Not_found'
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
139 let dir_handle = Unix.opendir path_prefix in
142 let entry = Unix.readdir dir_handle in
143 if is_useless entry then
145 else if is_dir (path_prefix ^ "/" ^ entry) then
146 entries := normalize_dir entry :: !entries
148 entries := strip_gz_suffix entry :: !entries
150 with End_of_file -> Unix.closedir dir_handle);
151 remove_duplicates !entries
152 with Unix.Unix_error (_, "opendir", _) -> []
154 let ls_http_single _ url_prefix =
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'
160 let get_file _ path =
161 if Sys.file_exists (path ^ gz_suffix) then
163 else if Sys.file_exists path then
168 let get_http uri url =
170 match Pcre.split ~rex:cic_scheme_sep_RE uri with
171 | [scheme; path] -> scheme, path
175 sprintf "%s%s/%s" (Lazy.force Http_getter_env.cache_dir) scheme path
177 if Sys.file_exists (cache_name ^ gz_suffix) then
178 cache_name ^ gz_suffix
179 else if Sys.file_exists cache_name then
181 else begin (* fill cache *)
182 Http_getter_misc.mkdir ~parents:true (Filename.dirname cache_name);
184 Http_getter_wget.get_and_save (url ^ gz_suffix) (cache_name ^ gz_suffix);
185 cache_name ^ gz_suffix
186 with Http_client_error _ ->
188 Http_getter_wget.get_and_save url cache_name;
190 with Http_client_error _ ->
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
198 let remove_http _ _ =
199 prerr_endline "Http_getter_storage.remove: not implemented for HTTP scheme";
202 (**************************** RESOLUTION OF PREFIXES ************************)
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
212 let rec aux = function
213 | (rex, _, url_prefix, attrs) :: tl ->
214 (match write, is_readwrite attrs, exists with
215 | true ,false, _ -> aux tl
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
222 (Pcre.replace_first ~rex ~templ:url_prefix uri) :: (aux tl))
227 let resolve_prefix w e u =
228 match resolve_prefixes w e u with
233 (Printf.sprintf "resolve_prefix write:%b exists:%b" w e,u))
235 (* uncomment to debug prefix resolution *)
237 let resolve_prefix w e u =
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");
245 (************************* DISPATCHERS ***************************************)
247 type 'a storage_method = {
251 file: string -> string -> 'a; (* unresolved uri, resolved uri *)
252 http: string -> string -> 'a; (* unresolved uri, resolved uri *)
255 let invoke_method storage_method uri url =
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
262 raise (Unsupported_scheme url)
263 with Not_found' -> raise (Resource_not_found (storage_method.name, uri))
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
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))
277 invoke_method storage_method uri url
278 with Resource_not_found _ -> aux tl)
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
286 (******************************** EXPORTED FUNCTIONS *************************)
294 file = exists_file; http = exists_http; } s
295 with Resource_not_found _ -> false
297 let resolve ?(must_exists=true) ~writable =
304 exists = must_exists;
305 file = resolve_file ~must_exists;
306 http = resolve_http ~must_exists; }
313 file = remove_file; http = remove_http; }
315 let filename ?(find = false) =
316 (if find then dispatch_multi else dispatch_single)
320 file = get_file; http = get_http; }
329 file = ls_file_single; http = ls_http_single; } s
330 with Resource_not_found _ -> []
332 let direct_results = List.flatten (ls_all uri_prefix) in
334 (fun results (_, uri_prefix', _, _) ->
335 if Filename.dirname uri_prefix' = strip_trailing_slash uri_prefix then
336 (Filename.basename uri_prefix' ^ "/") :: results
340 (Lazy.force (prefix_map ()))
344 (sprintf "rm -rf %s/" (Lazy.force Http_getter_env.cache_dir)))
346 let list_writable_prefixes _ =
348 (fun (_,_,url,attrs) ->
349 if is_readwrite attrs then
353 (Lazy.force (prefix_map ()))
355 let is_legacy uri = List.for_all has_legacy (get_attrs uri)
357 (* implement this in a fast way! *)
359 let buri = strip_trailing_slash buri ^ "/" in
360 let files = ls buri in
361 is_empty_listing files
363 let is_read_only uri =
364 let is_empty_dir path =
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
373 is_empty_listing files
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 *)
385 aux false (lookup uri)
387 let activate_system_mode () =
388 let map = Lazy.force (prefix_map ()) in
391 (fun ((rex, urip, urlp, attrs) as entry) ->
392 if has_legacy attrs then
394 else if has_rdonly attrs then
395 Some (rex, urip, urlp, List.filter ((<>) `Read_only) attrs)
400 let map = map in (* just to remember that ocamlc 'lazy' is a ... *)
401 prefix_map_ref := (lazy map)