]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/getter/http_getter_misc.ml
6db793369acfd10f747fe9728a5f02d3565821d4
[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 wget ?output url =
81   debug_print
82     (sprintf "wgetting %s (output: %s)" url
83       (match output with None -> "default" | Some f -> f));
84   match url with
85   | url when Pcre.pmatch ~rex:file_scheme_RE url -> (* file:// *)
86       (let src_fname = Pcre.replace ~rex:file_scheme_RE url in
87       match output with
88       | Some dst_fname -> cp src_fname dst_fname
89       | None ->
90           let dst_fname = Filename.basename src_fname in
91           if src_fname <> dst_fname then
92             cp src_fname dst_fname
93           else  (* src and dst are the same: do nothing *)
94             ())
95   | url when Pcre.pmatch ~rex:http_scheme_RE url -> (* http:// *)
96       (let oc = 
97         open_out (match output with Some f -> f | None -> Filename.basename url)
98       in
99       Http_client.http_get_iter (fun data -> output_string oc data) url;
100       close_out oc)
101   | scheme -> (* unsupported scheme *)
102       failwith ("Http_getter_misc.wget: unsupported scheme: " ^ scheme)
103
104 let gzip ?(keep = false) ?output fname =
105   let output = match output with None -> fname ^ ".gz" | Some fname -> fname in
106   debug_print (sprintf "gzipping %s (keep: %b, output: %s)" fname keep output);
107   let (ic, oc) = (open_in fname, Gzip.open_out output) in
108   let buf = String.create bufsiz in
109   (try
110     while true do
111       let bytes = input ic buf 0 bufsiz in
112       if bytes = 0 then raise End_of_file else Gzip.output oc buf 0 bytes
113     done
114   with End_of_file -> ());
115   close_in ic; Gzip.close_out oc;
116   if not keep then Sys.remove fname
117 ;;
118
119 let gunzip ?(keep = false) ?output fname =
120     (* assumption: given file name ends with ".gz" or output is set *)
121   let output =
122     match output with
123     | None ->
124         if (Pcre.pmatch ~rex:trailing_dot_gz_RE fname) then
125           Pcre.replace ~rex:trailing_dot_gz_RE fname
126         else
127           failwith
128             "Http_getter_misc.gunzip: unable to determine output file name"
129     | Some fname -> fname
130   in
131   debug_print (sprintf "gunzipping %s (keep: %b, output: %s)"
132     fname keep output);
133   let (ic, oc) = (Gzip.open_in fname, open_out output) in
134   let buf = String.create bufsiz in
135   (try
136     while true do
137       let bytes = Gzip.input ic buf 0 bufsiz in
138       if bytes = 0 then raise End_of_file else Pervasives.output oc buf 0 bytes
139     done
140   with End_of_file -> ());
141   Gzip.close_in ic; close_out oc;
142   if not keep then Sys.remove fname
143 ;;
144
145 let tempfile () = Filename.temp_file "http_getter_" ""
146
147 exception Mkdir_failure of string * string;;  (* dirname, failure reason *)
148 let dir_perm = 0o755
149
150 let mkdir ?(parents = false) dirname =
151   let mkdirhier () =
152     let (pieces, hd) =
153       let split = Pcre.split ~rex:dir_sep_RE dirname in
154       if Pcre.pmatch ~rex:heading_slash_RE dirname then
155         (List.tl split, "/")
156       else
157         (split, "")
158     in
159     ignore
160       (List.fold_left
161         (fun pre dir ->
162           let next_dir =
163             sprintf "%s%s%s" pre (match pre with "/" | "" -> "" | _ -> "/") dir
164           in
165           (try
166             (match (Unix.stat next_dir).Unix.st_kind with
167             | Unix.S_DIR -> ()  (* dir component already exists, go on! *)
168             | _ ->  (* dir component already exists but isn't a dir, abort! *)
169                 raise
170                   (Mkdir_failure (dirname,
171                     sprintf "'%s' already exists but is not a dir" next_dir)))
172           with Unix.Unix_error (Unix.ENOENT, "stat", _) ->
173             (* dir component doesn't exists, create it and go on! *)
174             Unix.mkdir next_dir dir_perm);
175           next_dir)
176         hd pieces)
177   in
178   if parents then mkdirhier () else Unix.mkdir dirname dir_perm
179
180 let string_of_proc_status = function
181   | Unix.WEXITED code -> sprintf "[Exited: %d]" code
182   | Unix.WSIGNALED sg -> sprintf "[Killed: %d]" sg
183   | Unix.WSTOPPED sg -> sprintf "[Stopped: %d]" sg
184
185 let http_get url =
186   if Pcre.pmatch ~rex:file_scheme_RE url then begin
187       (* file:// URL. Read data from file system *)
188     let fname = Pcre.replace ~rex:file_scheme_RE url in
189     try
190       let size = (Unix.stat fname).Unix.st_size in
191       let buf = String.create size in
192       let ic = open_in fname in
193       really_input ic buf 0 size;
194       close_in ic;
195       Some buf
196     with Unix.Unix_error (Unix.ENOENT, "stat", _) -> None
197   end else  (* other URL, pass it to Http_client *)
198     try
199       Some (Http_client.http_get url)
200     with e ->
201       debug_print (sprintf
202         "Warning: Http_client failed on url %s with exception: %s"
203         url (Printexc.to_string e));
204       None
205
206 let is_blank_line =
207   let blank_line_RE = Pcre.regexp "(^#)|(^\\s*$)" in
208   fun line ->
209     Pcre.pmatch ~rex:blank_line_RE line
210