]> matita.cs.unibo.it Git - helm.git/blob - components/getter/http_getter_misc.ml
tagged 0.5.0-rc1
[helm.git] / components / getter / http_getter_misc.ml
1 (*
2  * Copyright (C) 2003-2004:
3  *    Stefano Zacchiroli <zack@cs.unibo.it>
4  *    for the HELM Team http://helm.cs.unibo.it/
5  *
6  *  This file is part of HELM, an Hypertextual, Electronic
7  *  Library of Mathematics, developed at the Computer Science
8  *  Department, University of Bologna, Italy.
9  *
10  *  HELM is free software; you can redistribute it and/or
11  *  modify it under the terms of the GNU General Public License
12  *  as published by the Free Software Foundation; either version 2
13  *  of the License, or (at your option) any later version.
14  *
15  *  HELM is distributed in the hope that it will be useful,
16  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *  GNU General Public License for more details.
19  *
20  *  You should have received a copy of the GNU General Public License
21  *  along with HELM; if not, write to the Free Software
22  *  Foundation, Inc., 59 Temple Place - Suite 330, Boston,
23  *  MA  02111-1307, USA.
24  *
25  *  For details, see the HELM World-Wide-Web page,
26  *  http://helm.cs.unibo.it/
27  *)
28
29 (* $Id$ *)
30
31 open Printf
32
33 let file_scheme_prefix = "file://"
34
35 let trailing_dot_gz_RE = Pcre.regexp "\\.gz$"   (* for g{,un}zip *)
36 let url_RE = Pcre.regexp "^([\\w.-]+)(:(\\d+))?(/.*)?$"
37 let http_scheme_RE = Pcre.regexp ~flags:[`CASELESS] "^http://"
38 let file_scheme_RE = Pcre.regexp ~flags:[`CASELESS] ("^" ^ file_scheme_prefix)
39 let dir_sep_RE = Pcre.regexp "/"
40 let heading_slash_RE = Pcre.regexp "^/"
41
42 let local_url =
43   let rex = Pcre.regexp ("^(" ^ file_scheme_prefix ^ ")(.*)(.gz)$") in
44   fun s ->
45     try
46       Some ((Pcre.extract ~rex s).(2))
47     with Not_found -> None
48
49 let bufsiz = 16384  (* for file system I/O *)
50 let tcp_bufsiz = 4096 (* for TCP I/O *)
51
52 let fold_file f init fname =
53   let ic = open_in fname in
54   let rec aux acc =
55     let line = try Some (input_line ic) with End_of_file -> None in
56     match line with
57     | None -> acc
58     | Some line -> aux (f line acc)
59   in
60   let res = try aux init with e -> close_in ic; raise e in
61   close_in ic;
62   res
63
64 let iter_file f = fold_file (fun line _ -> f line) ()
65
66 let iter_buf_size = 10240
67
68 let iter_file_data f fname =
69   let ic = open_in fname in
70   let buf = String.create iter_buf_size in
71   try
72     while true do
73       let bytes = input ic buf 0 iter_buf_size in
74       if bytes = 0 then raise End_of_file;
75       f (String.sub buf 0 bytes)
76     done
77   with End_of_file -> close_in ic
78
79 let hashtbl_sorted_fold f tbl init =
80   let sorted_keys =
81     List.sort compare (Hashtbl.fold (fun key _ keys -> key::keys) tbl [])
82   in
83   List.fold_left (fun acc k -> f k (Hashtbl.find tbl k) acc) init sorted_keys
84
85 let hashtbl_sorted_iter f tbl =
86   let sorted_keys =
87     List.sort compare (Hashtbl.fold (fun key _ keys -> key::keys) tbl [])
88   in
89     List.iter (fun k -> f k (Hashtbl.find tbl k)) sorted_keys
90
91 let cp src dst =
92   try 
93     let ic = open_in src in
94       try
95         let oc = open_out dst in
96         let buf = String.create bufsiz in
97           (try
98              while true do
99                let bytes = input ic buf 0 bufsiz in
100                  if bytes = 0 then raise End_of_file else output oc buf 0 bytes
101              done
102            with 
103                End_of_file -> ()
104           );
105           close_in ic; close_out oc
106       with 
107           Sys_error s -> 
108             Http_getter_logger.log s;
109             close_in ic
110         | e -> 
111             Http_getter_logger.log (Printexc.to_string e);
112             close_in ic;
113             raise e
114   with 
115       Sys_error s -> 
116         Http_getter_logger.log s
117     | e -> 
118         Http_getter_logger.log (Printexc.to_string e);
119         raise e
120
121 let wget ?output url =
122   Http_getter_logger.log
123     (sprintf "wgetting %s (output: %s)" url
124       (match output with None -> "default" | Some f -> f));
125   match url with
126   | url when Pcre.pmatch ~rex:file_scheme_RE url -> (* file:// *)
127       (let src_fname = Pcre.replace ~rex:file_scheme_RE url in
128       match output with
129       | Some dst_fname -> cp src_fname dst_fname
130       | None ->
131           let dst_fname = Filename.basename src_fname in
132           if src_fname <> dst_fname then
133             cp src_fname dst_fname
134           else  (* src and dst are the same: do nothing *)
135             ())
136   | url when Pcre.pmatch ~rex:http_scheme_RE url -> (* http:// *)
137       (let oc = 
138         open_out (match output with Some f -> f | None -> Filename.basename url)
139       in
140       Http_user_agent.get_iter (fun data -> output_string oc data) url;
141       close_out oc)
142   | scheme -> (* unsupported scheme *)
143       failwith ("Http_getter_misc.wget: unsupported scheme: " ^ scheme)
144
145 let gzip ?(keep = false) ?output fname =
146   let output = match output with None -> fname ^ ".gz" | Some fname -> fname in
147   Http_getter_logger.log ~level:3
148     (sprintf "gzipping %s (keep: %b, output: %s)" fname keep output);
149   let (ic, oc) = (open_in fname, Gzip.open_out output) in
150   let buf = String.create bufsiz in
151   (try
152     while true do
153       let bytes = input ic buf 0 bufsiz in
154       if bytes = 0 then raise End_of_file else Gzip.output oc buf 0 bytes
155     done
156   with End_of_file -> ());
157   close_in ic; Gzip.close_out oc;
158   if not keep then Sys.remove fname
159 ;;
160
161 let gunzip ?(keep = false) ?output fname =
162     (* assumption: given file name ends with ".gz" or output is set *)
163   let output =
164     match output with
165     | None ->
166         if (Pcre.pmatch ~rex:trailing_dot_gz_RE fname) then
167           Pcre.replace ~rex:trailing_dot_gz_RE fname
168         else
169           failwith
170             "Http_getter_misc.gunzip: unable to determine output file name"
171     | Some fname -> fname
172   in
173   Http_getter_logger.log ~level:3
174     (sprintf "gunzipping %s (keep: %b, output: %s)" fname keep output);
175   (* Open the zipped file manually since Gzip.open_in may
176    * leak the descriptor if it raises an exception *)
177   let zic = open_in fname in
178   begin
179     try
180       let ic = Gzip.open_in_chan zic in
181       let oc = open_out output in
182       let buf = String.create bufsiz in
183       (try
184         while true do
185           let bytes = Gzip.input ic buf 0 bufsiz in
186           if bytes = 0 then raise End_of_file else Pervasives.output oc buf 0 bytes
187         done
188       with End_of_file -> ());
189         close_out oc;
190         Gzip.close_in ic
191     with
192       e -> close_in zic ; raise e
193   end ;
194   if not keep then Sys.remove fname
195 ;;
196
197 let tempfile () = Filename.temp_file "http_getter_" ""
198
199 exception Mkdir_failure of string * string;;  (* dirname, failure reason *)
200 let dir_perm = 0o755
201
202 let mkdir ?(parents = false) dirname =
203   let mkdirhier () =
204     let (pieces, hd) =
205       let split = Pcre.split ~rex:dir_sep_RE dirname in
206       if Pcre.pmatch ~rex:heading_slash_RE dirname then
207         (List.tl split, "/")
208       else
209         (split, "")
210     in
211     ignore
212       (List.fold_left
213         (fun pre dir ->
214           let next_dir =
215             sprintf "%s%s%s" pre (match pre with "/" | "" -> "" | _ -> "/") dir
216           in
217           (try
218             (match (Unix.stat next_dir).Unix.st_kind with
219             | Unix.S_DIR -> ()  (* dir component already exists, go on! *)
220             | _ ->  (* dir component already exists but isn't a dir, abort! *)
221                 raise
222                   (Mkdir_failure (dirname,
223                     sprintf "'%s' already exists but is not a dir" next_dir)))
224           with Unix.Unix_error (Unix.ENOENT, "stat", _) ->
225             (* dir component doesn't exists, create it and go on! *)
226             Unix.mkdir next_dir dir_perm);
227           next_dir)
228         hd pieces)
229   in
230   if parents then mkdirhier () else Unix.mkdir dirname dir_perm
231
232 let string_of_proc_status = function
233   | Unix.WEXITED code -> sprintf "[Exited: %d]" code
234   | Unix.WSIGNALED sg -> sprintf "[Killed: %d]" sg
235   | Unix.WSTOPPED sg -> sprintf "[Stopped: %d]" sg
236
237 let http_get url =
238   if Pcre.pmatch ~rex:file_scheme_RE url then begin
239       (* file:// URL. Read data from file system *)
240     let fname = Pcre.replace ~rex:file_scheme_RE url in
241     try
242       let size = (Unix.stat fname).Unix.st_size in
243       let buf = String.create size in
244       let ic = open_in fname in
245       really_input ic buf 0 size ;
246       close_in ic;
247       Some buf
248     with Unix.Unix_error (Unix.ENOENT, "stat", _) -> None
249   end else  (* other URL, pass it to Http_user_agent *)
250     try
251       Some (Http_user_agent.get url)
252     with e ->
253       Http_getter_logger.log (sprintf
254         "Warning: Http_user_agent failed on url %s with exception: %s"
255         url (Printexc.to_string e));
256       None
257
258 let is_blank_line =
259   let blank_line_RE = Pcre.regexp "(^#)|(^\\s*$)" in
260   fun line ->
261     Pcre.pmatch ~rex:blank_line_RE line
262
263 let normalize_dir s =  (* append "/" if missing *)
264   let len = String.length s in
265   try
266     if s.[len - 1] = '/' then s
267     else s ^ "/"
268   with Invalid_argument _ -> (* string is empty *) "/"
269
270 let strip_trailing_slash s =
271   try
272     let len = String.length s in
273     if s.[len - 1] = '/' then String.sub s 0 (len - 1)
274     else s
275   with Invalid_argument _ -> s
276
277 let strip_suffix ~suffix s =
278   try
279     let s_len = String.length s in
280     let suffix_len = String.length suffix in
281     let suffix_sub = String.sub s (s_len - suffix_len) suffix_len in
282     if suffix_sub <> suffix then raise (Invalid_argument "Http_getter_misc.strip_suffix");
283     String.sub s 0 (s_len - suffix_len)
284   with Invalid_argument _ ->
285     raise (Invalid_argument "Http_getter_misc.strip_suffix")
286
287 let rec list_uniq = function 
288   | [] -> []
289   | h::[] -> [h]
290   | h1::h2::tl when h1 = h2 -> list_uniq (h2 :: tl) 
291   | h1::tl (* when h1 <> h2 *) -> h1 :: list_uniq tl
292
293 let extension s =
294   try
295     let idx = String.rindex s '.' in
296     String.sub s idx (String.length s - idx)
297   with Not_found -> ""
298
299 let temp_file_of_uri uri =
300   let flat_string s s' c =
301     let cs = String.copy s in
302     for i = 0 to (String.length s) - 1 do
303       if String.contains s' s.[i] then cs.[i] <- c
304     done;
305     cs
306   in
307   let user = try Unix.getlogin () with _ -> "" in
308   Filename.open_temp_file (user ^ flat_string uri ".-=:;!?/&" '_') ""
309
310 let backtick cmd =
311   let ic = Unix.open_process_in cmd in
312   let res = input_line ic in
313   ignore (Unix.close_process_in ic);
314   res
315