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