]> matita.cs.unibo.it Git - helm.git/blob - helm/http_getter/http_getter_misc.ml
- the mathql interpreter is not helm-dependent any more
[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 res =
45     try
46       Zack.fold_in f init inchan
47     with e -> close_in inchan; raise e
48   in
49   close_in inchan;
50   res
51
52 let iter_file f = fold_file (fun _ line -> f line) ()
53
54 let hashtbl_sorted_fold f tbl init =
55   let sorted_keys =
56     List.sort compare (Hashtbl.fold (fun key _ keys -> key::keys) tbl [])
57   in
58   List.fold_left (fun acc k -> f k (Hashtbl.find tbl k) acc) init sorted_keys
59
60 let cp src dst =
61   let (ic, oc) = (open_in src, open_out dst) in
62   let buf = String.create bufsiz in
63   (try
64     while true do
65       let bytes = input ic buf 0 bufsiz in
66       if bytes = 0 then raise End_of_file else output oc buf 0 bytes
67     done
68   with End_of_file -> ());
69   close_in ic; close_out oc
70
71 let parse_url url =
72   try
73     let subs =
74       Pcre.extract ~rex:url_RE (Pcre.replace ~rex:http_scheme_RE url)
75     in
76     (subs.(1),
77     (if subs.(2) = "" then 80 else int_of_string subs.(3)),
78     (if subs.(4) = "" then "/" else subs.(4)))
79   with exc ->
80     failwith
81       (sprintf "Can't parse url: %s (exception: %s)"
82         url (Printexc.to_string exc))
83 let init_socket addr port =
84   let inet_addr = (Unix.gethostbyname addr).Unix.h_addr_list.(0) in
85   let sockaddr = Unix.ADDR_INET (inet_addr, port) in
86   let suck = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in
87   Unix.connect suck sockaddr;
88   let outchan = Unix.out_channel_of_descr suck in
89   let inchan = Unix.in_channel_of_descr suck in
90   (inchan, outchan)
91 let http_get_iter_buf ~callback url =
92   let (address, port, path) = parse_url url in
93   let buf = String.create tcp_bufsiz in
94   let (inchan, outchan) = init_socket address port in
95   output_string outchan (sprintf "GET %s\r\n" path);
96   flush outchan;
97   (try
98     while true do
99       match input inchan buf 0 tcp_bufsiz with
100       | 0 -> raise End_of_file
101       | bytes when bytes = tcp_bufsiz ->  (* buffer full, no need to slice it *)
102           callback buf
103       | bytes when bytes < tcp_bufsiz ->  (* buffer not full, slice it *)
104           callback (String.sub buf 0 bytes)
105       | _ -> (* ( bytes < 0 ) || ( bytes > tcp_bufsiz ) *)
106           assert false
107     done
108   with End_of_file -> ());
109   close_in inchan (* close also outchan, same fd *)
110
111 let wget ?output url =
112   debug_print
113     (sprintf "wgetting %s (output: %s)" url
114       (match output with None -> "default" | Some f -> f));
115   match url with
116   | url when Pcre.pmatch ~rex:file_scheme_RE url -> (* file:// *)
117       (let src_fname = Pcre.replace ~rex:file_scheme_RE url in
118       match output with
119       | Some dst_fname -> cp src_fname dst_fname
120       | None ->
121           let dst_fname = Filename.basename src_fname in
122           if src_fname <> dst_fname then
123             cp src_fname dst_fname
124           else  (* src and dst are the same: do nothing *)
125             ())
126   | url when Pcre.pmatch ~rex:http_scheme_RE url -> (* http:// *)
127       (let oc = 
128         open_out (match output with Some f -> f | None -> Filename.basename url)
129       in
130       http_get_iter_buf ~callback:(fun data -> output_string oc data) url;
131       close_out oc)
132   | scheme -> (* unsupported scheme *)
133       failwith ("Http_getter_misc.wget: unsupported scheme: " ^ scheme)
134
135 let gzip ?(keep = false) ?output fname =
136   let output = match output with None -> fname ^ ".gz" | Some fname -> fname in
137   debug_print (sprintf "gzipping %s (keep: %b, output: %s)" fname keep output);
138   let (ic, oc) = (open_in fname, Gzip.open_out output) 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
150 let gunzip ?(keep = false) ?output fname =
151     (* assumption: given file name ends with ".gz" or output is set *)
152   let output =
153     match output with
154     | None ->
155         if (Pcre.pmatch ~rex:trailing_dot_gz_RE fname) then
156           Pcre.replace ~rex:trailing_dot_gz_RE fname
157         else
158           failwith
159             "Http_getter_misc.gunzip: unable to determine output file name"
160     | Some fname -> fname
161   in
162   debug_print (sprintf "gunzipping %s (keep: %b, output: %s)"
163     fname keep output);
164   let (ic, oc) = (Gzip.open_in fname, open_out output) in
165   let buf = String.create bufsiz in
166   (try
167     while true do
168       let bytes = Gzip.input ic buf 0 bufsiz in
169       if bytes = 0 then raise End_of_file else Pervasives.output oc buf 0 bytes
170     done
171   with End_of_file -> ());
172   Gzip.close_in ic; close_out oc;
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 netclient *)
229     try
230       Some (Http_client.Convenience.http_get url)
231     with Http_client.Http_error (code, _) -> None
232
233   (** apply a transformation "string list -> string list" to file lines *)
234 let mangle_file ~fname f =
235   let ic = open_in fname in
236   let lines = Zack.input_lines ic in
237   close_in ic;
238   let oc = open_out fname in
239   Zack.output_lines (f lines) oc;
240   close_out oc
241 ;;
242
243 let add_line ~fname ?position line =
244   mangle_file ~fname
245     (fun lines ->
246       match position with
247       | None -> lines @ [line]
248       | Some i ->
249           assert (i >= 0);
250           let rec add_after i = function
251             | (acc, []) -> acc @ [line] (* eof *)
252             | (acc, ((hd::tl) as l)) ->
253                 if i = 0 then
254                   acc @ [line] @ l
255                 else
256                   add_after (i-1) (acc @ [hd], tl)
257           in
258           add_after i ([], lines))
259 ;;
260
261 let remove_line ~fname position =
262   mangle_file ~fname
263     (fun lines ->
264       assert (position >= 0);
265       let rec remove i = function
266         | (acc, []) -> acc  (* eof *)
267         | (acc, ((hd::tl) as l)) ->
268             if i = 0 then
269               acc @ tl
270             else
271               remove (i-1) (acc @ [hd], tl)
272       in
273       remove position ([], lines))
274 ;;
275
276 let is_blank_line =
277   let blank_line_RE = Pcre.regexp "(^#)|(^\\s*$)" in
278   fun line ->
279     Pcre.pmatch ~rex:blank_line_RE line
280 ;;
281