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