]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/getter/http_getter_storage.ml
test branch
[helm.git] / helm / ocaml / 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 let trailing_slash_RE = Pcre.regexp "/$"
39 let relative_RE_raw = "(^[^/]+(/[^/]+)*/?$)"
40 let relative_RE = Pcre.regexp relative_RE_raw
41 let file_scheme_RE_raw = "(^file://)"
42 let extended_file_scheme_RE = Pcre.regexp "(^file:/+)"
43 let file_scheme_RE = Pcre.regexp (relative_RE_raw ^ "|" ^ file_scheme_RE_raw)
44 let http_scheme_RE = Pcre.regexp "^http://"
45 let newline_RE = Pcre.regexp "\\n"
46 let cic_scheme_sep_RE = Pcre.regexp ":/"
47 let gz_suffix = ".gz"
48 let gz_suffix_len = String.length gz_suffix
49
50 let path_of_file_url url =
51   assert (Pcre.pmatch ~rex:file_scheme_RE url);
52   if Pcre.pmatch ~rex:relative_RE url then
53     url
54   else  (* absolute path, add heading "/" if missing *)
55     "/" ^ (Pcre.replace ~rex:extended_file_scheme_RE url)
56
57   (** associative list regular expressions -> url prefixes
58    * sorted with longest prefixes first *)
59 let prefix_map = lazy (
60   let map_w_length =
61     List.map
62       (fun (uri_prefix, (url_prefix, attrs)) ->
63         let uri_prefix = normalize_dir uri_prefix in
64         let url_prefix = normalize_dir url_prefix in
65         let regexp = Pcre.regexp ("^(" ^ Pcre.quote uri_prefix ^ ")") in
66         (regexp, String.length uri_prefix, uri_prefix, url_prefix, attrs))
67       (Lazy.force Http_getter_env.prefixes)
68   in
69   let decreasing_length (_, len1, _, _, _) (_, len2, _, _, _) =
70     compare len2 len1 in
71   List.map
72     (fun (regexp, len, uri_prefix, url_prefix, attrs) ->
73       (regexp, strip_trailing_slash uri_prefix, url_prefix, attrs))
74     (List.fast_sort decreasing_length map_w_length))
75
76 let lookup uri =
77   let matches =
78     List.filter (fun (rex, _, _, _) -> Pcre.pmatch ~rex uri)
79       (Lazy.force prefix_map) in
80   if matches = [] then raise (Unresolvable_URI uri);
81   matches
82
83 let resolve_prefix uri =
84   match lookup uri with
85   | (rex, _, url_prefix, _) :: _ ->
86       Pcre.replace_first ~rex ~templ:url_prefix uri
87   | [] -> assert false
88
89 let resolve_prefixes uri =
90   let matches = lookup uri in
91   List.map
92     (fun (rex, _, url_prefix, _) ->
93       Pcre.replace_first ~rex ~templ:url_prefix uri)
94     matches
95
96 let get_attrs uri =
97   match lookup uri with
98   | (_, _, _, attrs) :: _ -> attrs
99   | [] -> assert false
100
101 let is_legacy uri = List.exists ((=) `Legacy) (get_attrs uri)
102
103 let is_read_only uri =
104   is_legacy uri || List.exists ((=) `Read_only) (get_attrs uri)
105
106 let exists_http _ url =
107   Http_getter_wget.exists (url ^ gz_suffix) || Http_getter_wget.exists url
108
109 let exists_file _ fname =
110   Sys.file_exists (fname ^ gz_suffix) || Sys.file_exists fname
111
112 let resolve_http _ url =
113   try
114     List.find Http_getter_wget.exists [ url ^ gz_suffix; url ]
115   with Not_found -> raise Not_found'
116
117 let resolve_file _ fname =
118   try
119     List.find Sys.file_exists [ fname ^ gz_suffix; fname ]
120   with Not_found -> raise Not_found'
121
122 let strip_gz_suffix fname =
123   if extension fname = gz_suffix then
124     String.sub fname 0 (String.length fname - gz_suffix_len)
125   else
126     fname
127
128 let remove_duplicates l =
129   Http_getter_misc.list_uniq (List.fast_sort Pervasives.compare l)
130
131 let ls_file_single _ path_prefix =
132   let is_dir fname = (Unix.stat fname).Unix.st_kind = Unix.S_DIR in
133   let is_useless dir = try dir.[0] = '.' with _ -> false in
134   let entries = ref [] in
135   try
136     let dir_handle = Unix.opendir path_prefix in
137     (try
138       while true do
139         let entry = Unix.readdir dir_handle in
140         if is_useless entry then
141           ()
142         else if is_dir (path_prefix ^ "/" ^ entry) then
143           entries := normalize_dir entry :: !entries
144         else
145           entries := strip_gz_suffix entry :: !entries
146       done
147     with End_of_file -> Unix.closedir dir_handle);
148     remove_duplicates !entries
149   with Unix.Unix_error (_, "opendir", _) -> []
150
151 let ls_http_single _ url_prefix =
152   try
153     let index = Http_getter_wget.get (normalize_dir url_prefix ^ index_fname) in
154     Pcre.split ~rex:newline_RE index
155   with Http_client_error _ -> raise Not_found'
156
157 let get_file _ path =
158   if Sys.file_exists (path ^ gz_suffix) then
159     path ^ gz_suffix
160   else if Sys.file_exists path then
161     path
162   else
163     raise Not_found'
164
165 let get_http uri url =
166   let scheme, path =
167     match Pcre.split ~rex:cic_scheme_sep_RE uri with
168     | [scheme; path] -> scheme, path
169     | _ -> assert false
170   in
171   let cache_name =
172     sprintf "%s%s/%s" (Lazy.force Http_getter_env.cache_dir) scheme path
173   in
174   if Sys.file_exists (cache_name ^ gz_suffix) then
175     cache_name ^ gz_suffix
176   else if Sys.file_exists cache_name then
177     cache_name
178   else begin  (* fill cache *)
179     Http_getter_misc.mkdir ~parents:true (Filename.dirname cache_name);
180     (try
181       Http_getter_wget.get_and_save (url ^ gz_suffix) (cache_name ^ gz_suffix);
182       cache_name ^ gz_suffix
183     with Http_client_error _ ->
184       (try
185         Http_getter_wget.get_and_save url cache_name;
186         cache_name
187       with Http_client_error _ ->
188         raise Not_found'))
189   end
190
191 let remove_file _ path =
192   if Sys.file_exists (path ^ gz_suffix) then Sys.remove (path ^ gz_suffix);
193   if Sys.file_exists path then Sys.remove path
194
195 let remove_http _ _ =
196   prerr_endline "Http_getter_storage.remove: not implemented for HTTP scheme";
197   assert false
198
199 type 'a storage_method = {
200   name: string;
201   file: string -> string -> 'a; (* unresolved uri, resolved uri *)
202   http: string -> string -> 'a; (* unresolved uri, resolved uri *)
203 }
204
205 let normalize_root uri =  (* add trailing slash to roots *)
206   try
207     if uri.[String.length uri - 1] = ':' then uri ^ "/"
208     else uri
209   with Invalid_argument _ -> uri
210
211 let invoke_method storage_method uri url =
212   try
213     if Pcre.pmatch ~rex:file_scheme_RE url then
214       storage_method.file uri (path_of_file_url url)
215     else if Pcre.pmatch ~rex:http_scheme_RE url then
216       storage_method.http uri url
217     else
218       raise (Unsupported_scheme url)
219   with Not_found' -> raise (Resource_not_found (storage_method.name, uri))
220
221 let dispatch_single storage_method uri =
222   assert (extension uri <> gz_suffix);
223   let uri = normalize_root uri in
224   let url = resolve_prefix uri in
225   invoke_method storage_method uri url
226
227 let dispatch_multi storage_method uri =
228   let urls = resolve_prefixes uri in
229   let rec aux = function
230     | [] -> raise (Resource_not_found (storage_method.name, uri))
231     | url :: tl ->
232         (try
233           invoke_method storage_method uri url
234         with Resource_not_found _ -> aux tl)
235   in
236   aux urls
237
238 let exists =
239   dispatch_single { name = "exists"; file = exists_file; http = exists_http }
240
241 let resolve =
242   dispatch_single { name = "resolve"; file = resolve_file; http = resolve_http }
243
244 let ls_single =
245   dispatch_single { name = "ls"; file = ls_file_single; http = ls_http_single }
246
247 let remove =
248   dispatch_single { name = "remove"; file = remove_file; http = remove_http }
249
250 let filename ?(find = false) =
251   if find then
252     dispatch_multi { name = "filename"; file = get_file; http = get_http }
253   else
254     dispatch_single { name = "filename"; file = get_file; http = get_http }
255
256   (* ls_single performs ls only below a single prefix, but prefixes which have
257    * common prefix (sorry) with a given one may need to be considered as well
258    * for example: when doing "ls cic:/" we would like to see the "cic:/matita"
259    * directory *)
260 let ls uri_prefix =
261 (*   prerr_endline ("Http_getter_storage.ls " ^ uri_prefix); *)
262   let direct_results = ls_single uri_prefix in
263   List.fold_left
264     (fun results (_, uri_prefix', _, _) ->
265       if Filename.dirname uri_prefix' = strip_trailing_slash uri_prefix then
266         (Filename.basename uri_prefix' ^ "/") :: results
267       else
268         results)
269     direct_results
270     (Lazy.force prefix_map)
271
272 let clean_cache () =
273   ignore (Sys.command
274     (sprintf "rm -rf %s/" (Lazy.force Http_getter_env.cache_dir)))
275