Initial version of diskzip
[virt-df.git] / diskzip / diskzip.ml
1 (* 'diskzip' command for intelligently compressing disk images.
2    (C) Copyright 2007 Richard W.M. Jones, Red Hat Inc.
3    http://libvirt.org/
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 2 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software
17    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  *)
19
20 open Unix
21 open Printf
22
23 open Diskzip_gettext.Gettext
24
25 type output = File of string | Dir of string
26 type extcompress = BZip2 | GZip | External of string
27
28 let rec main () =
29   (* Program name changes behaviour. *)
30   let compressing =
31     let name = Sys.argv.(0) in
32     let name = Filename.basename name in       (* just the executable name *)
33     let name = Filename.chop_extension name in (* remove .opt or .exe *)
34     let name = String.lowercase name in
35     match name with
36     | "diskzcat" -> false
37     | "diskzip" -> true
38     | name ->
39         eprintf
40           (f_"diskzip: unknown executable name '%s', assuming 'diskzip'\n")
41           name in
42   let compressing = ref compressing in
43
44   (* Command line argument parsing. *)
45   let version () =
46     printf "diskzip\n"; (* XXX version XXX *)
47     exit 0
48   in
49
50   let output = ref None in
51   let set_output path =
52     if !output <> None then (
53       prerr_endline (s_"diskzip: '-o' option cannot appear more than once");
54       exit 2
55     );
56     try
57       let statbuf = stat path in
58       if statbuf.st_kind = S_DIR then
59         output := Some (Dir path)
60       else
61         output := Some (File path)
62     with
63     (* No such file or directory, assume it's a file output. *)
64     | Unix_error (ENOENT, _, _) -> output := Some (File path)
65   in
66
67   (* By default we don't use any external compression program. *)
68   let extcompress = ref None in
69   let set_extcompress t () =
70     if !extcompress <> None then (
71       prerr_endline (s_"diskzip: '-z' or '-j' cannot appear more than once");
72       exit 2
73     );
74     extcompress := Some t
75   in
76
77   let force = ref false in
78
79   let argspec = Arg.align [
80     "-d", Arg.Clear compressing,
81       " " ^ s_ "Uncompress (default: depends on executable name)";
82     "--debug", Arg.Set Diskimage.debug,
83       " " ^ s_ "Debug mode (default: false)";
84     "-f", Arg.Set force,
85       " " ^ s_"Force compress even if stdout looks like a tty";
86     "-j", Arg.Unit (set_extcompress BZip2),
87       " " ^ s_"Pipe the output/input through bzip2";
88     "-o", Arg.String set_output,
89       "path" ^ s_"Set the output filename or directory name";
90     "-p", Arg.String (fun prog -> set_extcompress (External prog) ()),
91       "prog" ^ s_"Pipe the output/input through external program";
92     "--version", Arg.Unit version,
93       " " ^ s_"Display version and exit";
94     "-z", Arg.Unit (set_extcompress GZip),
95       " " ^ s_"Pipe the output/input through gzip";
96   ] in
97
98   let args = ref [] in
99   let anon_fun str = args := str :: !args in
100   let usage_msg = s_"diskzip: Intelligently compress disk images
101
102 SUMMARY
103   diskzip [-options] disk.img [disk.img ...] > output.dz
104   diskzcat [-options] output.dz > disk.img
105
106 OPTIONS" in
107
108   Arg.parse argspec anon_fun usage_msg;
109
110   (* Turn refs back into normal values. *)
111   let compressing = !compressing in
112   let extcompress = !extcompress in
113   let output = !output in
114   let force = !force in
115   let args = !args in
116
117   (* Check the arguments make sense. *)
118   if compressing && output <> None then (
119     prerr_endline (s_"diskzip: '-o' option cannot be used when compressing");
120     exit 2
121   );
122   if compressing && args = [] then (
123     prerr_endline (s_"diskzip: no input");
124     exit 2
125   );
126   if compressing && not force && isatty stdout then (
127     prerr_endline (s_"diskzip: compressed data not written to a terminal, use '-f' to force");
128     exit 2
129   );
130
131   (* Run the compression or decompression functions. *)
132   if compressing then
133     go_compress extcompress args
134   else
135     go_decompress ?output extcompress args
136
137 and go_decompress ?output extcompress args =
138   (* Read the input, which may be a single named file, or a series of
139    * files (we just concatenate them).  We may have to feed the input
140    * through an external program.
141    *)
142   let () =
143     match args with
144     | [] -> ()                          (* Reading from stdin. *)
145     | [file] ->                         (* Read the named file. *)
146         let fd = openfile file [O_RDONLY] 0 in
147         dup2 fd stdin;
148         close fd
149     | files ->                          (* Concatenate files. *)
150         let rfd, wfd = pipe () in
151         let pid = fork () in
152         if pid = 0 then (               (* child *)
153           close rfd;
154           dup2 wfd stdout;
155           close wfd;
156           execvp "cat" (Array.of_list ("cat" :: "--" :: files))
157         ) else (                        (* parent *)
158           close wfd;
159           dup2 rfd stdin;
160           close rfd
161         )
162   in
163   (match extcompress with
164    | None -> ()
165    | Some prog ->
166        let prog, progargs =
167          match prog with
168          | BZip2 -> "bzip2", [|"bzip2"; "-cd"|]
169          | GZip -> "gzip", [|"gzip"; "-cd"|]
170          | External prog -> "sh", [|"sh"; "-c"; prog |] in
171        let rfd, wfd = pipe () in
172        let pid = fork () in
173        if pid = 0 then (                (* child *)
174          close rfd;
175          dup2 wfd stdout;
176          close wfd;
177          execvp prog progargs
178        ) else (                         (* parent *)
179          close wfd;
180          dup2 rfd stdin;
181          close rfd
182        )
183   )
184
185 (*
186   let header = read_header () in
187   XXX
188
189 *)
190
191
192
193
194
195
196
197
198 (* Do compression. *)
199 and go_compress extcompress images =
200   (* Create a Diskimage machine description from the requested images.  This
201    * also checks that everything we need is readable.
202    *)
203   let machine =
204     Diskimage.open_machine "diskzip" (List.map (fun n -> (n,n)) images) in
205
206   (* Scan the images for filesystems. *)
207   let machine = Diskimage.scan_machine machine in
208
209   (* Redirect output through external pipe if asked. *)
210   (match extcompress with
211    | None -> ()
212    | Some prog ->
213        let prog, progargs =
214          match prog with
215          | BZip2 -> "bzip2", [|"bzip2"; "-c"|]
216          | GZip -> "gzip", [|"gzip"; "-c"|]
217          | External prog -> "sh", [|"sh"; "-c"; prog |] in
218        let rfd, wfd = pipe () in
219        let pid = fork () in
220        if pid = 0 then (                (* child *)
221          close wfd;
222          dup2 rfd stdin;
223          close rfd;
224          execvp prog progargs
225        ) else (                         (* parent *)
226          close rfd;
227          dup2 wfd stdout;
228          close wfd
229        )
230   )
231
232
233
234
235
236
237
238
239 (*
240 (* Since we have the wonderful pa_bitmatch, might as well use it to
241  * define a robust binary format for the compressed files.
242  *)
243 and write_header ... =
244   let bs = BITSTRING {
245     0xD152 : 16; 0x01 : 8; 0x00 : 8;    (* file magic, version 1.0 *)
246     nr_disks : 8;                       (* number of disks being packed *)
247     
248
249
250
251   } in
252   
253 and read_header () =
254   (* Diskzip headers are limited to overall max size of 1024 bytes. *)
255   let bs = Bitmatch.bitstring_of_file_descr_max stdin 1024 in
256
257   bitmatch bs with
258   | { 0xD152 : 16;                      (* file magic *)
259       0x01 : 8; (_ as minor) : 8;       (* major, minor versions *)
260     } ->
261
262   (* Is this a later version (major != 1)? *)
263   | { 0xD152 : 16;                      (* file magic *)
264       (_ as major) : 8; (_ as minor) : 8 } when major <> 1 ->
265       eprintf (f_"diskzip: archive version %d.%d, this program only understands version 1.x")
266         major minor;
267       exit 1
268
269   (* If it looks like gzip or bzip2, exit with an informative error. *)
270   | { 0o37 : 8; 0o213 : 8 } ->          (* gzip *)
271       prerr_endline (s_"diskzip: This looks like a gzip archive. Did you mean to pass the '-z' option?");
272       exit 1
273   | { "BZh" : 24 : string } ->          (* bzip2 *)
274       prerr_endline (s_"diskzip: This looks like a bzip2 archive. Did you mean to pass the '-j' option?");
275       exit 1
276
277   (* If it looks like a disk image (MBR), give an error. *)
278   | { _ : 4080 : bitstring; 0x55 : 8; 0xAA : 8 } ->
279       prerr_endline (s_"diskzip: This looks like a disk image. Did you mean to compress it?");
280       exit 1
281
282   | { _ } ->
283       prerr_endline (s_"diskzip: Not a diskzip archive.");
284       exit 1
285 *)
286
287 let () = main ()