]> matita.cs.unibo.it Git - helm.git/blob - helm/http_getter/http_getter_misc.ml
- added debugging log messages inside 'wget'
[helm.git] / helm / http_getter / http_getter_misc.ml
1 (*
2  * Copyright (C) 2003:
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 Http_getter_debugger;;
30 open Printf;;
31
32 let trailing_dot_gz_RE = Pcre.regexp "\\.gz$"   (* for g{,un}zip *)
33 let url_RE = Pcre.regexp "^([\\w.]+)(:(\\d+))?(/.*)?$"
34 let http_scheme_RE = Pcre.regexp ~flags:[`CASELESS] "^http://"
35 let file_scheme_RE = Pcre.regexp ~flags:[`CASELESS] "^file://"
36 let dir_sep_RE = Pcre.regexp "/"
37 let heading_slash_RE = Pcre.regexp "^/"
38
39 let bufsiz = 16384  (* for file system I/O *)
40 let tcp_bufsiz = 4096 (* for TCP I/O *)
41
42 let fold_file f init fname =
43   let inchan = open_in fname in
44   let rec fold_lines' value =
45     try 
46       let line = input_line inchan in 
47       fold_lines' (f value line)
48     with End_of_file -> value
49   in
50   let res = (try fold_lines' init with e -> (close_in inchan; raise e)) in
51   close_in inchan;
52   res
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 cp src dst =
62   let (ic, oc) = (open_in src, open_out dst) in
63   let buf = String.create bufsiz in
64   (try
65     while true do
66       let bytes = input ic buf 0 bufsiz in
67       if bytes = 0 then raise End_of_file else output oc buf 0 bytes
68     done
69   with End_of_file -> ());
70   close_in ic; close_out oc
71
72 let parse_url url =
73   try
74     let subs =
75       Pcre.extract ~rex:url_RE (Pcre.replace ~rex:http_scheme_RE url)
76     in
77     (subs.(1),
78     (if subs.(2) = "" then 80 else int_of_string subs.(3)),
79     (if subs.(4) = "" then "/" else subs.(4)))
80   with exc ->
81     failwith
82       (sprintf "Can't parse url: %s (exception: %s)"
83         url (Printexc.to_string exc))
84 let init_socket addr port =
85   let inet_addr = (Unix.gethostbyname addr).Unix.h_addr_list.(0) in
86   let sockaddr = Unix.ADDR_INET (inet_addr, port) in
87   let suck = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in
88   Unix.connect suck sockaddr;
89   let outchan = Unix.out_channel_of_descr suck in
90   let inchan = Unix.in_channel_of_descr suck in
91   (inchan, outchan)
92 let http_get_iter_buf ~callback url =
93   let (address, port, path) = parse_url url in
94   let buf = String.create tcp_bufsiz in
95   let (inchan, outchan) = init_socket address port in
96   output_string outchan (sprintf "GET %s\r\n" path);
97   flush outchan;
98   (try
99     while true do
100       match input inchan buf 0 tcp_bufsiz with
101       | 0 -> raise End_of_file
102       | bytes when bytes = tcp_bufsiz ->  (* buffer full, no need to slice it *)
103           callback buf
104       | bytes when bytes < tcp_bufsiz ->  (* buffer not full, slice it *)
105           callback (String.sub buf 0 bytes)
106       | _ -> (* ( bytes < 0 ) || ( bytes > tcp_bufsiz ) *)
107           assert false
108     done
109   with End_of_file -> ());
110   close_in inchan (* close also outchan, same fd *)
111
112 let wget ?output url =
113   debug_print
114     (sprintf "wgetting %s (output: %s)" url
115       (match output with None -> "default" | Some f -> f));
116   match url with
117   | url when Pcre.pmatch ~rex:file_scheme_RE url -> (* file:// *)
118       (let src_fname = Pcre.replace ~rex:file_scheme_RE url in
119       match output with
120       | Some dst_fname -> cp src_fname dst_fname
121       | None ->
122           let dst_fname = Filename.basename src_fname in
123           if src_fname <> dst_fname then
124             cp src_fname dst_fname
125           else  (* src and dst are the same: do nothing *)
126             ())
127   | url when Pcre.pmatch ~rex:http_scheme_RE url -> (* http:// *)
128       (let oc = 
129         open_out (match output with Some f -> f | None -> Filename.basename url)
130       in
131       http_get_iter_buf ~callback:(fun data -> output_string oc data) url;
132       close_out oc)
133   | scheme -> (* unsupported scheme *)
134       failwith ("Http_getter_misc.wget: unsupported scheme: " ^ scheme)
135
136 let gzip ?(keep = false) fname =
137   debug_print (sprintf "gzipping %s (keep: %b)" fname keep);
138   let (ic, oc) = (open_in fname, Gzip.open_out (fname ^ ".gz")) in
139   let buf = String.create bufsiz in
140   (try
141     while true do
142       let bytes = input ic buf 0 bufsiz in
143       if bytes = 0 then raise End_of_file else Gzip.output oc buf 0 bytes
144     done
145   with End_of_file -> ());
146   close_in ic; Gzip.close_out oc;
147   if not keep then Sys.remove fname
148
149 let gunzip ?(keep = false) fname =
150   debug_print (sprintf "gunzipping %s (keep: %b)" fname keep);
151   let basename = Pcre.replace ~rex:trailing_dot_gz_RE fname in
152   assert (basename <> fname);
153   let (ic, oc) = (Gzip.open_in fname, open_out basename) in
154   let buf = String.create bufsiz in
155   (try
156     while true do
157       let bytes = Gzip.input ic buf 0 bufsiz in
158       if bytes = 0 then raise End_of_file else output oc buf 0 bytes
159     done
160   with End_of_file -> ());
161   Gzip.close_in ic; close_out oc;
162   if not keep then Sys.remove fname
163
164 let tempfile () = Filename.temp_file "http_getter_" ""
165
166 exception Mkdir_failure of string * string;;  (* dirname, failure reason *)
167 let dir_perm = 0o755
168
169 let mkdir ?(parents = false) dirname =
170   let mkdirhier () =
171     let (pieces, hd) =
172       let split = Pcre.split ~rex:dir_sep_RE dirname in
173       if Pcre.pmatch ~rex:heading_slash_RE dirname then
174         (List.tl split, "/")
175       else
176         (split, "")
177     in
178     ignore
179       (List.fold_left
180         (fun pre dir ->
181           let next_dir =
182             sprintf "%s%s%s" pre (match pre with "/" | "" -> "" | _ -> "/") dir
183           in
184           (try
185             (match (Unix.stat next_dir).Unix.st_kind with
186             | Unix.S_DIR -> ()  (* dir component already exists, go on! *)
187             | _ ->  (* dir component already exists but isn't a dir, abort! *)
188                 raise
189                   (Mkdir_failure (dirname,
190                     sprintf "'%s' already exists but is not a dir" next_dir)))
191           with Unix.Unix_error (Unix.ENOENT, "stat", _) ->
192             (* dir component doesn't exists, create it and go on! *)
193             Unix.mkdir next_dir dir_perm);
194           next_dir)
195         hd pieces)
196   in
197   if parents then mkdirhier () else Unix.mkdir dirname dir_perm
198
199 let string_of_proc_status = function
200   | Unix.WEXITED code -> sprintf "[Exited: %d]" code
201   | Unix.WSIGNALED sg -> sprintf "[Killed: %d]" sg
202   | Unix.WSTOPPED sg -> sprintf "[Stopped: %d]" sg
203
204 let http_get url =
205   if Pcre.pmatch ~rex:file_scheme_RE url then begin
206       (* file:// URL. Read data from file system *)
207     let fname = Pcre.replace ~rex:file_scheme_RE url in
208     try
209       let size = (Unix.stat fname).Unix.st_size in
210       let buf = String.create size in
211       let ic = open_in fname in
212       really_input ic buf 0 size;
213       close_in ic;
214       Some buf
215     with Unix.Unix_error (Unix.ENOENT, "stat", _) -> None
216   end else  (* other URL, pass it to netclient *)
217     try
218       Some (Http_client.Convenience.http_get url)
219     with Http_client.Http_error (code, _) -> None
220