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 =
85 let len = String.length s in
86 len < 7 || String.sub s (len - 7) 7 <> ".xml.gz") files
88 (************************* GLOBALS PREFIXES **********************************)
90 (** associative list regular expressions -> url prefixes
91 * sorted with longest prefixes first *)
92 let prefix_map_ref = ref (lazy (
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))))
101 let prefix_map () = !prefix_map_ref
103 (** given an uri returns the prefixes for it *)
106 List.filter (fun (rex, _, l, _) -> Pcre.pmatch ~rex uri)
107 (Lazy.force (prefix_map ())) in
108 if matches = [] then raise (Unresolvable_URI uri);
111 let get_attrs uri = List.map (fun (_, _, _, attrs) -> attrs) (lookup uri)
113 (*************************** ACTIONS ******************************************)
115 let exists_http _ url =
116 Http_getter_wget.exists (url ^ gz_suffix) || Http_getter_wget.exists url
118 let exists_file _ fname =
119 Sys.file_exists (fname ^ gz_suffix) || Sys.file_exists fname
121 let resolve_http ~must_exists _ url =
124 List.find Http_getter_wget.exists [ url ^ gz_suffix; url ]
127 with Not_found -> raise Not_found'
129 let resolve_file ~must_exists _ fname =
132 List.find Sys.file_exists [ fname ^ gz_suffix; fname ]
135 with Not_found -> raise Not_found'
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
142 let dir_handle = Unix.opendir path_prefix in
145 let entry = Unix.readdir dir_handle in
146 if is_useless entry then
148 else if is_dir (path_prefix ^ "/" ^ entry) then
149 entries := normalize_dir entry :: !entries
151 entries := strip_gz_suffix entry :: !entries
153 with End_of_file -> Unix.closedir dir_handle);
154 remove_duplicates !entries
155 with Unix.Unix_error (_, "opendir", _) -> []
157 let ls_http_single _ url_prefix =
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'
163 let get_file _ path =
164 if Sys.file_exists (path ^ gz_suffix) then
166 else if Sys.file_exists path then
171 let get_http uri url =
173 match Pcre.split ~rex:cic_scheme_sep_RE uri with
174 | [scheme; path] -> scheme, path
178 sprintf "%s%s/%s" (Lazy.force Http_getter_env.cache_dir) scheme path
180 if Sys.file_exists (cache_name ^ gz_suffix) then
181 cache_name ^ gz_suffix
182 else if Sys.file_exists cache_name then
184 else begin (* fill cache *)
185 Http_getter_misc.mkdir ~parents:true (Filename.dirname cache_name);
187 Http_getter_wget.get_and_save (url ^ gz_suffix) (cache_name ^ gz_suffix);
188 cache_name ^ gz_suffix
189 with Http_client_error _ ->
191 Http_getter_wget.get_and_save url cache_name;
193 with Http_client_error _ ->
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
201 let remove_http _ _ =
202 prerr_endline "Http_getter_storage.remove: not implemented for HTTP scheme";
205 (**************************** RESOLUTION OF PREFIXES ************************)
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
215 let rec aux = function
216 | (rex, _, url_prefix, attrs) :: tl ->
217 (match write, is_readwrite attrs, exists with
218 | true ,false, _ -> aux tl
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
225 (Pcre.replace_first ~rex ~templ:url_prefix uri) :: (aux tl))
230 let resolve_prefix w e u =
231 match resolve_prefixes w e u with
236 (Printf.sprintf "resolve_prefix write:%b exists:%b" w e,u))
238 (* uncomment to debug prefix resolution *)
240 let resolve_prefix w e u =
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");
248 (************************* DISPATCHERS ***************************************)
250 type 'a storage_method = {
254 file: string -> string -> 'a; (* unresolved uri, resolved uri *)
255 http: string -> string -> 'a; (* unresolved uri, resolved uri *)
258 let invoke_method storage_method uri url =
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
265 raise (Unsupported_scheme url)
266 with Not_found' -> raise (Resource_not_found (storage_method.name, uri))
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
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))
280 invoke_method storage_method uri url
281 with Resource_not_found _ -> aux tl)
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
289 (******************************** EXPORTED FUNCTIONS *************************)
297 file = exists_file; http = exists_http; } s
298 with Resource_not_found _ -> false
300 let resolve ?(must_exists=true) ~writable =
307 exists = must_exists;
308 file = resolve_file ~must_exists;
309 http = resolve_http ~must_exists; }
316 file = remove_file; http = remove_http; }
318 let filename ?(find = false) =
319 (if find then dispatch_multi else dispatch_single)
323 file = get_file; http = get_http; }
332 file = ls_file_single; http = ls_http_single; } s
333 with Resource_not_found _ -> []
335 let direct_results = List.flatten (ls_all uri_prefix) in
337 (fun results (_, uri_prefix', _, _) ->
338 if Filename.dirname uri_prefix' = strip_trailing_slash uri_prefix then
339 (Filename.basename uri_prefix' ^ "/") :: results
343 (Lazy.force (prefix_map ()))
347 (sprintf "rm -rf %s/" (Lazy.force Http_getter_env.cache_dir)))
349 let list_writable_prefixes _ =
351 (fun (_,_,url,attrs) ->
352 if is_readwrite attrs then
356 (Lazy.force (prefix_map ()))
358 let is_legacy uri = List.for_all has_legacy (get_attrs uri)
360 (* implement this in a fast way! *)
362 let buri = strip_trailing_slash buri ^ "/" in
363 let files = ls buri in
364 is_empty_listing files
366 let is_read_only uri =
367 let is_empty_dir path =
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
376 is_empty_listing files
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 *)
388 aux false (lookup uri)
390 let activate_system_mode () =
391 let map = Lazy.force (prefix_map ()) in
394 (fun ((rex, urip, urlp, attrs) as entry) ->
395 if has_legacy attrs then
397 else if has_rdonly attrs then
398 Some (rex, urip, urlp, List.filter ((<>) `Read_only) attrs)
403 let map = map in (* just to remember that ocamlc 'lazy' is a ... *)
404 prefix_map_ref := (lazy map)