]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/getter/http_getter_misc.ml
local_url predicate (recognize file:// urls)
[helm.git] / helm / ocaml / 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 open Printf
30
31 let trailing_dot_gz_RE = Pcre.regexp "\\.gz$"   (* for g{,un}zip *)
32 let url_RE = Pcre.regexp "^([\\w.-]+)(:(\\d+))?(/.*)?$"
33 let http_scheme_RE = Pcre.regexp ~flags:[`CASELESS] "^http://"
34 let file_scheme_RE = Pcre.regexp ~flags:[`CASELESS] "^file://"
35 let dir_sep_RE = Pcre.regexp "/"
36 let heading_slash_RE = Pcre.regexp "^/"
37
38 let is_local_url s = Pcre.pmatch ~rex:file_scheme_RE s
39
40 let bufsiz = 16384  (* for file system I/O *)
41 let tcp_bufsiz = 4096 (* for TCP I/O *)
42
43 let fold_file f init fname =
44   let ic = open_in fname in
45   let rec aux acc =
46     let line = try Some (input_line ic) with End_of_file -> None in
47     match line with
48     | None -> acc
49     | Some line -> aux (f line acc)
50   in
51   let res = try aux init with e -> close_in ic; raise e in
52   close_in ic;
53   res
54
55 let iter_file f = fold_file (fun line _ -> f line) ()
56
57 let hashtbl_sorted_fold f tbl init =
58   let sorted_keys =
59     List.sort compare (Hashtbl.fold (fun key _ keys -> key::keys) tbl [])
60   in
61   List.fold_left (fun acc k -> f k (Hashtbl.find tbl k) acc) init sorted_keys
62
63 let hashtbl_sorted_iter f tbl =
64   let sorted_keys =
65     List.sort compare (Hashtbl.fold (fun key _ keys -> key::keys) tbl [])
66   in
67     List.iter (fun k -> f k (Hashtbl.find tbl k)) sorted_keys
68
69 let cp src dst =
70   try 
71     let ic = open_in src in
72       try
73         let oc = open_out dst in
74         let buf = String.create bufsiz in
75           (try
76              while true do
77                let bytes = input ic buf 0 bufsiz in
78                  if bytes = 0 then raise End_of_file else output oc buf 0 bytes
79              done
80            with 
81                End_of_file -> ()
82           );
83           close_in ic; close_out oc
84       with 
85           Sys_error s -> 
86             Http_getter_logger.log s;
87             close_in ic
88         | e -> 
89             Http_getter_logger.log (Printexc.to_string e);
90             close_in ic;
91             raise e
92   with 
93       Sys_error s -> 
94         Http_getter_logger.log s
95     | e -> 
96         Http_getter_logger.log (Printexc.to_string e);
97         raise e
98
99 let wget ?output url =
100   Http_getter_logger.log
101     (sprintf "wgetting %s (output: %s)" url
102       (match output with None -> "default" | Some f -> f));
103   match url with
104   | url when Pcre.pmatch ~rex:file_scheme_RE url -> (* file:// *)
105       (let src_fname = Pcre.replace ~rex:file_scheme_RE url in
106       match output with
107       | Some dst_fname -> cp src_fname dst_fname
108       | None ->
109           let dst_fname = Filename.basename src_fname in
110           if src_fname <> dst_fname then
111             cp src_fname dst_fname
112           else  (* src and dst are the same: do nothing *)
113             ())
114   | url when Pcre.pmatch ~rex:http_scheme_RE url -> (* http:// *)
115       (let oc = 
116         open_out (match output with Some f -> f | None -> Filename.basename url)
117       in
118       Http_user_agent.get_iter (fun data -> output_string oc data) url;
119       close_out oc)
120   | scheme -> (* unsupported scheme *)
121       failwith ("Http_getter_misc.wget: unsupported scheme: " ^ scheme)
122
123 let gzip ?(keep = false) ?output fname =
124   let output = match output with None -> fname ^ ".gz" | Some fname -> fname in
125   Http_getter_logger.log ~level:3
126     (sprintf "gzipping %s (keep: %b, output: %s)" fname keep output);
127   let (ic, oc) = (open_in fname, Gzip.open_out output) in
128   let buf = String.create bufsiz in
129   (try
130     while true do
131       let bytes = input ic buf 0 bufsiz in
132       if bytes = 0 then raise End_of_file else Gzip.output oc buf 0 bytes
133     done
134   with End_of_file -> ());
135   close_in ic; Gzip.close_out oc;
136   if not keep then Sys.remove fname
137 ;;
138
139 let gunzip ?(keep = false) ?output fname =
140     (* assumption: given file name ends with ".gz" or output is set *)
141   let output =
142     match output with
143     | None ->
144         if (Pcre.pmatch ~rex:trailing_dot_gz_RE fname) then
145           Pcre.replace ~rex:trailing_dot_gz_RE fname
146         else
147           failwith
148             "Http_getter_misc.gunzip: unable to determine output file name"
149     | Some fname -> fname
150   in
151   Http_getter_logger.log ~level:3
152     (sprintf "gunzipping %s (keep: %b, output: %s)" fname keep output);
153   (* Open the zipped file manually since Gzip.open_in may
154    * leak the descriptor if it raises an exception *)
155   let zic = open_in fname in
156   begin
157     try
158       let ic = Gzip.open_in_chan zic in
159       Http_getter_logger.log (sprintf "LUCA: OK" );
160       let oc = open_out output in
161       let buf = String.create bufsiz in
162       (try
163         while true do
164           let bytes = Gzip.input ic buf 0 bufsiz in
165           if bytes = 0 then raise End_of_file else Pervasives.output oc buf 0 bytes
166         done
167       with End_of_file -> ());
168         close_out oc;
169         Gzip.close_in ic
170     with
171       e -> close_in zic ; raise e
172   end ;
173   if not keep then Sys.remove fname
174 ;;
175
176 let tempfile () = Filename.temp_file "http_getter_" ""
177
178 exception Mkdir_failure of string * string;;  (* dirname, failure reason *)
179 let dir_perm = 0o755
180
181 let mkdir ?(parents = false) dirname =
182   let mkdirhier () =
183     let (pieces, hd) =
184       let split = Pcre.split ~rex:dir_sep_RE dirname in
185       if Pcre.pmatch ~rex:heading_slash_RE dirname then
186         (List.tl split, "/")
187       else
188         (split, "")
189     in
190     ignore
191       (List.fold_left
192         (fun pre dir ->
193           let next_dir =
194             sprintf "%s%s%s" pre (match pre with "/" | "" -> "" | _ -> "/") dir
195           in
196           (try
197             (match (Unix.stat next_dir).Unix.st_kind with
198             | Unix.S_DIR -> ()  (* dir component already exists, go on! *)
199             | _ ->  (* dir component already exists but isn't a dir, abort! *)
200                 raise
201                   (Mkdir_failure (dirname,
202                     sprintf "'%s' already exists but is not a dir" next_dir)))
203           with Unix.Unix_error (Unix.ENOENT, "stat", _) ->
204             (* dir component doesn't exists, create it and go on! *)
205             Unix.mkdir next_dir dir_perm);
206           next_dir)
207         hd pieces)
208   in
209   if parents then mkdirhier () else Unix.mkdir dirname dir_perm
210
211 let string_of_proc_status = function
212   | Unix.WEXITED code -> sprintf "[Exited: %d]" code
213   | Unix.WSIGNALED sg -> sprintf "[Killed: %d]" sg
214   | Unix.WSTOPPED sg -> sprintf "[Stopped: %d]" sg
215
216 let http_get url =
217   if Pcre.pmatch ~rex:file_scheme_RE url then begin
218       (* file:// URL. Read data from file system *)
219     let fname = Pcre.replace ~rex:file_scheme_RE url in
220     try
221       let size = (Unix.stat fname).Unix.st_size in
222       let buf = String.create size in
223       let ic = open_in fname in
224       really_input ic buf 0 size ;
225       close_in ic;
226       Some buf
227     with Unix.Unix_error (Unix.ENOENT, "stat", _) -> None
228   end else  (* other URL, pass it to Http_user_agent *)
229     try
230       Some (Http_user_agent.get url)
231     with e ->
232       Http_getter_logger.log (sprintf
233         "Warning: Http_user_agent failed on url %s with exception: %s"
234         url (Printexc.to_string e));
235       None
236
237 let is_blank_line =
238   let blank_line_RE = Pcre.regexp "(^#)|(^\\s*$)" in
239   fun line ->
240     Pcre.pmatch ~rex:blank_line_RE line
241