2 * Copyright (C) 2003-2004:
3 * Stefano Zacchiroli <zack@cs.unibo.it>
4 * for the HELM Team http://helm.cs.unibo.it/
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.
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.
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.
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,
25 * For details, see the HELM World-Wide-Web page,
26 * http://helm.cs.unibo.it/
33 let file_scheme_prefix = "file://"
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 "^/"
43 let rex = Pcre.regexp ("^(" ^ file_scheme_prefix ^ ")(.*)(.gz)$") in
46 Some ((Pcre.extract ~rex s).(2))
47 with Not_found -> None
49 let bufsiz = 16384 (* for file system I/O *)
50 let tcp_bufsiz = 4096 (* for TCP I/O *)
52 let fold_file f init fname =
53 let ic = open_in fname in
55 let line = try Some (input_line ic) with End_of_file -> None in
58 | Some line -> aux (f line acc)
60 let res = try aux init with e -> close_in ic; raise e in
64 let iter_file f = fold_file (fun line _ -> f line) ()
66 let iter_buf_size = 10240
68 let iter_file_data f fname =
69 let ic = open_in fname in
70 let buf = String.create iter_buf_size in
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)
77 with End_of_file -> close_in ic
79 let hashtbl_sorted_fold f tbl init =
81 List.sort compare (Hashtbl.fold (fun key _ keys -> key::keys) tbl [])
83 List.fold_left (fun acc k -> f k (Hashtbl.find tbl k) acc) init sorted_keys
85 let hashtbl_sorted_iter f tbl =
87 List.sort compare (Hashtbl.fold (fun key _ keys -> key::keys) tbl [])
89 List.iter (fun k -> f k (Hashtbl.find tbl k)) sorted_keys
93 let ic = open_in src in
95 let oc = open_out dst in
96 let buf = String.create bufsiz in
99 let bytes = input ic buf 0 bufsiz in
100 if bytes = 0 then raise End_of_file else output oc buf 0 bytes
105 close_in ic; close_out oc
108 Http_getter_logger.log s;
111 Http_getter_logger.log (Printexc.to_string e);
116 Http_getter_logger.log s
118 Http_getter_logger.log (Printexc.to_string e);
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));
126 | url when Pcre.pmatch ~rex:file_scheme_RE url -> (* file:// *)
127 (let src_fname = Pcre.replace ~rex:file_scheme_RE url in
129 | Some dst_fname -> cp src_fname dst_fname
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 *)
136 | url when Pcre.pmatch ~rex:http_scheme_RE url -> (* http:// *)
138 open_out (match output with Some f -> f | None -> Filename.basename url)
140 Http_user_agent.get_iter (fun data -> output_string oc data) url;
142 | scheme -> (* unsupported scheme *)
143 failwith ("Http_getter_misc.wget: unsupported scheme: " ^ scheme)
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
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
156 with End_of_file -> ());
157 close_in ic; Gzip.close_out oc;
158 if not keep then Sys.remove fname
161 let gunzip ?(keep = false) ?output fname =
162 (* assumption: given file name ends with ".gz" or output is set *)
166 if (Pcre.pmatch ~rex:trailing_dot_gz_RE fname) then
167 Pcre.replace ~rex:trailing_dot_gz_RE fname
170 "Http_getter_misc.gunzip: unable to determine output file name"
171 | Some fname -> fname
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
180 let ic = Gzip.open_in_chan zic in
181 let oc = open_out output in
182 let buf = String.create bufsiz in
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
188 with End_of_file -> ());
192 e -> close_in zic ; raise e
194 if not keep then Sys.remove fname
197 let tempfile () = Filename.temp_file "http_getter_" ""
199 exception Mkdir_failure of string * string;; (* dirname, failure reason *)
202 let mkdir ?(parents = false) dirname =
205 let split = Pcre.split ~rex:dir_sep_RE dirname in
206 if Pcre.pmatch ~rex:heading_slash_RE dirname then
215 sprintf "%s%s%s" pre (match pre with "/" | "" -> "" | _ -> "/") dir
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! *)
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);
230 if parents then mkdirhier () else Unix.mkdir dirname dir_perm
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
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
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 ;
248 with Unix.Unix_error (Unix.ENOENT, "stat", _) -> None
249 end else (* other URL, pass it to Http_user_agent *)
251 Some (Http_user_agent.get url)
253 Http_getter_logger.log (sprintf
254 "Warning: Http_user_agent failed on url %s with exception: %s"
255 url (Printexc.to_string e));
259 let blank_line_RE = Pcre.regexp "(^#)|(^\\s*$)" in
261 Pcre.pmatch ~rex:blank_line_RE line
263 let normalize_dir s = (* append "/" if missing *)
264 let len = String.length s in
266 if s.[len - 1] = '/' then s
268 with Invalid_argument _ -> (* string is empty *) "/"
270 let strip_trailing_slash s =
272 let len = String.length s in
273 if s.[len - 1] = '/' then String.sub s 0 (len - 1)
275 with Invalid_argument _ -> s
277 let strip_suffix ~suffix s =
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 "");
283 String.sub s 0 (s_len - suffix_len)
284 with Invalid_argument _ ->
285 raise (Invalid_argument "Http_getter_misc.strip_suffix")
287 let rec list_uniq = function
290 | h1::h2::tl when h1 = h2 -> list_uniq (h2 :: tl)
291 | h1::tl (* when h1 <> h2 *) -> h1 :: list_uniq tl
295 let idx = String.rindex s '.' in
296 String.sub s idx (String.length s - idx)
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
307 let user = try Unix.getlogin () with _ -> "" in
308 Filename.open_temp_file (user ^ flat_string uri ".-=:;!?/&" '_') ""
311 let ic = Unix.open_process_in cmd in
312 let res = input_line ic in
313 ignore (Unix.close_process_in ic);