tests: Use squashfs for static data where possible.
[libguestfs.git] / src / generator.ml
1 #!/usr/bin/env ocaml
2 (* libguestfs
3  * Copyright (C) 2009 Red Hat Inc.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18  *)
19
20 (* This script generates a large amount of code and documentation for
21  * all the daemon actions.
22  *
23  * To add a new action there are only two files you need to change,
24  * this one to describe the interface (see the big table below), and
25  * daemon/<somefile>.c to write the implementation.
26  *
27  * After editing this file, run it (./src/generator.ml) to regenerate all the
28  * output files.  Note that if you are using a separate build directory you
29  * must run generator.ml from the _source_ directory.
30  *
31  * IMPORTANT: This script should NOT print any warnings.  If it prints
32  * warnings, you should treat them as errors.
33  * [Need to add -warn-error to ocaml command line]
34  *)
35
36 #load "unix.cma";;
37 #load "str.cma";;
38
39 open Printf
40
41 type style = ret * args
42 and ret =
43     (* "RErr" as a return value means an int used as a simple error
44      * indication, ie. 0 or -1.
45      *)
46   | RErr
47
48     (* "RInt" as a return value means an int which is -1 for error
49      * or any value >= 0 on success.  Only use this for smallish
50      * positive ints (0 <= i < 2^30).
51      *)
52   | RInt of string
53
54     (* "RInt64" is the same as RInt, but is guaranteed to be able
55      * to return a full 64 bit value, _except_ that -1 means error
56      * (so -1 cannot be a valid, non-error return value).
57      *)
58   | RInt64 of string
59
60     (* "RBool" is a bool return value which can be true/false or
61      * -1 for error.
62      *)
63   | RBool of string
64
65     (* "RConstString" is a string that refers to a constant value.
66      * The return value must NOT be NULL (since NULL indicates
67      * an error).
68      *
69      * Try to avoid using this.  In particular you cannot use this
70      * for values returned from the daemon, because there is no
71      * thread-safe way to return them in the C API.
72      *)
73   | RConstString of string
74
75     (* "RConstOptString" is an even more broken version of
76      * "RConstString".  The returned string may be NULL and there
77      * is no way to return an error indication.  Avoid using this!
78      *)
79   | RConstOptString of string
80
81     (* "RString" is a returned string.  It must NOT be NULL, since
82      * a NULL return indicates an error.  The caller frees this.
83      *)
84   | RString of string
85
86     (* "RStringList" is a list of strings.  No string in the list
87      * can be NULL.  The caller frees the strings and the array.
88      *)
89   | RStringList of string
90
91     (* "RStruct" is a function which returns a single named structure
92      * or an error indication (in C, a struct, and in other languages
93      * with varying representations, but usually very efficient).  See
94      * after the function list below for the structures. 
95      *)
96   | RStruct of string * string          (* name of retval, name of struct *)
97
98     (* "RStructList" is a function which returns either a list/array
99      * of structures (could be zero-length), or an error indication.
100      *)
101   | RStructList of string * string      (* name of retval, name of struct *)
102
103     (* Key-value pairs of untyped strings.  Turns into a hashtable or
104      * dictionary in languages which support it.  DON'T use this as a
105      * general "bucket" for results.  Prefer a stronger typed return
106      * value if one is available, or write a custom struct.  Don't use
107      * this if the list could potentially be very long, since it is
108      * inefficient.  Keys should be unique.  NULLs are not permitted.
109      *)
110   | RHashtable of string
111
112     (* "RBufferOut" is handled almost exactly like RString, but
113      * it allows the string to contain arbitrary 8 bit data including
114      * ASCII NUL.  In the C API this causes an implicit extra parameter
115      * to be added of type <size_t *size_r>.  The extra parameter
116      * returns the actual size of the return buffer in bytes.
117      *
118      * Other programming languages support strings with arbitrary 8 bit
119      * data.
120      *
121      * At the RPC layer we have to use the opaque<> type instead of
122      * string<>.  Returned data is still limited to the max message
123      * size (ie. ~ 2 MB).
124      *)
125   | RBufferOut of string
126
127 and args = argt list    (* Function parameters, guestfs handle is implicit. *)
128
129     (* Note in future we should allow a "variable args" parameter as
130      * the final parameter, to allow commands like
131      *   chmod mode file [file(s)...]
132      * This is not implemented yet, but many commands (such as chmod)
133      * are currently defined with the argument order keeping this future
134      * possibility in mind.
135      *)
136 and argt =
137   | String of string    (* const char *name, cannot be NULL *)
138   | OptString of string (* const char *name, may be NULL *)
139   | StringList of string(* list of strings (each string cannot be NULL) *)
140   | Bool of string      (* boolean *)
141   | Int of string       (* int (smallish ints, signed, <= 31 bits) *)
142     (* These are treated as filenames (simple string parameters) in
143      * the C API and bindings.  But in the RPC protocol, we transfer
144      * the actual file content up to or down from the daemon.
145      * FileIn: local machine -> daemon (in request)
146      * FileOut: daemon -> local machine (in reply)
147      * In guestfish (only), the special name "-" means read from
148      * stdin or write to stdout.
149      *)
150   | FileIn of string
151   | FileOut of string
152 (* Not implemented:
153     (* Opaque buffer which can contain arbitrary 8 bit data.
154      * In the C API, this is expressed as <char *, int> pair.
155      * Most other languages have a string type which can contain
156      * ASCII NUL.  We use whatever type is appropriate for each
157      * language.
158      * Buffers are limited by the total message size.  To transfer
159      * large blocks of data, use FileIn/FileOut parameters instead.
160      * To return an arbitrary buffer, use RBufferOut.
161      *)
162   | BufferIn of string
163 *)
164
165 type flags =
166   | ProtocolLimitWarning  (* display warning about protocol size limits *)
167   | DangerWillRobinson    (* flags particularly dangerous commands *)
168   | FishAlias of string   (* provide an alias for this cmd in guestfish *)
169   | FishAction of string  (* call this function in guestfish *)
170   | NotInFish             (* do not export via guestfish *)
171   | NotInDocs             (* do not add this function to documentation *)
172   | DeprecatedBy of string (* function is deprecated, use .. instead *)
173
174 (* You can supply zero or as many tests as you want per API call.
175  *
176  * Note that the test environment has 3 block devices, of size 500MB,
177  * 50MB and 10MB (respectively /dev/sda, /dev/sdb, /dev/sdc), and
178  * a fourth squashfs block device with some known files on it (/dev/sdd).
179  *
180  * Note for partitioning purposes, the 500MB device has 1015 cylinders.
181  * Number of cylinders was 63 for IDE emulated disks with precisely
182  * the same size.  How exactly this is calculated is a mystery.
183  *
184  * The squashfs block device (/dev/sdd) comes from images/test.sqsh.
185  *
186  * To be able to run the tests in a reasonable amount of time,
187  * the virtual machine and block devices are reused between tests.
188  * So don't try testing kill_subprocess :-x
189  *
190  * Between each test we blockdev-setrw, umount-all, lvm-remove-all.
191  *
192  * Don't assume anything about the previous contents of the block
193  * devices.  Use 'Init*' to create some initial scenarios.
194  *
195  * You can add a prerequisite clause to any individual test.  This
196  * is a run-time check, which, if it fails, causes the test to be
197  * skipped.  Useful if testing a command which might not work on
198  * all variations of libguestfs builds.  A test that has prerequisite
199  * of 'Always' is run unconditionally.
200  *
201  * In addition, packagers can skip individual tests by setting the
202  * environment variables:     eg:
203  *   SKIP_TEST_<CMD>_<NUM>=1  SKIP_TEST_COMMAND_3=1  (skips test #3 of command)
204  *   SKIP_TEST_<CMD>=1        SKIP_TEST_ZEROFREE=1   (skips all zerofree tests)
205  *)
206 type tests = (test_init * test_prereq * test) list
207 and test =
208     (* Run the command sequence and just expect nothing to fail. *)
209   | TestRun of seq
210     (* Run the command sequence and expect the output of the final
211      * command to be the string.
212      *)
213   | TestOutput of seq * string
214     (* Run the command sequence and expect the output of the final
215      * command to be the list of strings.
216      *)
217   | TestOutputList of seq * string list
218     (* Run the command sequence and expect the output of the final
219      * command to be the list of block devices (could be either
220      * "/dev/sd.." or "/dev/hd.." form - we don't check the 5th
221      * character of each string).
222      *)
223   | TestOutputListOfDevices of seq * string list
224     (* Run the command sequence and expect the output of the final
225      * command to be the integer.
226      *)
227   | TestOutputInt of seq * int
228     (* Run the command sequence and expect the output of the final
229      * command to be <op> <int>, eg. ">=", "1".
230      *)
231   | TestOutputIntOp of seq * string * int
232     (* Run the command sequence and expect the output of the final
233      * command to be a true value (!= 0 or != NULL).
234      *)
235   | TestOutputTrue of seq
236     (* Run the command sequence and expect the output of the final
237      * command to be a false value (== 0 or == NULL, but not an error).
238      *)
239   | TestOutputFalse of seq
240     (* Run the command sequence and expect the output of the final
241      * command to be a list of the given length (but don't care about
242      * content).
243      *)
244   | TestOutputLength of seq * int
245     (* Run the command sequence and expect the output of the final
246      * command to be a buffer (RBufferOut), ie. string + size.
247      *)
248   | TestOutputBuffer of seq * string
249     (* Run the command sequence and expect the output of the final
250      * command to be a structure.
251      *)
252   | TestOutputStruct of seq * test_field_compare list
253     (* Run the command sequence and expect the final command (only)
254      * to fail.
255      *)
256   | TestLastFail of seq
257
258 and test_field_compare =
259   | CompareWithInt of string * int
260   | CompareWithIntOp of string * string * int
261   | CompareWithString of string * string
262   | CompareFieldsIntEq of string * string
263   | CompareFieldsStrEq of string * string
264
265 (* Test prerequisites. *)
266 and test_prereq =
267     (* Test always runs. *)
268   | Always
269     (* Test is currently disabled - eg. it fails, or it tests some
270      * unimplemented feature.
271      *)
272   | Disabled
273     (* 'string' is some C code (a function body) that should return
274      * true or false.  The test will run if the code returns true.
275      *)
276   | If of string
277     (* As for 'If' but the test runs _unless_ the code returns true. *)
278   | Unless of string
279
280 (* Some initial scenarios for testing. *)
281 and test_init =
282     (* Do nothing, block devices could contain random stuff including
283      * LVM PVs, and some filesystems might be mounted.  This is usually
284      * a bad idea.
285      *)
286   | InitNone
287
288     (* Block devices are empty and no filesystems are mounted. *)
289   | InitEmpty
290
291     (* /dev/sda contains a single partition /dev/sda1, which is formatted
292      * as ext2, empty [except for lost+found] and mounted on /.
293      * /dev/sdb and /dev/sdc may have random content.
294      * No LVM.
295      *)
296   | InitBasicFS
297
298     (* /dev/sda:
299      *   /dev/sda1 (is a PV):
300      *     /dev/VG/LV (size 8MB):
301      *       formatted as ext2, empty [except for lost+found], mounted on /
302      * /dev/sdb and /dev/sdc may have random content.
303      *)
304   | InitBasicFSonLVM
305
306     (* /dev/sdd (the squashfs, see images/ directory in source)
307      * is mounted on /
308      *)
309   | InitSquashFS
310
311 (* Sequence of commands for testing. *)
312 and seq = cmd list
313 and cmd = string list
314
315 (* Note about long descriptions: When referring to another
316  * action, use the format C<guestfs_other> (ie. the full name of
317  * the C function).  This will be replaced as appropriate in other
318  * language bindings.
319  *
320  * Apart from that, long descriptions are just perldoc paragraphs.
321  *)
322
323 (* These test functions are used in the language binding tests. *)
324
325 let test_all_args = [
326   String "str";
327   OptString "optstr";
328   StringList "strlist";
329   Bool "b";
330   Int "integer";
331   FileIn "filein";
332   FileOut "fileout";
333 ]
334
335 let test_all_rets = [
336   (* except for RErr, which is tested thoroughly elsewhere *)
337   "test0rint",         RInt "valout";
338   "test0rint64",       RInt64 "valout";
339   "test0rbool",        RBool "valout";
340   "test0rconststring", RConstString "valout";
341   "test0rconstoptstring", RConstOptString "valout";
342   "test0rstring",      RString "valout";
343   "test0rstringlist",  RStringList "valout";
344   "test0rstruct",      RStruct ("valout", "lvm_pv");
345   "test0rstructlist",  RStructList ("valout", "lvm_pv");
346   "test0rhashtable",   RHashtable "valout";
347 ]
348
349 let test_functions = [
350   ("test0", (RErr, test_all_args), -1, [NotInFish; NotInDocs],
351    [],
352    "internal test function - do not use",
353    "\
354 This is an internal test function which is used to test whether
355 the automatically generated bindings can handle every possible
356 parameter type correctly.
357
358 It echos the contents of each parameter to stdout.
359
360 You probably don't want to call this function.");
361 ] @ List.flatten (
362   List.map (
363     fun (name, ret) ->
364       [(name, (ret, [String "val"]), -1, [NotInFish; NotInDocs],
365         [],
366         "internal test function - do not use",
367         "\
368 This is an internal test function which is used to test whether
369 the automatically generated bindings can handle every possible
370 return type correctly.
371
372 It converts string C<val> to the return type.
373
374 You probably don't want to call this function.");
375        (name ^ "err", (ret, []), -1, [NotInFish; NotInDocs],
376         [],
377         "internal test function - do not use",
378         "\
379 This is an internal test function which is used to test whether
380 the automatically generated bindings can handle every possible
381 return type correctly.
382
383 This function always returns an error.
384
385 You probably don't want to call this function.")]
386   ) test_all_rets
387 )
388
389 (* non_daemon_functions are any functions which don't get processed
390  * in the daemon, eg. functions for setting and getting local
391  * configuration values.
392  *)
393
394 let non_daemon_functions = test_functions @ [
395   ("launch", (RErr, []), -1, [FishAlias "run"; FishAction "launch"],
396    [],
397    "launch the qemu subprocess",
398    "\
399 Internally libguestfs is implemented by running a virtual machine
400 using L<qemu(1)>.
401
402 You should call this after configuring the handle
403 (eg. adding drives) but before performing any actions.");
404
405   ("wait_ready", (RErr, []), -1, [NotInFish],
406    [],
407    "wait until the qemu subprocess launches",
408    "\
409 Internally libguestfs is implemented by running a virtual machine
410 using L<qemu(1)>.
411
412 You should call this after C<guestfs_launch> to wait for the launch
413 to complete.");
414
415   ("kill_subprocess", (RErr, []), -1, [],
416    [],
417    "kill the qemu subprocess",
418    "\
419 This kills the qemu subprocess.  You should never need to call this.");
420
421   ("add_drive", (RErr, [String "filename"]), -1, [FishAlias "add"],
422    [],
423    "add an image to examine or modify",
424    "\
425 This function adds a virtual machine disk image C<filename> to the
426 guest.  The first time you call this function, the disk appears as IDE
427 disk 0 (C</dev/sda>) in the guest, the second time as C</dev/sdb>, and
428 so on.
429
430 You don't necessarily need to be root when using libguestfs.  However
431 you obviously do need sufficient permissions to access the filename
432 for whatever operations you want to perform (ie. read access if you
433 just want to read the image or write access if you want to modify the
434 image).
435
436 This is equivalent to the qemu parameter
437 C<-drive file=filename,cache=off,if=...>.
438
439 Note that this call checks for the existence of C<filename>.  This
440 stops you from specifying other types of drive which are supported
441 by qemu such as C<nbd:> and C<http:> URLs.  To specify those, use
442 the general C<guestfs_config> call instead.");
443
444   ("add_cdrom", (RErr, [String "filename"]), -1, [FishAlias "cdrom"],
445    [],
446    "add a CD-ROM disk image to examine",
447    "\
448 This function adds a virtual CD-ROM disk image to the guest.
449
450 This is equivalent to the qemu parameter C<-cdrom filename>.
451
452 Note that this call checks for the existence of C<filename>.  This
453 stops you from specifying other types of drive which are supported
454 by qemu such as C<nbd:> and C<http:> URLs.  To specify those, use
455 the general C<guestfs_config> call instead.");
456
457   ("add_drive_ro", (RErr, [String "filename"]), -1, [FishAlias "add-ro"],
458    [],
459    "add a drive in snapshot mode (read-only)",
460    "\
461 This adds a drive in snapshot mode, making it effectively
462 read-only.
463
464 Note that writes to the device are allowed, and will be seen for
465 the duration of the guestfs handle, but they are written
466 to a temporary file which is discarded as soon as the guestfs
467 handle is closed.  We don't currently have any method to enable
468 changes to be committed, although qemu can support this.
469
470 This is equivalent to the qemu parameter
471 C<-drive file=filename,snapshot=on,if=...>.
472
473 Note that this call checks for the existence of C<filename>.  This
474 stops you from specifying other types of drive which are supported
475 by qemu such as C<nbd:> and C<http:> URLs.  To specify those, use
476 the general C<guestfs_config> call instead.");
477
478   ("config", (RErr, [String "qemuparam"; OptString "qemuvalue"]), -1, [],
479    [],
480    "add qemu parameters",
481    "\
482 This can be used to add arbitrary qemu command line parameters
483 of the form C<-param value>.  Actually it's not quite arbitrary - we
484 prevent you from setting some parameters which would interfere with
485 parameters that we use.
486
487 The first character of C<param> string must be a C<-> (dash).
488
489 C<value> can be NULL.");
490
491   ("set_qemu", (RErr, [String "qemu"]), -1, [FishAlias "qemu"],
492    [],
493    "set the qemu binary",
494    "\
495 Set the qemu binary that we will use.
496
497 The default is chosen when the library was compiled by the
498 configure script.
499
500 You can also override this by setting the C<LIBGUESTFS_QEMU>
501 environment variable.
502
503 Setting C<qemu> to C<NULL> restores the default qemu binary.");
504
505   ("get_qemu", (RConstString "qemu", []), -1, [],
506    [InitNone, Always, TestRun (
507       [["get_qemu"]])],
508    "get the qemu binary",
509    "\
510 Return the current qemu binary.
511
512 This is always non-NULL.  If it wasn't set already, then this will
513 return the default qemu binary name.");
514
515   ("set_path", (RErr, [String "path"]), -1, [FishAlias "path"],
516    [],
517    "set the search path",
518    "\
519 Set the path that libguestfs searches for kernel and initrd.img.
520
521 The default is C<$libdir/guestfs> unless overridden by setting
522 C<LIBGUESTFS_PATH> environment variable.
523
524 Setting C<path> to C<NULL> restores the default path.");
525
526   ("get_path", (RConstString "path", []), -1, [],
527    [InitNone, Always, TestRun (
528       [["get_path"]])],
529    "get the search path",
530    "\
531 Return the current search path.
532
533 This is always non-NULL.  If it wasn't set already, then this will
534 return the default path.");
535
536   ("set_append", (RErr, [OptString "append"]), -1, [FishAlias "append"],
537    [],
538    "add options to kernel command line",
539    "\
540 This function is used to add additional options to the
541 guest kernel command line.
542
543 The default is C<NULL> unless overridden by setting
544 C<LIBGUESTFS_APPEND> environment variable.
545
546 Setting C<append> to C<NULL> means I<no> additional options
547 are passed (libguestfs always adds a few of its own).");
548
549   ("get_append", (RConstOptString "append", []), -1, [],
550    (* This cannot be tested with the current framework.  The
551     * function can return NULL in normal operations, which the
552     * test framework interprets as an error.
553     *)
554    [],
555    "get the additional kernel options",
556    "\
557 Return the additional kernel options which are added to the
558 guest kernel command line.
559
560 If C<NULL> then no options are added.");
561
562   ("set_autosync", (RErr, [Bool "autosync"]), -1, [FishAlias "autosync"],
563    [],
564    "set autosync mode",
565    "\
566 If C<autosync> is true, this enables autosync.  Libguestfs will make a
567 best effort attempt to run C<guestfs_umount_all> followed by
568 C<guestfs_sync> when the handle is closed
569 (also if the program exits without closing handles).
570
571 This is disabled by default (except in guestfish where it is
572 enabled by default).");
573
574   ("get_autosync", (RBool "autosync", []), -1, [],
575    [InitNone, Always, TestRun (
576       [["get_autosync"]])],
577    "get autosync mode",
578    "\
579 Get the autosync flag.");
580
581   ("set_verbose", (RErr, [Bool "verbose"]), -1, [FishAlias "verbose"],
582    [],
583    "set verbose mode",
584    "\
585 If C<verbose> is true, this turns on verbose messages (to C<stderr>).
586
587 Verbose messages are disabled unless the environment variable
588 C<LIBGUESTFS_DEBUG> is defined and set to C<1>.");
589
590   ("get_verbose", (RBool "verbose", []), -1, [],
591    [],
592    "get verbose mode",
593    "\
594 This returns the verbose messages flag.");
595
596   ("is_ready", (RBool "ready", []), -1, [],
597    [InitNone, Always, TestOutputTrue (
598       [["is_ready"]])],
599    "is ready to accept commands",
600    "\
601 This returns true iff this handle is ready to accept commands
602 (in the C<READY> state).
603
604 For more information on states, see L<guestfs(3)>.");
605
606   ("is_config", (RBool "config", []), -1, [],
607    [InitNone, Always, TestOutputFalse (
608       [["is_config"]])],
609    "is in configuration state",
610    "\
611 This returns true iff this handle is being configured
612 (in the C<CONFIG> state).
613
614 For more information on states, see L<guestfs(3)>.");
615
616   ("is_launching", (RBool "launching", []), -1, [],
617    [InitNone, Always, TestOutputFalse (
618       [["is_launching"]])],
619    "is launching subprocess",
620    "\
621 This returns true iff this handle is launching the subprocess
622 (in the C<LAUNCHING> state).
623
624 For more information on states, see L<guestfs(3)>.");
625
626   ("is_busy", (RBool "busy", []), -1, [],
627    [InitNone, Always, TestOutputFalse (
628       [["is_busy"]])],
629    "is busy processing a command",
630    "\
631 This returns true iff this handle is busy processing a command
632 (in the C<BUSY> state).
633
634 For more information on states, see L<guestfs(3)>.");
635
636   ("get_state", (RInt "state", []), -1, [],
637    [],
638    "get the current state",
639    "\
640 This returns the current state as an opaque integer.  This is
641 only useful for printing debug and internal error messages.
642
643 For more information on states, see L<guestfs(3)>.");
644
645   ("set_busy", (RErr, []), -1, [NotInFish],
646    [],
647    "set state to busy",
648    "\
649 This sets the state to C<BUSY>.  This is only used when implementing
650 actions using the low-level API.
651
652 For more information on states, see L<guestfs(3)>.");
653
654   ("set_ready", (RErr, []), -1, [NotInFish],
655    [],
656    "set state to ready",
657    "\
658 This sets the state to C<READY>.  This is only used when implementing
659 actions using the low-level API.
660
661 For more information on states, see L<guestfs(3)>.");
662
663   ("end_busy", (RErr, []), -1, [NotInFish],
664    [],
665    "leave the busy state",
666    "\
667 This sets the state to C<READY>, or if in C<CONFIG> then it leaves the
668 state as is.  This is only used when implementing
669 actions using the low-level API.
670
671 For more information on states, see L<guestfs(3)>.");
672
673   ("set_memsize", (RErr, [Int "memsize"]), -1, [FishAlias "memsize"],
674    [InitNone, Always, TestOutputInt (
675       [["set_memsize"; "500"];
676        ["get_memsize"]], 500)],
677    "set memory allocated to the qemu subprocess",
678    "\
679 This sets the memory size in megabytes allocated to the
680 qemu subprocess.  This only has any effect if called before
681 C<guestfs_launch>.
682
683 You can also change this by setting the environment
684 variable C<LIBGUESTFS_MEMSIZE> before the handle is
685 created.
686
687 For more information on the architecture of libguestfs,
688 see L<guestfs(3)>.");
689
690   ("get_memsize", (RInt "memsize", []), -1, [],
691    [InitNone, Always, TestOutputIntOp (
692       [["get_memsize"]], ">=", 256)],
693    "get memory allocated to the qemu subprocess",
694    "\
695 This gets the memory size in megabytes allocated to the
696 qemu subprocess.
697
698 If C<guestfs_set_memsize> was not called
699 on this handle, and if C<LIBGUESTFS_MEMSIZE> was not set,
700 then this returns the compiled-in default value for memsize.
701
702 For more information on the architecture of libguestfs,
703 see L<guestfs(3)>.");
704
705   ("get_pid", (RInt "pid", []), -1, [FishAlias "pid"],
706    [InitNone, Always, TestOutputIntOp (
707       [["get_pid"]], ">=", 1)],
708    "get PID of qemu subprocess",
709    "\
710 Return the process ID of the qemu subprocess.  If there is no
711 qemu subprocess, then this will return an error.
712
713 This is an internal call used for debugging and testing.");
714
715   ("version", (RStruct ("version", "version"), []), -1, [],
716    [InitNone, Always, TestOutputStruct (
717       [["version"]], [CompareWithInt ("major", 1)])],
718    "get the library version number",
719    "\
720 Return the libguestfs version number that the program is linked
721 against.
722
723 Note that because of dynamic linking this is not necessarily
724 the version of libguestfs that you compiled against.  You can
725 compile the program, and then at runtime dynamically link
726 against a completely different C<libguestfs.so> library.
727
728 This call was added in version C<1.0.58>.  In previous
729 versions of libguestfs there was no way to get the version
730 number.  From C code you can use ELF weak linking tricks to find out if
731 this symbol exists (if it doesn't, then it's an earlier version).
732
733 The call returns a structure with four elements.  The first
734 three (C<major>, C<minor> and C<release>) are numbers and
735 correspond to the usual version triplet.  The fourth element
736 (C<extra>) is a string and is normally empty, but may be
737 used for distro-specific information.
738
739 To construct the original version string:
740 C<$major.$minor.$release$extra>
741
742 I<Note:> Don't use this call to test for availability
743 of features.  Distro backports makes this unreliable.");
744
745 ]
746
747 (* daemon_functions are any functions which cause some action
748  * to take place in the daemon.
749  *)
750
751 let daemon_functions = [
752   ("mount", (RErr, [String "device"; String "mountpoint"]), 1, [],
753    [InitEmpty, Always, TestOutput (
754       [["sfdiskM"; "/dev/sda"; ","];
755        ["mkfs"; "ext2"; "/dev/sda1"];
756        ["mount"; "/dev/sda1"; "/"];
757        ["write_file"; "/new"; "new file contents"; "0"];
758        ["cat"; "/new"]], "new file contents")],
759    "mount a guest disk at a position in the filesystem",
760    "\
761 Mount a guest disk at a position in the filesystem.  Block devices
762 are named C</dev/sda>, C</dev/sdb> and so on, as they were added to
763 the guest.  If those block devices contain partitions, they will have
764 the usual names (eg. C</dev/sda1>).  Also LVM C</dev/VG/LV>-style
765 names can be used.
766
767 The rules are the same as for L<mount(2)>:  A filesystem must
768 first be mounted on C</> before others can be mounted.  Other
769 filesystems can only be mounted on directories which already
770 exist.
771
772 The mounted filesystem is writable, if we have sufficient permissions
773 on the underlying device.
774
775 The filesystem options C<sync> and C<noatime> are set with this
776 call, in order to improve reliability.");
777
778   ("sync", (RErr, []), 2, [],
779    [ InitEmpty, Always, TestRun [["sync"]]],
780    "sync disks, writes are flushed through to the disk image",
781    "\
782 This syncs the disk, so that any writes are flushed through to the
783 underlying disk image.
784
785 You should always call this if you have modified a disk image, before
786 closing the handle.");
787
788   ("touch", (RErr, [String "path"]), 3, [],
789    [InitBasicFS, Always, TestOutputTrue (
790       [["touch"; "/new"];
791        ["exists"; "/new"]])],
792    "update file timestamps or create a new file",
793    "\
794 Touch acts like the L<touch(1)> command.  It can be used to
795 update the timestamps on a file, or, if the file does not exist,
796 to create a new zero-length file.");
797
798   ("cat", (RString "content", [String "path"]), 4, [ProtocolLimitWarning],
799    [InitSquashFS, Always, TestOutput (
800       [["cat"; "/known-2"]], "abcdef\n")],
801    "list the contents of a file",
802    "\
803 Return the contents of the file named C<path>.
804
805 Note that this function cannot correctly handle binary files
806 (specifically, files containing C<\\0> character which is treated
807 as end of string).  For those you need to use the C<guestfs_read_file>
808 or C<guestfs_download> functions which have a more complex interface.");
809
810   ("ll", (RString "listing", [String "directory"]), 5, [],
811    [], (* XXX Tricky to test because it depends on the exact format
812         * of the 'ls -l' command, which changes between F10 and F11.
813         *)
814    "list the files in a directory (long format)",
815    "\
816 List the files in C<directory> (relative to the root directory,
817 there is no cwd) in the format of 'ls -la'.
818
819 This command is mostly useful for interactive sessions.  It
820 is I<not> intended that you try to parse the output string.");
821
822   ("ls", (RStringList "listing", [String "directory"]), 6, [],
823    [InitBasicFS, Always, TestOutputList (
824       [["touch"; "/new"];
825        ["touch"; "/newer"];
826        ["touch"; "/newest"];
827        ["ls"; "/"]], ["lost+found"; "new"; "newer"; "newest"])],
828    "list the files in a directory",
829    "\
830 List the files in C<directory> (relative to the root directory,
831 there is no cwd).  The '.' and '..' entries are not returned, but
832 hidden files are shown.
833
834 This command is mostly useful for interactive sessions.  Programs
835 should probably use C<guestfs_readdir> instead.");
836
837   ("list_devices", (RStringList "devices", []), 7, [],
838    [InitEmpty, Always, TestOutputListOfDevices (
839       [["list_devices"]], ["/dev/sda"; "/dev/sdb"; "/dev/sdc"; "/dev/sdd"])],
840    "list the block devices",
841    "\
842 List all the block devices.
843
844 The full block device names are returned, eg. C</dev/sda>");
845
846   ("list_partitions", (RStringList "partitions", []), 8, [],
847    [InitBasicFS, Always, TestOutputListOfDevices (
848       [["list_partitions"]], ["/dev/sda1"]);
849     InitEmpty, Always, TestOutputListOfDevices (
850       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
851        ["list_partitions"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
852    "list the partitions",
853    "\
854 List all the partitions detected on all block devices.
855
856 The full partition device names are returned, eg. C</dev/sda1>
857
858 This does not return logical volumes.  For that you will need to
859 call C<guestfs_lvs>.");
860
861   ("pvs", (RStringList "physvols", []), 9, [],
862    [InitBasicFSonLVM, Always, TestOutputListOfDevices (
863       [["pvs"]], ["/dev/sda1"]);
864     InitEmpty, Always, TestOutputListOfDevices (
865       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
866        ["pvcreate"; "/dev/sda1"];
867        ["pvcreate"; "/dev/sda2"];
868        ["pvcreate"; "/dev/sda3"];
869        ["pvs"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
870    "list the LVM physical volumes (PVs)",
871    "\
872 List all the physical volumes detected.  This is the equivalent
873 of the L<pvs(8)> command.
874
875 This returns a list of just the device names that contain
876 PVs (eg. C</dev/sda2>).
877
878 See also C<guestfs_pvs_full>.");
879
880   ("vgs", (RStringList "volgroups", []), 10, [],
881    [InitBasicFSonLVM, Always, TestOutputList (
882       [["vgs"]], ["VG"]);
883     InitEmpty, Always, TestOutputList (
884       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
885        ["pvcreate"; "/dev/sda1"];
886        ["pvcreate"; "/dev/sda2"];
887        ["pvcreate"; "/dev/sda3"];
888        ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
889        ["vgcreate"; "VG2"; "/dev/sda3"];
890        ["vgs"]], ["VG1"; "VG2"])],
891    "list the LVM volume groups (VGs)",
892    "\
893 List all the volumes groups detected.  This is the equivalent
894 of the L<vgs(8)> command.
895
896 This returns a list of just the volume group names that were
897 detected (eg. C<VolGroup00>).
898
899 See also C<guestfs_vgs_full>.");
900
901   ("lvs", (RStringList "logvols", []), 11, [],
902    [InitBasicFSonLVM, Always, TestOutputList (
903       [["lvs"]], ["/dev/VG/LV"]);
904     InitEmpty, Always, TestOutputList (
905       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
906        ["pvcreate"; "/dev/sda1"];
907        ["pvcreate"; "/dev/sda2"];
908        ["pvcreate"; "/dev/sda3"];
909        ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
910        ["vgcreate"; "VG2"; "/dev/sda3"];
911        ["lvcreate"; "LV1"; "VG1"; "50"];
912        ["lvcreate"; "LV2"; "VG1"; "50"];
913        ["lvcreate"; "LV3"; "VG2"; "50"];
914        ["lvs"]], ["/dev/VG1/LV1"; "/dev/VG1/LV2"; "/dev/VG2/LV3"])],
915    "list the LVM logical volumes (LVs)",
916    "\
917 List all the logical volumes detected.  This is the equivalent
918 of the L<lvs(8)> command.
919
920 This returns a list of the logical volume device names
921 (eg. C</dev/VolGroup00/LogVol00>).
922
923 See also C<guestfs_lvs_full>.");
924
925   ("pvs_full", (RStructList ("physvols", "lvm_pv"), []), 12, [],
926    [], (* XXX how to test? *)
927    "list the LVM physical volumes (PVs)",
928    "\
929 List all the physical volumes detected.  This is the equivalent
930 of the L<pvs(8)> command.  The \"full\" version includes all fields.");
931
932   ("vgs_full", (RStructList ("volgroups", "lvm_vg"), []), 13, [],
933    [], (* XXX how to test? *)
934    "list the LVM volume groups (VGs)",
935    "\
936 List all the volumes groups detected.  This is the equivalent
937 of the L<vgs(8)> command.  The \"full\" version includes all fields.");
938
939   ("lvs_full", (RStructList ("logvols", "lvm_lv"), []), 14, [],
940    [], (* XXX how to test? *)
941    "list the LVM logical volumes (LVs)",
942    "\
943 List all the logical volumes detected.  This is the equivalent
944 of the L<lvs(8)> command.  The \"full\" version includes all fields.");
945
946   ("read_lines", (RStringList "lines", [String "path"]), 15, [],
947    [InitSquashFS, Always, TestOutputList (
948       [["read_lines"; "/known-4"]], ["abc"; "def"; "ghi"]);
949     InitSquashFS, Always, TestOutputList (
950       [["read_lines"; "/empty"]], [])],
951    "read file as lines",
952    "\
953 Return the contents of the file named C<path>.
954
955 The file contents are returned as a list of lines.  Trailing
956 C<LF> and C<CRLF> character sequences are I<not> returned.
957
958 Note that this function cannot correctly handle binary files
959 (specifically, files containing C<\\0> character which is treated
960 as end of line).  For those you need to use the C<guestfs_read_file>
961 function which has a more complex interface.");
962
963   ("aug_init", (RErr, [String "root"; Int "flags"]), 16, [],
964    [], (* XXX Augeas code needs tests. *)
965    "create a new Augeas handle",
966    "\
967 Create a new Augeas handle for editing configuration files.
968 If there was any previous Augeas handle associated with this
969 guestfs session, then it is closed.
970
971 You must call this before using any other C<guestfs_aug_*>
972 commands.
973
974 C<root> is the filesystem root.  C<root> must not be NULL,
975 use C</> instead.
976
977 The flags are the same as the flags defined in
978 E<lt>augeas.hE<gt>, the logical I<or> of the following
979 integers:
980
981 =over 4
982
983 =item C<AUG_SAVE_BACKUP> = 1
984
985 Keep the original file with a C<.augsave> extension.
986
987 =item C<AUG_SAVE_NEWFILE> = 2
988
989 Save changes into a file with extension C<.augnew>, and
990 do not overwrite original.  Overrides C<AUG_SAVE_BACKUP>.
991
992 =item C<AUG_TYPE_CHECK> = 4
993
994 Typecheck lenses (can be expensive).
995
996 =item C<AUG_NO_STDINC> = 8
997
998 Do not use standard load path for modules.
999
1000 =item C<AUG_SAVE_NOOP> = 16
1001
1002 Make save a no-op, just record what would have been changed.
1003
1004 =item C<AUG_NO_LOAD> = 32
1005
1006 Do not load the tree in C<guestfs_aug_init>.
1007
1008 =back
1009
1010 To close the handle, you can call C<guestfs_aug_close>.
1011
1012 To find out more about Augeas, see L<http://augeas.net/>.");
1013
1014   ("aug_close", (RErr, []), 26, [],
1015    [], (* XXX Augeas code needs tests. *)
1016    "close the current Augeas handle",
1017    "\
1018 Close the current Augeas handle and free up any resources
1019 used by it.  After calling this, you have to call
1020 C<guestfs_aug_init> again before you can use any other
1021 Augeas functions.");
1022
1023   ("aug_defvar", (RInt "nrnodes", [String "name"; OptString "expr"]), 17, [],
1024    [], (* XXX Augeas code needs tests. *)
1025    "define an Augeas variable",
1026    "\
1027 Defines an Augeas variable C<name> whose value is the result
1028 of evaluating C<expr>.  If C<expr> is NULL, then C<name> is
1029 undefined.
1030
1031 On success this returns the number of nodes in C<expr>, or
1032 C<0> if C<expr> evaluates to something which is not a nodeset.");
1033
1034   ("aug_defnode", (RStruct ("nrnodescreated", "int_bool"), [String "name"; String "expr"; String "val"]), 18, [],
1035    [], (* XXX Augeas code needs tests. *)
1036    "define an Augeas node",
1037    "\
1038 Defines a variable C<name> whose value is the result of
1039 evaluating C<expr>.
1040
1041 If C<expr> evaluates to an empty nodeset, a node is created,
1042 equivalent to calling C<guestfs_aug_set> C<expr>, C<value>.
1043 C<name> will be the nodeset containing that single node.
1044
1045 On success this returns a pair containing the
1046 number of nodes in the nodeset, and a boolean flag
1047 if a node was created.");
1048
1049   ("aug_get", (RString "val", [String "path"]), 19, [],
1050    [], (* XXX Augeas code needs tests. *)
1051    "look up the value of an Augeas path",
1052    "\
1053 Look up the value associated with C<path>.  If C<path>
1054 matches exactly one node, the C<value> is returned.");
1055
1056   ("aug_set", (RErr, [String "path"; String "val"]), 20, [],
1057    [], (* XXX Augeas code needs tests. *)
1058    "set Augeas path to value",
1059    "\
1060 Set the value associated with C<path> to C<value>.");
1061
1062   ("aug_insert", (RErr, [String "path"; String "label"; Bool "before"]), 21, [],
1063    [], (* XXX Augeas code needs tests. *)
1064    "insert a sibling Augeas node",
1065    "\
1066 Create a new sibling C<label> for C<path>, inserting it into
1067 the tree before or after C<path> (depending on the boolean
1068 flag C<before>).
1069
1070 C<path> must match exactly one existing node in the tree, and
1071 C<label> must be a label, ie. not contain C</>, C<*> or end
1072 with a bracketed index C<[N]>.");
1073
1074   ("aug_rm", (RInt "nrnodes", [String "path"]), 22, [],
1075    [], (* XXX Augeas code needs tests. *)
1076    "remove an Augeas path",
1077    "\
1078 Remove C<path> and all of its children.
1079
1080 On success this returns the number of entries which were removed.");
1081
1082   ("aug_mv", (RErr, [String "src"; String "dest"]), 23, [],
1083    [], (* XXX Augeas code needs tests. *)
1084    "move Augeas node",
1085    "\
1086 Move the node C<src> to C<dest>.  C<src> must match exactly
1087 one node.  C<dest> is overwritten if it exists.");
1088
1089   ("aug_match", (RStringList "matches", [String "path"]), 24, [],
1090    [], (* XXX Augeas code needs tests. *)
1091    "return Augeas nodes which match path",
1092    "\
1093 Returns a list of paths which match the path expression C<path>.
1094 The returned paths are sufficiently qualified so that they match
1095 exactly one node in the current tree.");
1096
1097   ("aug_save", (RErr, []), 25, [],
1098    [], (* XXX Augeas code needs tests. *)
1099    "write all pending Augeas changes to disk",
1100    "\
1101 This writes all pending changes to disk.
1102
1103 The flags which were passed to C<guestfs_aug_init> affect exactly
1104 how files are saved.");
1105
1106   ("aug_load", (RErr, []), 27, [],
1107    [], (* XXX Augeas code needs tests. *)
1108    "load files into the tree",
1109    "\
1110 Load files into the tree.
1111
1112 See C<aug_load> in the Augeas documentation for the full gory
1113 details.");
1114
1115   ("aug_ls", (RStringList "matches", [String "path"]), 28, [],
1116    [], (* XXX Augeas code needs tests. *)
1117    "list Augeas nodes under a path",
1118    "\
1119 This is just a shortcut for listing C<guestfs_aug_match>
1120 C<path/*> and sorting the resulting nodes into alphabetical order.");
1121
1122   ("rm", (RErr, [String "path"]), 29, [],
1123    [InitBasicFS, Always, TestRun
1124       [["touch"; "/new"];
1125        ["rm"; "/new"]];
1126     InitBasicFS, Always, TestLastFail
1127       [["rm"; "/new"]];
1128     InitBasicFS, Always, TestLastFail
1129       [["mkdir"; "/new"];
1130        ["rm"; "/new"]]],
1131    "remove a file",
1132    "\
1133 Remove the single file C<path>.");
1134
1135   ("rmdir", (RErr, [String "path"]), 30, [],
1136    [InitBasicFS, Always, TestRun
1137       [["mkdir"; "/new"];
1138        ["rmdir"; "/new"]];
1139     InitBasicFS, Always, TestLastFail
1140       [["rmdir"; "/new"]];
1141     InitBasicFS, Always, TestLastFail
1142       [["touch"; "/new"];
1143        ["rmdir"; "/new"]]],
1144    "remove a directory",
1145    "\
1146 Remove the single directory C<path>.");
1147
1148   ("rm_rf", (RErr, [String "path"]), 31, [],
1149    [InitBasicFS, Always, TestOutputFalse
1150       [["mkdir"; "/new"];
1151        ["mkdir"; "/new/foo"];
1152        ["touch"; "/new/foo/bar"];
1153        ["rm_rf"; "/new"];
1154        ["exists"; "/new"]]],
1155    "remove a file or directory recursively",
1156    "\
1157 Remove the file or directory C<path>, recursively removing the
1158 contents if its a directory.  This is like the C<rm -rf> shell
1159 command.");
1160
1161   ("mkdir", (RErr, [String "path"]), 32, [],
1162    [InitBasicFS, Always, TestOutputTrue
1163       [["mkdir"; "/new"];
1164        ["is_dir"; "/new"]];
1165     InitBasicFS, Always, TestLastFail
1166       [["mkdir"; "/new/foo/bar"]]],
1167    "create a directory",
1168    "\
1169 Create a directory named C<path>.");
1170
1171   ("mkdir_p", (RErr, [String "path"]), 33, [],
1172    [InitBasicFS, Always, TestOutputTrue
1173       [["mkdir_p"; "/new/foo/bar"];
1174        ["is_dir"; "/new/foo/bar"]];
1175     InitBasicFS, Always, TestOutputTrue
1176       [["mkdir_p"; "/new/foo/bar"];
1177        ["is_dir"; "/new/foo"]];
1178     InitBasicFS, Always, TestOutputTrue
1179       [["mkdir_p"; "/new/foo/bar"];
1180        ["is_dir"; "/new"]];
1181     (* Regression tests for RHBZ#503133: *)
1182     InitBasicFS, Always, TestRun
1183       [["mkdir"; "/new"];
1184        ["mkdir_p"; "/new"]];
1185     InitBasicFS, Always, TestLastFail
1186       [["touch"; "/new"];
1187        ["mkdir_p"; "/new"]]],
1188    "create a directory and parents",
1189    "\
1190 Create a directory named C<path>, creating any parent directories
1191 as necessary.  This is like the C<mkdir -p> shell command.");
1192
1193   ("chmod", (RErr, [Int "mode"; String "path"]), 34, [],
1194    [], (* XXX Need stat command to test *)
1195    "change file mode",
1196    "\
1197 Change the mode (permissions) of C<path> to C<mode>.  Only
1198 numeric modes are supported.");
1199
1200   ("chown", (RErr, [Int "owner"; Int "group"; String "path"]), 35, [],
1201    [], (* XXX Need stat command to test *)
1202    "change file owner and group",
1203    "\
1204 Change the file owner to C<owner> and group to C<group>.
1205
1206 Only numeric uid and gid are supported.  If you want to use
1207 names, you will need to locate and parse the password file
1208 yourself (Augeas support makes this relatively easy).");
1209
1210   ("exists", (RBool "existsflag", [String "path"]), 36, [],
1211    [InitSquashFS, Always, TestOutputTrue (
1212       [["exists"; "/empty"]]);
1213     InitSquashFS, Always, TestOutputTrue (
1214       [["exists"; "/directory"]])],
1215    "test if file or directory exists",
1216    "\
1217 This returns C<true> if and only if there is a file, directory
1218 (or anything) with the given C<path> name.
1219
1220 See also C<guestfs_is_file>, C<guestfs_is_dir>, C<guestfs_stat>.");
1221
1222   ("is_file", (RBool "fileflag", [String "path"]), 37, [],
1223    [InitSquashFS, Always, TestOutputTrue (
1224       [["is_file"; "/known-1"]]);
1225     InitSquashFS, Always, TestOutputFalse (
1226       [["is_file"; "/directory"]])],
1227    "test if file exists",
1228    "\
1229 This returns C<true> if and only if there is a file
1230 with the given C<path> name.  Note that it returns false for
1231 other objects like directories.
1232
1233 See also C<guestfs_stat>.");
1234
1235   ("is_dir", (RBool "dirflag", [String "path"]), 38, [],
1236    [InitSquashFS, Always, TestOutputFalse (
1237       [["is_dir"; "/known-3"]]);
1238     InitSquashFS, Always, TestOutputTrue (
1239       [["is_dir"; "/directory"]])],
1240    "test if file exists",
1241    "\
1242 This returns C<true> if and only if there is a directory
1243 with the given C<path> name.  Note that it returns false for
1244 other objects like files.
1245
1246 See also C<guestfs_stat>.");
1247
1248   ("pvcreate", (RErr, [String "device"]), 39, [],
1249    [InitEmpty, Always, TestOutputListOfDevices (
1250       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1251        ["pvcreate"; "/dev/sda1"];
1252        ["pvcreate"; "/dev/sda2"];
1253        ["pvcreate"; "/dev/sda3"];
1254        ["pvs"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
1255    "create an LVM physical volume",
1256    "\
1257 This creates an LVM physical volume on the named C<device>,
1258 where C<device> should usually be a partition name such
1259 as C</dev/sda1>.");
1260
1261   ("vgcreate", (RErr, [String "volgroup"; StringList "physvols"]), 40, [],
1262    [InitEmpty, Always, TestOutputList (
1263       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1264        ["pvcreate"; "/dev/sda1"];
1265        ["pvcreate"; "/dev/sda2"];
1266        ["pvcreate"; "/dev/sda3"];
1267        ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1268        ["vgcreate"; "VG2"; "/dev/sda3"];
1269        ["vgs"]], ["VG1"; "VG2"])],
1270    "create an LVM volume group",
1271    "\
1272 This creates an LVM volume group called C<volgroup>
1273 from the non-empty list of physical volumes C<physvols>.");
1274
1275   ("lvcreate", (RErr, [String "logvol"; String "volgroup"; Int "mbytes"]), 41, [],
1276    [InitEmpty, Always, TestOutputList (
1277       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1278        ["pvcreate"; "/dev/sda1"];
1279        ["pvcreate"; "/dev/sda2"];
1280        ["pvcreate"; "/dev/sda3"];
1281        ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1282        ["vgcreate"; "VG2"; "/dev/sda3"];
1283        ["lvcreate"; "LV1"; "VG1"; "50"];
1284        ["lvcreate"; "LV2"; "VG1"; "50"];
1285        ["lvcreate"; "LV3"; "VG2"; "50"];
1286        ["lvcreate"; "LV4"; "VG2"; "50"];
1287        ["lvcreate"; "LV5"; "VG2"; "50"];
1288        ["lvs"]],
1289       ["/dev/VG1/LV1"; "/dev/VG1/LV2";
1290        "/dev/VG2/LV3"; "/dev/VG2/LV4"; "/dev/VG2/LV5"])],
1291    "create an LVM volume group",
1292    "\
1293 This creates an LVM volume group called C<logvol>
1294 on the volume group C<volgroup>, with C<size> megabytes.");
1295
1296   ("mkfs", (RErr, [String "fstype"; String "device"]), 42, [],
1297    [InitEmpty, Always, TestOutput (
1298       [["sfdiskM"; "/dev/sda"; ","];
1299        ["mkfs"; "ext2"; "/dev/sda1"];
1300        ["mount"; "/dev/sda1"; "/"];
1301        ["write_file"; "/new"; "new file contents"; "0"];
1302        ["cat"; "/new"]], "new file contents")],
1303    "make a filesystem",
1304    "\
1305 This creates a filesystem on C<device> (usually a partition
1306 or LVM logical volume).  The filesystem type is C<fstype>, for
1307 example C<ext3>.");
1308
1309   ("sfdisk", (RErr, [String "device";
1310                      Int "cyls"; Int "heads"; Int "sectors";
1311                      StringList "lines"]), 43, [DangerWillRobinson],
1312    [],
1313    "create partitions on a block device",
1314    "\
1315 This is a direct interface to the L<sfdisk(8)> program for creating
1316 partitions on block devices.
1317
1318 C<device> should be a block device, for example C</dev/sda>.
1319
1320 C<cyls>, C<heads> and C<sectors> are the number of cylinders, heads
1321 and sectors on the device, which are passed directly to sfdisk as
1322 the I<-C>, I<-H> and I<-S> parameters.  If you pass C<0> for any
1323 of these, then the corresponding parameter is omitted.  Usually for
1324 'large' disks, you can just pass C<0> for these, but for small
1325 (floppy-sized) disks, sfdisk (or rather, the kernel) cannot work
1326 out the right geometry and you will need to tell it.
1327
1328 C<lines> is a list of lines that we feed to C<sfdisk>.  For more
1329 information refer to the L<sfdisk(8)> manpage.
1330
1331 To create a single partition occupying the whole disk, you would
1332 pass C<lines> as a single element list, when the single element being
1333 the string C<,> (comma).
1334
1335 See also: C<guestfs_sfdisk_l>, C<guestfs_sfdisk_N>");
1336
1337   ("write_file", (RErr, [String "path"; String "content"; Int "size"]), 44, [ProtocolLimitWarning],
1338    [InitBasicFS, Always, TestOutput (
1339       [["write_file"; "/new"; "new file contents"; "0"];
1340        ["cat"; "/new"]], "new file contents");
1341     InitBasicFS, Always, TestOutput (
1342       [["write_file"; "/new"; "\nnew file contents\n"; "0"];
1343        ["cat"; "/new"]], "\nnew file contents\n");
1344     InitBasicFS, Always, TestOutput (
1345       [["write_file"; "/new"; "\n\n"; "0"];
1346        ["cat"; "/new"]], "\n\n");
1347     InitBasicFS, Always, TestOutput (
1348       [["write_file"; "/new"; ""; "0"];
1349        ["cat"; "/new"]], "");
1350     InitBasicFS, Always, TestOutput (
1351       [["write_file"; "/new"; "\n\n\n"; "0"];
1352        ["cat"; "/new"]], "\n\n\n");
1353     InitBasicFS, Always, TestOutput (
1354       [["write_file"; "/new"; "\n"; "0"];
1355        ["cat"; "/new"]], "\n")],
1356    "create a file",
1357    "\
1358 This call creates a file called C<path>.  The contents of the
1359 file is the string C<content> (which can contain any 8 bit data),
1360 with length C<size>.
1361
1362 As a special case, if C<size> is C<0>
1363 then the length is calculated using C<strlen> (so in this case
1364 the content cannot contain embedded ASCII NULs).
1365
1366 I<NB.> Owing to a bug, writing content containing ASCII NUL
1367 characters does I<not> work, even if the length is specified.
1368 We hope to resolve this bug in a future version.  In the meantime
1369 use C<guestfs_upload>.");
1370
1371   ("umount", (RErr, [String "pathordevice"]), 45, [FishAlias "unmount"],
1372    [InitEmpty, Always, TestOutputListOfDevices (
1373       [["sfdiskM"; "/dev/sda"; ","];
1374        ["mkfs"; "ext2"; "/dev/sda1"];
1375        ["mount"; "/dev/sda1"; "/"];
1376        ["mounts"]], ["/dev/sda1"]);
1377     InitEmpty, Always, TestOutputList (
1378       [["sfdiskM"; "/dev/sda"; ","];
1379        ["mkfs"; "ext2"; "/dev/sda1"];
1380        ["mount"; "/dev/sda1"; "/"];
1381        ["umount"; "/"];
1382        ["mounts"]], [])],
1383    "unmount a filesystem",
1384    "\
1385 This unmounts the given filesystem.  The filesystem may be
1386 specified either by its mountpoint (path) or the device which
1387 contains the filesystem.");
1388
1389   ("mounts", (RStringList "devices", []), 46, [],
1390    [InitBasicFS, Always, TestOutputListOfDevices (
1391       [["mounts"]], ["/dev/sda1"])],
1392    "show mounted filesystems",
1393    "\
1394 This returns the list of currently mounted filesystems.  It returns
1395 the list of devices (eg. C</dev/sda1>, C</dev/VG/LV>).
1396
1397 Some internal mounts are not shown.
1398
1399 See also: C<guestfs_mountpoints>");
1400
1401   ("umount_all", (RErr, []), 47, [FishAlias "unmount-all"],
1402    [InitBasicFS, Always, TestOutputList (
1403       [["umount_all"];
1404        ["mounts"]], []);
1405     (* check that umount_all can unmount nested mounts correctly: *)
1406     InitEmpty, Always, TestOutputList (
1407       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1408        ["mkfs"; "ext2"; "/dev/sda1"];
1409        ["mkfs"; "ext2"; "/dev/sda2"];
1410        ["mkfs"; "ext2"; "/dev/sda3"];
1411        ["mount"; "/dev/sda1"; "/"];
1412        ["mkdir"; "/mp1"];
1413        ["mount"; "/dev/sda2"; "/mp1"];
1414        ["mkdir"; "/mp1/mp2"];
1415        ["mount"; "/dev/sda3"; "/mp1/mp2"];
1416        ["mkdir"; "/mp1/mp2/mp3"];
1417        ["umount_all"];
1418        ["mounts"]], [])],
1419    "unmount all filesystems",
1420    "\
1421 This unmounts all mounted filesystems.
1422
1423 Some internal mounts are not unmounted by this call.");
1424
1425   ("lvm_remove_all", (RErr, []), 48, [DangerWillRobinson],
1426    [],
1427    "remove all LVM LVs, VGs and PVs",
1428    "\
1429 This command removes all LVM logical volumes, volume groups
1430 and physical volumes.");
1431
1432   ("file", (RString "description", [String "path"]), 49, [],
1433    [InitSquashFS, Always, TestOutput (
1434       [["file"; "/empty"]], "empty");
1435     InitSquashFS, Always, TestOutput (
1436       [["file"; "/known-1"]], "ASCII text");
1437     InitSquashFS, Always, TestLastFail (
1438       [["file"; "/notexists"]])],
1439    "determine file type",
1440    "\
1441 This call uses the standard L<file(1)> command to determine
1442 the type or contents of the file.  This also works on devices,
1443 for example to find out whether a partition contains a filesystem.
1444
1445 This call will also transparently look inside various types
1446 of compressed file.
1447
1448 The exact command which runs is C<file -zbsL path>.  Note in
1449 particular that the filename is not prepended to the output
1450 (the C<-b> option).");
1451
1452   ("command", (RString "output", [StringList "arguments"]), 50, [ProtocolLimitWarning],
1453    [InitBasicFS, Always, TestOutput (
1454       [["upload"; "test-command"; "/test-command"];
1455        ["chmod"; "0o755"; "/test-command"];
1456        ["command"; "/test-command 1"]], "Result1");
1457     InitBasicFS, Always, TestOutput (
1458       [["upload"; "test-command"; "/test-command"];
1459        ["chmod"; "0o755"; "/test-command"];
1460        ["command"; "/test-command 2"]], "Result2\n");
1461     InitBasicFS, Always, TestOutput (
1462       [["upload"; "test-command"; "/test-command"];
1463        ["chmod"; "0o755"; "/test-command"];
1464        ["command"; "/test-command 3"]], "\nResult3");
1465     InitBasicFS, Always, TestOutput (
1466       [["upload"; "test-command"; "/test-command"];
1467        ["chmod"; "0o755"; "/test-command"];
1468        ["command"; "/test-command 4"]], "\nResult4\n");
1469     InitBasicFS, Always, TestOutput (
1470       [["upload"; "test-command"; "/test-command"];
1471        ["chmod"; "0o755"; "/test-command"];
1472        ["command"; "/test-command 5"]], "\nResult5\n\n");
1473     InitBasicFS, Always, TestOutput (
1474       [["upload"; "test-command"; "/test-command"];
1475        ["chmod"; "0o755"; "/test-command"];
1476        ["command"; "/test-command 6"]], "\n\nResult6\n\n");
1477     InitBasicFS, Always, TestOutput (
1478       [["upload"; "test-command"; "/test-command"];
1479        ["chmod"; "0o755"; "/test-command"];
1480        ["command"; "/test-command 7"]], "");
1481     InitBasicFS, Always, TestOutput (
1482       [["upload"; "test-command"; "/test-command"];
1483        ["chmod"; "0o755"; "/test-command"];
1484        ["command"; "/test-command 8"]], "\n");
1485     InitBasicFS, Always, TestOutput (
1486       [["upload"; "test-command"; "/test-command"];
1487        ["chmod"; "0o755"; "/test-command"];
1488        ["command"; "/test-command 9"]], "\n\n");
1489     InitBasicFS, Always, TestOutput (
1490       [["upload"; "test-command"; "/test-command"];
1491        ["chmod"; "0o755"; "/test-command"];
1492        ["command"; "/test-command 10"]], "Result10-1\nResult10-2\n");
1493     InitBasicFS, Always, TestOutput (
1494       [["upload"; "test-command"; "/test-command"];
1495        ["chmod"; "0o755"; "/test-command"];
1496        ["command"; "/test-command 11"]], "Result11-1\nResult11-2");
1497     InitBasicFS, Always, TestLastFail (
1498       [["upload"; "test-command"; "/test-command"];
1499        ["chmod"; "0o755"; "/test-command"];
1500        ["command"; "/test-command"]])],
1501    "run a command from the guest filesystem",
1502    "\
1503 This call runs a command from the guest filesystem.  The
1504 filesystem must be mounted, and must contain a compatible
1505 operating system (ie. something Linux, with the same
1506 or compatible processor architecture).
1507
1508 The single parameter is an argv-style list of arguments.
1509 The first element is the name of the program to run.
1510 Subsequent elements are parameters.  The list must be
1511 non-empty (ie. must contain a program name).  Note that
1512 the command runs directly, and is I<not> invoked via
1513 the shell (see C<guestfs_sh>).
1514
1515 The return value is anything printed to I<stdout> by
1516 the command.
1517
1518 If the command returns a non-zero exit status, then
1519 this function returns an error message.  The error message
1520 string is the content of I<stderr> from the command.
1521
1522 The C<$PATH> environment variable will contain at least
1523 C</usr/bin> and C</bin>.  If you require a program from
1524 another location, you should provide the full path in the
1525 first parameter.
1526
1527 Shared libraries and data files required by the program
1528 must be available on filesystems which are mounted in the
1529 correct places.  It is the caller's responsibility to ensure
1530 all filesystems that are needed are mounted at the right
1531 locations.");
1532
1533   ("command_lines", (RStringList "lines", [StringList "arguments"]), 51, [ProtocolLimitWarning],
1534    [InitBasicFS, Always, TestOutputList (
1535       [["upload"; "test-command"; "/test-command"];
1536        ["chmod"; "0o755"; "/test-command"];
1537        ["command_lines"; "/test-command 1"]], ["Result1"]);
1538     InitBasicFS, Always, TestOutputList (
1539       [["upload"; "test-command"; "/test-command"];
1540        ["chmod"; "0o755"; "/test-command"];
1541        ["command_lines"; "/test-command 2"]], ["Result2"]);
1542     InitBasicFS, Always, TestOutputList (
1543       [["upload"; "test-command"; "/test-command"];
1544        ["chmod"; "0o755"; "/test-command"];
1545        ["command_lines"; "/test-command 3"]], ["";"Result3"]);
1546     InitBasicFS, Always, TestOutputList (
1547       [["upload"; "test-command"; "/test-command"];
1548        ["chmod"; "0o755"; "/test-command"];
1549        ["command_lines"; "/test-command 4"]], ["";"Result4"]);
1550     InitBasicFS, Always, TestOutputList (
1551       [["upload"; "test-command"; "/test-command"];
1552        ["chmod"; "0o755"; "/test-command"];
1553        ["command_lines"; "/test-command 5"]], ["";"Result5";""]);
1554     InitBasicFS, Always, TestOutputList (
1555       [["upload"; "test-command"; "/test-command"];
1556        ["chmod"; "0o755"; "/test-command"];
1557        ["command_lines"; "/test-command 6"]], ["";"";"Result6";""]);
1558     InitBasicFS, Always, TestOutputList (
1559       [["upload"; "test-command"; "/test-command"];
1560        ["chmod"; "0o755"; "/test-command"];
1561        ["command_lines"; "/test-command 7"]], []);
1562     InitBasicFS, Always, TestOutputList (
1563       [["upload"; "test-command"; "/test-command"];
1564        ["chmod"; "0o755"; "/test-command"];
1565        ["command_lines"; "/test-command 8"]], [""]);
1566     InitBasicFS, Always, TestOutputList (
1567       [["upload"; "test-command"; "/test-command"];
1568        ["chmod"; "0o755"; "/test-command"];
1569        ["command_lines"; "/test-command 9"]], ["";""]);
1570     InitBasicFS, Always, TestOutputList (
1571       [["upload"; "test-command"; "/test-command"];
1572        ["chmod"; "0o755"; "/test-command"];
1573        ["command_lines"; "/test-command 10"]], ["Result10-1";"Result10-2"]);
1574     InitBasicFS, Always, TestOutputList (
1575       [["upload"; "test-command"; "/test-command"];
1576        ["chmod"; "0o755"; "/test-command"];
1577        ["command_lines"; "/test-command 11"]], ["Result11-1";"Result11-2"])],
1578    "run a command, returning lines",
1579    "\
1580 This is the same as C<guestfs_command>, but splits the
1581 result into a list of lines.
1582
1583 See also: C<guestfs_sh_lines>");
1584
1585   ("stat", (RStruct ("statbuf", "stat"), [String "path"]), 52, [],
1586    [InitSquashFS, Always, TestOutputStruct (
1587       [["stat"; "/empty"]], [CompareWithInt ("size", 0)])],
1588    "get file information",
1589    "\
1590 Returns file information for the given C<path>.
1591
1592 This is the same as the C<stat(2)> system call.");
1593
1594   ("lstat", (RStruct ("statbuf", "stat"), [String "path"]), 53, [],
1595    [InitSquashFS, Always, TestOutputStruct (
1596       [["lstat"; "/empty"]], [CompareWithInt ("size", 0)])],
1597    "get file information for a symbolic link",
1598    "\
1599 Returns file information for the given C<path>.
1600
1601 This is the same as C<guestfs_stat> except that if C<path>
1602 is a symbolic link, then the link is stat-ed, not the file it
1603 refers to.
1604
1605 This is the same as the C<lstat(2)> system call.");
1606
1607   ("statvfs", (RStruct ("statbuf", "statvfs"), [String "path"]), 54, [],
1608    [InitSquashFS, Always, TestOutputStruct (
1609       [["statvfs"; "/"]], [CompareWithInt ("namemax", 256);
1610                            CompareWithInt ("bsize", 131072)])],
1611    "get file system statistics",
1612    "\
1613 Returns file system statistics for any mounted file system.
1614 C<path> should be a file or directory in the mounted file system
1615 (typically it is the mount point itself, but it doesn't need to be).
1616
1617 This is the same as the C<statvfs(2)> system call.");
1618
1619   ("tune2fs_l", (RHashtable "superblock", [String "device"]), 55, [],
1620    [], (* XXX test *)
1621    "get ext2/ext3/ext4 superblock details",
1622    "\
1623 This returns the contents of the ext2, ext3 or ext4 filesystem
1624 superblock on C<device>.
1625
1626 It is the same as running C<tune2fs -l device>.  See L<tune2fs(8)>
1627 manpage for more details.  The list of fields returned isn't
1628 clearly defined, and depends on both the version of C<tune2fs>
1629 that libguestfs was built against, and the filesystem itself.");
1630
1631   ("blockdev_setro", (RErr, [String "device"]), 56, [],
1632    [InitEmpty, Always, TestOutputTrue (
1633       [["blockdev_setro"; "/dev/sda"];
1634        ["blockdev_getro"; "/dev/sda"]])],
1635    "set block device to read-only",
1636    "\
1637 Sets the block device named C<device> to read-only.
1638
1639 This uses the L<blockdev(8)> command.");
1640
1641   ("blockdev_setrw", (RErr, [String "device"]), 57, [],
1642    [InitEmpty, Always, TestOutputFalse (
1643       [["blockdev_setrw"; "/dev/sda"];
1644        ["blockdev_getro"; "/dev/sda"]])],
1645    "set block device to read-write",
1646    "\
1647 Sets the block device named C<device> to read-write.
1648
1649 This uses the L<blockdev(8)> command.");
1650
1651   ("blockdev_getro", (RBool "ro", [String "device"]), 58, [],
1652    [InitEmpty, Always, TestOutputTrue (
1653       [["blockdev_setro"; "/dev/sda"];
1654        ["blockdev_getro"; "/dev/sda"]])],
1655    "is block device set to read-only",
1656    "\
1657 Returns a boolean indicating if the block device is read-only
1658 (true if read-only, false if not).
1659
1660 This uses the L<blockdev(8)> command.");
1661
1662   ("blockdev_getss", (RInt "sectorsize", [String "device"]), 59, [],
1663    [InitEmpty, Always, TestOutputInt (
1664       [["blockdev_getss"; "/dev/sda"]], 512)],
1665    "get sectorsize of block device",
1666    "\
1667 This returns the size of sectors on a block device.
1668 Usually 512, but can be larger for modern devices.
1669
1670 (Note, this is not the size in sectors, use C<guestfs_blockdev_getsz>
1671 for that).
1672
1673 This uses the L<blockdev(8)> command.");
1674
1675   ("blockdev_getbsz", (RInt "blocksize", [String "device"]), 60, [],
1676    [InitEmpty, Always, TestOutputInt (
1677       [["blockdev_getbsz"; "/dev/sda"]], 4096)],
1678    "get blocksize of block device",
1679    "\
1680 This returns the block size of a device.
1681
1682 (Note this is different from both I<size in blocks> and
1683 I<filesystem block size>).
1684
1685 This uses the L<blockdev(8)> command.");
1686
1687   ("blockdev_setbsz", (RErr, [String "device"; Int "blocksize"]), 61, [],
1688    [], (* XXX test *)
1689    "set blocksize of block device",
1690    "\
1691 This sets the block size of a device.
1692
1693 (Note this is different from both I<size in blocks> and
1694 I<filesystem block size>).
1695
1696 This uses the L<blockdev(8)> command.");
1697
1698   ("blockdev_getsz", (RInt64 "sizeinsectors", [String "device"]), 62, [],
1699    [InitEmpty, Always, TestOutputInt (
1700       [["blockdev_getsz"; "/dev/sda"]], 1024000)],
1701    "get total size of device in 512-byte sectors",
1702    "\
1703 This returns the size of the device in units of 512-byte sectors
1704 (even if the sectorsize isn't 512 bytes ... weird).
1705
1706 See also C<guestfs_blockdev_getss> for the real sector size of
1707 the device, and C<guestfs_blockdev_getsize64> for the more
1708 useful I<size in bytes>.
1709
1710 This uses the L<blockdev(8)> command.");
1711
1712   ("blockdev_getsize64", (RInt64 "sizeinbytes", [String "device"]), 63, [],
1713    [InitEmpty, Always, TestOutputInt (
1714       [["blockdev_getsize64"; "/dev/sda"]], 524288000)],
1715    "get total size of device in bytes",
1716    "\
1717 This returns the size of the device in bytes.
1718
1719 See also C<guestfs_blockdev_getsz>.
1720
1721 This uses the L<blockdev(8)> command.");
1722
1723   ("blockdev_flushbufs", (RErr, [String "device"]), 64, [],
1724    [InitEmpty, Always, TestRun
1725       [["blockdev_flushbufs"; "/dev/sda"]]],
1726    "flush device buffers",
1727    "\
1728 This tells the kernel to flush internal buffers associated
1729 with C<device>.
1730
1731 This uses the L<blockdev(8)> command.");
1732
1733   ("blockdev_rereadpt", (RErr, [String "device"]), 65, [],
1734    [InitEmpty, Always, TestRun
1735       [["blockdev_rereadpt"; "/dev/sda"]]],
1736    "reread partition table",
1737    "\
1738 Reread the partition table on C<device>.
1739
1740 This uses the L<blockdev(8)> command.");
1741
1742   ("upload", (RErr, [FileIn "filename"; String "remotefilename"]), 66, [],
1743    [InitBasicFS, Always, TestOutput (
1744       (* Pick a file from cwd which isn't likely to change. *)
1745       [["upload"; "../COPYING.LIB"; "/COPYING.LIB"];
1746        ["checksum"; "md5"; "/COPYING.LIB"]], "e3eda01d9815f8d24aae2dbd89b68b06")],
1747    "upload a file from the local machine",
1748    "\
1749 Upload local file C<filename> to C<remotefilename> on the
1750 filesystem.
1751
1752 C<filename> can also be a named pipe.
1753
1754 See also C<guestfs_download>.");
1755
1756   ("download", (RErr, [String "remotefilename"; FileOut "filename"]), 67, [],
1757    [InitBasicFS, Always, TestOutput (
1758       (* Pick a file from cwd which isn't likely to change. *)
1759       [["upload"; "../COPYING.LIB"; "/COPYING.LIB"];
1760        ["download"; "/COPYING.LIB"; "testdownload.tmp"];
1761        ["upload"; "testdownload.tmp"; "/upload"];
1762        ["checksum"; "md5"; "/upload"]], "e3eda01d9815f8d24aae2dbd89b68b06")],
1763    "download a file to the local machine",
1764    "\
1765 Download file C<remotefilename> and save it as C<filename>
1766 on the local machine.
1767
1768 C<filename> can also be a named pipe.
1769
1770 See also C<guestfs_upload>, C<guestfs_cat>.");
1771
1772   ("checksum", (RString "checksum", [String "csumtype"; String "path"]), 68, [],
1773    [InitSquashFS, Always, TestOutput (
1774       [["checksum"; "crc"; "/known-3"]], "2891671662");
1775     InitSquashFS, Always, TestLastFail (
1776       [["checksum"; "crc"; "/notexists"]]);
1777     InitSquashFS, Always, TestOutput (
1778       [["checksum"; "md5"; "/known-3"]], "46d6ca27ee07cdc6fa99c2e138cc522c");
1779     InitSquashFS, Always, TestOutput (
1780       [["checksum"; "sha1"; "/known-3"]], "b7ebccc3ee418311091c3eda0a45b83c0a770f15");
1781     InitSquashFS, Always, TestOutput (
1782       [["checksum"; "sha224"; "/known-3"]], "d2cd1774b28f3659c14116be0a6dc2bb5c4b350ce9cd5defac707741");
1783     InitSquashFS, Always, TestOutput (
1784       [["checksum"; "sha256"; "/known-3"]], "75bb71b90cd20cb13f86d2bea8dad63ac7194e7517c3b52b8d06ff52d3487d30");
1785     InitSquashFS, Always, TestOutput (
1786       [["checksum"; "sha384"; "/known-3"]], "5fa7883430f357b5d7b7271d3a1d2872b51d73cba72731de6863d3dea55f30646af2799bef44d5ea776a5ec7941ac640");
1787     InitSquashFS, Always, TestOutput (
1788       [["checksum"; "sha512"; "/known-3"]], "2794062c328c6b216dca90443b7f7134c5f40e56bd0ed7853123275a09982a6f992e6ca682f9d2fba34a4c5e870d8fe077694ff831e3032a004ee077e00603f6")],
1789    "compute MD5, SHAx or CRC checksum of file",
1790    "\
1791 This call computes the MD5, SHAx or CRC checksum of the
1792 file named C<path>.
1793
1794 The type of checksum to compute is given by the C<csumtype>
1795 parameter which must have one of the following values:
1796
1797 =over 4
1798
1799 =item C<crc>
1800
1801 Compute the cyclic redundancy check (CRC) specified by POSIX
1802 for the C<cksum> command.
1803
1804 =item C<md5>
1805
1806 Compute the MD5 hash (using the C<md5sum> program).
1807
1808 =item C<sha1>
1809
1810 Compute the SHA1 hash (using the C<sha1sum> program).
1811
1812 =item C<sha224>
1813
1814 Compute the SHA224 hash (using the C<sha224sum> program).
1815
1816 =item C<sha256>
1817
1818 Compute the SHA256 hash (using the C<sha256sum> program).
1819
1820 =item C<sha384>
1821
1822 Compute the SHA384 hash (using the C<sha384sum> program).
1823
1824 =item C<sha512>
1825
1826 Compute the SHA512 hash (using the C<sha512sum> program).
1827
1828 =back
1829
1830 The checksum is returned as a printable string.");
1831
1832   ("tar_in", (RErr, [FileIn "tarfile"; String "directory"]), 69, [],
1833    [InitBasicFS, Always, TestOutput (
1834       [["tar_in"; "../images/helloworld.tar"; "/"];
1835        ["cat"; "/hello"]], "hello\n")],
1836    "unpack tarfile to directory",
1837    "\
1838 This command uploads and unpacks local file C<tarfile> (an
1839 I<uncompressed> tar file) into C<directory>.
1840
1841 To upload a compressed tarball, use C<guestfs_tgz_in>.");
1842
1843   ("tar_out", (RErr, [String "directory"; FileOut "tarfile"]), 70, [],
1844    [],
1845    "pack directory into tarfile",
1846    "\
1847 This command packs the contents of C<directory> and downloads
1848 it to local file C<tarfile>.
1849
1850 To download a compressed tarball, use C<guestfs_tgz_out>.");
1851
1852   ("tgz_in", (RErr, [FileIn "tarball"; String "directory"]), 71, [],
1853    [InitBasicFS, Always, TestOutput (
1854       [["tgz_in"; "../images/helloworld.tar.gz"; "/"];
1855        ["cat"; "/hello"]], "hello\n")],
1856    "unpack compressed tarball to directory",
1857    "\
1858 This command uploads and unpacks local file C<tarball> (a
1859 I<gzip compressed> tar file) into C<directory>.
1860
1861 To upload an uncompressed tarball, use C<guestfs_tar_in>.");
1862
1863   ("tgz_out", (RErr, [String "directory"; FileOut "tarball"]), 72, [],
1864    [],
1865    "pack directory into compressed tarball",
1866    "\
1867 This command packs the contents of C<directory> and downloads
1868 it to local file C<tarball>.
1869
1870 To download an uncompressed tarball, use C<guestfs_tar_out>.");
1871
1872   ("mount_ro", (RErr, [String "device"; String "mountpoint"]), 73, [],
1873    [InitBasicFS, Always, TestLastFail (
1874       [["umount"; "/"];
1875        ["mount_ro"; "/dev/sda1"; "/"];
1876        ["touch"; "/new"]]);
1877     InitBasicFS, Always, TestOutput (
1878       [["write_file"; "/new"; "data"; "0"];
1879        ["umount"; "/"];
1880        ["mount_ro"; "/dev/sda1"; "/"];
1881        ["cat"; "/new"]], "data")],
1882    "mount a guest disk, read-only",
1883    "\
1884 This is the same as the C<guestfs_mount> command, but it
1885 mounts the filesystem with the read-only (I<-o ro>) flag.");
1886
1887   ("mount_options", (RErr, [String "options"; String "device"; String "mountpoint"]), 74, [],
1888    [],
1889    "mount a guest disk with mount options",
1890    "\
1891 This is the same as the C<guestfs_mount> command, but it
1892 allows you to set the mount options as for the
1893 L<mount(8)> I<-o> flag.");
1894
1895   ("mount_vfs", (RErr, [String "options"; String "vfstype"; String "device"; String "mountpoint"]), 75, [],
1896    [],
1897    "mount a guest disk with mount options and vfstype",
1898    "\
1899 This is the same as the C<guestfs_mount> command, but it
1900 allows you to set both the mount options and the vfstype
1901 as for the L<mount(8)> I<-o> and I<-t> flags.");
1902
1903   ("debug", (RString "result", [String "subcmd"; StringList "extraargs"]), 76, [],
1904    [],
1905    "debugging and internals",
1906    "\
1907 The C<guestfs_debug> command exposes some internals of
1908 C<guestfsd> (the guestfs daemon) that runs inside the
1909 qemu subprocess.
1910
1911 There is no comprehensive help for this command.  You have
1912 to look at the file C<daemon/debug.c> in the libguestfs source
1913 to find out what you can do.");
1914
1915   ("lvremove", (RErr, [String "device"]), 77, [],
1916    [InitEmpty, Always, TestOutputList (
1917       [["sfdiskM"; "/dev/sda"; ","];
1918        ["pvcreate"; "/dev/sda1"];
1919        ["vgcreate"; "VG"; "/dev/sda1"];
1920        ["lvcreate"; "LV1"; "VG"; "50"];
1921        ["lvcreate"; "LV2"; "VG"; "50"];
1922        ["lvremove"; "/dev/VG/LV1"];
1923        ["lvs"]], ["/dev/VG/LV2"]);
1924     InitEmpty, Always, TestOutputList (
1925       [["sfdiskM"; "/dev/sda"; ","];
1926        ["pvcreate"; "/dev/sda1"];
1927        ["vgcreate"; "VG"; "/dev/sda1"];
1928        ["lvcreate"; "LV1"; "VG"; "50"];
1929        ["lvcreate"; "LV2"; "VG"; "50"];
1930        ["lvremove"; "/dev/VG"];
1931        ["lvs"]], []);
1932     InitEmpty, Always, TestOutputList (
1933       [["sfdiskM"; "/dev/sda"; ","];
1934        ["pvcreate"; "/dev/sda1"];
1935        ["vgcreate"; "VG"; "/dev/sda1"];
1936        ["lvcreate"; "LV1"; "VG"; "50"];
1937        ["lvcreate"; "LV2"; "VG"; "50"];
1938        ["lvremove"; "/dev/VG"];
1939        ["vgs"]], ["VG"])],
1940    "remove an LVM logical volume",
1941    "\
1942 Remove an LVM logical volume C<device>, where C<device> is
1943 the path to the LV, such as C</dev/VG/LV>.
1944
1945 You can also remove all LVs in a volume group by specifying
1946 the VG name, C</dev/VG>.");
1947
1948   ("vgremove", (RErr, [String "vgname"]), 78, [],
1949    [InitEmpty, Always, TestOutputList (
1950       [["sfdiskM"; "/dev/sda"; ","];
1951        ["pvcreate"; "/dev/sda1"];
1952        ["vgcreate"; "VG"; "/dev/sda1"];
1953        ["lvcreate"; "LV1"; "VG"; "50"];
1954        ["lvcreate"; "LV2"; "VG"; "50"];
1955        ["vgremove"; "VG"];
1956        ["lvs"]], []);
1957     InitEmpty, Always, TestOutputList (
1958       [["sfdiskM"; "/dev/sda"; ","];
1959        ["pvcreate"; "/dev/sda1"];
1960        ["vgcreate"; "VG"; "/dev/sda1"];
1961        ["lvcreate"; "LV1"; "VG"; "50"];
1962        ["lvcreate"; "LV2"; "VG"; "50"];
1963        ["vgremove"; "VG"];
1964        ["vgs"]], [])],
1965    "remove an LVM volume group",
1966    "\
1967 Remove an LVM volume group C<vgname>, (for example C<VG>).
1968
1969 This also forcibly removes all logical volumes in the volume
1970 group (if any).");
1971
1972   ("pvremove", (RErr, [String "device"]), 79, [],
1973    [InitEmpty, Always, TestOutputListOfDevices (
1974       [["sfdiskM"; "/dev/sda"; ","];
1975        ["pvcreate"; "/dev/sda1"];
1976        ["vgcreate"; "VG"; "/dev/sda1"];
1977        ["lvcreate"; "LV1"; "VG"; "50"];
1978        ["lvcreate"; "LV2"; "VG"; "50"];
1979        ["vgremove"; "VG"];
1980        ["pvremove"; "/dev/sda1"];
1981        ["lvs"]], []);
1982     InitEmpty, Always, TestOutputListOfDevices (
1983       [["sfdiskM"; "/dev/sda"; ","];
1984        ["pvcreate"; "/dev/sda1"];
1985        ["vgcreate"; "VG"; "/dev/sda1"];
1986        ["lvcreate"; "LV1"; "VG"; "50"];
1987        ["lvcreate"; "LV2"; "VG"; "50"];
1988        ["vgremove"; "VG"];
1989        ["pvremove"; "/dev/sda1"];
1990        ["vgs"]], []);
1991     InitEmpty, Always, TestOutputListOfDevices (
1992       [["sfdiskM"; "/dev/sda"; ","];
1993        ["pvcreate"; "/dev/sda1"];
1994        ["vgcreate"; "VG"; "/dev/sda1"];
1995        ["lvcreate"; "LV1"; "VG"; "50"];
1996        ["lvcreate"; "LV2"; "VG"; "50"];
1997        ["vgremove"; "VG"];
1998        ["pvremove"; "/dev/sda1"];
1999        ["pvs"]], [])],
2000    "remove an LVM physical volume",
2001    "\
2002 This wipes a physical volume C<device> so that LVM will no longer
2003 recognise it.
2004
2005 The implementation uses the C<pvremove> command which refuses to
2006 wipe physical volumes that contain any volume groups, so you have
2007 to remove those first.");
2008
2009   ("set_e2label", (RErr, [String "device"; String "label"]), 80, [],
2010    [InitBasicFS, Always, TestOutput (
2011       [["set_e2label"; "/dev/sda1"; "testlabel"];
2012        ["get_e2label"; "/dev/sda1"]], "testlabel")],
2013    "set the ext2/3/4 filesystem label",
2014    "\
2015 This sets the ext2/3/4 filesystem label of the filesystem on
2016 C<device> to C<label>.  Filesystem labels are limited to
2017 16 characters.
2018
2019 You can use either C<guestfs_tune2fs_l> or C<guestfs_get_e2label>
2020 to return the existing label on a filesystem.");
2021
2022   ("get_e2label", (RString "label", [String "device"]), 81, [],
2023    [],
2024    "get the ext2/3/4 filesystem label",
2025    "\
2026 This returns the ext2/3/4 filesystem label of the filesystem on
2027 C<device>.");
2028
2029   ("set_e2uuid", (RErr, [String "device"; String "uuid"]), 82, [],
2030    [InitBasicFS, Always, TestOutput (
2031       [["set_e2uuid"; "/dev/sda1"; "a3a61220-882b-4f61-89f4-cf24dcc7297d"];
2032        ["get_e2uuid"; "/dev/sda1"]], "a3a61220-882b-4f61-89f4-cf24dcc7297d");
2033     InitBasicFS, Always, TestOutput (
2034       [["set_e2uuid"; "/dev/sda1"; "clear"];
2035        ["get_e2uuid"; "/dev/sda1"]], "");
2036     (* We can't predict what UUIDs will be, so just check the commands run. *)
2037     InitBasicFS, Always, TestRun (
2038       [["set_e2uuid"; "/dev/sda1"; "random"]]);
2039     InitBasicFS, Always, TestRun (
2040       [["set_e2uuid"; "/dev/sda1"; "time"]])],
2041    "set the ext2/3/4 filesystem UUID",
2042    "\
2043 This sets the ext2/3/4 filesystem UUID of the filesystem on
2044 C<device> to C<uuid>.  The format of the UUID and alternatives
2045 such as C<clear>, C<random> and C<time> are described in the
2046 L<tune2fs(8)> manpage.
2047
2048 You can use either C<guestfs_tune2fs_l> or C<guestfs_get_e2uuid>
2049 to return the existing UUID of a filesystem.");
2050
2051   ("get_e2uuid", (RString "uuid", [String "device"]), 83, [],
2052    [],
2053    "get the ext2/3/4 filesystem UUID",
2054    "\
2055 This returns the ext2/3/4 filesystem UUID of the filesystem on
2056 C<device>.");
2057
2058   ("fsck", (RInt "status", [String "fstype"; String "device"]), 84, [],
2059    [InitBasicFS, Always, TestOutputInt (
2060       [["umount"; "/dev/sda1"];
2061        ["fsck"; "ext2"; "/dev/sda1"]], 0);
2062     InitBasicFS, Always, TestOutputInt (
2063       [["umount"; "/dev/sda1"];
2064        ["zero"; "/dev/sda1"];
2065        ["fsck"; "ext2"; "/dev/sda1"]], 8)],
2066    "run the filesystem checker",
2067    "\
2068 This runs the filesystem checker (fsck) on C<device> which
2069 should have filesystem type C<fstype>.
2070
2071 The returned integer is the status.  See L<fsck(8)> for the
2072 list of status codes from C<fsck>.
2073
2074 Notes:
2075
2076 =over 4
2077
2078 =item *
2079
2080 Multiple status codes can be summed together.
2081
2082 =item *
2083
2084 A non-zero return code can mean \"success\", for example if
2085 errors have been corrected on the filesystem.
2086
2087 =item *
2088
2089 Checking or repairing NTFS volumes is not supported
2090 (by linux-ntfs).
2091
2092 =back
2093
2094 This command is entirely equivalent to running C<fsck -a -t fstype device>.");
2095
2096   ("zero", (RErr, [String "device"]), 85, [],
2097    [InitBasicFS, Always, TestOutput (
2098       [["umount"; "/dev/sda1"];
2099        ["zero"; "/dev/sda1"];
2100        ["file"; "/dev/sda1"]], "data")],
2101    "write zeroes to the device",
2102    "\
2103 This command writes zeroes over the first few blocks of C<device>.
2104
2105 How many blocks are zeroed isn't specified (but it's I<not> enough
2106 to securely wipe the device).  It should be sufficient to remove
2107 any partition tables, filesystem superblocks and so on.
2108
2109 See also: C<guestfs_scrub_device>.");
2110
2111   ("grub_install", (RErr, [String "root"; String "device"]), 86, [],
2112    (* Test disabled because grub-install incompatible with virtio-blk driver.
2113     * See also: https://bugzilla.redhat.com/show_bug.cgi?id=479760
2114     *)
2115    [InitBasicFS, Disabled, TestOutputTrue (
2116       [["grub_install"; "/"; "/dev/sda1"];
2117        ["is_dir"; "/boot"]])],
2118    "install GRUB",
2119    "\
2120 This command installs GRUB (the Grand Unified Bootloader) on
2121 C<device>, with the root directory being C<root>.");
2122
2123   ("cp", (RErr, [String "src"; String "dest"]), 87, [],
2124    [InitBasicFS, Always, TestOutput (
2125       [["write_file"; "/old"; "file content"; "0"];
2126        ["cp"; "/old"; "/new"];
2127        ["cat"; "/new"]], "file content");
2128     InitBasicFS, Always, TestOutputTrue (
2129       [["write_file"; "/old"; "file content"; "0"];
2130        ["cp"; "/old"; "/new"];
2131        ["is_file"; "/old"]]);
2132     InitBasicFS, Always, TestOutput (
2133       [["write_file"; "/old"; "file content"; "0"];
2134        ["mkdir"; "/dir"];
2135        ["cp"; "/old"; "/dir/new"];
2136        ["cat"; "/dir/new"]], "file content")],
2137    "copy a file",
2138    "\
2139 This copies a file from C<src> to C<dest> where C<dest> is
2140 either a destination filename or destination directory.");
2141
2142   ("cp_a", (RErr, [String "src"; String "dest"]), 88, [],
2143    [InitBasicFS, Always, TestOutput (
2144       [["mkdir"; "/olddir"];
2145        ["mkdir"; "/newdir"];
2146        ["write_file"; "/olddir/file"; "file content"; "0"];
2147        ["cp_a"; "/olddir"; "/newdir"];
2148        ["cat"; "/newdir/olddir/file"]], "file content")],
2149    "copy a file or directory recursively",
2150    "\
2151 This copies a file or directory from C<src> to C<dest>
2152 recursively using the C<cp -a> command.");
2153
2154   ("mv", (RErr, [String "src"; String "dest"]), 89, [],
2155    [InitBasicFS, Always, TestOutput (
2156       [["write_file"; "/old"; "file content"; "0"];
2157        ["mv"; "/old"; "/new"];
2158        ["cat"; "/new"]], "file content");
2159     InitBasicFS, Always, TestOutputFalse (
2160       [["write_file"; "/old"; "file content"; "0"];
2161        ["mv"; "/old"; "/new"];
2162        ["is_file"; "/old"]])],
2163    "move a file",
2164    "\
2165 This moves a file from C<src> to C<dest> where C<dest> is
2166 either a destination filename or destination directory.");
2167
2168   ("drop_caches", (RErr, [Int "whattodrop"]), 90, [],
2169    [InitEmpty, Always, TestRun (
2170       [["drop_caches"; "3"]])],
2171    "drop kernel page cache, dentries and inodes",
2172    "\
2173 This instructs the guest kernel to drop its page cache,
2174 and/or dentries and inode caches.  The parameter C<whattodrop>
2175 tells the kernel what precisely to drop, see
2176 L<http://linux-mm.org/Drop_Caches>
2177
2178 Setting C<whattodrop> to 3 should drop everything.
2179
2180 This automatically calls L<sync(2)> before the operation,
2181 so that the maximum guest memory is freed.");
2182
2183   ("dmesg", (RString "kmsgs", []), 91, [],
2184    [InitEmpty, Always, TestRun (
2185       [["dmesg"]])],
2186    "return kernel messages",
2187    "\
2188 This returns the kernel messages (C<dmesg> output) from
2189 the guest kernel.  This is sometimes useful for extended
2190 debugging of problems.
2191
2192 Another way to get the same information is to enable
2193 verbose messages with C<guestfs_set_verbose> or by setting
2194 the environment variable C<LIBGUESTFS_DEBUG=1> before
2195 running the program.");
2196
2197   ("ping_daemon", (RErr, []), 92, [],
2198    [InitEmpty, Always, TestRun (
2199       [["ping_daemon"]])],
2200    "ping the guest daemon",
2201    "\
2202 This is a test probe into the guestfs daemon running inside
2203 the qemu subprocess.  Calling this function checks that the
2204 daemon responds to the ping message, without affecting the daemon
2205 or attached block device(s) in any other way.");
2206
2207   ("equal", (RBool "equality", [String "file1"; String "file2"]), 93, [],
2208    [InitBasicFS, Always, TestOutputTrue (
2209       [["write_file"; "/file1"; "contents of a file"; "0"];
2210        ["cp"; "/file1"; "/file2"];
2211        ["equal"; "/file1"; "/file2"]]);
2212     InitBasicFS, Always, TestOutputFalse (
2213       [["write_file"; "/file1"; "contents of a file"; "0"];
2214        ["write_file"; "/file2"; "contents of another file"; "0"];
2215        ["equal"; "/file1"; "/file2"]]);
2216     InitBasicFS, Always, TestLastFail (
2217       [["equal"; "/file1"; "/file2"]])],
2218    "test if two files have equal contents",
2219    "\
2220 This compares the two files C<file1> and C<file2> and returns
2221 true if their content is exactly equal, or false otherwise.
2222
2223 The external L<cmp(1)> program is used for the comparison.");
2224
2225   ("strings", (RStringList "stringsout", [String "path"]), 94, [ProtocolLimitWarning],
2226    [InitSquashFS, Always, TestOutputList (
2227       [["strings"; "/known-5"]], ["abcdefghi"; "jklmnopqr"]);
2228     InitSquashFS, Always, TestOutputList (
2229       [["strings"; "/empty"]], [])],
2230    "print the printable strings in a file",
2231    "\
2232 This runs the L<strings(1)> command on a file and returns
2233 the list of printable strings found.");
2234
2235   ("strings_e", (RStringList "stringsout", [String "encoding"; String "path"]), 95, [ProtocolLimitWarning],
2236    [InitSquashFS, Always, TestOutputList (
2237       [["strings_e"; "b"; "/known-5"]], []);
2238     InitBasicFS, Disabled, TestOutputList (
2239       [["write_file"; "/new"; "\000h\000e\000l\000l\000o\000\n\000w\000o\000r\000l\000d\000\n"; "24"];
2240        ["strings_e"; "b"; "/new"]], ["hello"; "world"])],
2241    "print the printable strings in a file",
2242    "\
2243 This is like the C<guestfs_strings> command, but allows you to
2244 specify the encoding.
2245
2246 See the L<strings(1)> manpage for the full list of encodings.
2247
2248 Commonly useful encodings are C<l> (lower case L) which will
2249 show strings inside Windows/x86 files.
2250
2251 The returned strings are transcoded to UTF-8.");
2252
2253   ("hexdump", (RString "dump", [String "path"]), 96, [ProtocolLimitWarning],
2254    [InitSquashFS, Always, TestOutput (
2255       [["hexdump"; "/known-4"]], "00000000  61 62 63 0a 64 65 66 0a  67 68 69                 |abc.def.ghi|\n0000000b\n");
2256     (* Test for RHBZ#501888c2 regression which caused large hexdump
2257      * commands to segfault.
2258      *)
2259     InitSquashFS, Always, TestRun (
2260       [["hexdump"; "/100krandom"]])],
2261    "dump a file in hexadecimal",
2262    "\
2263 This runs C<hexdump -C> on the given C<path>.  The result is
2264 the human-readable, canonical hex dump of the file.");
2265
2266   ("zerofree", (RErr, [String "device"]), 97, [],
2267    [InitNone, Always, TestOutput (
2268       [["sfdiskM"; "/dev/sda"; ","];
2269        ["mkfs"; "ext3"; "/dev/sda1"];
2270        ["mount"; "/dev/sda1"; "/"];
2271        ["write_file"; "/new"; "test file"; "0"];
2272        ["umount"; "/dev/sda1"];
2273        ["zerofree"; "/dev/sda1"];
2274        ["mount"; "/dev/sda1"; "/"];
2275        ["cat"; "/new"]], "test file")],
2276    "zero unused inodes and disk blocks on ext2/3 filesystem",
2277    "\
2278 This runs the I<zerofree> program on C<device>.  This program
2279 claims to zero unused inodes and disk blocks on an ext2/3
2280 filesystem, thus making it possible to compress the filesystem
2281 more effectively.
2282
2283 You should B<not> run this program if the filesystem is
2284 mounted.
2285
2286 It is possible that using this program can damage the filesystem
2287 or data on the filesystem.");
2288
2289   ("pvresize", (RErr, [String "device"]), 98, [],
2290    [],
2291    "resize an LVM physical volume",
2292    "\
2293 This resizes (expands or shrinks) an existing LVM physical
2294 volume to match the new size of the underlying device.");
2295
2296   ("sfdisk_N", (RErr, [String "device"; Int "partnum";
2297                        Int "cyls"; Int "heads"; Int "sectors";
2298                        String "line"]), 99, [DangerWillRobinson],
2299    [],
2300    "modify a single partition on a block device",
2301    "\
2302 This runs L<sfdisk(8)> option to modify just the single
2303 partition C<n> (note: C<n> counts from 1).
2304
2305 For other parameters, see C<guestfs_sfdisk>.  You should usually
2306 pass C<0> for the cyls/heads/sectors parameters.");
2307
2308   ("sfdisk_l", (RString "partitions", [String "device"]), 100, [],
2309    [],
2310    "display the partition table",
2311    "\
2312 This displays the partition table on C<device>, in the
2313 human-readable output of the L<sfdisk(8)> command.  It is
2314 not intended to be parsed.");
2315
2316   ("sfdisk_kernel_geometry", (RString "partitions", [String "device"]), 101, [],
2317    [],
2318    "display the kernel geometry",
2319    "\
2320 This displays the kernel's idea of the geometry of C<device>.
2321
2322 The result is in human-readable format, and not designed to
2323 be parsed.");
2324
2325   ("sfdisk_disk_geometry", (RString "partitions", [String "device"]), 102, [],
2326    [],
2327    "display the disk geometry from the partition table",
2328    "\
2329 This displays the disk geometry of C<device> read from the
2330 partition table.  Especially in the case where the underlying
2331 block device has been resized, this can be different from the
2332 kernel's idea of the geometry (see C<guestfs_sfdisk_kernel_geometry>).
2333
2334 The result is in human-readable format, and not designed to
2335 be parsed.");
2336
2337   ("vg_activate_all", (RErr, [Bool "activate"]), 103, [],
2338    [],
2339    "activate or deactivate all volume groups",
2340    "\
2341 This command activates or (if C<activate> is false) deactivates
2342 all logical volumes in all volume groups.
2343 If activated, then they are made known to the
2344 kernel, ie. they appear as C</dev/mapper> devices.  If deactivated,
2345 then those devices disappear.
2346
2347 This command is the same as running C<vgchange -a y|n>");
2348
2349   ("vg_activate", (RErr, [Bool "activate"; StringList "volgroups"]), 104, [],
2350    [],
2351    "activate or deactivate some volume groups",
2352    "\
2353 This command activates or (if C<activate> is false) deactivates
2354 all logical volumes in the listed volume groups C<volgroups>.
2355 If activated, then they are made known to the
2356 kernel, ie. they appear as C</dev/mapper> devices.  If deactivated,
2357 then those devices disappear.
2358
2359 This command is the same as running C<vgchange -a y|n volgroups...>
2360
2361 Note that if C<volgroups> is an empty list then B<all> volume groups
2362 are activated or deactivated.");
2363
2364   ("lvresize", (RErr, [String "device"; Int "mbytes"]), 105, [],
2365    [InitNone, Always, TestOutput (
2366       [["sfdiskM"; "/dev/sda"; ","];
2367        ["pvcreate"; "/dev/sda1"];
2368        ["vgcreate"; "VG"; "/dev/sda1"];
2369        ["lvcreate"; "LV"; "VG"; "10"];
2370        ["mkfs"; "ext2"; "/dev/VG/LV"];
2371        ["mount"; "/dev/VG/LV"; "/"];
2372        ["write_file"; "/new"; "test content"; "0"];
2373        ["umount"; "/"];
2374        ["lvresize"; "/dev/VG/LV"; "20"];
2375        ["e2fsck_f"; "/dev/VG/LV"];
2376        ["resize2fs"; "/dev/VG/LV"];
2377        ["mount"; "/dev/VG/LV"; "/"];
2378        ["cat"; "/new"]], "test content")],
2379    "resize an LVM logical volume",
2380    "\
2381 This resizes (expands or shrinks) an existing LVM logical
2382 volume to C<mbytes>.  When reducing, data in the reduced part
2383 is lost.");
2384
2385   ("resize2fs", (RErr, [String "device"]), 106, [],
2386    [], (* lvresize tests this *)
2387    "resize an ext2/ext3 filesystem",
2388    "\
2389 This resizes an ext2 or ext3 filesystem to match the size of
2390 the underlying device.
2391
2392 I<Note:> It is sometimes required that you run C<guestfs_e2fsck_f>
2393 on the C<device> before calling this command.  For unknown reasons
2394 C<resize2fs> sometimes gives an error about this and sometimes not.
2395 In any case, it is always safe to call C<guestfs_e2fsck_f> before
2396 calling this function.");
2397
2398   ("find", (RStringList "names", [String "directory"]), 107, [],
2399    [InitBasicFS, Always, TestOutputList (
2400       [["find"; "/"]], ["lost+found"]);
2401     InitBasicFS, Always, TestOutputList (
2402       [["touch"; "/a"];
2403        ["mkdir"; "/b"];
2404        ["touch"; "/b/c"];
2405        ["find"; "/"]], ["a"; "b"; "b/c"; "lost+found"]);
2406     InitBasicFS, Always, TestOutputList (
2407       [["mkdir_p"; "/a/b/c"];
2408        ["touch"; "/a/b/c/d"];
2409        ["find"; "/a/b/"]], ["c"; "c/d"])],
2410    "find all files and directories",
2411    "\
2412 This command lists out all files and directories, recursively,
2413 starting at C<directory>.  It is essentially equivalent to
2414 running the shell command C<find directory -print> but some
2415 post-processing happens on the output, described below.
2416
2417 This returns a list of strings I<without any prefix>.  Thus
2418 if the directory structure was:
2419
2420  /tmp/a
2421  /tmp/b
2422  /tmp/c/d
2423
2424 then the returned list from C<guestfs_find> C</tmp> would be
2425 4 elements:
2426
2427  a
2428  b
2429  c
2430  c/d
2431
2432 If C<directory> is not a directory, then this command returns
2433 an error.
2434
2435 The returned list is sorted.");
2436
2437   ("e2fsck_f", (RErr, [String "device"]), 108, [],
2438    [], (* lvresize tests this *)
2439    "check an ext2/ext3 filesystem",
2440    "\
2441 This runs C<e2fsck -p -f device>, ie. runs the ext2/ext3
2442 filesystem checker on C<device>, noninteractively (C<-p>),
2443 even if the filesystem appears to be clean (C<-f>).
2444
2445 This command is only needed because of C<guestfs_resize2fs>
2446 (q.v.).  Normally you should use C<guestfs_fsck>.");
2447
2448   ("sleep", (RErr, [Int "secs"]), 109, [],
2449    [InitNone, Always, TestRun (
2450       [["sleep"; "1"]])],
2451    "sleep for some seconds",
2452    "\
2453 Sleep for C<secs> seconds.");
2454
2455   ("ntfs_3g_probe", (RInt "status", [Bool "rw"; String "device"]), 110, [],
2456    [InitNone, Always, TestOutputInt (
2457       [["sfdiskM"; "/dev/sda"; ","];
2458        ["mkfs"; "ntfs"; "/dev/sda1"];
2459        ["ntfs_3g_probe"; "true"; "/dev/sda1"]], 0);
2460     InitNone, Always, TestOutputInt (
2461       [["sfdiskM"; "/dev/sda"; ","];
2462        ["mkfs"; "ext2"; "/dev/sda1"];
2463        ["ntfs_3g_probe"; "true"; "/dev/sda1"]], 12)],
2464    "probe NTFS volume",
2465    "\
2466 This command runs the L<ntfs-3g.probe(8)> command which probes
2467 an NTFS C<device> for mountability.  (Not all NTFS volumes can
2468 be mounted read-write, and some cannot be mounted at all).
2469
2470 C<rw> is a boolean flag.  Set it to true if you want to test
2471 if the volume can be mounted read-write.  Set it to false if
2472 you want to test if the volume can be mounted read-only.
2473
2474 The return value is an integer which C<0> if the operation
2475 would succeed, or some non-zero value documented in the
2476 L<ntfs-3g.probe(8)> manual page.");
2477
2478   ("sh", (RString "output", [String "command"]), 111, [],
2479    [], (* XXX needs tests *)
2480    "run a command via the shell",
2481    "\
2482 This call runs a command from the guest filesystem via the
2483 guest's C</bin/sh>.
2484
2485 This is like C<guestfs_command>, but passes the command to:
2486
2487  /bin/sh -c \"command\"
2488
2489 Depending on the guest's shell, this usually results in
2490 wildcards being expanded, shell expressions being interpolated
2491 and so on.
2492
2493 All the provisos about C<guestfs_command> apply to this call.");
2494
2495   ("sh_lines", (RStringList "lines", [String "command"]), 112, [],
2496    [], (* XXX needs tests *)
2497    "run a command via the shell returning lines",
2498    "\
2499 This is the same as C<guestfs_sh>, but splits the result
2500 into a list of lines.
2501
2502 See also: C<guestfs_command_lines>");
2503
2504   ("glob_expand", (RStringList "paths", [String "pattern"]), 113, [],
2505    [InitBasicFS, Always, TestOutputList (
2506       [["mkdir_p"; "/a/b/c"];
2507        ["touch"; "/a/b/c/d"];
2508        ["touch"; "/a/b/c/e"];
2509        ["glob_expand"; "/a/b/c/*"]], ["/a/b/c/d"; "/a/b/c/e"]);
2510     InitBasicFS, Always, TestOutputList (
2511       [["mkdir_p"; "/a/b/c"];
2512        ["touch"; "/a/b/c/d"];
2513        ["touch"; "/a/b/c/e"];
2514        ["glob_expand"; "/a/*/c/*"]], ["/a/b/c/d"; "/a/b/c/e"]);
2515     InitBasicFS, Always, TestOutputList (
2516       [["mkdir_p"; "/a/b/c"];
2517        ["touch"; "/a/b/c/d"];
2518        ["touch"; "/a/b/c/e"];
2519        ["glob_expand"; "/a/*/x/*"]], [])],
2520    "expand a wildcard path",
2521    "\
2522 This command searches for all the pathnames matching
2523 C<pattern> according to the wildcard expansion rules
2524 used by the shell.
2525
2526 If no paths match, then this returns an empty list
2527 (note: not an error).
2528
2529 It is just a wrapper around the C L<glob(3)> function
2530 with flags C<GLOB_MARK|GLOB_BRACE>.
2531 See that manual page for more details.");
2532
2533   ("scrub_device", (RErr, [String "device"]), 114, [DangerWillRobinson],
2534    [InitNone, Always, TestRun ( (* use /dev/sdc because it's smaller *)
2535       [["scrub_device"; "/dev/sdc"]])],
2536    "scrub (securely wipe) a device",
2537    "\
2538 This command writes patterns over C<device> to make data retrieval
2539 more difficult.
2540
2541 It is an interface to the L<scrub(1)> program.  See that
2542 manual page for more details.");
2543
2544   ("scrub_file", (RErr, [String "file"]), 115, [],
2545    [InitBasicFS, Always, TestRun (
2546       [["write_file"; "/file"; "content"; "0"];
2547        ["scrub_file"; "/file"]])],
2548    "scrub (securely wipe) a file",
2549    "\
2550 This command writes patterns over a file to make data retrieval
2551 more difficult.
2552
2553 The file is I<removed> after scrubbing.
2554
2555 It is an interface to the L<scrub(1)> program.  See that
2556 manual page for more details.");
2557
2558   ("scrub_freespace", (RErr, [String "dir"]), 116, [],
2559    [], (* XXX needs testing *)
2560    "scrub (securely wipe) free space",
2561    "\
2562 This command creates the directory C<dir> and then fills it
2563 with files until the filesystem is full, and scrubs the files
2564 as for C<guestfs_scrub_file>, and deletes them.
2565 The intention is to scrub any free space on the partition
2566 containing C<dir>.
2567
2568 It is an interface to the L<scrub(1)> program.  See that
2569 manual page for more details.");
2570
2571   ("mkdtemp", (RString "dir", [String "template"]), 117, [],
2572    [InitBasicFS, Always, TestRun (
2573       [["mkdir"; "/tmp"];
2574        ["mkdtemp"; "/tmp/tmpXXXXXX"]])],
2575    "create a temporary directory",
2576    "\
2577 This command creates a temporary directory.  The
2578 C<template> parameter should be a full pathname for the
2579 temporary directory name with the final six characters being
2580 \"XXXXXX\".
2581
2582 For example: \"/tmp/myprogXXXXXX\" or \"/Temp/myprogXXXXXX\",
2583 the second one being suitable for Windows filesystems.
2584
2585 The name of the temporary directory that was created
2586 is returned.
2587
2588 The temporary directory is created with mode 0700
2589 and is owned by root.
2590
2591 The caller is responsible for deleting the temporary
2592 directory and its contents after use.
2593
2594 See also: L<mkdtemp(3)>");
2595
2596   ("wc_l", (RInt "lines", [String "path"]), 118, [],
2597    [InitSquashFS, Always, TestOutputInt (
2598       [["wc_l"; "/10klines"]], 10000)],
2599    "count lines in a file",
2600    "\
2601 This command counts the lines in a file, using the
2602 C<wc -l> external command.");
2603
2604   ("wc_w", (RInt "words", [String "path"]), 119, [],
2605    [InitSquashFS, Always, TestOutputInt (
2606       [["wc_w"; "/10klines"]], 10000)],
2607    "count words in a file",
2608    "\
2609 This command counts the words in a file, using the
2610 C<wc -w> external command.");
2611
2612   ("wc_c", (RInt "chars", [String "path"]), 120, [],
2613    [InitSquashFS, Always, TestOutputInt (
2614       [["wc_c"; "/100kallspaces"]], 102400)],
2615    "count characters in a file",
2616    "\
2617 This command counts the characters in a file, using the
2618 C<wc -c> external command.");
2619
2620   ("head", (RStringList "lines", [String "path"]), 121, [ProtocolLimitWarning],
2621    [InitSquashFS, Always, TestOutputList (
2622       [["head"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz";"3abcdefghijklmnopqrstuvwxyz";"4abcdefghijklmnopqrstuvwxyz";"5abcdefghijklmnopqrstuvwxyz";"6abcdefghijklmnopqrstuvwxyz";"7abcdefghijklmnopqrstuvwxyz";"8abcdefghijklmnopqrstuvwxyz";"9abcdefghijklmnopqrstuvwxyz"])],
2623    "return first 10 lines of a file",
2624    "\
2625 This command returns up to the first 10 lines of a file as
2626 a list of strings.");
2627
2628   ("head_n", (RStringList "lines", [Int "nrlines"; String "path"]), 122, [ProtocolLimitWarning],
2629    [InitSquashFS, Always, TestOutputList (
2630       [["head_n"; "3"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz"]);
2631     InitSquashFS, Always, TestOutputList (
2632       [["head_n"; "-9997"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz"]);
2633     InitSquashFS, Always, TestOutputList (
2634       [["head_n"; "0"; "/10klines"]], [])],
2635    "return first N lines of a file",
2636    "\
2637 If the parameter C<nrlines> is a positive number, this returns the first
2638 C<nrlines> lines of the file C<path>.
2639
2640 If the parameter C<nrlines> is a negative number, this returns lines
2641 from the file C<path>, excluding the last C<nrlines> lines.
2642
2643 If the parameter C<nrlines> is zero, this returns an empty list.");
2644
2645   ("tail", (RStringList "lines", [String "path"]), 123, [ProtocolLimitWarning],
2646    [InitSquashFS, Always, TestOutputList (
2647       [["tail"; "/10klines"]], ["9990abcdefghijklmnopqrstuvwxyz";"9991abcdefghijklmnopqrstuvwxyz";"9992abcdefghijklmnopqrstuvwxyz";"9993abcdefghijklmnopqrstuvwxyz";"9994abcdefghijklmnopqrstuvwxyz";"9995abcdefghijklmnopqrstuvwxyz";"9996abcdefghijklmnopqrstuvwxyz";"9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"])],
2648    "return last 10 lines of a file",
2649    "\
2650 This command returns up to the last 10 lines of a file as
2651 a list of strings.");
2652
2653   ("tail_n", (RStringList "lines", [Int "nrlines"; String "path"]), 124, [ProtocolLimitWarning],
2654    [InitSquashFS, Always, TestOutputList (
2655       [["tail_n"; "3"; "/10klines"]], ["9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"]);
2656     InitSquashFS, Always, TestOutputList (
2657       [["tail_n"; "-9998"; "/10klines"]], ["9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"]);
2658     InitSquashFS, Always, TestOutputList (
2659       [["tail_n"; "0"; "/10klines"]], [])],
2660    "return last N lines of a file",
2661    "\
2662 If the parameter C<nrlines> is a positive number, this returns the last
2663 C<nrlines> lines of the file C<path>.
2664
2665 If the parameter C<nrlines> is a negative number, this returns lines
2666 from the file C<path>, starting with the C<-nrlines>th line.
2667
2668 If the parameter C<nrlines> is zero, this returns an empty list.");
2669
2670   ("df", (RString "output", []), 125, [],
2671    [], (* XXX Tricky to test because it depends on the exact format
2672         * of the 'df' command and other imponderables.
2673         *)
2674    "report file system disk space usage",
2675    "\
2676 This command runs the C<df> command to report disk space used.
2677
2678 This command is mostly useful for interactive sessions.  It
2679 is I<not> intended that you try to parse the output string.
2680 Use C<statvfs> from programs.");
2681
2682   ("df_h", (RString "output", []), 126, [],
2683    [], (* XXX Tricky to test because it depends on the exact format
2684         * of the 'df' command and other imponderables.
2685         *)
2686    "report file system disk space usage (human readable)",
2687    "\
2688 This command runs the C<df -h> command to report disk space used
2689 in human-readable format.
2690
2691 This command is mostly useful for interactive sessions.  It
2692 is I<not> intended that you try to parse the output string.
2693 Use C<statvfs> from programs.");
2694
2695   ("du", (RInt64 "sizekb", [String "path"]), 127, [],
2696    [InitSquashFS, Always, TestOutputInt (
2697       [["du"; "/directory"]], 0 (* squashfs doesn't have blocks *))],
2698    "estimate file space usage",
2699    "\
2700 This command runs the C<du -s> command to estimate file space
2701 usage for C<path>.
2702
2703 C<path> can be a file or a directory.  If C<path> is a directory
2704 then the estimate includes the contents of the directory and all
2705 subdirectories (recursively).
2706
2707 The result is the estimated size in I<kilobytes>
2708 (ie. units of 1024 bytes).");
2709
2710   ("initrd_list", (RStringList "filenames", [String "path"]), 128, [],
2711    [InitSquashFS, Always, TestOutputList (
2712       [["initrd_list"; "/initrd"]], ["empty";"known-1";"known-2";"known-3";"known-4"; "known-5"])],
2713    "list files in an initrd",
2714    "\
2715 This command lists out files contained in an initrd.
2716
2717 The files are listed without any initial C</> character.  The
2718 files are listed in the order they appear (not necessarily
2719 alphabetical).  Directory names are listed as separate items.
2720
2721 Old Linux kernels (2.4 and earlier) used a compressed ext2
2722 filesystem as initrd.  We I<only> support the newer initramfs
2723 format (compressed cpio files).");
2724
2725   ("mount_loop", (RErr, [String "file"; String "mountpoint"]), 129, [],
2726    [],
2727    "mount a file using the loop device",
2728    "\
2729 This command lets you mount C<file> (a filesystem image
2730 in a file) on a mount point.  It is entirely equivalent to
2731 the command C<mount -o loop file mountpoint>.");
2732
2733   ("mkswap", (RErr, [String "device"]), 130, [],
2734    [InitEmpty, Always, TestRun (
2735       [["sfdiskM"; "/dev/sda"; ","];
2736        ["mkswap"; "/dev/sda1"]])],
2737    "create a swap partition",
2738    "\
2739 Create a swap partition on C<device>.");
2740
2741   ("mkswap_L", (RErr, [String "label"; String "device"]), 131, [],
2742    [InitEmpty, Always, TestRun (
2743       [["sfdiskM"; "/dev/sda"; ","];
2744        ["mkswap_L"; "hello"; "/dev/sda1"]])],
2745    "create a swap partition with a label",
2746    "\
2747 Create a swap partition on C<device> with label C<label>.");
2748
2749   ("mkswap_U", (RErr, [String "uuid"; String "device"]), 132, [],
2750    [InitEmpty, Always, TestRun (
2751       [["sfdiskM"; "/dev/sda"; ","];
2752        ["mkswap_U"; "a3a61220-882b-4f61-89f4-cf24dcc7297d"; "/dev/sda1"]])],
2753    "create a swap partition with an explicit UUID",
2754    "\
2755 Create a swap partition on C<device> with UUID C<uuid>.");
2756
2757   ("mknod", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; String "path"]), 133, [],
2758    [InitBasicFS, Always, TestOutputStruct (
2759       [["mknod"; "0o10777"; "0"; "0"; "/node"];
2760        (* NB: default umask 022 means 0777 -> 0755 in these tests *)
2761        ["stat"; "/node"]], [CompareWithInt ("mode", 0o10755)]);
2762     InitBasicFS, Always, TestOutputStruct (
2763       [["mknod"; "0o60777"; "66"; "99"; "/node"];
2764        ["stat"; "/node"]], [CompareWithInt ("mode", 0o60755)])],
2765    "make block, character or FIFO devices",
2766    "\
2767 This call creates block or character special devices, or
2768 named pipes (FIFOs).
2769
2770 The C<mode> parameter should be the mode, using the standard
2771 constants.  C<devmajor> and C<devminor> are the
2772 device major and minor numbers, only used when creating block
2773 and character special devices.");
2774
2775   ("mkfifo", (RErr, [Int "mode"; String "path"]), 134, [],
2776    [InitBasicFS, Always, TestOutputStruct (
2777       [["mkfifo"; "0o777"; "/node"];
2778        ["stat"; "/node"]], [CompareWithInt ("mode", 0o10755)])],
2779    "make FIFO (named pipe)",
2780    "\
2781 This call creates a FIFO (named pipe) called C<path> with
2782 mode C<mode>.  It is just a convenient wrapper around
2783 C<guestfs_mknod>.");
2784
2785   ("mknod_b", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; String "path"]), 135, [],
2786    [InitBasicFS, Always, TestOutputStruct (
2787       [["mknod_b"; "0o777"; "99"; "66"; "/node"];
2788        ["stat"; "/node"]], [CompareWithInt ("mode", 0o60755)])],
2789    "make block device node",
2790    "\
2791 This call creates a block device node called C<path> with
2792 mode C<mode> and device major/minor C<devmajor> and C<devminor>.
2793 It is just a convenient wrapper around C<guestfs_mknod>.");
2794
2795   ("mknod_c", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; String "path"]), 136, [],
2796    [InitBasicFS, Always, TestOutputStruct (
2797       [["mknod_c"; "0o777"; "99"; "66"; "/node"];
2798        ["stat"; "/node"]], [CompareWithInt ("mode", 0o20755)])],
2799    "make char device node",
2800    "\
2801 This call creates a char device node called C<path> with
2802 mode C<mode> and device major/minor C<devmajor> and C<devminor>.
2803 It is just a convenient wrapper around C<guestfs_mknod>.");
2804
2805   ("umask", (RInt "oldmask", [Int "mask"]), 137, [],
2806    [], (* XXX umask is one of those stateful things that we should
2807         * reset between each test.
2808         *)
2809    "set file mode creation mask (umask)",
2810    "\
2811 This function sets the mask used for creating new files and
2812 device nodes to C<mask & 0777>.
2813
2814 Typical umask values would be C<022> which creates new files
2815 with permissions like \"-rw-r--r--\" or \"-rwxr-xr-x\", and
2816 C<002> which creates new files with permissions like
2817 \"-rw-rw-r--\" or \"-rwxrwxr-x\".
2818
2819 The default umask is C<022>.  This is important because it
2820 means that directories and device nodes will be created with
2821 C<0644> or C<0755> mode even if you specify C<0777>.
2822
2823 See also L<umask(2)>, C<guestfs_mknod>, C<guestfs_mkdir>.
2824
2825 This call returns the previous umask.");
2826
2827   ("readdir", (RStructList ("entries", "dirent"), [String "dir"]), 138, [],
2828    [],
2829    "read directories entries",
2830    "\
2831 This returns the list of directory entries in directory C<dir>.
2832
2833 All entries in the directory are returned, including C<.> and
2834 C<..>.  The entries are I<not> sorted, but returned in the same
2835 order as the underlying filesystem.
2836
2837 Also this call returns basic file type information about each
2838 file.  The C<ftyp> field will contain one of the following characters:
2839
2840 =over 4
2841
2842 =item 'b'
2843
2844 Block special
2845
2846 =item 'c'
2847
2848 Char special
2849
2850 =item 'd'
2851
2852 Directory
2853
2854 =item 'f'
2855
2856 FIFO (named pipe)
2857
2858 =item 'l'
2859
2860 Symbolic link
2861
2862 =item 'r'
2863
2864 Regular file
2865
2866 =item 's'
2867
2868 Socket
2869
2870 =item 'u'
2871
2872 Unknown file type
2873
2874 =item '?'
2875
2876 The L<readdir(3)> returned a C<d_type> field with an
2877 unexpected value
2878
2879 =back
2880
2881 This function is primarily intended for use by programs.  To
2882 get a simple list of names, use C<guestfs_ls>.  To get a printable
2883 directory for human consumption, use C<guestfs_ll>.");
2884
2885   ("sfdiskM", (RErr, [String "device"; StringList "lines"]), 139, [DangerWillRobinson],
2886    [],
2887    "create partitions on a block device",
2888    "\
2889 This is a simplified interface to the C<guestfs_sfdisk>
2890 command, where partition sizes are specified in megabytes
2891 only (rounded to the nearest cylinder) and you don't need
2892 to specify the cyls, heads and sectors parameters which
2893 were rarely if ever used anyway.
2894
2895 See also C<guestfs_sfdisk> and the L<sfdisk(8)> manpage.");
2896
2897   ("zfile", (RString "description", [String "method"; String "path"]), 140, [DeprecatedBy "file"],
2898    [],
2899    "determine file type inside a compressed file",
2900    "\
2901 This command runs C<file> after first decompressing C<path>
2902 using C<method>.
2903
2904 C<method> must be one of C<gzip>, C<compress> or C<bzip2>.
2905
2906 Since 1.0.63, use C<guestfs_file> instead which can now
2907 process compressed files.");
2908
2909   ("getxattrs", (RStructList ("xattrs", "xattr"), [String "path"]), 141, [],
2910    [],
2911    "list extended attributes of a file or directory",
2912    "\
2913 This call lists the extended attributes of the file or directory
2914 C<path>.
2915
2916 At the system call level, this is a combination of the
2917 L<listxattr(2)> and L<getxattr(2)> calls.
2918
2919 See also: C<guestfs_lgetxattrs>, L<attr(5)>.");
2920
2921   ("lgetxattrs", (RStructList ("xattrs", "xattr"), [String "path"]), 142, [],
2922    [],
2923    "list extended attributes of a file or directory",
2924    "\
2925 This is the same as C<guestfs_getxattrs>, but if C<path>
2926 is a symbolic link, then it returns the extended attributes
2927 of the link itself.");
2928
2929   ("setxattr", (RErr, [String "xattr";
2930                        String "val"; Int "vallen"; (* will be BufferIn *)
2931                        String "path"]), 143, [],
2932    [],
2933    "set extended attribute of a file or directory",
2934    "\
2935 This call sets the extended attribute named C<xattr>
2936 of the file C<path> to the value C<val> (of length C<vallen>).
2937 The value is arbitrary 8 bit data.
2938
2939 See also: C<guestfs_lsetxattr>, L<attr(5)>.");
2940
2941   ("lsetxattr", (RErr, [String "xattr";
2942                         String "val"; Int "vallen"; (* will be BufferIn *)
2943                         String "path"]), 144, [],
2944    [],
2945    "set extended attribute of a file or directory",
2946    "\
2947 This is the same as C<guestfs_setxattr>, but if C<path>
2948 is a symbolic link, then it sets an extended attribute
2949 of the link itself.");
2950
2951   ("removexattr", (RErr, [String "xattr"; String "path"]), 145, [],
2952    [],
2953    "remove extended attribute of a file or directory",
2954    "\
2955 This call removes the extended attribute named C<xattr>
2956 of the file C<path>.
2957
2958 See also: C<guestfs_lremovexattr>, L<attr(5)>.");
2959
2960   ("lremovexattr", (RErr, [String "xattr"; String "path"]), 146, [],
2961    [],
2962    "remove extended attribute of a file or directory",
2963    "\
2964 This is the same as C<guestfs_removexattr>, but if C<path>
2965 is a symbolic link, then it removes an extended attribute
2966 of the link itself.");
2967
2968   ("mountpoints", (RHashtable "mps", []), 147, [],
2969    [],
2970    "show mountpoints",
2971    "\
2972 This call is similar to C<guestfs_mounts>.  That call returns
2973 a list of devices.  This one returns a hash table (map) of
2974 device name to directory where the device is mounted.");
2975
2976   ("mkmountpoint", (RErr, [String "path"]), 148, [],
2977    [],
2978    "create a mountpoint",
2979    "\
2980 C<guestfs_mkmountpoint> and C<guestfs_rmmountpoint> are
2981 specialized calls that can be used to create extra mountpoints
2982 before mounting the first filesystem.
2983
2984 These calls are I<only> necessary in some very limited circumstances,
2985 mainly the case where you want to mount a mix of unrelated and/or
2986 read-only filesystems together.
2987
2988 For example, live CDs often contain a \"Russian doll\" nest of
2989 filesystems, an ISO outer layer, with a squashfs image inside, with
2990 an ext2/3 image inside that.  You can unpack this as follows
2991 in guestfish:
2992
2993  add-ro Fedora-11-i686-Live.iso
2994  run
2995  mkmountpoint /cd
2996  mkmountpoint /squash
2997  mkmountpoint /ext3
2998  mount /dev/sda /cd
2999  mount-loop /cd/LiveOS/squashfs.img /squash
3000  mount-loop /squash/LiveOS/ext3fs.img /ext3
3001
3002 The inner filesystem is now unpacked under the /ext3 mountpoint.");
3003
3004   ("rmmountpoint", (RErr, [String "path"]), 149, [],
3005    [],
3006    "remove a mountpoint",
3007    "\
3008 This calls removes a mountpoint that was previously created
3009 with C<guestfs_mkmountpoint>.  See C<guestfs_mkmountpoint>
3010 for full details.");
3011
3012   ("read_file", (RBufferOut "content", [String "path"]), 150, [ProtocolLimitWarning],
3013    [InitSquashFS, Always, TestOutputBuffer (
3014       [["read_file"; "/known-4"]], "abc\ndef\nghi")],
3015    "read a file",
3016    "\
3017 This calls returns the contents of the file C<path> as a
3018 buffer.
3019
3020 Unlike C<guestfs_cat>, this function can correctly
3021 handle files that contain embedded ASCII NUL characters.
3022 However unlike C<guestfs_download>, this function is limited
3023 in the total size of file that can be handled.");
3024
3025   ("grep", (RStringList "lines", [String "regex"; String "path"]), 151, [ProtocolLimitWarning],
3026    [InitSquashFS, Always, TestOutputList (
3027       [["grep"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"]);
3028     InitSquashFS, Always, TestOutputList (
3029       [["grep"; "nomatch"; "/test-grep.txt"]], [])],
3030    "return lines matching a pattern",
3031    "\
3032 This calls the external C<grep> program and returns the
3033 matching lines.");
3034
3035   ("egrep", (RStringList "lines", [String "regex"; String "path"]), 152, [ProtocolLimitWarning],
3036    [InitSquashFS, Always, TestOutputList (
3037       [["egrep"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"])],
3038    "return lines matching a pattern",
3039    "\
3040 This calls the external C<egrep> program and returns the
3041 matching lines.");
3042
3043   ("fgrep", (RStringList "lines", [String "pattern"; String "path"]), 153, [ProtocolLimitWarning],
3044    [InitSquashFS, Always, TestOutputList (
3045       [["fgrep"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"])],
3046    "return lines matching a pattern",
3047    "\
3048 This calls the external C<fgrep> program and returns the
3049 matching lines.");
3050
3051   ("grepi", (RStringList "lines", [String "regex"; String "path"]), 154, [ProtocolLimitWarning],
3052    [InitSquashFS, Always, TestOutputList (
3053       [["grepi"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"; "ABC"])],
3054    "return lines matching a pattern",
3055    "\
3056 This calls the external C<grep -i> program and returns the
3057 matching lines.");
3058
3059   ("egrepi", (RStringList "lines", [String "regex"; String "path"]), 155, [ProtocolLimitWarning],
3060    [InitSquashFS, Always, TestOutputList (
3061       [["egrepi"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"; "ABC"])],
3062    "return lines matching a pattern",
3063    "\
3064 This calls the external C<egrep -i> program and returns the
3065 matching lines.");
3066
3067   ("fgrepi", (RStringList "lines", [String "pattern"; String "path"]), 156, [ProtocolLimitWarning],
3068    [InitSquashFS, Always, TestOutputList (
3069       [["fgrepi"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"; "ABC"])],
3070    "return lines matching a pattern",
3071    "\
3072 This calls the external C<fgrep -i> program and returns the
3073 matching lines.");
3074
3075   ("zgrep", (RStringList "lines", [String "regex"; String "path"]), 157, [ProtocolLimitWarning],
3076    [InitSquashFS, Always, TestOutputList (
3077       [["zgrep"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"])],
3078    "return lines matching a pattern",
3079    "\
3080 This calls the external C<zgrep> program and returns the
3081 matching lines.");
3082
3083   ("zegrep", (RStringList "lines", [String "regex"; String "path"]), 158, [ProtocolLimitWarning],
3084    [InitSquashFS, Always, TestOutputList (
3085       [["zegrep"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"])],
3086    "return lines matching a pattern",
3087    "\
3088 This calls the external C<zegrep> program and returns the
3089 matching lines.");
3090
3091   ("zfgrep", (RStringList "lines", [String "pattern"; String "path"]), 159, [ProtocolLimitWarning],
3092    [InitSquashFS, Always, TestOutputList (
3093       [["zfgrep"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"])],
3094    "return lines matching a pattern",
3095    "\
3096 This calls the external C<zfgrep> program and returns the
3097 matching lines.");
3098
3099   ("zgrepi", (RStringList "lines", [String "regex"; String "path"]), 160, [ProtocolLimitWarning],
3100    [InitSquashFS, Always, TestOutputList (
3101       [["zgrepi"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"; "ABC"])],
3102    "return lines matching a pattern",
3103    "\
3104 This calls the external C<zgrep -i> program and returns the
3105 matching lines.");
3106
3107   ("zegrepi", (RStringList "lines", [String "regex"; String "path"]), 161, [ProtocolLimitWarning],
3108    [InitSquashFS, Always, TestOutputList (
3109       [["zegrepi"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"; "ABC"])],
3110    "return lines matching a pattern",
3111    "\
3112 This calls the external C<zegrep -i> program and returns the
3113 matching lines.");
3114
3115   ("zfgrepi", (RStringList "lines", [String "pattern"; String "path"]), 162, [ProtocolLimitWarning],
3116    [InitSquashFS, Always, TestOutputList (
3117       [["zfgrepi"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"; "ABC"])],
3118    "return lines matching a pattern",
3119    "\
3120 This calls the external C<zfgrep -i> program and returns the
3121 matching lines.");
3122
3123 ]
3124
3125 let all_functions = non_daemon_functions @ daemon_functions
3126
3127 (* In some places we want the functions to be displayed sorted
3128  * alphabetically, so this is useful:
3129  *)
3130 let all_functions_sorted =
3131   List.sort (fun (n1,_,_,_,_,_,_) (n2,_,_,_,_,_,_) ->
3132                compare n1 n2) all_functions
3133
3134 (* Field types for structures. *)
3135 type field =
3136   | FChar                       (* C 'char' (really, a 7 bit byte). *)
3137   | FString                     (* nul-terminated ASCII string. *)
3138   | FBuffer                     (* opaque buffer of bytes, (char *, int) pair *)
3139   | FUInt32
3140   | FInt32
3141   | FUInt64
3142   | FInt64
3143   | FBytes                      (* Any int measure that counts bytes. *)
3144   | FUUID                       (* 32 bytes long, NOT nul-terminated. *)
3145   | FOptPercent                 (* [0..100], or -1 meaning "not present". *)
3146
3147 (* Because we generate extra parsing code for LVM command line tools,
3148  * we have to pull out the LVM columns separately here.
3149  *)
3150 let lvm_pv_cols = [
3151   "pv_name", FString;
3152   "pv_uuid", FUUID;
3153   "pv_fmt", FString;
3154   "pv_size", FBytes;
3155   "dev_size", FBytes;
3156   "pv_free", FBytes;
3157   "pv_used", FBytes;
3158   "pv_attr", FString (* XXX *);
3159   "pv_pe_count", FInt64;
3160   "pv_pe_alloc_count", FInt64;
3161   "pv_tags", FString;
3162   "pe_start", FBytes;
3163   "pv_mda_count", FInt64;
3164   "pv_mda_free", FBytes;
3165   (* Not in Fedora 10:
3166      "pv_mda_size", FBytes;
3167   *)
3168 ]
3169 let lvm_vg_cols = [
3170   "vg_name", FString;
3171   "vg_uuid", FUUID;
3172   "vg_fmt", FString;
3173   "vg_attr", FString (* XXX *);
3174   "vg_size", FBytes;
3175   "vg_free", FBytes;
3176   "vg_sysid", FString;
3177   "vg_extent_size", FBytes;
3178   "vg_extent_count", FInt64;
3179   "vg_free_count", FInt64;
3180   "max_lv", FInt64;
3181   "max_pv", FInt64;
3182   "pv_count", FInt64;
3183   "lv_count", FInt64;
3184   "snap_count", FInt64;
3185   "vg_seqno", FInt64;
3186   "vg_tags", FString;
3187   "vg_mda_count", FInt64;
3188   "vg_mda_free", FBytes;
3189   (* Not in Fedora 10:
3190      "vg_mda_size", FBytes;
3191   *)
3192 ]
3193 let lvm_lv_cols = [
3194   "lv_name", FString;
3195   "lv_uuid", FUUID;
3196   "lv_attr", FString (* XXX *);
3197   "lv_major", FInt64;
3198   "lv_minor", FInt64;
3199   "lv_kernel_major", FInt64;
3200   "lv_kernel_minor", FInt64;
3201   "lv_size", FBytes;
3202   "seg_count", FInt64;
3203   "origin", FString;
3204   "snap_percent", FOptPercent;
3205   "copy_percent", FOptPercent;
3206   "move_pv", FString;
3207   "lv_tags", FString;
3208   "mirror_log", FString;
3209   "modules", FString;
3210 ]
3211
3212 (* Names and fields in all structures (in RStruct and RStructList)
3213  * that we support.
3214  *)
3215 let structs = [
3216   (* The old RIntBool return type, only ever used for aug_defnode.  Do
3217    * not use this struct in any new code.
3218    *)
3219   "int_bool", [
3220     "i", FInt32;                (* for historical compatibility *)
3221     "b", FInt32;                (* for historical compatibility *)
3222   ];
3223
3224   (* LVM PVs, VGs, LVs. *)
3225   "lvm_pv", lvm_pv_cols;
3226   "lvm_vg", lvm_vg_cols;
3227   "lvm_lv", lvm_lv_cols;
3228
3229   (* Column names and types from stat structures.
3230    * NB. Can't use things like 'st_atime' because glibc header files
3231    * define some of these as macros.  Ugh.
3232    *)
3233   "stat", [
3234     "dev", FInt64;
3235     "ino", FInt64;
3236     "mode", FInt64;
3237     "nlink", FInt64;
3238     "uid", FInt64;
3239     "gid", FInt64;
3240     "rdev", FInt64;
3241     "size", FInt64;
3242     "blksize", FInt64;
3243     "blocks", FInt64;
3244     "atime", FInt64;
3245     "mtime", FInt64;
3246     "ctime", FInt64;
3247   ];
3248   "statvfs", [
3249     "bsize", FInt64;
3250     "frsize", FInt64;
3251     "blocks", FInt64;
3252     "bfree", FInt64;
3253     "bavail", FInt64;
3254     "files", FInt64;
3255     "ffree", FInt64;
3256     "favail", FInt64;
3257     "fsid", FInt64;
3258     "flag", FInt64;
3259     "namemax", FInt64;
3260   ];
3261
3262   (* Column names in dirent structure. *)
3263   "dirent", [
3264     "ino", FInt64;
3265     (* 'b' 'c' 'd' 'f' (FIFO) 'l' 'r' (regular file) 's' 'u' '?' *)
3266     "ftyp", FChar;
3267     "name", FString;
3268   ];
3269
3270   (* Version numbers. *)
3271   "version", [
3272     "major", FInt64;
3273     "minor", FInt64;
3274     "release", FInt64;
3275     "extra", FString;
3276   ];
3277
3278   (* Extended attribute. *)
3279   "xattr", [
3280     "attrname", FString;
3281     "attrval", FBuffer;
3282   ];
3283 ] (* end of structs *)
3284
3285 (* Ugh, Java has to be different ..
3286  * These names are also used by the Haskell bindings.
3287  *)
3288 let java_structs = [
3289   "int_bool", "IntBool";
3290   "lvm_pv", "PV";
3291   "lvm_vg", "VG";
3292   "lvm_lv", "LV";
3293   "stat", "Stat";
3294   "statvfs", "StatVFS";
3295   "dirent", "Dirent";
3296   "version", "Version";
3297   "xattr", "XAttr";
3298 ]
3299
3300 (* Used for testing language bindings. *)
3301 type callt =
3302   | CallString of string
3303   | CallOptString of string option
3304   | CallStringList of string list
3305   | CallInt of int
3306   | CallBool of bool
3307
3308 (* Used to memoize the result of pod2text. *)
3309 let pod2text_memo_filename = "src/.pod2text.data"
3310 let pod2text_memo : ((int * string * string), string list) Hashtbl.t =
3311   try
3312     let chan = open_in pod2text_memo_filename in
3313     let v = input_value chan in
3314     close_in chan;
3315     v
3316   with
3317     _ -> Hashtbl.create 13
3318
3319 (* Useful functions.
3320  * Note we don't want to use any external OCaml libraries which
3321  * makes this a bit harder than it should be.
3322  *)
3323 let failwithf fs = ksprintf failwith fs
3324
3325 let replace_char s c1 c2 =
3326   let s2 = String.copy s in
3327   let r = ref false in
3328   for i = 0 to String.length s2 - 1 do
3329     if String.unsafe_get s2 i = c1 then (
3330       String.unsafe_set s2 i c2;
3331       r := true
3332     )
3333   done;
3334   if not !r then s else s2
3335
3336 let isspace c =
3337   c = ' '
3338   (* || c = '\f' *) || c = '\n' || c = '\r' || c = '\t' (* || c = '\v' *)
3339
3340 let triml ?(test = isspace) str =
3341   let i = ref 0 in
3342   let n = ref (String.length str) in
3343   while !n > 0 && test str.[!i]; do
3344     decr n;
3345     incr i
3346   done;
3347   if !i = 0 then str
3348   else String.sub str !i !n
3349
3350 let trimr ?(test = isspace) str =
3351   let n = ref (String.length str) in
3352   while !n > 0 && test str.[!n-1]; do
3353     decr n
3354   done;
3355   if !n = String.length str then str
3356   else String.sub str 0 !n
3357
3358 let trim ?(test = isspace) str =
3359   trimr ~test (triml ~test str)
3360
3361 let rec find s sub =
3362   let len = String.length s in
3363   let sublen = String.length sub in
3364   let rec loop i =
3365     if i <= len-sublen then (
3366       let rec loop2 j =
3367         if j < sublen then (
3368           if s.[i+j] = sub.[j] then loop2 (j+1)
3369           else -1
3370         ) else
3371           i (* found *)
3372       in
3373       let r = loop2 0 in
3374       if r = -1 then loop (i+1) else r
3375     ) else
3376       -1 (* not found *)
3377   in
3378   loop 0
3379
3380 let rec replace_str s s1 s2 =
3381   let len = String.length s in
3382   let sublen = String.length s1 in
3383   let i = find s s1 in
3384   if i = -1 then s
3385   else (
3386     let s' = String.sub s 0 i in
3387     let s'' = String.sub s (i+sublen) (len-i-sublen) in
3388     s' ^ s2 ^ replace_str s'' s1 s2
3389   )
3390
3391 let rec string_split sep str =
3392   let len = String.length str in
3393   let seplen = String.length sep in
3394   let i = find str sep in
3395   if i = -1 then [str]
3396   else (
3397     let s' = String.sub str 0 i in
3398     let s'' = String.sub str (i+seplen) (len-i-seplen) in
3399     s' :: string_split sep s''
3400   )
3401
3402 let files_equal n1 n2 =
3403   let cmd = sprintf "cmp -s %s %s" (Filename.quote n1) (Filename.quote n2) in
3404   match Sys.command cmd with
3405   | 0 -> true
3406   | 1 -> false
3407   | i -> failwithf "%s: failed with error code %d" cmd i
3408
3409 let rec find_map f = function
3410   | [] -> raise Not_found
3411   | x :: xs ->
3412       match f x with
3413       | Some y -> y
3414       | None -> find_map f xs
3415
3416 let iteri f xs =
3417   let rec loop i = function
3418     | [] -> ()
3419     | x :: xs -> f i x; loop (i+1) xs
3420   in
3421   loop 0 xs
3422
3423 let mapi f xs =
3424   let rec loop i = function
3425     | [] -> []
3426     | x :: xs -> let r = f i x in r :: loop (i+1) xs
3427   in
3428   loop 0 xs
3429
3430 let name_of_argt = function
3431   | String n | OptString n | StringList n | Bool n | Int n
3432   | FileIn n | FileOut n -> n
3433
3434 let java_name_of_struct typ =
3435   try List.assoc typ java_structs
3436   with Not_found ->
3437     failwithf
3438       "java_name_of_struct: no java_structs entry corresponding to %s" typ
3439
3440 let cols_of_struct typ =
3441   try List.assoc typ structs
3442   with Not_found ->
3443     failwithf "cols_of_struct: unknown struct %s" typ
3444
3445 let seq_of_test = function
3446   | TestRun s | TestOutput (s, _) | TestOutputList (s, _)
3447   | TestOutputListOfDevices (s, _)
3448   | TestOutputInt (s, _) | TestOutputIntOp (s, _, _)
3449   | TestOutputTrue s | TestOutputFalse s
3450   | TestOutputLength (s, _) | TestOutputBuffer (s, _)
3451   | TestOutputStruct (s, _)
3452   | TestLastFail s -> s
3453
3454 (* Handling for function flags. *)
3455 let protocol_limit_warning =
3456   "Because of the message protocol, there is a transfer limit
3457 of somewhere between 2MB and 4MB.  To transfer large files you should use
3458 FTP."
3459
3460 let danger_will_robinson =
3461   "B<This command is dangerous.  Without careful use you
3462 can easily destroy all your data>."
3463
3464 let deprecation_notice flags =
3465   try
3466     let alt =
3467       find_map (function DeprecatedBy str -> Some str | _ -> None) flags in
3468     let txt =
3469       sprintf "This function is deprecated.
3470 In new code, use the C<%s> call instead.
3471
3472 Deprecated functions will not be removed from the API, but the
3473 fact that they are deprecated indicates that there are problems
3474 with correct use of these functions." alt in
3475     Some txt
3476   with
3477     Not_found -> None
3478
3479 (* Check function names etc. for consistency. *)
3480 let check_functions () =
3481   let contains_uppercase str =
3482     let len = String.length str in
3483     let rec loop i =
3484       if i >= len then false
3485       else (
3486         let c = str.[i] in
3487         if c >= 'A' && c <= 'Z' then true
3488         else loop (i+1)
3489       )
3490     in
3491     loop 0
3492   in
3493
3494   (* Check function names. *)
3495   List.iter (
3496     fun (name, _, _, _, _, _, _) ->
3497       if String.length name >= 7 && String.sub name 0 7 = "guestfs" then
3498         failwithf "function name %s does not need 'guestfs' prefix" name;
3499       if name = "" then
3500         failwithf "function name is empty";
3501       if name.[0] < 'a' || name.[0] > 'z' then
3502         failwithf "function name %s must start with lowercase a-z" name;
3503       if String.contains name '-' then
3504         failwithf "function name %s should not contain '-', use '_' instead."
3505           name
3506   ) all_functions;
3507
3508   (* Check function parameter/return names. *)
3509   List.iter (
3510     fun (name, style, _, _, _, _, _) ->
3511       let check_arg_ret_name n =
3512         if contains_uppercase n then
3513           failwithf "%s param/ret %s should not contain uppercase chars"
3514             name n;
3515         if String.contains n '-' || String.contains n '_' then
3516           failwithf "%s param/ret %s should not contain '-' or '_'"
3517             name n;
3518         if n = "value" then
3519           failwithf "%s has a param/ret called 'value', which causes conflicts in the OCaml bindings, use something like 'val' or a more descriptive name" name;
3520         if n = "int" || n = "char" || n = "short" || n = "long" then
3521           failwithf "%s has a param/ret which conflicts with a C type (eg. 'int', 'char' etc.)" name;
3522         if n = "i" || n = "n" then
3523           failwithf "%s has a param/ret called 'i' or 'n', which will cause some conflicts in the generated code" name;
3524         if n = "argv" || n = "args" then
3525           failwithf "%s has a param/ret called 'argv' or 'args', which will cause some conflicts in the generated code" name
3526       in
3527
3528       (match fst style with
3529        | RErr -> ()
3530        | RInt n | RInt64 n | RBool n
3531        | RConstString n | RConstOptString n | RString n
3532        | RStringList n | RStruct (n, _) | RStructList (n, _)
3533        | RHashtable n | RBufferOut n ->
3534            check_arg_ret_name n
3535       );
3536       List.iter (fun arg -> check_arg_ret_name (name_of_argt arg)) (snd style)
3537   ) all_functions;
3538
3539   (* Check short descriptions. *)
3540   List.iter (
3541     fun (name, _, _, _, _, shortdesc, _) ->
3542       if shortdesc.[0] <> Char.lowercase shortdesc.[0] then
3543         failwithf "short description of %s should begin with lowercase." name;
3544       let c = shortdesc.[String.length shortdesc-1] in
3545       if c = '\n' || c = '.' then
3546         failwithf "short description of %s should not end with . or \\n." name
3547   ) all_functions;
3548
3549   (* Check long dscriptions. *)
3550   List.iter (
3551     fun (name, _, _, _, _, _, longdesc) ->
3552       if longdesc.[String.length longdesc-1] = '\n' then
3553         failwithf "long description of %s should not end with \\n." name
3554   ) all_functions;
3555
3556   (* Check proc_nrs. *)
3557   List.iter (
3558     fun (name, _, proc_nr, _, _, _, _) ->
3559       if proc_nr <= 0 then
3560         failwithf "daemon function %s should have proc_nr > 0" name
3561   ) daemon_functions;
3562
3563   List.iter (
3564     fun (name, _, proc_nr, _, _, _, _) ->
3565       if proc_nr <> -1 then
3566         failwithf "non-daemon function %s should have proc_nr -1" name
3567   ) non_daemon_functions;
3568
3569   let proc_nrs =
3570     List.map (fun (name, _, proc_nr, _, _, _, _) -> name, proc_nr)
3571       daemon_functions in
3572   let proc_nrs =
3573     List.sort (fun (_,nr1) (_,nr2) -> compare nr1 nr2) proc_nrs in
3574   let rec loop = function
3575     | [] -> ()
3576     | [_] -> ()
3577     | (name1,nr1) :: ((name2,nr2) :: _ as rest) when nr1 < nr2 ->
3578         loop rest
3579     | (name1,nr1) :: (name2,nr2) :: _ ->
3580         failwithf "%s and %s have conflicting procedure numbers (%d, %d)"
3581           name1 name2 nr1 nr2
3582   in
3583   loop proc_nrs;
3584
3585   (* Check tests. *)
3586   List.iter (
3587     function
3588       (* Ignore functions that have no tests.  We generate a
3589        * warning when the user does 'make check' instead.
3590        *)
3591     | name, _, _, _, [], _, _ -> ()
3592     | name, _, _, _, tests, _, _ ->
3593         let funcs =
3594           List.map (
3595             fun (_, _, test) ->
3596               match seq_of_test test with
3597               | [] ->
3598                   failwithf "%s has a test containing an empty sequence" name
3599               | cmds -> List.map List.hd cmds
3600           ) tests in
3601         let funcs = List.flatten funcs in
3602
3603         let tested = List.mem name funcs in
3604
3605         if not tested then
3606           failwithf "function %s has tests but does not test itself" name
3607   ) all_functions
3608
3609 (* 'pr' prints to the current output file. *)
3610 let chan = ref stdout
3611 let pr fs = ksprintf (output_string !chan) fs
3612
3613 (* Generate a header block in a number of standard styles. *)
3614 type comment_style = CStyle | HashStyle | OCamlStyle | HaskellStyle
3615 type license = GPLv2 | LGPLv2
3616
3617 let generate_header comment license =
3618   let c = match comment with
3619     | CStyle ->     pr "/* "; " *"
3620     | HashStyle ->  pr "# ";  "#"
3621     | OCamlStyle -> pr "(* "; " *"
3622     | HaskellStyle -> pr "{- "; "  " in
3623   pr "libguestfs generated file\n";
3624   pr "%s WARNING: THIS FILE IS GENERATED BY 'src/generator.ml'.\n" c;
3625   pr "%s ANY CHANGES YOU MAKE TO THIS FILE WILL BE LOST.\n" c;
3626   pr "%s\n" c;
3627   pr "%s Copyright (C) 2009 Red Hat Inc.\n" c;
3628   pr "%s\n" c;
3629   (match license with
3630    | GPLv2 ->
3631        pr "%s This program is free software; you can redistribute it and/or modify\n" c;
3632        pr "%s it under the terms of the GNU General Public License as published by\n" c;
3633        pr "%s the Free Software Foundation; either version 2 of the License, or\n" c;
3634        pr "%s (at your option) any later version.\n" c;
3635        pr "%s\n" c;
3636        pr "%s This program is distributed in the hope that it will be useful,\n" c;
3637        pr "%s but WITHOUT ANY WARRANTY; without even the implied warranty of\n" c;
3638        pr "%s MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n" c;
3639        pr "%s GNU General Public License for more details.\n" c;
3640        pr "%s\n" c;
3641        pr "%s You should have received a copy of the GNU General Public License along\n" c;
3642        pr "%s with this program; if not, write to the Free Software Foundation, Inc.,\n" c;
3643        pr "%s 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n" c;
3644
3645    | LGPLv2 ->
3646        pr "%s This library is free software; you can redistribute it and/or\n" c;
3647        pr "%s modify it under the terms of the GNU Lesser General Public\n" c;
3648        pr "%s License as published by the Free Software Foundation; either\n" c;
3649        pr "%s version 2 of the License, or (at your option) any later version.\n" c;
3650        pr "%s\n" c;
3651        pr "%s This library is distributed in the hope that it will be useful,\n" c;
3652        pr "%s but WITHOUT ANY WARRANTY; without even the implied warranty of\n" c;
3653        pr "%s MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n" c;
3654        pr "%s Lesser General Public License for more details.\n" c;
3655        pr "%s\n" c;
3656        pr "%s You should have received a copy of the GNU Lesser General Public\n" c;
3657        pr "%s License along with this library; if not, write to the Free Software\n" c;
3658        pr "%s Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n" c;
3659   );
3660   (match comment with
3661    | CStyle -> pr " */\n"
3662    | HashStyle -> ()
3663    | OCamlStyle -> pr " *)\n"
3664    | HaskellStyle -> pr "-}\n"
3665   );
3666   pr "\n"
3667
3668 (* Start of main code generation functions below this line. *)
3669
3670 (* Generate the pod documentation for the C API. *)
3671 let rec generate_actions_pod () =
3672   List.iter (
3673     fun (shortname, style, _, flags, _, _, longdesc) ->
3674       if not (List.mem NotInDocs flags) then (
3675         let name = "guestfs_" ^ shortname in
3676         pr "=head2 %s\n\n" name;
3677         pr " ";
3678         generate_prototype ~extern:false ~handle:"handle" name style;
3679         pr "\n\n";
3680         pr "%s\n\n" longdesc;
3681         (match fst style with
3682          | RErr ->
3683              pr "This function returns 0 on success or -1 on error.\n\n"
3684          | RInt _ ->
3685              pr "On error this function returns -1.\n\n"
3686          | RInt64 _ ->
3687              pr "On error this function returns -1.\n\n"
3688          | RBool _ ->
3689              pr "This function returns a C truth value on success or -1 on error.\n\n"
3690          | RConstString _ ->
3691              pr "This function returns a string, or NULL on error.
3692 The string is owned by the guest handle and must I<not> be freed.\n\n"
3693          | RConstOptString _ ->
3694              pr "This function returns a string which may be NULL.
3695 There is way to return an error from this function.
3696 The string is owned by the guest handle and must I<not> be freed.\n\n"
3697          | RString _ ->
3698              pr "This function returns a string, or NULL on error.
3699 I<The caller must free the returned string after use>.\n\n"
3700          | RStringList _ ->
3701              pr "This function returns a NULL-terminated array of strings
3702 (like L<environ(3)>), or NULL if there was an error.
3703 I<The caller must free the strings and the array after use>.\n\n"
3704          | RStruct (_, typ) ->
3705              pr "This function returns a C<struct guestfs_%s *>,
3706 or NULL if there was an error.
3707 I<The caller must call C<guestfs_free_%s> after use>.\n\n" typ typ
3708          | RStructList (_, typ) ->
3709              pr "This function returns a C<struct guestfs_%s_list *>
3710 (see E<lt>guestfs-structs.hE<gt>),
3711 or NULL if there was an error.
3712 I<The caller must call C<guestfs_free_%s_list> after use>.\n\n" typ typ
3713          | RHashtable _ ->
3714              pr "This function returns a NULL-terminated array of
3715 strings, or NULL if there was an error.
3716 The array of strings will always have length C<2n+1>, where
3717 C<n> keys and values alternate, followed by the trailing NULL entry.
3718 I<The caller must free the strings and the array after use>.\n\n"
3719          | RBufferOut _ ->
3720              pr "This function returns a buffer, or NULL on error.
3721 The size of the returned buffer is written to C<*size_r>.
3722 I<The caller must free the returned buffer after use>.\n\n"
3723         );