]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/getter/http_getter_misc.ml
- getter revolution: split backend and frontend (this is the backend)
[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 open Http_getter_debugger
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://"
37 let dir_sep_RE = Pcre.regexp "/"
38 let heading_slash_RE = Pcre.regexp "^/"
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   let (ic, oc) = (open_in src, open_out dst) in
71   let buf = String.create bufsiz in
72   (try
73     while true do
74       let bytes = input ic buf 0 bufsiz in
75       if bytes = 0 then raise End_of_file else output oc buf 0 bytes
76     done
77   with End_of_file -> ());
78   close_in ic; close_out oc
79
80 let parse_url url =
81   try
82     let subs =
83       Pcre.extract ~rex:url_RE (Pcre.replace ~rex:http_scheme_RE url)
84     in
85     (subs.(1),
86     (if subs.(2) = "" then 80 else int_of_string subs.(3)),
87     (if subs.(4) = "" then "/" else subs.(4)))
88   with exc ->
89     failwith
90       (sprintf "Can't parse url: %s (exception: %s)"
91         url (Printexc.to_string exc))
92 let init_socket addr port =
93   let inet_addr = (Unix.gethostbyname addr).Unix.h_addr_list.(0) in
94   let sockaddr = Unix.ADDR_INET (inet_addr, port) in
95   let suck = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in
96   Unix.connect suck sockaddr;
97   let outchan = Unix.out_channel_of_descr suck in
98   let inchan = Unix.in_channel_of_descr suck in
99   (inchan, outchan)
100 let http_get_iter_buf ~callback url =
101   let (address, port, path) = parse_url url in
102   let buf = String.create tcp_bufsiz in
103   let (inchan, outchan) = init_socket address port in
104   output_string outchan (sprintf "GET %s\r\n" path);
105   flush outchan;
106   (try
107     while true do
108       match input inchan buf 0 tcp_bufsiz with
109       | 0 -> raise End_of_file
110       | bytes when bytes = tcp_bufsiz ->  (* buffer full, no need to slice it *)
111           callback buf
112       | bytes when bytes < tcp_bufsiz ->  (* buffer not full, slice it *)
113           callback (String.sub buf 0 bytes)
114       | _ -> (* ( bytes < 0 ) || ( bytes > tcp_bufsiz ) *)
115           assert false
116     done
117   with End_of_file -> ());
118   close_in inchan (* close also outchan, same fd *)
119
120 let wget ?output url =
121   debug_print
122     (sprintf "wgetting %s (output: %s)" url
123       (match output with None -> "default" | Some f -> f));
124   match url with
125   | url when Pcre.pmatch ~rex:file_scheme_RE url -> (* file:// *)
126       (let src_fname = Pcre.replace ~rex:file_scheme_RE url in
127       match output with
128       | Some dst_fname -> cp src_fname dst_fname
129       | None ->
130           let dst_fname = Filename.basename src_fname in
131           if src_fname <> dst_fname then
132             cp src_fname dst_fname
133           else  (* src and dst are the same: do nothing *)
134             ())
135   | url when Pcre.pmatch ~rex:http_scheme_RE url -> (* http:// *)
136       (let oc = 
137         open_out (match output with Some f -> f | None -> Filename.basename url)
138       in
139       http_get_iter_buf ~callback:(fun data -> output_string oc data) url;
140       close_out oc)
141   | scheme -> (* unsupported scheme *)
142       failwith ("Http_getter_misc.wget: unsupported scheme: " ^ scheme)
143
144 let gzip ?(keep = false) ?output fname =
145   let output = match output with None -> fname ^ ".gz" | Some fname -> fname in
146   debug_print (sprintf "gzipping %s (keep: %b, output: %s)" fname keep output);
147   let (ic, oc) = (open_in fname, Gzip.open_out output) in
148   let buf = String.create bufsiz in
149   (try
150     while true do
151       let bytes = input ic buf 0 bufsiz in
152       if bytes = 0 then raise End_of_file else Gzip.output oc buf 0 bytes
153     done
154   with End_of_file -> ());
155   close_in ic; Gzip.close_out oc;
156   if not keep then Sys.remove fname
157 ;;
158
159 let gunzip ?(keep = false) ?output fname =
160     (* assumption: given file name ends with ".gz" or output is set *)
161   let output =
162     match output with
163     | None ->
164         if (Pcre.pmatch ~rex:trailing_dot_gz_RE fname) then
165           Pcre.replace ~rex:trailing_dot_gz_RE fname
166         else
167           failwith
168             "Http_getter_misc.gunzip: unable to determine output file name"
169     | Some fname -> fname
170   in
171   debug_print (sprintf "gunzipping %s (keep: %b, output: %s)"
172     fname keep output);
173   let (ic, oc) = (Gzip.open_in fname, open_out output) in
174   let buf = String.create bufsiz in
175   (try
176     while true do
177       let bytes = Gzip.input ic buf 0 bufsiz in
178       if bytes = 0 then raise End_of_file else Pervasives.output oc buf 0 bytes
179     done
180   with End_of_file -> ());
181   Gzip.close_in ic; close_out oc;
182   if not keep then Sys.remove fname
183 ;;
184
185 let tempfile () = Filename.temp_file "http_getter_" ""
186
187 exception Mkdir_failure of string * string;;  (* dirname, failure reason *)
188 let dir_perm = 0o755
189
190 let mkdir ?(parents = false) dirname =
191   let mkdirhier () =
192     let (pieces, hd) =
193       let split = Pcre.split ~rex:dir_sep_RE dirname in
194       if Pcre.pmatch ~rex:heading_slash_RE dirname then
195         (List.tl split, "/")
196       else
197         (split, "")
198     in
199     ignore
200       (List.fold_left
201         (fun pre dir ->
202           let next_dir =
203             sprintf "%s%s%s" pre (match pre with "/" | "" -> "" | _ -> "/") dir
204           in
205           (try
206             (match (Unix.stat next_dir).Unix.st_kind with
207             | Unix.S_DIR -> ()  (* dir component already exists, go on! *)
208             | _ ->  (* dir component already exists but isn't a dir, abort! *)
209                 raise
210                   (Mkdir_failure (dirname,
211                     sprintf "'%s' already exists but is not a dir" next_dir)))
212           with Unix.Unix_error (Unix.ENOENT, "stat", _) ->
213             (* dir component doesn't exists, create it and go on! *)
214             Unix.mkdir next_dir dir_perm);
215           next_dir)
216         hd pieces)
217   in
218   if parents then mkdirhier () else Unix.mkdir dirname dir_perm
219
220 let string_of_proc_status = function
221   | Unix.WEXITED code -> sprintf "[Exited: %d]" code
222   | Unix.WSIGNALED sg -> sprintf "[Killed: %d]" sg
223   | Unix.WSTOPPED sg -> sprintf "[Stopped: %d]" sg
224
225 let http_get url =
226   if Pcre.pmatch ~rex:file_scheme_RE url then begin
227       (* file:// URL. Read data from file system *)
228     let fname = Pcre.replace ~rex:file_scheme_RE url in
229     try
230       let size = (Unix.stat fname).Unix.st_size in
231       let buf = String.create size in
232       let ic = open_in fname in
233       really_input ic buf 0 size;
234       close_in ic;
235       Some buf
236     with Unix.Unix_error (Unix.ENOENT, "stat", _) -> None
237   end else  (* other URL, pass it to Http_client *)
238     try
239       Some (Http_client.http_get url)
240     with e ->
241       prerr_endline (sprintf
242         "Warning: Http_client failed on url %s with exception: %s"
243         url (Printexc.to_string e));
244       None
245
246 let is_blank_line =
247   let blank_line_RE = Pcre.regexp "(^#)|(^\\s*$)" in
248   fun line ->
249     Pcre.pmatch ~rex:blank_line_RE line
250