603fe209dba75c8d7429a9e356c1601cb3ec93d7
[libguestfs.git] / src / guestfs.pod
1 =encoding utf8
2
3 =head1 NAME
4
5 guestfs - Library for accessing and modifying virtual machine images
6
7 =head1 SYNOPSIS
8
9  #include <guestfs.h>
10  
11  guestfs_h *g = guestfs_create ();
12  guestfs_add_drive (g, "guest.img");
13  guestfs_launch (g);
14  guestfs_mount (g, "/dev/sda1", "/");
15  guestfs_touch (g, "/hello");
16  guestfs_umount (g, "/");
17  guestfs_sync (g);
18  guestfs_close (g);
19
20  cc prog.c -o prog -lguestfs
21 or:
22  cc prog.c -o prog `pkg-config libguestfs --cflags --libs`
23
24 =head1 DESCRIPTION
25
26 Libguestfs is a library for accessing and modifying guest disk images.
27 Amongst the things this is good for: making batch configuration
28 changes to guests, getting disk used/free statistics (see also:
29 virt-df), migrating between virtualization systems (see also:
30 virt-p2v), performing partial backups, performing partial guest
31 clones, cloning guests and changing registry/UUID/hostname info, and
32 much else besides.
33
34 Libguestfs uses Linux kernel and qemu code, and can access any type of
35 guest filesystem that Linux and qemu can, including but not limited
36 to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition
37 schemes, qcow, qcow2, vmdk.
38
39 Libguestfs provides ways to enumerate guest storage (eg. partitions,
40 LVs, what filesystem is in each LV, etc.).  It can also run commands
41 in the context of the guest.  Also you can access filesystems over
42 FUSE.
43
44 Libguestfs is a library that can be linked with C and C++ management
45 programs (or management programs written in OCaml, Perl, Python, Ruby,
46 Java, PHP, Haskell or C#).  You can also use it from shell scripts or the
47 command line.
48
49 You don't need to be root to use libguestfs, although obviously you do
50 need enough permissions to access the disk images.
51
52 Libguestfs is a large API because it can do many things.  For a gentle
53 introduction, please read the L</API OVERVIEW> section next.
54
55 =head1 API OVERVIEW
56
57 This section provides a gentler overview of the libguestfs API.  We
58 also try to group API calls together, where that may not be obvious
59 from reading about the individual calls in the main section of this
60 manual.
61
62 =head2 HANDLES
63
64 Before you can use libguestfs calls, you have to create a handle.
65 Then you must add at least one disk image to the handle, followed by
66 launching the handle, then performing whatever operations you want,
67 and finally closing the handle.  By convention we use the single
68 letter C<g> for the name of the handle variable, although of course
69 you can use any name you want.
70
71 The general structure of all libguestfs-using programs looks like
72 this:
73
74  guestfs_h *g = guestfs_create ();
75  
76  /* Call guestfs_add_drive additional times if there are
77   * multiple disk images.
78   */
79  guestfs_add_drive (g, "guest.img");
80  
81  /* Most manipulation calls won't work until you've launched
82   * the handle 'g'.  You have to do this _after_ adding drives
83   * and _before_ other commands.
84   */
85  guestfs_launch (g);
86  
87  /* Now you can examine what partitions, LVs etc are available.
88   */
89  char **partitions = guestfs_list_partitions (g);
90  char **logvols = guestfs_lvs (g);
91  
92  /* To access a filesystem in the image, you must mount it.
93   */
94  guestfs_mount (g, "/dev/sda1", "/");
95  
96  /* Now you can perform filesystem actions on the guest
97   * disk image.
98   */
99  guestfs_touch (g, "/hello");
100  
101  /* You only need to call guestfs_sync if you have made
102   * changes to the guest image.  (But if you've made changes
103   * then you *must* sync).  See also: guestfs_umount and
104   * guestfs_umount_all calls.
105   */
106  guestfs_sync (g);
107  
108  /* Close the handle 'g'. */
109  guestfs_close (g);
110
111 The code above doesn't include any error checking.  In real code you
112 should check return values carefully for errors.  In general all
113 functions that return integers return C<-1> on error, and all
114 functions that return pointers return C<NULL> on error.  See section
115 L</ERROR HANDLING> below for how to handle errors, and consult the
116 documentation for each function call below to see precisely how they
117 return error indications.
118
119 =head2 DISK IMAGES
120
121 The image filename (C<"guest.img"> in the example above) could be a
122 disk image from a virtual machine, a L<dd(1)> copy of a physical hard
123 disk, an actual block device, or simply an empty file of zeroes that
124 you have created through L<posix_fallocate(3)>.  Libguestfs lets you
125 do useful things to all of these.
126
127 The call you should use in modern code for adding drives is
128 L</guestfs_add_drive_opts>.  To add a disk image, allowing writes, and
129 specifying that the format is raw, do:
130
131  guestfs_add_drive_opts (g, filename,
132                          GUESTFS_ADD_DRIVE_OPTS_FORMAT, "raw",
133                          -1);
134
135 You can add a disk read-only using:
136
137  guestfs_add_drive_opts (g, filename,
138                          GUESTFS_ADD_DRIVE_OPTS_FORMAT, "raw",
139                          GUESTFS_ADD_DRIVE_OPTS_READONLY, 1,
140                          -1);
141
142 or by calling the older function L</guestfs_add_drive_ro>.  In either
143 case libguestfs won't modify the file.
144
145 Be extremely cautious if the disk image is in use, eg. if it is being
146 used by a virtual machine.  Adding it read-write will almost certainly
147 cause disk corruption, but adding it read-only is safe.
148
149 You must add at least one disk image, and you may add multiple disk
150 images.  In the API, the disk images are usually referred to as
151 C</dev/sda> (for the first one you added), C</dev/sdb> (for the second
152 one you added), etc.
153
154 Once L</guestfs_launch> has been called you cannot add any more images.
155 You can call L</guestfs_list_devices> to get a list of the device
156 names, in the order that you added them.  See also L</BLOCK DEVICE
157 NAMING> below.
158
159 =head2 MOUNTING
160
161 Before you can read or write files, create directories and so on in a
162 disk image that contains filesystems, you have to mount those
163 filesystems using L</guestfs_mount>.  If you already know that a disk
164 image contains (for example) one partition with a filesystem on that
165 partition, then you can mount it directly:
166
167  guestfs_mount (g, "/dev/sda1", "/");
168
169 where C</dev/sda1> means literally the first partition (C<1>) of the
170 first disk image that we added (C</dev/sda>).  If the disk contains
171 Linux LVM2 logical volumes you could refer to those instead (eg. C</dev/VG/LV>).
172
173 If you are given a disk image and you don't know what it contains then
174 you have to find out.  Libguestfs can do that too: use
175 L</guestfs_list_partitions> and L</guestfs_lvs> to list possible
176 partitions and LVs, and either try mounting each to see what is
177 mountable, or else examine them with L</guestfs_vfs_type> or
178 L</guestfs_file>.  Libguestfs also has a set of APIs for inspection of
179 disk images (see L</INSPECTION> below).  But you might find it easier
180 to look at higher level programs built on top of libguestfs, in
181 particular L<virt-inspector(1)>.
182
183 To mount a disk image read-only, use L</guestfs_mount_ro>.  There are
184 several other variations of the C<guestfs_mount_*> call.
185
186 =head2 FILESYSTEM ACCESS AND MODIFICATION
187
188 The majority of the libguestfs API consists of fairly low-level calls
189 for accessing and modifying the files, directories, symlinks etc on
190 mounted filesystems.  There are over a hundred such calls which you
191 can find listed in detail below in this man page, and we don't even
192 pretend to cover them all in this overview.
193
194 Specify filenames as full paths, starting with C<"/"> and including
195 the mount point.
196
197 For example, if you mounted a filesystem at C<"/"> and you want to
198 read the file called C<"etc/passwd"> then you could do:
199
200  char *data = guestfs_cat (g, "/etc/passwd");
201
202 This would return C<data> as a newly allocated buffer containing the
203 full content of that file (with some conditions: see also
204 L</DOWNLOADING> below), or C<NULL> if there was an error.
205
206 As another example, to create a top-level directory on that filesystem
207 called C<"var"> you would do:
208
209  guestfs_mkdir (g, "/var");
210
211 To create a symlink you could do:
212
213  guestfs_ln_s (g, "/etc/init.d/portmap",
214                "/etc/rc3.d/S30portmap");
215
216 Libguestfs will reject attempts to use relative paths and there is no
217 concept of a current working directory.
218
219 Libguestfs can return errors in many situations: for example if the
220 filesystem isn't writable, or if a file or directory that you
221 requested doesn't exist.  If you are using the C API (documented here)
222 you have to check for those error conditions after each call.  (Other
223 language bindings turn these errors into exceptions).
224
225 File writes are affected by the per-handle umask, set by calling
226 L</guestfs_umask> and defaulting to 022.  See L</UMASK>.
227
228 =head2 PARTITIONING
229
230 Libguestfs contains API calls to read, create and modify partition
231 tables on disk images.
232
233 In the common case where you want to create a single partition
234 covering the whole disk, you should use the L</guestfs_part_disk>
235 call:
236
237  const char *parttype = "mbr";
238  if (disk_is_larger_than_2TB)
239    parttype = "gpt";
240  guestfs_part_disk (g, "/dev/sda", parttype);
241
242 Obviously this effectively wipes anything that was on that disk image
243 before.
244
245 =head2 LVM2
246
247 Libguestfs provides access to a large part of the LVM2 API, such as
248 L</guestfs_lvcreate> and L</guestfs_vgremove>.  It won't make much sense
249 unless you familiarize yourself with the concepts of physical volumes,
250 volume groups and logical volumes.
251
252 This author strongly recommends reading the LVM HOWTO, online at
253 L<http://tldp.org/HOWTO/LVM-HOWTO/>.
254
255 =head2 DOWNLOADING
256
257 Use L</guestfs_cat> to download small, text only files.  This call
258 is limited to files which are less than 2 MB and which cannot contain
259 any ASCII NUL (C<\0>) characters.  However it has a very simple
260 to use API.
261
262 L</guestfs_read_file> can be used to read files which contain
263 arbitrary 8 bit data, since it returns a (pointer, size) pair.
264 However it is still limited to "small" files, less than 2 MB.
265
266 L</guestfs_download> can be used to download any file, with no
267 limits on content or size (even files larger than 4 GB).
268
269 To download multiple files, see L</guestfs_tar_out> and
270 L</guestfs_tgz_out>.
271
272 =head2 UPLOADING
273
274 It's often the case that you want to write a file or files to the disk
275 image.
276
277 To write a small file with fixed content, use L</guestfs_write>.  To
278 create a file of all zeroes, use L</guestfs_truncate_size> (sparse) or
279 L</guestfs_fallocate64> (with all disk blocks allocated).  There are a
280 variety of other functions for creating test files, for example
281 L</guestfs_fill> and L</guestfs_fill_pattern>.
282
283 To upload a single file, use L</guestfs_upload>.  This call has no
284 limits on file content or size (even files larger than 4 GB).
285
286 To upload multiple files, see L</guestfs_tar_in> and L</guestfs_tgz_in>.
287
288 However the fastest way to upload I<large numbers of arbitrary files>
289 is to turn them into a squashfs or CD ISO (see L<mksquashfs(8)> and
290 L<mkisofs(8)>), then attach this using L</guestfs_add_drive_ro>.  If
291 you add the drive in a predictable way (eg. adding it last after all
292 other drives) then you can get the device name from
293 L</guestfs_list_devices> and mount it directly using
294 L</guestfs_mount_ro>.  Note that squashfs images are sometimes
295 non-portable between kernel versions, and they don't support labels or
296 UUIDs.  If you want to pre-build an image or you need to mount it
297 using a label or UUID, use an ISO image instead.
298
299 =head2 COPYING
300
301 There are various different commands for copying between files and
302 devices and in and out of the guest filesystem.  These are summarised
303 in the table below.
304
305 =over 4
306
307 =item B<file> to B<file>
308
309 Use L</guestfs_cp> to copy a single file, or
310 L</guestfs_cp_a> to copy directories recursively.
311
312 =item B<file or device> to B<file or device>
313
314 Use L</guestfs_dd> which efficiently uses L<dd(1)>
315 to copy between files and devices in the guest.
316
317 Example: duplicate the contents of an LV:
318
319  guestfs_dd (g, "/dev/VG/Original", "/dev/VG/Copy");
320
321 The destination (C</dev/VG/Copy>) must be at least as large as the
322 source (C</dev/VG/Original>).  To copy less than the whole
323 source device, use L</guestfs_copy_size>.
324
325 =item B<file on the host> to B<file or device>
326
327 Use L</guestfs_upload>.  See L</UPLOADING> above.
328
329 =item B<file or device> to B<file on the host>
330
331 Use L</guestfs_download>.  See L</DOWNLOADING> above.
332
333 =back
334
335 =head2 LISTING FILES
336
337 L</guestfs_ll> is just designed for humans to read (mainly when using
338 the L<guestfish(1)>-equivalent command C<ll>).
339
340 L</guestfs_ls> is a quick way to get a list of files in a directory
341 from programs, as a flat list of strings.
342
343 L</guestfs_readdir> is a programmatic way to get a list of files in a
344 directory, plus additional information about each one.  It is more
345 equivalent to using the L<readdir(3)> call on a local filesystem.
346
347 L</guestfs_find> and L</guestfs_find0> can be used to recursively list
348 files.
349
350 =head2 RUNNING COMMANDS
351
352 Although libguestfs is primarily an API for manipulating files
353 inside guest images, we also provide some limited facilities for
354 running commands inside guests.
355
356 There are many limitations to this:
357
358 =over 4
359
360 =item *
361
362 The kernel version that the command runs under will be different
363 from what it expects.
364
365 =item *
366
367 If the command needs to communicate with daemons, then most likely
368 they won't be running.
369
370 =item *
371
372 The command will be running in limited memory.
373
374 =item *
375
376 The network may not be available unless you enable it
377 (see L</guestfs_set_network>).
378
379 =item *
380
381 Only supports Linux guests (not Windows, BSD, etc).
382
383 =item *
384
385 Architecture limitations (eg. won't work for a PPC guest on
386 an X86 host).
387
388 =item *
389
390 For SELinux guests, you may need to enable SELinux and load policy
391 first.  See L</SELINUX> in this manpage.
392
393 =item *
394
395 I<Security:> It is not safe to run commands from untrusted, possibly
396 malicious guests.  These commands may attempt to exploit your program
397 by sending unexpected output.  They could also try to exploit the
398 Linux kernel or qemu provided by the libguestfs appliance.  They could
399 use the network provided by the libguestfs appliance to bypass
400 ordinary network partitions and firewalls.  They could use the
401 elevated privileges or different SELinux context of your program
402 to their advantage.
403
404 A secure alternative is to use libguestfs to install a "firstboot"
405 script (a script which runs when the guest next boots normally), and
406 to have this script run the commands you want in the normal context of
407 the running guest, network security and so on.
408
409 =back
410
411 The two main API calls to run commands are L</guestfs_command> and
412 L</guestfs_sh> (there are also variations).
413
414 The difference is that L</guestfs_sh> runs commands using the shell, so
415 any shell globs, redirections, etc will work.
416
417 =head2 CONFIGURATION FILES
418
419 To read and write configuration files in Linux guest filesystems, we
420 strongly recommend using Augeas.  For example, Augeas understands how
421 to read and write, say, a Linux shadow password file or X.org
422 configuration file, and so avoids you having to write that code.
423
424 The main Augeas calls are bound through the C<guestfs_aug_*> APIs.  We
425 don't document Augeas itself here because there is excellent
426 documentation on the L<http://augeas.net/> website.
427
428 If you don't want to use Augeas (you fool!) then try calling
429 L</guestfs_read_lines> to get the file as a list of lines which
430 you can iterate over.
431
432 =head2 SELINUX
433
434 We support SELinux guests.  To ensure that labeling happens correctly
435 in SELinux guests, you need to enable SELinux and load the guest's
436 policy:
437
438 =over 4
439
440 =item 1.
441
442 Before launching, do:
443
444  guestfs_set_selinux (g, 1);
445
446 =item 2.
447
448 After mounting the guest's filesystem(s), load the policy.  This
449 is best done by running the L<load_policy(8)> command in the
450 guest itself:
451
452  guestfs_sh (g, "/usr/sbin/load_policy");
453
454 (Older versions of C<load_policy> require you to specify the
455 name of the policy file).
456
457 =item 3.
458
459 Optionally, set the security context for the API.  The correct
460 security context to use can only be known by inspecting the
461 guest.  As an example:
462
463  guestfs_setcon (g, "unconfined_u:unconfined_r:unconfined_t:s0");
464
465 =back
466
467 This will work for running commands and editing existing files.
468
469 When new files are created, you may need to label them explicitly,
470 for example by running the external command
471 C<restorecon pathname>.
472
473 =head2 UMASK
474
475 Certain calls are affected by the current file mode creation mask (the
476 "umask").  In particular ones which create files or directories, such
477 as L</guestfs_touch>, L</guestfs_mknod> or L</guestfs_mkdir>.  This
478 affects either the default mode that the file is created with or
479 modifies the mode that you supply.
480
481 The default umask is C<022>, so files are created with modes such as
482 C<0644> and directories with C<0755>.
483
484 There are two ways to avoid being affected by umask.  Either set umask
485 to 0 (call C<guestfs_umask (g, 0)> early after launching).  Or call
486 L</guestfs_chmod> after creating each file or directory.
487
488 For more information about umask, see L<umask(2)>.
489
490 =head2 ENCRYPTED DISKS
491
492 Libguestfs allows you to access Linux guests which have been
493 encrypted using whole disk encryption that conforms to the
494 Linux Unified Key Setup (LUKS) standard.  This includes
495 nearly all whole disk encryption systems used by modern
496 Linux guests.
497
498 Use L</guestfs_vfs_type> to identify LUKS-encrypted block
499 devices (it returns the string C<crypto_LUKS>).
500
501 Then open these devices by calling L</guestfs_luks_open>.
502 Obviously you will require the passphrase!
503
504 Opening a LUKS device creates a new device mapper device
505 called C</dev/mapper/mapname> (where C<mapname> is the
506 string you supply to L</guestfs_luks_open>).
507 Reads and writes to this mapper device are decrypted from and
508 encrypted to the underlying block device respectively.
509
510 LVM volume groups on the device can be made visible by calling
511 L</guestfs_vgscan> followed by L</guestfs_vg_activate_all>.
512 The logical volume(s) can now be mounted in the usual way.
513
514 Use the reverse process to close a LUKS device.  Unmount
515 any logical volumes on it, deactivate the volume groups
516 by caling C<guestfs_vg_activate (g, 0, ["/dev/VG"])>.
517 Then close the mapper device by calling
518 L</guestfs_luks_close> on the C</dev/mapper/mapname>
519 device (I<not> the underlying encrypted block device).
520
521 =head2 INSPECTION
522
523 Libguestfs has APIs for inspecting an unknown disk image to find out
524 if it contains operating systems.  (These APIs used to be in a
525 separate Perl-only library called L<Sys::Guestfs::Lib(3)> but since
526 version 1.5.3 the most frequently used part of this library has been
527 rewritten in C and moved into the core code).
528
529 Add all disks belonging to the unknown virtual machine and call
530 L</guestfs_launch> in the usual way.
531
532 Then call L</guestfs_inspect_os>.  This function uses other libguestfs
533 calls and certain heuristics, and returns a list of operating systems
534 that were found.  An empty list means none were found.  A single
535 element is the root filesystem of the operating system.  For dual- or
536 multi-boot guests, multiple roots can be returned, each one
537 corresponding to a separate operating system.  (Multi-boot virtual
538 machines are extremely rare in the world of virtualization, but since
539 this scenario can happen, we have built libguestfs to deal with it.)
540
541 For each root, you can then call various C<guestfs_inspect_get_*>
542 functions to get additional details about that operating system.  For
543 example, call L</guestfs_inspect_get_type> to return the string
544 C<windows> or C<linux> for Windows and Linux-based operating systems
545 respectively.
546
547 Un*x-like and Linux-based operating systems usually consist of several
548 filesystems which are mounted at boot time (for example, a separate
549 boot partition mounted on C</boot>).  The inspection rules are able to
550 detect how filesystems correspond to mount points.  Call
551 C<guestfs_inspect_get_mountpoints> to get this mapping.  It might
552 return a hash table like this example:
553
554  /boot => /dev/sda1
555  /     => /dev/vg_guest/lv_root
556  /usr  => /dev/vg_guest/lv_usr
557
558 The caller can then make calls to L</guestfs_mount_options> to
559 mount the filesystems as suggested.
560
561 Be careful to mount filesystems in the right order (eg. C</> before
562 C</usr>).  Sorting the keys of the hash by length, shortest first,
563 should work.
564
565 Inspection currently only works for some common operating systems.
566 Contributors are welcome to send patches for other operating systems
567 that we currently cannot detect.
568
569 Encrypted disks must be opened before inspection.  See
570 L</ENCRYPTED DISKS> for more details.  The L</guestfs_inspect_os>
571 function just ignores any encrypted devices.
572
573 A note on the implementation: The call L</guestfs_inspect_os> performs
574 inspection and caches the results in the guest handle.  Subsequent
575 calls to C<guestfs_inspect_get_*> return this cached information, but
576 I<do not> re-read the disks.  If you change the content of the guest
577 disks, you can redo inspection by calling L</guestfs_inspect_os>
578 again.
579
580 =head2 SPECIAL CONSIDERATIONS FOR WINDOWS GUESTS
581
582 Libguestfs can mount NTFS partitions.  It does this using the
583 L<http://www.ntfs-3g.org/> driver.
584
585 DOS and Windows still use drive letters, and the filesystems are
586 always treated as case insensitive by Windows itself, and therefore
587 you might find a Windows configuration file referring to a path like
588 C<c:\windows\system32>.  When the filesystem is mounted in libguestfs,
589 that directory might be referred to as C</WINDOWS/System32>.
590
591 Drive letter mappings are outside the scope of libguestfs.  You have
592 to use libguestfs to read the appropriate Windows Registry and
593 configuration files, to determine yourself how drives are mapped (see
594 also L<hivex(3)> and L<virt-inspector(1)>).
595
596 Replacing backslash characters with forward slash characters is also
597 outside the scope of libguestfs, but something that you can easily do.
598
599 Where we can help is in resolving the case insensitivity of paths.
600 For this, call L</guestfs_case_sensitive_path>.
601
602 Libguestfs also provides some help for decoding Windows Registry
603 "hive" files, through the library C<hivex> which is part of the
604 libguestfs project although ships as a separate tarball.  You have to
605 locate and download the hive file(s) yourself, and then pass them to
606 C<hivex> functions.  See also the programs L<hivexml(1)>,
607 L<hivexsh(1)>, L<hivexregedit(1)> and L<virt-win-reg(1)> for more help
608 on this issue.
609
610 =head2 USING LIBGUESTFS WITH OTHER PROGRAMMING LANGUAGES
611
612 Although we don't want to discourage you from using the C API, we will
613 mention here that the same API is also available in other languages.
614
615 The API is broadly identical in all supported languages.  This means
616 that the C call C<guestfs_mount(g,path)> is
617 C<$g-E<gt>mount($path)> in Perl, C<g.mount(path)> in Python,
618 and C<Guestfs.mount g path> in OCaml.  In other words, a
619 straightforward, predictable isomorphism between each language.
620
621 Error messages are automatically transformed
622 into exceptions if the language supports it.
623
624 We don't try to "object orientify" parts of the API in OO languages,
625 although contributors are welcome to write higher level APIs above
626 what we provide in their favourite languages if they wish.
627
628 =over 4
629
630 =item B<C++>
631
632 You can use the I<guestfs.h> header file from C++ programs.  The C++
633 API is identical to the C API.  C++ classes and exceptions are not
634 used.
635
636 =item B<C#>
637
638 The C# bindings are highly experimental.  Please read the warnings
639 at the top of C<csharp/Libguestfs.cs>.
640
641 =item B<Haskell>
642
643 This is the only language binding that is working but incomplete.
644 Only calls which return simple integers have been bound in Haskell,
645 and we are looking for help to complete this binding.
646
647 =item B<Java>
648
649 Full documentation is contained in the Javadoc which is distributed
650 with libguestfs.
651
652 =item B<OCaml>
653
654 For documentation see the file C<guestfs.mli>.
655
656 =item B<Perl>
657
658 For documentation see L<Sys::Guestfs(3)>.
659
660 =item B<PHP>
661
662 For documentation see C<README-PHP> supplied with libguestfs
663 sources or in the php-libguestfs package for your distribution.
664
665 The PHP binding only works correctly on 64 bit machines.
666
667 =item B<Python>
668
669 For documentation do:
670
671  $ python
672  >>> import guestfs
673  >>> help (guestfs)
674
675 =item B<Ruby>
676
677 Use the Guestfs module.  There is no Ruby-specific documentation, but
678 you can find examples written in Ruby in the libguestfs source.
679
680 =item B<shell scripts>
681
682 For documentation see L<guestfish(1)>.
683
684 =back
685
686 =head2 LIBGUESTFS GOTCHAS
687
688 L<http://en.wikipedia.org/wiki/Gotcha_(programming)>: "A feature of a
689 system [...] that works in the way it is documented but is
690 counterintuitive and almost invites mistakes."
691
692 Since we developed libguestfs and the associated tools, there are
693 several things we would have designed differently, but are now stuck
694 with for backwards compatibility or other reasons.  If there is ever a
695 libguestfs 2.0 release, you can expect these to change.  Beware of
696 them.
697
698 =over 4
699
700 =item Autosync / forgetting to sync.
701
702 When modifying a filesystem from C or another language, you B<must>
703 unmount all filesystems and call L</guestfs_sync> explicitly before
704 you close the libguestfs handle.  You can also call:
705
706  guestfs_set_autosync (g, 1);
707
708 to have the unmount/sync done automatically for you when the handle 'g'
709 is closed.  (This feature is called "autosync", L</guestfs_set_autosync>
710 q.v.)
711
712 If you forget to do this, then it is entirely possible that your
713 changes won't be written out, or will be partially written, or (very
714 rarely) that you'll get disk corruption.
715
716 Note that in L<guestfish(3)> autosync is the default.  So quick and
717 dirty guestfish scripts that forget to sync will work just fine, which
718 can make this very puzzling if you are trying to debug a problem.
719
720 Update: Autosync is enabled by default for all API users starting from
721 libguestfs 1.5.24.
722
723 =item Mount option C<-o sync> should not be the default.
724
725 If you use L</guestfs_mount>, then C<-o sync,noatime> are added
726 implicitly.  However C<-o sync> does not add any reliability benefit,
727 but does have a very large performance impact.
728
729 The work around is to use L</guestfs_mount_options> and set the mount
730 options that you actually want to use.
731
732 =item Read-only should be the default.
733
734 In L<guestfish(3)>, I<--ro> should be the default, and you should
735 have to specify I<--rw> if you want to make changes to the image.
736
737 This would reduce the potential to corrupt live VM images.
738
739 Note that many filesystems change the disk when you just mount and
740 unmount, even if you didn't perform any writes.  You need to use
741 L</guestfs_add_drive_ro> to guarantee that the disk is not changed.
742
743 =item guestfish command line is hard to use.
744
745 C<guestfish disk.img> doesn't do what people expect (open C<disk.img>
746 for examination).  It tries to run a guestfish command C<disk.img>
747 which doesn't exist, so it fails.  In earlier versions of guestfish
748 the error message was also unintuitive, but we have corrected this
749 since.  Like the Bourne shell, we should have used C<guestfish -c
750 command> to run commands.
751
752 =item guestfish megabyte modifiers don't work right on all commands
753
754 In recent guestfish you can use C<1M> to mean 1 megabyte (and
755 similarly for other modifiers).  What guestfish actually does is to
756 multiply the number part by the modifier part and pass the result to
757 the C API.  However this doesn't work for a few APIs which aren't
758 expecting bytes, but are already expecting some other unit
759 (eg. megabytes).
760
761 The most common is L</guestfs_lvcreate>.  The guestfish command:
762
763  lvcreate LV VG 100M
764
765 does not do what you might expect.  Instead because
766 L</guestfs_lvcreate> is already expecting megabytes, this tries to
767 create a 100 I<terabyte> (100 megabytes * megabytes) logical volume.
768 The error message you get from this is also a little obscure.
769
770 This could be fixed in the generator by specially marking parameters
771 and return values which take bytes or other units.
772
773 =item Library should return errno with error messages.
774
775 It would be a nice-to-have to be able to get the original value of
776 'errno' from inside the appliance along error paths (where set).
777 Currently L<guestmount(1)> goes through hoops to try to reverse the
778 error message string into an errno, see the function error() in
779 fuse/guestmount.c.
780
781 In libguestfs 1.5.4, the protocol was changed so that the
782 Linux errno is sent back from the daemon.
783
784 In libguestfs 1.7.1, the protocol was changed again to send the
785 errno back as a string (for portability between differing Un*xes).
786
787 =item Ambiguity between devices and paths
788
789 There is a subtle ambiguity in the API between a device name
790 (eg. C</dev/sdb2>) and a similar pathname.  A file might just happen
791 to be called C<sdb2> in the directory C</dev> (consider some non-Unix
792 VM image).
793
794 In the current API we usually resolve this ambiguity by having two
795 separate calls, for example L</guestfs_checksum> and
796 L</guestfs_checksum_device>.  Some API calls are ambiguous and
797 (incorrectly) resolve the problem by detecting if the path supplied
798 begins with C</dev/>.
799
800 To avoid both the ambiguity and the need to duplicate some calls, we
801 could make paths/devices into structured names.  One way to do this
802 would be to use a notation like grub (C<hd(0,0)>), although nobody
803 really likes this aspect of grub.  Another way would be to use a
804 structured type, equivalent to this OCaml type:
805
806  type path = Path of string | Device of int | Partition of int * int
807
808 which would allow you to pass arguments like:
809
810  Path "/foo/bar"
811  Device 1            (* /dev/sdb, or perhaps /dev/sda *)
812  Partition (1, 2)    (* /dev/sdb2 (or is it /dev/sda2 or /dev/sdb3?) *)
813  Path "/dev/sdb2"    (* not a device *)
814
815 As you can see there are still problems to resolve even with this
816 representation.  Also consider how it might work in guestfish.
817
818 =back
819
820 =head2 PROTOCOL LIMITS
821
822 Internally libguestfs uses a message-based protocol to pass API calls
823 and their responses to and from a small "appliance" (see L</INTERNALS>
824 for plenty more detail about this).  The maximum message size used by
825 the protocol is slightly less than 4 MB.  For some API calls you may
826 need to be aware of this limit.  The API calls which may be affected
827 are individually documented, with a link back to this section of the
828 documentation.
829
830 A simple call such as L</guestfs_cat> returns its result (the file
831 data) in a simple string.  Because this string is at some point
832 internally encoded as a message, the maximum size that it can return
833 is slightly under 4 MB.  If the requested file is larger than this
834 then you will get an error.
835
836 In order to transfer large files into and out of the guest filesystem,
837 you need to use particular calls that support this.  The sections
838 L</UPLOADING> and L</DOWNLOADING> document how to do this.
839
840 You might also consider mounting the disk image using our FUSE
841 filesystem support (L<guestmount(1)>).
842
843 =head2 KEYS AND PASSPHRASES
844
845 Certain libguestfs calls take a parameter that contains sensitive key
846 material, passed in as a C string.
847
848 In the future we would hope to change the libguestfs implementation so
849 that keys are L<mlock(2)>-ed into physical RAM, and thus can never end
850 up in swap.  However this is I<not> done at the moment, because of the
851 complexity of such an implementation.
852
853 Therefore you should be aware that any key parameter you pass to
854 libguestfs might end up being written out to the swap partition.  If
855 this is a concern, scrub the swap partition or don't use libguestfs on
856 encrypted devices.
857
858 =head1 CONNECTION MANAGEMENT
859
860 =head2 guestfs_h *
861
862 C<guestfs_h> is the opaque type representing a connection handle.
863 Create a handle by calling L</guestfs_create>.  Call L</guestfs_close>
864 to free the handle and release all resources used.
865
866 For information on using multiple handles and threads, see the section
867 L</MULTIPLE HANDLES AND MULTIPLE THREADS> below.
868
869 =head2 guestfs_create
870
871  guestfs_h *guestfs_create (void);
872
873 Create a connection handle.
874
875 You have to call L</guestfs_add_drive_opts> (or one of the equivalent
876 calls) on the handle at least once.
877
878 This function returns a non-NULL pointer to a handle on success or
879 NULL on error.
880
881 After configuring the handle, you have to call L</guestfs_launch>.
882
883 You may also want to configure error handling for the handle.  See
884 L</ERROR HANDLING> section below.
885
886 =head2 guestfs_close
887
888  void guestfs_close (guestfs_h *g);
889
890 This closes the connection handle and frees up all resources used.
891
892 =head1 ERROR HANDLING
893
894 The convention in all functions that return C<int> is that they return
895 C<-1> to indicate an error.  You can get additional information on
896 errors by calling L</guestfs_last_error> and/or by setting up an error
897 handler with L</guestfs_set_error_handler>.
898
899 The default error handler prints the information string to C<stderr>.
900
901 Out of memory errors are handled differently.  The default action is
902 to call L<abort(3)>.  If this is undesirable, then you can set a
903 handler using L</guestfs_set_out_of_memory_handler>.
904
905 =head2 guestfs_last_error
906
907  const char *guestfs_last_error (guestfs_h *g);
908
909 This returns the last error message that happened on C<g>.  If
910 there has not been an error since the handle was created, then this
911 returns C<NULL>.
912
913 The lifetime of the returned string is until the next error occurs, or
914 L</guestfs_close> is called.
915
916 The error string is not localized (ie. is always in English), because
917 this makes searching for error messages in search engines give the
918 largest number of results.
919
920 =head2 guestfs_set_error_handler
921
922  typedef void (*guestfs_error_handler_cb) (guestfs_h *g,
923                                            void *opaque,
924                                            const char *msg);
925  void guestfs_set_error_handler (guestfs_h *g,
926                                  guestfs_error_handler_cb cb,
927                                  void *opaque);
928
929 The callback C<cb> will be called if there is an error.  The
930 parameters passed to the callback are an opaque data pointer and the
931 error message string.
932
933 Note that the message string C<msg> is freed as soon as the callback
934 function returns, so if you want to stash it somewhere you must make
935 your own copy.
936
937 The default handler prints messages on C<stderr>.
938
939 If you set C<cb> to C<NULL> then I<no> handler is called.
940
941 =head2 guestfs_get_error_handler
942
943  guestfs_error_handler_cb guestfs_get_error_handler (guestfs_h *g,
944                                                      void **opaque_rtn);
945
946 Returns the current error handler callback.
947
948 =head2 guestfs_set_out_of_memory_handler
949
950  typedef void (*guestfs_abort_cb) (void);
951  int guestfs_set_out_of_memory_handler (guestfs_h *g,
952                                         guestfs_abort_cb);
953
954 The callback C<cb> will be called if there is an out of memory
955 situation.  I<Note this callback must not return>.
956
957 The default is to call L<abort(3)>.
958
959 You cannot set C<cb> to C<NULL>.  You can't ignore out of memory
960 situations.
961
962 =head2 guestfs_get_out_of_memory_handler
963
964  guestfs_abort_fn guestfs_get_out_of_memory_handler (guestfs_h *g);
965
966 This returns the current out of memory handler.
967
968 =head1 PATH
969
970 Libguestfs needs a kernel and initrd.img, which it finds by looking
971 along an internal path.
972
973 By default it looks for these in the directory C<$libdir/guestfs>
974 (eg. C</usr/local/lib/guestfs> or C</usr/lib64/guestfs>).
975
976 Use L</guestfs_set_path> or set the environment variable
977 L</LIBGUESTFS_PATH> to change the directories that libguestfs will
978 search in.  The value is a colon-separated list of paths.  The current
979 directory is I<not> searched unless the path contains an empty element
980 or C<.>.  For example C<LIBGUESTFS_PATH=:/usr/lib/guestfs> would
981 search the current directory and then C</usr/lib/guestfs>.
982
983 =head1 HIGH-LEVEL API ACTIONS
984
985 =head2 ABI GUARANTEE
986
987 We guarantee the libguestfs ABI (binary interface), for public,
988 high-level actions as outlined in this section.  Although we will
989 deprecate some actions, for example if they get replaced by newer
990 calls, we will keep the old actions forever.  This allows you the
991 developer to program in confidence against the libguestfs API.
992
993 @ACTIONS@
994
995 =head1 STRUCTURES
996
997 @STRUCTS@
998
999 =head1 AVAILABILITY
1000
1001 =head2 GROUPS OF FUNCTIONALITY IN THE APPLIANCE
1002
1003 Using L</guestfs_available> you can test availability of
1004 the following groups of functions.  This test queries the
1005 appliance to see if the appliance you are currently using
1006 supports the functionality.
1007
1008 @AVAILABILITY@
1009
1010 =head2 GUESTFISH supported COMMAND
1011
1012 In L<guestfish(3)> there is a handy interactive command
1013 C<supported> which prints out the available groups and
1014 whether they are supported by this build of libguestfs.
1015 Note however that you have to do C<run> first.
1016
1017 =head2 SINGLE CALLS AT COMPILE TIME
1018
1019 Since version 1.5.8, C<E<lt>guestfs.hE<gt>> defines symbols
1020 for each C API function, such as:
1021
1022  #define LIBGUESTFS_HAVE_DD 1
1023
1024 if L</guestfs_dd> is available.
1025
1026 Before version 1.5.8, if you needed to test whether a single
1027 libguestfs function is available at compile time, we recommended using
1028 build tools such as autoconf or cmake.  For example in autotools you
1029 could use:
1030
1031  AC_CHECK_LIB([guestfs],[guestfs_create])
1032  AC_CHECK_FUNCS([guestfs_dd])
1033
1034 which would result in C<HAVE_GUESTFS_DD> being either defined
1035 or not defined in your program.
1036
1037 =head2 SINGLE CALLS AT RUN TIME
1038
1039 Testing at compile time doesn't guarantee that a function really
1040 exists in the library.  The reason is that you might be dynamically
1041 linked against a previous I<libguestfs.so> (dynamic library)
1042 which doesn't have the call.  This situation unfortunately results
1043 in a segmentation fault, which is a shortcoming of the C dynamic
1044 linking system itself.
1045
1046 You can use L<dlopen(3)> to test if a function is available
1047 at run time, as in this example program (note that you still
1048 need the compile time check as well):
1049
1050  #include <stdio.h>
1051  #include <stdlib.h>
1052  #include <unistd.h>
1053  #include <dlfcn.h>
1054  #include <guestfs.h>
1055  
1056  main ()
1057  {
1058  #ifdef LIBGUESTFS_HAVE_DD
1059    void *dl;
1060    int has_function;
1061  
1062    /* Test if the function guestfs_dd is really available. */
1063    dl = dlopen (NULL, RTLD_LAZY);
1064    if (!dl) {
1065      fprintf (stderr, "dlopen: %s\n", dlerror ());
1066      exit (EXIT_FAILURE);
1067    }
1068    has_function = dlsym (dl, "guestfs_dd") != NULL;
1069    dlclose (dl);
1070  
1071    if (!has_function)
1072      printf ("this libguestfs.so does NOT have guestfs_dd function\n");
1073    else {
1074      printf ("this libguestfs.so has guestfs_dd function\n");
1075      /* Now it's safe to call
1076      guestfs_dd (g, "foo", "bar");
1077      */
1078    }
1079  #else
1080    printf ("guestfs_dd function was not found at compile time\n");
1081  #endif
1082   }
1083
1084 You may think the above is an awful lot of hassle, and it is.
1085 There are other ways outside of the C linking system to ensure
1086 that this kind of incompatibility never arises, such as using
1087 package versioning:
1088
1089  Requires: libguestfs >= 1.0.80
1090
1091 =head1 CALLS WITH OPTIONAL ARGUMENTS
1092
1093 A recent feature of the API is the introduction of calls which take
1094 optional arguments.  In C these are declared 3 ways.  The main way is
1095 as a call which takes variable arguments (ie. C<...>), as in this
1096 example:
1097
1098  int guestfs_add_drive_opts (guestfs_h *g, const char *filename, ...);
1099
1100 Call this with a list of optional arguments, terminated by C<-1>.
1101 So to call with no optional arguments specified:
1102
1103  guestfs_add_drive_opts (g, filename, -1);
1104
1105 With a single optional argument:
1106
1107  guestfs_add_drive_opts (g, filename,
1108                          GUESTFS_ADD_DRIVE_OPTS_FORMAT, "qcow2",
1109                          -1);
1110
1111 With two:
1112
1113  guestfs_add_drive_opts (g, filename,
1114                          GUESTFS_ADD_DRIVE_OPTS_FORMAT, "qcow2",
1115                          GUESTFS_ADD_DRIVE_OPTS_READONLY, 1,
1116                          -1);
1117
1118 and so forth.  Don't forget the terminating C<-1> otherwise
1119 Bad Things will happen!
1120
1121 =head2 USING va_list FOR OPTIONAL ARGUMENTS
1122
1123 The second variant has the same name with the suffix C<_va>, which
1124 works the same way but takes a C<va_list>.  See the C manual for
1125 details.  For the example function, this is declared:
1126
1127  int guestfs_add_drive_opts_va (guestfs_h *g, const char *filename,
1128                                 va_list args);
1129
1130 =head2 CONSTRUCTING OPTIONAL ARGUMENTS
1131
1132 The third variant is useful where you need to construct these
1133 calls.  You pass in a structure where you fill in the optional
1134 fields.  The structure has a bitmask as the first element which
1135 you must set to indicate which fields you have filled in.  For
1136 our example function the structure and call are declared:
1137
1138  struct guestfs_add_drive_opts_argv {
1139    uint64_t bitmask;
1140    int readonly;
1141    const char *format;
1142    /* ... */
1143  };
1144  int guestfs_add_drive_opts_argv (guestfs_h *g, const char *filename,
1145               const struct guestfs_add_drive_opts_argv *optargs);
1146
1147 You could call it like this:
1148
1149  struct guestfs_add_drive_opts_argv optargs = {
1150    .bitmask = GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK |
1151               GUESTFS_ADD_DRIVE_OPTS_FORMAT_BITMASK,
1152    .readonly = 1,
1153    .format = "qcow2"
1154  };
1155  
1156  guestfs_add_drive_opts_argv (g, filename, &optargs);
1157
1158 Notes:
1159
1160 =over 4
1161
1162 =item *
1163
1164 The C<_BITMASK> suffix on each option name when specifying the
1165 bitmask.
1166
1167 =item *
1168
1169 You do not need to fill in all fields of the structure.
1170
1171 =item *
1172
1173 There must be a one-to-one correspondence between fields of the
1174 structure that are filled in, and bits set in the bitmask.
1175
1176 =back
1177
1178 =head2 OPTIONAL ARGUMENTS IN OTHER LANGUAGES
1179
1180 In other languages, optional arguments are expressed in the
1181 way that is natural for that language.  We refer you to the
1182 language-specific documentation for more details on that.
1183
1184 For guestfish, see L<guestfish(1)/OPTIONAL ARGUMENTS>.
1185
1186 =begin html
1187
1188 <!-- old anchor for the next section -->
1189 <a name="state_machine_and_low_level_event_api"/>
1190
1191 =end html
1192
1193 =head1 ARCHITECTURE
1194
1195 Internally, libguestfs is implemented by running an appliance (a
1196 special type of small virtual machine) using L<qemu(1)>.  Qemu runs as
1197 a child process of the main program.
1198
1199   ___________________
1200  /                   \
1201  | main program      |
1202  |                   |
1203  |                   |           child process / appliance
1204  |                   |           __________________________
1205  |                   |          / qemu                     \
1206  +-------------------+   RPC    |      +-----------------+ |
1207  | libguestfs     <--------------------> guestfsd        | |
1208  |                   |          |      +-----------------+ |
1209  \___________________/          |      | Linux kernel    | |
1210                                 |      +--^--------------+ |
1211                                 \_________|________________/
1212                                           |
1213                                    _______v______
1214                                   /              \
1215                                   | Device or    |
1216                                   | disk image   |
1217                                   \______________/
1218
1219 The library, linked to the main program, creates the child process and
1220 hence the appliance in the L</guestfs_launch> function.
1221
1222 Inside the appliance is a Linux kernel and a complete stack of
1223 userspace tools (such as LVM and ext2 programs) and a small
1224 controlling daemon called L</guestfsd>.  The library talks to
1225 L</guestfsd> using remote procedure calls (RPC).  There is a mostly
1226 one-to-one correspondence between libguestfs API calls and RPC calls
1227 to the daemon.  Lastly the disk image(s) are attached to the qemu
1228 process which translates device access by the appliance's Linux kernel
1229 into accesses to the image.
1230
1231 A common misunderstanding is that the appliance "is" the virtual
1232 machine.  Although the disk image you are attached to might also be
1233 used by some virtual machine, libguestfs doesn't know or care about
1234 this.  (But you will care if both libguestfs's qemu process and your
1235 virtual machine are trying to update the disk image at the same time,
1236 since these usually results in massive disk corruption).
1237
1238 =head1 STATE MACHINE
1239
1240 libguestfs uses a state machine to model the child process:
1241
1242                          |
1243                     guestfs_create
1244                          |
1245                          |
1246                      ____V_____
1247                     /          \
1248                     |  CONFIG  |
1249                     \__________/
1250                      ^ ^   ^  \
1251                     /  |    \  \ guestfs_launch
1252                    /   |    _\__V______
1253                   /    |   /           \
1254                  /     |   | LAUNCHING |
1255                 /      |   \___________/
1256                /       |       /
1257               /        |  guestfs_launch
1258              /         |     /
1259     ______  /        __|____V
1260    /      \ ------> /        \
1261    | BUSY |         | READY  |
1262    \______/ <------ \________/
1263
1264 The normal transitions are (1) CONFIG (when the handle is created, but
1265 there is no child process), (2) LAUNCHING (when the child process is
1266 booting up), (3) alternating between READY and BUSY as commands are
1267 issued to, and carried out by, the child process.
1268
1269 The guest may be killed by L</guestfs_kill_subprocess>, or may die
1270 asynchronously at any time (eg. due to some internal error), and that
1271 causes the state to transition back to CONFIG.
1272
1273 Configuration commands for qemu such as L</guestfs_add_drive> can only
1274 be issued when in the CONFIG state.
1275
1276 The API offers one call that goes from CONFIG through LAUNCHING to
1277 READY.  L</guestfs_launch> blocks until the child process is READY to
1278 accept commands (or until some failure or timeout).
1279 L</guestfs_launch> internally moves the state from CONFIG to LAUNCHING
1280 while it is running.
1281
1282 API actions such as L</guestfs_mount> can only be issued when in the
1283 READY state.  These API calls block waiting for the command to be
1284 carried out (ie. the state to transition to BUSY and then back to
1285 READY).  There are no non-blocking versions, and no way to issue more
1286 than one command per handle at the same time.
1287
1288 Finally, the child process sends asynchronous messages back to the
1289 main program, such as kernel log messages.  You can register a
1290 callback to receive these messages.
1291
1292 =head2 SETTING CALLBACKS TO HANDLE EVENTS
1293
1294 The child process generates events in some situations.  Current events
1295 include: receiving a log message, the child process exits.
1296
1297 Use the C<guestfs_set_*_callback> functions to set a callback for
1298 different types of events.
1299
1300 Only I<one callback of each type> can be registered for each handle.
1301 Calling C<guestfs_set_*_callback> again overwrites the previous
1302 callback of that type.  Cancel all callbacks of this type by calling
1303 this function with C<cb> set to C<NULL>.
1304
1305 =head2 guestfs_set_log_message_callback
1306
1307  typedef void (*guestfs_log_message_cb) (guestfs_h *g, void *opaque,
1308                                          char *buf, int len);
1309  void guestfs_set_log_message_callback (guestfs_h *g,
1310                                         guestfs_log_message_cb cb,
1311                                         void *opaque);
1312
1313 The callback function C<cb> will be called whenever qemu or the guest
1314 writes anything to the console.
1315
1316 Use this function to capture kernel messages and similar.
1317
1318 Normally there is no log message handler, and log messages are just
1319 discarded.
1320
1321 =head2 guestfs_set_subprocess_quit_callback
1322
1323  typedef void (*guestfs_subprocess_quit_cb) (guestfs_h *g, void *opaque);
1324  void guestfs_set_subprocess_quit_callback (guestfs_h *g,
1325                                             guestfs_subprocess_quit_cb cb,
1326                                             void *opaque);
1327
1328 The callback function C<cb> will be called when the child process
1329 quits, either asynchronously or if killed by
1330 L</guestfs_kill_subprocess>.  (This corresponds to a transition from
1331 any state to the CONFIG state).
1332
1333 =head2 guestfs_set_launch_done_callback
1334
1335  typedef void (*guestfs_launch_done_cb) (guestfs_h *g, void *opaque);
1336  void guestfs_set_launch_done_callback (guestfs_h *g,
1337                                         guestfs_launch_done_cb cb,
1338                                         void *opaque);
1339
1340 The callback function C<cb> will be called when the child process
1341 becomes ready first time after it has been launched.  (This
1342 corresponds to a transition from LAUNCHING to the READY state).
1343
1344 =head2 guestfs_set_close_callback
1345
1346  typedef void (*guestfs_close_cb) (guestfs_h *g, void *opaque);
1347  void guestfs_set_close_callback (guestfs_h *g,
1348                                   guestfs_close_cb cb,
1349                                   void *opaque);
1350
1351 The callback function C<cb> will be called while the handle
1352 is being closed (synchronously from L</guestfs_close>).
1353
1354 Note that libguestfs installs an L<atexit(3)> handler to try to
1355 clean up handles that are open when the program exits.  This
1356 means that this callback might be called indirectly from
1357 L<exit(3)>, which can cause unexpected problems in higher-level
1358 languages (eg. if your HLL interpreter has already been cleaned
1359 up by the time this is called, and if your callback then jumps
1360 into some HLL function).
1361
1362 =head2 guestfs_set_progress_callback
1363
1364  typedef void (*guestfs_progress_cb) (guestfs_h *g, void *opaque,
1365                                       int proc_nr, int serial,
1366                                       uint64_t position, uint64_t total);
1367  void guestfs_set_progress_callback (guestfs_h *g,
1368                                      guestfs_progress_cb cb,
1369                                      void *opaque);
1370
1371 Some long-running operations can generate progress messages.  If
1372 this callback is registered, then it will be called each time a
1373 progress message is generated (usually two seconds after the
1374 operation started, and three times per second thereafter until
1375 it completes, although the frequency may change in future versions).
1376
1377 The callback receives two numbers: C<position> and C<total>.
1378 The units of C<total> are not defined, although for some
1379 operations C<total> may relate in some way to the amount of
1380 data to be transferred (eg. in bytes or megabytes), and
1381 C<position> may be the portion which has been transferred.
1382
1383 The only defined and stable parts of the API are:
1384
1385 =over 4
1386
1387 =item *
1388
1389 The callback can display to the user some type of progress bar or
1390 indicator which shows the ratio of C<position>:C<total>.
1391
1392 =item *
1393
1394 0 E<lt>= C<position> E<lt>= C<total>
1395
1396 =item *
1397
1398 If any progress notification is sent during a call, then a final
1399 progress notification is always sent when C<position> = C<total>.
1400
1401 This is to simplify caller code, so callers can easily set the
1402 progress indicator to "100%" at the end of the operation, without
1403 requiring special code to detect this case.
1404
1405 =back
1406
1407 The callback also receives the procedure number and serial number of
1408 the call.  These are only useful for debugging protocol issues, and
1409 the callback can normally ignore them.  The callback may want to
1410 print these numbers in error messages or debugging messages.
1411
1412 =head1 PRIVATE DATA AREA
1413
1414 You can attach named pieces of private data to the libguestfs handle,
1415 and fetch them by name for the lifetime of the handle.  This is called
1416 the private data area and is only available from the C API.
1417
1418 To attach a named piece of data, use the following call:
1419
1420  void guestfs_set_private (guestfs_h *g, const char *key, void *data);
1421
1422 C<key> is the name to associate with this data, and C<data> is an
1423 arbitrary pointer (which can be C<NULL>).  Any previous item with the
1424 same name is overwritten.
1425
1426 You can use any C<key> you want, but names beginning with an
1427 underscore character are reserved for internal libguestfs purposes
1428 (for implementing language bindings).  It is recommended to prefix the
1429 name with some unique string to avoid collisions with other users.
1430
1431 To retrieve the pointer, use:
1432
1433  void *guestfs_get_private (guestfs_h *g, const char *key);
1434
1435 This function returns C<NULL> if either no data is found associated
1436 with C<key>, or if the user previously set the C<key>'s C<data>
1437 pointer to C<NULL>.
1438
1439 Libguestfs does not try to look at or interpret the C<data> pointer in
1440 any way.  As far as libguestfs is concerned, it need not be a valid
1441 pointer at all.  In particular, libguestfs does I<not> try to free the
1442 data when the handle is closed.  If the data must be freed, then the
1443 caller must either free it before calling L</guestfs_close> or must
1444 set up a close callback to do it (see L</guestfs_set_close_callback>,
1445 and note that only one callback can be registered for a handle).
1446
1447 The private data area is implemented using a hash table, and should be
1448 reasonably efficient for moderate numbers of keys.
1449
1450 =head1 BLOCK DEVICE NAMING
1451
1452 In the kernel there is now quite a profusion of schemata for naming
1453 block devices (in this context, by I<block device> I mean a physical
1454 or virtual hard drive).  The original Linux IDE driver used names
1455 starting with C</dev/hd*>.  SCSI devices have historically used a
1456 different naming scheme, C</dev/sd*>.  When the Linux kernel I<libata>
1457 driver became a popular replacement for the old IDE driver
1458 (particularly for SATA devices) those devices also used the
1459 C</dev/sd*> scheme.  Additionally we now have virtual machines with
1460 paravirtualized drivers.  This has created several different naming
1461 systems, such as C</dev/vd*> for virtio disks and C</dev/xvd*> for Xen
1462 PV disks.
1463
1464 As discussed above, libguestfs uses a qemu appliance running an
1465 embedded Linux kernel to access block devices.  We can run a variety
1466 of appliances based on a variety of Linux kernels.
1467
1468 This causes a problem for libguestfs because many API calls use device
1469 or partition names.  Working scripts and the recipe (example) scripts
1470 that we make available over the internet could fail if the naming
1471 scheme changes.
1472
1473 Therefore libguestfs defines C</dev/sd*> as the I<standard naming
1474 scheme>.  Internally C</dev/sd*> names are translated, if necessary,
1475 to other names as required.  For example, under RHEL 5 which uses the
1476 C</dev/hd*> scheme, any device parameter C</dev/sda2> is translated to
1477 C</dev/hda2> transparently.
1478
1479 Note that this I<only> applies to parameters.  The
1480 L</guestfs_list_devices>, L</guestfs_list_partitions> and similar calls
1481 return the true names of the devices and partitions as known to the
1482 appliance.
1483
1484 =head2 ALGORITHM FOR BLOCK DEVICE NAME TRANSLATION
1485
1486 Usually this translation is transparent.  However in some (very rare)
1487 cases you may need to know the exact algorithm.  Such cases include
1488 where you use L</guestfs_config> to add a mixture of virtio and IDE
1489 devices to the qemu-based appliance, so have a mixture of C</dev/sd*>
1490 and C</dev/vd*> devices.
1491
1492 The algorithm is applied only to I<parameters> which are known to be
1493 either device or partition names.  Return values from functions such
1494 as L</guestfs_list_devices> are never changed.
1495
1496 =over 4
1497
1498 =item *
1499
1500 Is the string a parameter which is a device or partition name?
1501
1502 =item *
1503
1504 Does the string begin with C</dev/sd>?
1505
1506 =item *
1507
1508 Does the named device exist?  If so, we use that device.
1509 However if I<not> then we continue with this algorithm.
1510
1511 =item *
1512
1513 Replace initial C</dev/sd> string with C</dev/hd>.
1514
1515 For example, change C</dev/sda2> to C</dev/hda2>.
1516
1517 If that named device exists, use it.  If not, continue.
1518
1519 =item *
1520
1521 Replace initial C</dev/sd> string with C</dev/vd>.
1522
1523 If that named device exists, use it.  If not, return an error.
1524
1525 =back
1526
1527 =head2 PORTABILITY CONCERNS
1528
1529 Although the standard naming scheme and automatic translation is
1530 useful for simple programs and guestfish scripts, for larger programs
1531 it is best not to rely on this mechanism.
1532
1533 Where possible for maximum future portability programs using
1534 libguestfs should use these future-proof techniques:
1535
1536 =over 4
1537
1538 =item *
1539
1540 Use L</guestfs_list_devices> or L</guestfs_list_partitions> to list
1541 actual device names, and then use those names directly.
1542
1543 Since those device names exist by definition, they will never be
1544 translated.
1545
1546 =item *
1547
1548 Use higher level ways to identify filesystems, such as LVM names,
1549 UUIDs and filesystem labels.
1550
1551 =back
1552
1553 =head1 INTERNALS
1554
1555 =head2 COMMUNICATION PROTOCOL
1556
1557 Don't rely on using this protocol directly.  This section documents
1558 how it currently works, but it may change at any time.
1559
1560 The protocol used to talk between the library and the daemon running
1561 inside the qemu virtual machine is a simple RPC mechanism built on top
1562 of XDR (RFC 1014, RFC 1832, RFC 4506).
1563
1564 The detailed format of structures is in C<src/guestfs_protocol.x>
1565 (note: this file is automatically generated).
1566
1567 There are two broad cases, ordinary functions that don't have any
1568 C<FileIn> and C<FileOut> parameters, which are handled with very
1569 simple request/reply messages.  Then there are functions that have any
1570 C<FileIn> or C<FileOut> parameters, which use the same request and
1571 reply messages, but they may also be followed by files sent using a
1572 chunked encoding.
1573
1574 =head3 ORDINARY FUNCTIONS (NO FILEIN/FILEOUT PARAMS)
1575
1576 For ordinary functions, the request message is:
1577
1578  total length (header + arguments,
1579       but not including the length word itself)
1580  struct guestfs_message_header (encoded as XDR)
1581  struct guestfs_<foo>_args (encoded as XDR)
1582
1583 The total length field allows the daemon to allocate a fixed size
1584 buffer into which it slurps the rest of the message.  As a result, the
1585 total length is limited to C<GUESTFS_MESSAGE_MAX> bytes (currently
1586 4MB), which means the effective size of any request is limited to
1587 somewhere under this size.
1588
1589 Note also that many functions don't take any arguments, in which case
1590 the C<guestfs_I<foo>_args> is completely omitted.
1591
1592 The header contains the procedure number (C<guestfs_proc>) which is
1593 how the receiver knows what type of args structure to expect, or none
1594 at all.
1595
1596 The reply message for ordinary functions is:
1597
1598  total length (header + ret,
1599       but not including the length word itself)
1600  struct guestfs_message_header (encoded as XDR)
1601  struct guestfs_<foo>_ret (encoded as XDR)
1602
1603 As above the C<guestfs_I<foo>_ret> structure may be completely omitted
1604 for functions that return no formal return values.
1605
1606 As above the total length of the reply is limited to
1607 C<GUESTFS_MESSAGE_MAX>.
1608
1609 In the case of an error, a flag is set in the header, and the reply
1610 message is slightly changed:
1611
1612  total length (header + error,
1613       but not including the length word itself)
1614  struct guestfs_message_header (encoded as XDR)
1615  struct guestfs_message_error (encoded as XDR)
1616
1617 The C<guestfs_message_error> structure contains the error message as a
1618 string.
1619
1620 =head3 FUNCTIONS THAT HAVE FILEIN PARAMETERS
1621
1622 A C<FileIn> parameter indicates that we transfer a file I<into> the
1623 guest.  The normal request message is sent (see above).  However this
1624 is followed by a sequence of file chunks.
1625
1626  total length (header + arguments,
1627       but not including the length word itself,
1628       and not including the chunks)
1629  struct guestfs_message_header (encoded as XDR)
1630  struct guestfs_<foo>_args (encoded as XDR)
1631  sequence of chunks for FileIn param #0
1632  sequence of chunks for FileIn param #1 etc.
1633
1634 The "sequence of chunks" is:
1635
1636  length of chunk (not including length word itself)
1637  struct guestfs_chunk (encoded as XDR)
1638  length of chunk
1639  struct guestfs_chunk (encoded as XDR)
1640    ...
1641  length of chunk
1642  struct guestfs_chunk (with data.data_len == 0)
1643
1644 The final chunk has the C<data_len> field set to zero.  Additionally a
1645 flag is set in the final chunk to indicate either successful
1646 completion or early cancellation.
1647
1648 At time of writing there are no functions that have more than one
1649 FileIn parameter.  However this is (theoretically) supported, by
1650 sending the sequence of chunks for each FileIn parameter one after
1651 another (from left to right).
1652
1653 Both the library (sender) I<and> the daemon (receiver) may cancel the
1654 transfer.  The library does this by sending a chunk with a special
1655 flag set to indicate cancellation.  When the daemon sees this, it
1656 cancels the whole RPC, does I<not> send any reply, and goes back to
1657 reading the next request.
1658
1659 The daemon may also cancel.  It does this by writing a special word
1660 C<GUESTFS_CANCEL_FLAG> to the socket.  The library listens for this
1661 during the transfer, and if it gets it, it will cancel the transfer
1662 (it sends a cancel chunk).  The special word is chosen so that even if
1663 cancellation happens right at the end of the transfer (after the
1664 library has finished writing and has started listening for the reply),
1665 the "spurious" cancel flag will not be confused with the reply
1666 message.
1667
1668 This protocol allows the transfer of arbitrary sized files (no 32 bit
1669 limit), and also files where the size is not known in advance
1670 (eg. from pipes or sockets).  However the chunks are rather small
1671 (C<GUESTFS_MAX_CHUNK_SIZE>), so that neither the library nor the
1672 daemon need to keep much in memory.
1673
1674 =head3 FUNCTIONS THAT HAVE FILEOUT PARAMETERS
1675
1676 The protocol for FileOut parameters is exactly the same as for FileIn
1677 parameters, but with the roles of daemon and library reversed.
1678
1679  total length (header + ret,
1680       but not including the length word itself,
1681       and not including the chunks)
1682  struct guestfs_message_header (encoded as XDR)
1683  struct guestfs_<foo>_ret (encoded as XDR)
1684  sequence of chunks for FileOut param #0
1685  sequence of chunks for FileOut param #1 etc.
1686
1687 =head3 INITIAL MESSAGE
1688
1689 When the daemon launches it sends an initial word
1690 (C<GUESTFS_LAUNCH_FLAG>) which indicates that the guest and daemon is
1691 alive.  This is what L</guestfs_launch> waits for.
1692
1693 =head3 PROGRESS NOTIFICATION MESSAGES
1694
1695 The daemon may send progress notification messages at any time.  These
1696 are distinguished by the normal length word being replaced by
1697 C<GUESTFS_PROGRESS_FLAG>, followed by a fixed size progress message.
1698
1699 The library turns them into progress callbacks (see
1700 C<guestfs_set_progress_callback>) if there is a callback registered,
1701 or discards them if not.
1702
1703 The daemon self-limits the frequency of progress messages it sends
1704 (see C<daemon/proto.c:notify_progress>).  Not all calls generate
1705 progress messages.
1706
1707 =head1 MULTIPLE HANDLES AND MULTIPLE THREADS
1708
1709 All high-level libguestfs actions are synchronous.  If you want
1710 to use libguestfs asynchronously then you must create a thread.
1711
1712 Only use the handle from a single thread.  Either use the handle
1713 exclusively from one thread, or provide your own mutex so that two
1714 threads cannot issue calls on the same handle at the same time.
1715
1716 See the graphical program guestfs-browser for one possible
1717 architecture for multithreaded programs using libvirt and libguestfs.
1718
1719 =head1 QEMU WRAPPERS
1720
1721 If you want to compile your own qemu, run qemu from a non-standard
1722 location, or pass extra arguments to qemu, then you can write a
1723 shell-script wrapper around qemu.
1724
1725 There is one important rule to remember: you I<must C<exec qemu>> as
1726 the last command in the shell script (so that qemu replaces the shell
1727 and becomes the direct child of the libguestfs-using program).  If you
1728 don't do this, then the qemu process won't be cleaned up correctly.
1729
1730 Here is an example of a wrapper, where I have built my own copy of
1731 qemu from source:
1732
1733  #!/bin/sh -
1734  qemudir=/home/rjones/d/qemu
1735  exec $qemudir/x86_64-softmmu/qemu-system-x86_64 -L $qemudir/pc-bios "$@"
1736
1737 Save this script as C</tmp/qemu.wrapper> (or wherever), C<chmod +x>,
1738 and then use it by setting the LIBGUESTFS_QEMU environment variable.
1739 For example:
1740
1741  LIBGUESTFS_QEMU=/tmp/qemu.wrapper guestfish
1742
1743 Note that libguestfs also calls qemu with the -help and -version
1744 options in order to determine features.
1745
1746 =head1 LIBGUESTFS VERSION NUMBERS
1747
1748 Since April 2010, libguestfs has started to make separate development
1749 and stable releases, along with corresponding branches in our git
1750 repository.  These separate releases can be identified by version
1751 number:
1752
1753                  even numbers for stable: 1.2.x, 1.4.x, ...
1754        .-------- odd numbers for development: 1.3.x, 1.5.x, ...
1755        |
1756        v
1757  1  .  3  .  5
1758  ^           ^
1759  |           |
1760  |           `-------- sub-version
1761  |
1762  `------ always '1' because we don't change the ABI
1763
1764 Thus "1.3.5" is the 5th update to the development branch "1.3".
1765
1766 As time passes we cherry pick fixes from the development branch and
1767 backport those into the stable branch, the effect being that the
1768 stable branch should get more stable and less buggy over time.  So the
1769 stable releases are ideal for people who don't need new features but
1770 would just like the software to work.
1771
1772 Our criteria for backporting changes are:
1773
1774 =over 4
1775
1776 =item *
1777
1778 Documentation changes which don't affect any code are
1779 backported unless the documentation refers to a future feature
1780 which is not in stable.
1781
1782 =item *
1783
1784 Bug fixes which are not controversial, fix obvious problems, and
1785 have been well tested are backported.
1786
1787 =item *
1788
1789 Simple rearrangements of code which shouldn't affect how it works get
1790 backported.  This is so that the code in the two branches doesn't get
1791 too far out of step, allowing us to backport future fixes more easily.
1792
1793 =item *
1794
1795 We I<don't> backport new features, new APIs, new tools etc, except in
1796 one exceptional case: the new feature is required in order to
1797 implement an important bug fix.
1798
1799 =back
1800
1801 A new stable branch starts when we think the new features in
1802 development are substantial and compelling enough over the current
1803 stable branch to warrant it.  When that happens we create new stable
1804 and development versions 1.N.0 and 1.(N+1).0 [N is even].  The new
1805 dot-oh release won't necessarily be so stable at this point, but by
1806 backporting fixes from development, that branch will stabilize over
1807 time.
1808
1809 =head1 ENVIRONMENT VARIABLES
1810
1811 =over 4
1812
1813 =item LIBGUESTFS_APPEND
1814
1815 Pass additional options to the guest kernel.
1816
1817 =item LIBGUESTFS_DEBUG
1818
1819 Set C<LIBGUESTFS_DEBUG=1> to enable verbose messages.  This
1820 has the same effect as calling C<guestfs_set_verbose (g, 1)>.
1821
1822 =item LIBGUESTFS_MEMSIZE
1823
1824 Set the memory allocated to the qemu process, in megabytes.  For
1825 example:
1826
1827  LIBGUESTFS_MEMSIZE=700
1828
1829 =item LIBGUESTFS_PATH
1830
1831 Set the path that libguestfs uses to search for kernel and initrd.img.
1832 See the discussion of paths in section PATH above.
1833
1834 =item LIBGUESTFS_QEMU
1835
1836 Set the default qemu binary that libguestfs uses.  If not set, then
1837 the qemu which was found at compile time by the configure script is
1838 used.
1839
1840 See also L</QEMU WRAPPERS> above.
1841
1842 =item LIBGUESTFS_TRACE
1843
1844 Set C<LIBGUESTFS_TRACE=1> to enable command traces.  This
1845 has the same effect as calling C<guestfs_set_trace (g, 1)>.
1846
1847 =item TMPDIR
1848
1849 Location of temporary directory, defaults to C</tmp>.
1850
1851 If libguestfs was compiled to use the supermin appliance then the
1852 real appliance is cached in this directory, shared between all
1853 handles belonging to the same EUID.  You can use C<$TMPDIR> to
1854 configure another directory to use in case C</tmp> is not large
1855 enough.
1856
1857 =back
1858
1859 =head1 SEE ALSO
1860
1861 L<guestfish(1)>,
1862 L<guestmount(1)>,
1863 L<virt-cat(1)>,
1864 L<virt-df(1)>,
1865 L<virt-edit(1)>,
1866 L<virt-inspector(1)>,
1867 L<virt-list-filesystems(1)>,
1868 L<virt-list-partitions(1)>,
1869 L<virt-ls(1)>,
1870 L<virt-make-fs(1)>,
1871 L<virt-rescue(1)>,
1872 L<virt-tar(1)>,
1873 L<virt-win-reg(1)>,
1874 L<qemu(1)>,
1875 L<febootstrap(1)>,
1876 L<hivex(3)>,
1877 L<http://libguestfs.org/>.
1878
1879 Tools with a similar purpose:
1880 L<fdisk(8)>,
1881 L<parted(8)>,
1882 L<kpartx(8)>,
1883 L<lvm(8)>,
1884 L<disktype(1)>.
1885
1886 =head1 BUGS
1887
1888 To get a list of bugs against libguestfs use this link:
1889
1890 L<https://bugzilla.redhat.com/buglist.cgi?component=libguestfs&product=Virtualization+Tools>
1891
1892 To report a new bug against libguestfs use this link:
1893
1894 L<https://bugzilla.redhat.com/enter_bug.cgi?component=libguestfs&product=Virtualization+Tools>
1895
1896 When reporting a bug, please check:
1897
1898 =over 4
1899
1900 =item *
1901
1902 That the bug hasn't been reported already.
1903
1904 =item *
1905
1906 That you are testing a recent version.
1907
1908 =item *
1909
1910 Describe the bug accurately, and give a way to reproduce it.
1911
1912 =item *
1913
1914 Run libguestfs-test-tool and paste the B<complete, unedited>
1915 output into the bug report.
1916
1917 =back
1918
1919 =head1 AUTHORS
1920
1921 Richard W.M. Jones (C<rjones at redhat dot com>)
1922
1923 =head1 COPYRIGHT
1924
1925 Copyright (C) 2009-2010 Red Hat Inc.
1926 L<http://libguestfs.org/>
1927
1928 This library is free software; you can redistribute it and/or
1929 modify it under the terms of the GNU Lesser General Public
1930 License as published by the Free Software Foundation; either
1931 version 2 of the License, or (at your option) any later version.
1932
1933 This library is distributed in the hope that it will be useful,
1934 but WITHOUT ANY WARRANTY; without even the implied warranty of
1935 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
1936 Lesser General Public License for more details.
1937
1938 You should have received a copy of the GNU Lesser General Public
1939 License along with this library; if not, write to the Free Software
1940 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA