guestfs - Library for accessing and modifying virtual machine images
#include <guestfs.h> guestfs_h *g = guestfs_create (); guestfs_add_drive (g, "guest.img"); guestfs_launch (g); guestfs_mount (g, "/dev/sda1", "/"); guestfs_touch (g, "/hello"); guestfs_umount (g, "/"); guestfs_sync (g); guestfs_close (g);
cc prog.c -o prog -lguestfs or: cc prog.c -o prog `pkg-config libguestfs --cflags --libs`
Libguestfs is a library for accessing and modifying guest disk images. Amongst the things this is good for: making batch configuration changes to guests, getting disk used/free statistics (see also: virt-df), migrating between virtualization systems (see also: virt-p2v), performing partial backups, performing partial guest clones, cloning guests and changing registry/UUID/hostname info, and much else besides.
Libguestfs uses Linux kernel and qemu code, and can access any type of guest filesystem that Linux and qemu can, including but not limited to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition schemes, qcow, qcow2, vmdk.
Libguestfs provides ways to enumerate guest storage (eg. partitions, LVs, what filesystem is in each LV, etc.). It can also run commands in the context of the guest. Also you can access filesystems over FUSE.
Libguestfs is a library that can be linked with C and C++ management programs (or management programs written in OCaml, Perl, Python, Ruby, Java, PHP, Haskell or C#). You can also use it from shell scripts or the command line.
You don't need to be root to use libguestfs, although obviously you do need enough permissions to access the disk images.
Libguestfs is a large API because it can do many things. For a gentle introduction, please read the API OVERVIEW section next.
This section provides a gentler overview of the libguestfs API. We also try to group API calls together, where that may not be obvious from reading about the individual calls in the main section of this manual.
Before you can use libguestfs calls, you have to create a handle.
Then you must add at least one disk image to the handle, followed by
launching the handle, then performing whatever operations you want,
and finally closing the handle. By convention we use the single
letter g
for the name of the handle variable, although of course
you can use any name you want.
The general structure of all libguestfs-using programs looks like this:
guestfs_h *g = guestfs_create (); /* Call guestfs_add_drive additional times if there are * multiple disk images. */ guestfs_add_drive (g, "guest.img"); /* Most manipulation calls won't work until you've launched * the handle 'g'. You have to do this _after_ adding drives * and _before_ other commands. */ guestfs_launch (g); /* Now you can examine what partitions, LVs etc are available. */ char **partitions = guestfs_list_partitions (g); char **logvols = guestfs_lvs (g); /* To access a filesystem in the image, you must mount it. */ guestfs_mount (g, "/dev/sda1", "/"); /* Now you can perform filesystem actions on the guest * disk image. */ guestfs_touch (g, "/hello"); /* You only need to call guestfs_sync if you have made * changes to the guest image. (But if you've made changes * then you *must* sync). See also: guestfs_umount and * guestfs_umount_all calls. */ guestfs_sync (g); /* Close the handle 'g'. */ guestfs_close (g);
The code above doesn't include any error checking. In real code you
should check return values carefully for errors. In general all
functions that return integers return -1
on error, and all
functions that return pointers return NULL
on error. See section
ERROR HANDLING below for how to handle errors, and consult the
documentation for each function call below to see precisely how they
return error indications.
The image filename ("guest.img"
in the example above) could be a
disk image from a virtual machine, a dd(1) copy of a physical hard
disk, an actual block device, or simply an empty file of zeroes that
you have created through posix_fallocate(3). Libguestfs lets you
do useful things to all of these.
The call you should use in modern code for adding drives is guestfs_add_drive_opts. To add a disk image, allowing writes, and specifying that the format is raw, do:
guestfs_add_drive_opts (g, filename, GUESTFS_ADD_DRIVE_OPTS_FORMAT, "raw", -1);
You can add a disk read-only using:
guestfs_add_drive_opts (g, filename, GUESTFS_ADD_DRIVE_OPTS_FORMAT, "raw", GUESTFS_ADD_DRIVE_OPTS_READONLY, 1, -1);
or by calling the older function guestfs_add_drive_ro. In either case libguestfs won't modify the file.
Be extremely cautious if the disk image is in use, eg. if it is being used by a virtual machine. Adding it read-write will almost certainly cause disk corruption, but adding it read-only is safe.
You must add at least one disk image, and you may add multiple disk
images. In the API, the disk images are usually referred to as
/dev/sda
(for the first one you added), /dev/sdb
(for the second
one you added), etc.
Once guestfs_launch has been called you cannot add any more images. You can call guestfs_list_devices to get a list of the device names, in the order that you added them. See also BLOCK DEVICE NAMING below.
Before you can read or write files, create directories and so on in a disk image that contains filesystems, you have to mount those filesystems using guestfs_mount. If you already know that a disk image contains (for example) one partition with a filesystem on that partition, then you can mount it directly:
guestfs_mount (g, "/dev/sda1", "/");
where /dev/sda1
means literally the first partition (1
) of the
first disk image that we added (/dev/sda
). If the disk contains
Linux LVM2 logical volumes you could refer to those instead (eg. /dev/VG/LV
).
If you are given a disk image and you don't know what it contains then you have to find out. Libguestfs can do that too: use guestfs_list_partitions and guestfs_lvs to list possible partitions and LVs, and either try mounting each to see what is mountable, or else examine them with guestfs_vfs_type or guestfs_file. Libguestfs also has a set of APIs for inspection of disk images (see INSPECTION below). But you might find it easier to look at higher level programs built on top of libguestfs, in particular virt-inspector(1).
To mount a disk image read-only, use guestfs_mount_ro. There are
several other variations of the guestfs_mount_*
call.
The majority of the libguestfs API consists of fairly low-level calls for accessing and modifying the files, directories, symlinks etc on mounted filesystems. There are over a hundred such calls which you can find listed in detail below in this man page, and we don't even pretend to cover them all in this overview.
Specify filenames as full paths, starting with "/"
and including
the mount point.
For example, if you mounted a filesystem at "/"
and you want to
read the file called "etc/passwd"
then you could do:
char *data = guestfs_cat (g, "/etc/passwd");
This would return data
as a newly allocated buffer containing the
full content of that file (with some conditions: see also
DOWNLOADING below), or NULL
if there was an error.
As another example, to create a top-level directory on that filesystem
called "var"
you would do:
guestfs_mkdir (g, "/var");
To create a symlink you could do:
guestfs_ln_s (g, "/etc/init.d/portmap", "/etc/rc3.d/S30portmap");
Libguestfs will reject attempts to use relative paths and there is no concept of a current working directory.
Libguestfs can return errors in many situations: for example if the filesystem isn't writable, or if a file or directory that you requested doesn't exist. If you are using the C API (documented here) you have to check for those error conditions after each call. (Other language bindings turn these errors into exceptions).
File writes are affected by the per-handle umask, set by calling guestfs_umask and defaulting to 022. See UMASK.
Libguestfs contains API calls to read, create and modify partition tables on disk images.
In the common case where you want to create a single partition covering the whole disk, you should use the guestfs_part_disk call:
const char *parttype = "mbr"; if (disk_is_larger_than_2TB) parttype = "gpt"; guestfs_part_disk (g, "/dev/sda", parttype);
Obviously this effectively wipes anything that was on that disk image before.
Libguestfs provides access to a large part of the LVM2 API, such as guestfs_lvcreate and guestfs_vgremove. It won't make much sense unless you familiarize yourself with the concepts of physical volumes, volume groups and logical volumes.
This author strongly recommends reading the LVM HOWTO, online at http://tldp.org/HOWTO/LVM-HOWTO/.
Use guestfs_cat to download small, text only files. This call
is limited to files which are less than 2 MB and which cannot contain
any ASCII NUL (\0
) characters. However it has a very simple
to use API.
guestfs_read_file can be used to read files which contain arbitrary 8 bit data, since it returns a (pointer, size) pair. However it is still limited to "small" files, less than 2 MB.
guestfs_download can be used to download any file, with no limits on content or size (even files larger than 4 GB).
To download multiple files, see guestfs_tar_out and guestfs_tgz_out.
It's often the case that you want to write a file or files to the disk image.
To write a small file with fixed content, use guestfs_write. To create a file of all zeroes, use guestfs_truncate_size (sparse) or guestfs_fallocate64 (with all disk blocks allocated). There are a variety of other functions for creating test files, for example guestfs_fill and guestfs_fill_pattern.
To upload a single file, use guestfs_upload. This call has no limits on file content or size (even files larger than 4 GB).
To upload multiple files, see guestfs_tar_in and guestfs_tgz_in.
However the fastest way to upload large numbers of arbitrary files is to turn them into a squashfs or CD ISO (see mksquashfs(8) and mkisofs(8)), then attach this using guestfs_add_drive_ro. If you add the drive in a predictable way (eg. adding it last after all other drives) then you can get the device name from guestfs_list_devices and mount it directly using guestfs_mount_ro. Note that squashfs images are sometimes non-portable between kernel versions, and they don't support labels or UUIDs. If you want to pre-build an image or you need to mount it using a label or UUID, use an ISO image instead.
There are various different commands for copying between files and devices and in and out of the guest filesystem. These are summarised in the table below.
Use guestfs_cp to copy a single file, or guestfs_cp_a to copy directories recursively.
Use guestfs_dd which efficiently uses dd(1) to copy between files and devices in the guest.
Example: duplicate the contents of an LV:
guestfs_dd (g, "/dev/VG/Original", "/dev/VG/Copy");
The destination (/dev/VG/Copy
) must be at least as large as the
source (/dev/VG/Original
). To copy less than the whole
source device, use guestfs_copy_size.
Use guestfs_upload. See UPLOADING above.
Use guestfs_download. See DOWNLOADING above.
guestfs_ll is just designed for humans to read (mainly when using
the guestfish(1)-equivalent command ll
).
guestfs_ls is a quick way to get a list of files in a directory from programs, as a flat list of strings.
guestfs_readdir is a programmatic way to get a list of files in a directory, plus additional information about each one. It is more equivalent to using the readdir(3) call on a local filesystem.
guestfs_find and guestfs_find0 can be used to recursively list files.
Although libguestfs is primarily an API for manipulating files inside guest images, we also provide some limited facilities for running commands inside guests.
There are many limitations to this:
The kernel version that the command runs under will be different from what it expects.
If the command needs to communicate with daemons, then most likely they won't be running.
The command will be running in limited memory.
The network may not be available unless you enable it (see guestfs_set_network).
Only supports Linux guests (not Windows, BSD, etc).
Architecture limitations (eg. won't work for a PPC guest on an X86 host).
For SELinux guests, you may need to enable SELinux and load policy first. See SELINUX in this manpage.
Security: It is not safe to run commands from untrusted, possibly malicious guests. These commands may attempt to exploit your program by sending unexpected output. They could also try to exploit the Linux kernel or qemu provided by the libguestfs appliance. They could use the network provided by the libguestfs appliance to bypass ordinary network partitions and firewalls. They could use the elevated privileges or different SELinux context of your program to their advantage.
A secure alternative is to use libguestfs to install a "firstboot" script (a script which runs when the guest next boots normally), and to have this script run the commands you want in the normal context of the running guest, network security and so on. For information about other security issues, see SECURITY.
The two main API calls to run commands are guestfs_command and guestfs_sh (there are also variations).
The difference is that guestfs_sh runs commands using the shell, so any shell globs, redirections, etc will work.
To read and write configuration files in Linux guest filesystems, we strongly recommend using Augeas. For example, Augeas understands how to read and write, say, a Linux shadow password file or X.org configuration file, and so avoids you having to write that code.
The main Augeas calls are bound through the guestfs_aug_*
APIs. We
don't document Augeas itself here because there is excellent
documentation on the http://augeas.net/ website.
If you don't want to use Augeas (you fool!) then try calling guestfs_read_lines to get the file as a list of lines which you can iterate over.
We support SELinux guests. To ensure that labeling happens correctly in SELinux guests, you need to enable SELinux and load the guest's policy:
Before launching, do:
guestfs_set_selinux (g, 1);
After mounting the guest's filesystem(s), load the policy. This is best done by running the load_policy(8) command in the guest itself:
guestfs_sh (g, "/usr/sbin/load_policy");
(Older versions of load_policy
require you to specify the
name of the policy file).
Optionally, set the security context for the API. The correct security context to use can only be known by inspecting the guest. As an example:
guestfs_setcon (g, "unconfined_u:unconfined_r:unconfined_t:s0");
This will work for running commands and editing existing files.
When new files are created, you may need to label them explicitly,
for example by running the external command
restorecon pathname
.
Certain calls are affected by the current file mode creation mask (the "umask"). In particular ones which create files or directories, such as guestfs_touch, guestfs_mknod or guestfs_mkdir. This affects either the default mode that the file is created with or modifies the mode that you supply.
The default umask is 022
, so files are created with modes such as
0644
and directories with 0755
.
There are two ways to avoid being affected by umask. Either set umask
to 0 (call guestfs_umask (g, 0)
early after launching). Or call
guestfs_chmod after creating each file or directory.
For more information about umask, see umask(2).
Libguestfs allows you to access Linux guests which have been encrypted using whole disk encryption that conforms to the Linux Unified Key Setup (LUKS) standard. This includes nearly all whole disk encryption systems used by modern Linux guests.
Use guestfs_vfs_type to identify LUKS-encrypted block
devices (it returns the string crypto_LUKS
).
Then open these devices by calling guestfs_luks_open. Obviously you will require the passphrase!
Opening a LUKS device creates a new device mapper device
called /dev/mapper/mapname
(where mapname
is the
string you supply to guestfs_luks_open).
Reads and writes to this mapper device are decrypted from and
encrypted to the underlying block device respectively.
LVM volume groups on the device can be made visible by calling guestfs_vgscan followed by guestfs_vg_activate_all. The logical volume(s) can now be mounted in the usual way.
Use the reverse process to close a LUKS device. Unmount
any logical volumes on it, deactivate the volume groups
by caling guestfs_vg_activate (g, 0, ["/dev/VG"])
.
Then close the mapper device by calling
guestfs_luks_close on the /dev/mapper/mapname
device (not the underlying encrypted block device).
Libguestfs has APIs for inspecting an unknown disk image to find out if it contains operating systems. (These APIs used to be in a separate Perl-only library called the Sys::Guestfs::Lib(3) manpage but since version 1.5.3 the most frequently used part of this library has been rewritten in C and moved into the core code).
Add all disks belonging to the unknown virtual machine and call guestfs_launch in the usual way.
Then call guestfs_inspect_os. This function uses other libguestfs calls and certain heuristics, and returns a list of operating systems that were found. An empty list means none were found. A single element is the root filesystem of the operating system. For dual- or multi-boot guests, multiple roots can be returned, each one corresponding to a separate operating system. (Multi-boot virtual machines are extremely rare in the world of virtualization, but since this scenario can happen, we have built libguestfs to deal with it.)
For each root, you can then call various guestfs_inspect_get_*
functions to get additional details about that operating system. For
example, call guestfs_inspect_get_type to return the string
windows
or linux
for Windows and Linux-based operating systems
respectively.
Un*x-like and Linux-based operating systems usually consist of several
filesystems which are mounted at boot time (for example, a separate
boot partition mounted on /boot
). The inspection rules are able to
detect how filesystems correspond to mount points. Call
guestfs_inspect_get_mountpoints
to get this mapping. It might
return a hash table like this example:
/boot => /dev/sda1 / => /dev/vg_guest/lv_root /usr => /dev/vg_guest/lv_usr
The caller can then make calls to guestfs_mount_options to mount the filesystems as suggested.
Be careful to mount filesystems in the right order (eg. /
before
/usr
). Sorting the keys of the hash by length, shortest first,
should work.
Inspection currently only works for some common operating systems. Contributors are welcome to send patches for other operating systems that we currently cannot detect.
Encrypted disks must be opened before inspection. See ENCRYPTED DISKS for more details. The guestfs_inspect_os function just ignores any encrypted devices.
A note on the implementation: The call guestfs_inspect_os performs
inspection and caches the results in the guest handle. Subsequent
calls to guestfs_inspect_get_*
return this cached information, but
do not re-read the disks. If you change the content of the guest
disks, you can redo inspection by calling guestfs_inspect_os
again.
Libguestfs can mount NTFS partitions. It does this using the http://www.ntfs-3g.org/ driver.
DOS and Windows still use drive letters, and the filesystems are
always treated as case insensitive by Windows itself, and therefore
you might find a Windows configuration file referring to a path like
c:\windows\system32
. When the filesystem is mounted in libguestfs,
that directory might be referred to as /WINDOWS/System32
.
Drive letter mappings are outside the scope of libguestfs. You have to use libguestfs to read the appropriate Windows Registry and configuration files, to determine yourself how drives are mapped (see also hivex(3) and virt-inspector(1)).
Replacing backslash characters with forward slash characters is also outside the scope of libguestfs, but something that you can easily do.
Where we can help is in resolving the case insensitivity of paths. For this, call guestfs_case_sensitive_path.
Libguestfs also provides some help for decoding Windows Registry
"hive" files, through the library hivex
which is part of the
libguestfs project although ships as a separate tarball. You have to
locate and download the hive file(s) yourself, and then pass them to
hivex
functions. See also the programs hivexml(1),
hivexsh(1), hivexregedit(1) and virt-win-reg(1) for more help
on this issue.
Although we don't want to discourage you from using the C API, we will mention here that the same API is also available in other languages.
The API is broadly identical in all supported languages. This means
that the C call guestfs_mount(g,path)
is
$g->mount($path)
in Perl, g.mount(path)
in Python,
and Guestfs.mount g path
in OCaml. In other words, a
straightforward, predictable isomorphism between each language.
Error messages are automatically transformed into exceptions if the language supports it.
We don't try to "object orientify" parts of the API in OO languages, although contributors are welcome to write higher level APIs above what we provide in their favourite languages if they wish.
You can use the guestfs.h header file from C++ programs. The C++ API is identical to the C API. C++ classes and exceptions are not used.
The C# bindings are highly experimental. Please read the warnings
at the top of csharp/Libguestfs.cs
.
This is the only language binding that is working but incomplete. Only calls which return simple integers have been bound in Haskell, and we are looking for help to complete this binding.
Full documentation is contained in the Javadoc which is distributed with libguestfs.
For documentation see the file guestfs.mli
.
For documentation see the Sys::Guestfs(3) manpage.
For documentation see README-PHP
supplied with libguestfs
sources or in the php-libguestfs package for your distribution.
The PHP binding only works correctly on 64 bit machines.
For documentation do:
$ python >>> import guestfs >>> help (guestfs)
Use the Guestfs module. There is no Ruby-specific documentation, but you can find examples written in Ruby in the libguestfs source.
For documentation see guestfish(1).
http://en.wikipedia.org/wiki/Gotcha_(programming): "A feature of a system [...] that works in the way it is documented but is counterintuitive and almost invites mistakes."
Since we developed libguestfs and the associated tools, there are several things we would have designed differently, but are now stuck with for backwards compatibility or other reasons. If there is ever a libguestfs 2.0 release, you can expect these to change. Beware of them.
When modifying a filesystem from C or another language, you must unmount all filesystems and call guestfs_sync explicitly before you close the libguestfs handle. You can also call:
guestfs_set_autosync (g, 1);
to have the unmount/sync done automatically for you when the handle 'g' is closed. (This feature is called "autosync", guestfs_set_autosync q.v.)
If you forget to do this, then it is entirely possible that your changes won't be written out, or will be partially written, or (very rarely) that you'll get disk corruption.
Note that in guestfish(3) autosync is the default. So quick and dirty guestfish scripts that forget to sync will work just fine, which can make this very puzzling if you are trying to debug a problem.
Update: Autosync is enabled by default for all API users starting from libguestfs 1.5.24.
-o sync
should not be the default.If you use guestfs_mount, then -o sync,noatime
are added
implicitly. However -o sync
does not add any reliability benefit,
but does have a very large performance impact.
The work around is to use guestfs_mount_options and set the mount options that you actually want to use.
In guestfish(3), --ro should be the default, and you should have to specify --rw if you want to make changes to the image.
This would reduce the potential to corrupt live VM images.
Note that many filesystems change the disk when you just mount and unmount, even if you didn't perform any writes. You need to use guestfs_add_drive_ro to guarantee that the disk is not changed.
guestfish disk.img
doesn't do what people expect (open disk.img
for examination). It tries to run a guestfish command disk.img
which doesn't exist, so it fails. In earlier versions of guestfish
the error message was also unintuitive, but we have corrected this
since. Like the Bourne shell, we should have used guestfish -c
command
to run commands.
In recent guestfish you can use 1M
to mean 1 megabyte (and
similarly for other modifiers). What guestfish actually does is to
multiply the number part by the modifier part and pass the result to
the C API. However this doesn't work for a few APIs which aren't
expecting bytes, but are already expecting some other unit
(eg. megabytes).
The most common is guestfs_lvcreate. The guestfish command:
lvcreate LV VG 100M
does not do what you might expect. Instead because guestfs_lvcreate is already expecting megabytes, this tries to create a 100 terabyte (100 megabytes * megabytes) logical volume. The error message you get from this is also a little obscure.
This could be fixed in the generator by specially marking parameters and return values which take bytes or other units.
It would be a nice-to-have to be able to get the original value of
'errno' from inside the appliance along error paths (where set).
Currently guestmount(1) goes through hoops to try to reverse the
error message string into an errno, see the function error()
in
fuse/guestmount.c.
In libguestfs 1.5.4, the protocol was changed so that the Linux errno is sent back from the daemon.
There is a subtle ambiguity in the API between a device name
(eg. /dev/sdb2
) and a similar pathname. A file might just happen
to be called sdb2
in the directory /dev
(consider some non-Unix
VM image).
In the current API we usually resolve this ambiguity by having two
separate calls, for example guestfs_checksum and
guestfs_checksum_device. Some API calls are ambiguous and
(incorrectly) resolve the problem by detecting if the path supplied
begins with /dev/
.
To avoid both the ambiguity and the need to duplicate some calls, we
could make paths/devices into structured names. One way to do this
would be to use a notation like grub (hd(0,0)
), although nobody
really likes this aspect of grub. Another way would be to use a
structured type, equivalent to this OCaml type:
type path = Path of string | Device of int | Partition of int * int
which would allow you to pass arguments like:
Path "/foo/bar" Device 1 (* /dev/sdb, or perhaps /dev/sda *) Partition (1, 2) (* /dev/sdb2 (or is it /dev/sda2 or /dev/sdb3?) *) Path "/dev/sdb2" (* not a device *)
As you can see there are still problems to resolve even with this representation. Also consider how it might work in guestfish.
Internally libguestfs uses a message-based protocol to pass API calls and their responses to and from a small "appliance" (see INTERNALS for plenty more detail about this). The maximum message size used by the protocol is slightly less than 4 MB. For some API calls you may need to be aware of this limit. The API calls which may be affected are individually documented, with a link back to this section of the documentation.
A simple call such as guestfs_cat returns its result (the file data) in a simple string. Because this string is at some point internally encoded as a message, the maximum size that it can return is slightly under 4 MB. If the requested file is larger than this then you will get an error.
In order to transfer large files into and out of the guest filesystem, you need to use particular calls that support this. The sections UPLOADING and DOWNLOADING document how to do this.
You might also consider mounting the disk image using our FUSE filesystem support (guestmount(1)).
Certain libguestfs calls take a parameter that contains sensitive key material, passed in as a C string.
In the future we would hope to change the libguestfs implementation so that keys are mlock(2)-ed into physical RAM, and thus can never end up in swap. However this is not done at the moment, because of the complexity of such an implementation.
Therefore you should be aware that any key parameter you pass to libguestfs might end up being written out to the swap partition. If this is a concern, scrub the swap partition or don't use libguestfs on encrypted devices.
All high-level libguestfs actions are synchronous. If you want to use libguestfs asynchronously then you must create a thread.
Only use the handle from a single thread. Either use the handle exclusively from one thread, or provide your own mutex so that two threads cannot issue calls on the same handle at the same time.
See the graphical program guestfs-browser for one possible architecture for multithreaded programs using libvirt and libguestfs.
Libguestfs needs a kernel and initrd.img, which it finds by looking along an internal path.
By default it looks for these in the directory $libdir/guestfs
(eg. /usr/local/lib/guestfs
or /usr/lib64/guestfs
).
Use guestfs_set_path or set the environment variable
LIBGUESTFS_PATH to change the directories that libguestfs will
search in. The value is a colon-separated list of paths. The current
directory is not searched unless the path contains an empty element
or .
. For example LIBGUESTFS_PATH=:/usr/lib/guestfs
would
search the current directory and then /usr/lib/guestfs
.
If you want to compile your own qemu, run qemu from a non-standard location, or pass extra arguments to qemu, then you can write a shell-script wrapper around qemu.
There is one important rule to remember: you must exec qemu
as
the last command in the shell script (so that qemu replaces the shell
and becomes the direct child of the libguestfs-using program). If you
don't do this, then the qemu process won't be cleaned up correctly.
Here is an example of a wrapper, where I have built my own copy of qemu from source:
#!/bin/sh - qemudir=/home/rjones/d/qemu exec $qemudir/x86_64-softmmu/qemu-system-x86_64 -L $qemudir/pc-bios "$@"
Save this script as /tmp/qemu.wrapper
(or wherever), chmod +x
,
and then use it by setting the LIBGUESTFS_QEMU environment variable.
For example:
LIBGUESTFS_QEMU=/tmp/qemu.wrapper guestfish
Note that libguestfs also calls qemu with the -help and -version options in order to determine features.
We guarantee the libguestfs ABI (binary interface), for public, high-level actions as outlined in this section. Although we will deprecate some actions, for example if they get replaced by newer calls, we will keep the old actions forever. This allows you the developer to program in confidence against the libguestfs API.
In the kernel there is now quite a profusion of schemata for naming
block devices (in this context, by block device I mean a physical
or virtual hard drive). The original Linux IDE driver used names
starting with /dev/hd*
. SCSI devices have historically used a
different naming scheme, /dev/sd*
. When the Linux kernel libata
driver became a popular replacement for the old IDE driver
(particularly for SATA devices) those devices also used the
/dev/sd*
scheme. Additionally we now have virtual machines with
paravirtualized drivers. This has created several different naming
systems, such as /dev/vd*
for virtio disks and /dev/xvd*
for Xen
PV disks.
As discussed above, libguestfs uses a qemu appliance running an embedded Linux kernel to access block devices. We can run a variety of appliances based on a variety of Linux kernels.
This causes a problem for libguestfs because many API calls use device or partition names. Working scripts and the recipe (example) scripts that we make available over the internet could fail if the naming scheme changes.
Therefore libguestfs defines /dev/sd*
as the standard naming
scheme. Internally /dev/sd*
names are translated, if necessary,
to other names as required. For example, under RHEL 5 which uses the
/dev/hd*
scheme, any device parameter /dev/sda2
is translated to
/dev/hda2
transparently.
Note that this only applies to parameters. The guestfs_list_devices, guestfs_list_partitions and similar calls return the true names of the devices and partitions as known to the appliance.
Usually this translation is transparent. However in some (very rare)
cases you may need to know the exact algorithm. Such cases include
where you use guestfs_config to add a mixture of virtio and IDE
devices to the qemu-based appliance, so have a mixture of /dev/sd*
and /dev/vd*
devices.
The algorithm is applied only to parameters which are known to be either device or partition names. Return values from functions such as guestfs_list_devices are never changed.
Is the string a parameter which is a device or partition name?
Does the string begin with /dev/sd
?
Does the named device exist? If so, we use that device. However if not then we continue with this algorithm.
Replace initial /dev/sd
string with /dev/hd
.
For example, change /dev/sda2
to /dev/hda2
.
If that named device exists, use it. If not, continue.
Replace initial /dev/sd
string with /dev/vd
.
If that named device exists, use it. If not, return an error.
Although the standard naming scheme and automatic translation is useful for simple programs and guestfish scripts, for larger programs it is best not to rely on this mechanism.
Where possible for maximum future portability programs using libguestfs should use these future-proof techniques:
Use guestfs_list_devices or guestfs_list_partitions to list actual device names, and then use those names directly.
Since those device names exist by definition, they will never be translated.
Use higher level ways to identify filesystems, such as LVM names, UUIDs and filesystem labels.
This section discusses security implications of using libguestfs, particularly with untrusted or malicious guests or disk images.
Be careful with any files or data that you download from a guest (by "download" we mean not just the guestfs_download command but any command that reads files, filenames, directories or anything else from a disk image). An attacker could manipulate the data to fool your program into doing the wrong thing. Consider cases such as:
the data (file etc) not being present
being present but empty
being much larger than normal
containing arbitrary 8 bit data
being in an unexpected character encoding
containing homoglyphs.
When you mount a filesystem under Linux, mistakes in the kernel filesystem (VFS) module can sometimes be escalated into exploits by deliberately creating a malicious, malformed filesystem. These exploits are very severe for two reasons. Firstly there are very many filesystem drivers in the kernel, and many of them are infrequently used and not much developer attention has been paid to the code. Linux userspace helps potential crackers by detecting the filesystem type and automatically choosing the right VFS driver, even if that filesystem type is obscure or unexpected for the administrator. Secondly, a kernel-level exploit is like a local root exploit (worse in some ways), giving immediate and total access to the system right down to the hardware level.
That explains why you should never mount a filesystem from an untrusted guest on your host kernel. How about libguestfs? We run a Linux kernel inside a qemu virtual machine, usually running as a non-root user. The attacker would need to write a filesystem which first exploited the kernel, and then exploited either qemu virtualization (eg. a faulty qemu driver) or the libguestfs protocol, and finally to be as serious as the host kernel exploit it would need to escalate its privileges to root. This multi-step escalation, performed by a static piece of data, is thought to be extremely hard to do, although we never say 'never' about security issues.
In any case callers can reduce the attack surface by forcing the filesystem type when mounting (use guestfs_mount_vfs).
The protocol is designed to be secure, being based on RFC 4506 (XDR) with a defined upper message size. However a program that uses libguestfs must also take care - for example you can write a program that downloads a binary from a disk image and executes it locally, and no amount of protocol security will save you from the consequences.
Parts of the inspection API (see INSPECTION) return untrusted strings directly from the guest, and these could contain any 8 bit data. Callers should be careful to escape these before printing them to a structured file (for example, use HTML escaping if creating a web page).
The inspection API parses guest configuration using two external libraries: Augeas (Linux configuration) and hivex (Windows Registry). Both are designed to be robust in the face of malicious data, although denial of service attacks are still possible, for example with oversized configuration files.
Be very cautious about running commands from the guest. By running a command in the guest, you are giving CPU time to a binary that you do not control, under the same user account as the library, albeit wrapped in qemu virtualization. More information and alternatives can be found in the section RUNNING COMMANDS.
https://bugzilla.redhat.com/642934
This security bug concerns the automatic disk format detection that qemu does on disk images.
A raw disk image is just the raw bytes, there is no header. Other disk images like qcow2 contain a special header. Qemu deals with this by looking for one of the known headers, and if none is found then assuming the disk image must be raw.
This allows a guest which has been given a raw disk image to write some other header. At next boot (or when the disk image is accessed by libguestfs) qemu would do autodetection and think the disk image format was, say, qcow2 based on the header written by the guest.
This in itself would not be a problem, but qcow2 offers many features, one of which is to allow a disk image to refer to another image (called the "backing disk"). It does this by placing the path to the backing disk into the qcow2 header. This path is not validated and could point to any host file (eg. "/etc/passwd"). The backing disk is then exposed through "holes" in the qcow2 disk image, which of course is completely under the control of the attacker.
In libguestfs this is rather hard to exploit except under two circumstances:
You have enabled the network or have opened the disk in write mode.
You are also running untrusted code from the guest (see RUNNING COMMANDS).
The way to avoid this is to specify the expected disk format when
adding disks (the optional format
option to
guestfs_add_drive_opts). You should always do this if the disk is
raw format, and it's a good idea for other cases too.
For disks added from libvirt using calls like guestfs_add_domain, the format is fetched from libvirt and passed through.
For libguestfs tools, use the --format command line parameter as appropriate.
guestfs_h
is the opaque type representing a connection handle.
Create a handle by calling guestfs_create. Call guestfs_close
to free the handle and release all resources used.
For information on using multiple handles and threads, see the section MULTIPLE HANDLES AND MULTIPLE THREADS below.
guestfs_h *guestfs_create (void);
Create a connection handle.
You have to call guestfs_add_drive_opts (or one of the equivalent calls) on the handle at least once.
This function returns a non-NULL pointer to a handle on success or NULL on error.
After configuring the handle, you have to call guestfs_launch.
You may also want to configure error handling for the handle. See ERROR HANDLING section below.
void guestfs_close (guestfs_h *g);
This closes the connection handle and frees up all resources used.
API functions can return errors. For example, almost all functions
that return int
will return -1
to indicate an error. You can
get additional information on
errors by calling guestfs_last_error and/or by setting up an error
handler with guestfs_set_error_handler.
When the handle is created, a default error handler is installed which
prints the error message string to stderr
. For small short-running
command line programs it is sufficient to do:
if (guestfs_launch (g) == -1) exit (EXIT_FAILURE);
since the default error handler will ensure that an error message has
been printed to stderr
before the program exits.
For other programs the caller will almost certainly want to install an alternate error handler or do error handling in-line like this:
g = guestfs_create (); /* This disables the default behaviour of printing errors on stderr. */ guestfs_set_error_handler (g, NULL, NULL); if (guestfs_launch (g) == -1) { /* Examine the error message and print it etc. */ char *msg = guestfs_last_error (g); fprintf (stderr, "%s\n", msg); /* ... */ }
Out of memory errors are handled differently. The default action is to call abort(3). If this is undesirable, then you can set a handler using guestfs_set_out_of_memory_handler.
guestfs_create returns NULL
if the handle cannot be created,
and because there is no handle if this happens there is no way to get
additional error information. However guestfs_create is supposed
to be a lightweight operation which can only fail because of
insufficient memory (it returns NULL in this case).
const char *guestfs_last_error (guestfs_h *g);
This returns the last error message that happened on g
. If
there has not been an error since the handle was created, then this
returns NULL
.
The lifetime of the returned string is until the next error occurs, or guestfs_close is called.
typedef void (*guestfs_error_handler_cb) (guestfs_h *g, void *opaque, const char *msg); void guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *opaque);
The callback cb
will be called if there is an error. The
parameters passed to the callback are an opaque data pointer and the
error message string.
Note that the message string msg
is freed as soon as the callback
function returns, so if you want to stash it somewhere you must make
your own copy.
The default handler prints messages on stderr
.
If you set cb
to NULL
then no handler is called.
guestfs_error_handler_cb guestfs_get_error_handler (guestfs_h *g, void **opaque_rtn);
Returns the current error handler callback.
typedef void (*guestfs_abort_cb) (void); int guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb);
The callback cb
will be called if there is an out of memory
situation. Note this callback must not return.
The default is to call abort(3).
You cannot set cb
to NULL
. You can't ignore out of memory
situations.
guestfs_abort_fn guestfs_get_out_of_memory_handler (guestfs_h *g);
This returns the current out of memory handler.
int guestfs_add_cdrom (guestfs_h *g, const char *filename);
This function adds a virtual CD-ROM disk image to the guest.
This is equivalent to the qemu parameter -cdrom filename
.
Notes:
This call checks for the existence of filename
. This
stops you from specifying other types of drive which are supported
by qemu such as nbd:
and http:
URLs. To specify those, use
the general guestfs_config
call instead.
If you just want to add an ISO file (often you use this as an
efficient way to transfer large files into the guest), then you
should probably use guestfs_add_drive_ro
instead.
This function returns 0 on success or -1 on error.
This function is deprecated.
In new code, use the add_drive_opts
call instead.
Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.
int guestfs_add_drive (guestfs_h *g, const char *filename);
This function is the equivalent of calling guestfs_add_drive_opts
with no optional parameters, so the disk is added writable, with
the format being detected automatically.
Automatic detection of the format opens you up to a potential
security hole when dealing with untrusted raw-format images.
See CVE-2010-3851 and RHBZ#642934. Specifying the format closes
this security hole. Therefore you should think about replacing
calls to this function with calls to guestfs_add_drive_opts
,
and specifying the format.
This function returns 0 on success or -1 on error.
int guestfs_add_drive_opts (guestfs_h *g, const char *filename, ...);
You may supply a list of optional arguments to this call.
Use zero or more of the following pairs of parameters,
and terminate the list with -1
on its own.
See CALLS WITH OPTIONAL ARGUMENTS.
GUESTFS_ADD_DRIVE_OPTS_READONLY, int readonly, GUESTFS_ADD_DRIVE_OPTS_FORMAT, const char *format, GUESTFS_ADD_DRIVE_OPTS_IFACE, const char *iface,
This function adds a virtual machine disk image filename
to
libguestfs. The first time you call this function, the disk
appears as /dev/sda
, the second time as /dev/sdb
, and
so on.
You don't necessarily need to be root when using libguestfs. However you obviously do need sufficient permissions to access the filename for whatever operations you want to perform (ie. read access if you just want to read the image or write access if you want to modify the image).
This call checks that filename
exists.
The optional arguments are:
readonly
If true then the image is treated as read-only. Writes are still allowed, but they are stored in a temporary snapshot overlay which is discarded at the end. The disk that you add is not modified.
format
This forces the image format. If you omit this (or use guestfs_add_drive
or guestfs_add_drive_ro
) then the format is automatically detected.
Possible formats include raw
and qcow2
.
Automatic detection of the format opens you up to a potential security hole when dealing with untrusted raw-format images. See CVE-2010-3851 and RHBZ#642934. Specifying the format closes this security hole.
iface
This rarely-used option lets you emulate the behaviour of the
deprecated guestfs_add_drive_with_if
call (q.v.)
This function returns 0 on success or -1 on error.
int guestfs_add_drive_opts_va (guestfs_h *g, const char *filename, va_list args);
This is the "va_list variant" of guestfs_add_drive_opts.
See CALLS WITH OPTIONAL ARGUMENTS.
int guestfs_add_drive_opts_argv (guestfs_h *g, const char *filename, const struct guestfs_add_drive_opts_argv *optargs);
This is the "argv variant" of guestfs_add_drive_opts.
See CALLS WITH OPTIONAL ARGUMENTS.
int guestfs_add_drive_ro (guestfs_h *g, const char *filename);
This function is the equivalent of calling guestfs_add_drive_opts
with the optional parameter GUESTFS_ADD_DRIVE_OPTS_READONLY
set to 1,
so the disk is added read-only, with the format being detected
automatically.
This function returns 0 on success or -1 on error.
int guestfs_add_drive_ro_with_if (guestfs_h *g, const char *filename, const char *iface);
This is the same as guestfs_add_drive_ro
but it allows you
to specify the QEMU interface emulation to use at run time.
This function returns 0 on success or -1 on error.
This function is deprecated.
In new code, use the add_drive_opts
call instead.
Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.
int guestfs_add_drive_with_if (guestfs_h *g, const char *filename, const char *iface);
This is the same as guestfs_add_drive
but it allows you
to specify the QEMU interface emulation to use at run time.
This function returns 0 on success or -1 on error.
This function is deprecated.
In new code, use the add_drive_opts
call instead.
Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.
int guestfs_aug_clear (guestfs_h *g, const char *augpath);
Set the value associated with path
to NULL
. This
is the same as the augtool(1) clear
command.
This function returns 0 on success or -1 on error.
int guestfs_aug_close (guestfs_h *g);
Close the current Augeas handle and free up any resources
used by it. After calling this, you have to call
guestfs_aug_init
again before you can use any other
Augeas functions.
This function returns 0 on success or -1 on error.
struct guestfs_int_bool * guestfs_aug_defnode (guestfs_h *g, const char *name, const char *expr, const char *val);
Defines a variable name
whose value is the result of
evaluating expr
.
If expr
evaluates to an empty nodeset, a node is created,
equivalent to calling guestfs_aug_set
expr
, value
.
name
will be the nodeset containing that single node.
On success this returns a pair containing the number of nodes in the nodeset, and a boolean flag if a node was created.
This function returns a struct guestfs_int_bool *
,
or NULL if there was an error.
The caller must call guestfs_free_int_bool
after use.
int guestfs_aug_defvar (guestfs_h *g, const char *name, const char *expr);
Defines an Augeas variable name
whose value is the result
of evaluating expr
. If expr
is NULL, then name
is
undefined.
On success this returns the number of nodes in expr
, or
0
if expr
evaluates to something which is not a nodeset.
On error this function returns -1.
char * guestfs_aug_get (guestfs_h *g, const char *augpath);
Look up the value associated with path
. If path
matches exactly one node, the value
is returned.
This function returns a string, or NULL on error. The caller must free the returned string after use.
int guestfs_aug_init (guestfs_h *g, const char *root, int flags);
Create a new Augeas handle for editing configuration files. If there was any previous Augeas handle associated with this guestfs session, then it is closed.
You must call this before using any other guestfs_aug_*
commands.
root
is the filesystem root. root
must not be NULL,
use /
instead.
The flags are the same as the flags defined in <augeas.h>, the logical or of the following integers:
AUG_SAVE_BACKUP
= 1Keep the original file with a .augsave
extension.
AUG_SAVE_NEWFILE
= 2Save changes into a file with extension .augnew
, and
do not overwrite original. Overrides AUG_SAVE_BACKUP
.
AUG_TYPE_CHECK
= 4Typecheck lenses (can be expensive).
AUG_NO_STDINC
= 8Do not use standard load path for modules.
AUG_SAVE_NOOP
= 16Make save a no-op, just record what would have been changed.
AUG_NO_LOAD
= 32Do not load the tree in guestfs_aug_init
.
To close the handle, you can call guestfs_aug_close
.
To find out more about Augeas, see http://augeas.net/.
This function returns 0 on success or -1 on error.
int guestfs_aug_insert (guestfs_h *g, const char *augpath, const char *label, int before);
Create a new sibling label
for path
, inserting it into
the tree before or after path
(depending on the boolean
flag before
).
path
must match exactly one existing node in the tree, and
label
must be a label, ie. not contain /
, *
or end
with a bracketed index [N]
.
This function returns 0 on success or -1 on error.
int guestfs_aug_load (guestfs_h *g);
Load files into the tree.
See aug_load
in the Augeas documentation for the full gory
details.
This function returns 0 on success or -1 on error.
char ** guestfs_aug_ls (guestfs_h *g, const char *augpath);
This is just a shortcut for listing guestfs_aug_match
path/*
and sorting the resulting nodes into alphabetical order.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
char ** guestfs_aug_match (guestfs_h *g, const char *augpath);
Returns a list of paths which match the path expression path
.
The returned paths are sufficiently qualified so that they match
exactly one node in the current tree.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
int guestfs_aug_mv (guestfs_h *g, const char *src, const char *dest);
Move the node src
to dest
. src
must match exactly
one node. dest
is overwritten if it exists.
This function returns 0 on success or -1 on error.
int guestfs_aug_rm (guestfs_h *g, const char *augpath);
Remove path
and all of its children.
On success this returns the number of entries which were removed.
On error this function returns -1.
int guestfs_aug_save (guestfs_h *g);
This writes all pending changes to disk.
The flags which were passed to guestfs_aug_init
affect exactly
how files are saved.
This function returns 0 on success or -1 on error.
int guestfs_aug_set (guestfs_h *g, const char *augpath, const char *val);
Set the value associated with path
to val
.
In the Augeas API, it is possible to clear a node by setting
the value to NULL. Due to an oversight in the libguestfs API
you cannot do that with this call. Instead you must use the
guestfs_aug_clear
call.
This function returns 0 on success or -1 on error.
int guestfs_available (guestfs_h *g, char *const *groups);
This command is used to check the availability of some groups of functionality in the appliance, which not all builds of the libguestfs appliance will be able to provide.
The libguestfs groups, and the functions that those
groups correspond to, are listed in guestfs(3)/AVAILABILITY.
You can also fetch this list at runtime by calling
guestfs_available_all_groups
.
The argument groups
is a list of group names, eg:
["inotify", "augeas"]
would check for the availability of
the Linux inotify functions and Augeas (configuration file
editing) functions.
The command returns no error if all requested groups are available.
It fails with an error if one or more of the requested groups is unavailable in the appliance.
If an unknown group name is included in the list of groups then an error is always returned.
Notes:
You must call guestfs_launch
before calling this function.
The reason is because we don't know what groups are supported by the appliance/daemon until it is running and can be queried.
If a group of functions is available, this does not necessarily mean that they will work. You still have to check for errors when calling individual API functions even if they are available.
It is usually the job of distro packagers to build complete functionality into the libguestfs appliance. Upstream libguestfs, if built from source with all requirements satisfied, will support everything.
This call was added in version 1.0.80
. In previous
versions of libguestfs all you could do would be to speculatively
execute a command to find out if the daemon implemented it.
See also guestfs_version
.
This function returns 0 on success or -1 on error.
char ** guestfs_available_all_groups (guestfs_h *g);
This command returns a list of all optional groups that this
daemon knows about. Note this returns both supported and unsupported
groups. To find out which ones the daemon can actually support
you have to call guestfs_available
on each member of the
returned list.
See also guestfs_available
and guestfs(3)/AVAILABILITY.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
int guestfs_base64_in (guestfs_h *g, const char *base64file, const char *filename);
This command uploads base64-encoded data from base64file
to filename
.
This function returns 0 on success or -1 on error.
int guestfs_base64_out (guestfs_h *g, const char *filename, const char *base64file);
This command downloads the contents of filename
, writing
it out to local file base64file
encoded as base64.
This function returns 0 on success or -1 on error.
int guestfs_blockdev_flushbufs (guestfs_h *g, const char *device);
This tells the kernel to flush internal buffers associated
with device
.
This uses the blockdev(8) command.
This function returns 0 on success or -1 on error.
int guestfs_blockdev_getbsz (guestfs_h *g, const char *device);
This returns the block size of a device.
(Note this is different from both size in blocks and filesystem block size).
This uses the blockdev(8) command.
On error this function returns -1.
int guestfs_blockdev_getro (guestfs_h *g, const char *device);
Returns a boolean indicating if the block device is read-only (true if read-only, false if not).
This uses the blockdev(8) command.
This function returns a C truth value on success or -1 on error.
int64_t guestfs_blockdev_getsize64 (guestfs_h *g, const char *device);
This returns the size of the device in bytes.
See also guestfs_blockdev_getsz
.
This uses the blockdev(8) command.
On error this function returns -1.
int guestfs_blockdev_getss (guestfs_h *g, const char *device);
This returns the size of sectors on a block device. Usually 512, but can be larger for modern devices.
(Note, this is not the size in sectors, use guestfs_blockdev_getsz
for that).
This uses the blockdev(8) command.
On error this function returns -1.
int64_t guestfs_blockdev_getsz (guestfs_h *g, const char *device);
This returns the size of the device in units of 512-byte sectors (even if the sectorsize isn't 512 bytes ... weird).
See also guestfs_blockdev_getss
for the real sector size of
the device, and guestfs_blockdev_getsize64
for the more
useful size in bytes.
This uses the blockdev(8) command.
On error this function returns -1.
int guestfs_blockdev_rereadpt (guestfs_h *g, const char *device);
Reread the partition table on device
.
This uses the blockdev(8) command.
This function returns 0 on success or -1 on error.
int guestfs_blockdev_setbsz (guestfs_h *g, const char *device, int blocksize);
This sets the block size of a device.
(Note this is different from both size in blocks and filesystem block size).
This uses the blockdev(8) command.
This function returns 0 on success or -1 on error.
int guestfs_blockdev_setro (guestfs_h *g, const char *device);
Sets the block device named device
to read-only.
This uses the blockdev(8) command.
This function returns 0 on success or -1 on error.
int guestfs_blockdev_setrw (guestfs_h *g, const char *device);
Sets the block device named device
to read-write.
This uses the blockdev(8) command.
This function returns 0 on success or -1 on error.
char * guestfs_case_sensitive_path (guestfs_h *g, const char *path);
This can be used to resolve case insensitive paths on a filesystem which is case sensitive. The use case is to resolve paths which you have read from Windows configuration files or the Windows Registry, to the true path.
The command handles a peculiarity of the Linux ntfs-3g filesystem driver (and probably others), which is that although the underlying filesystem is case-insensitive, the driver exports the filesystem to Linux as case-sensitive.
One consequence of this is that special directories such
as c:\windows
may appear as /WINDOWS
or /windows
(or other things) depending on the precise details of how
they were created. In Windows itself this would not be
a problem.
Bug or feature? You decide: http://www.tuxera.com/community/ntfs-3g-faq/#posixfilenames1
This function resolves the true case of each element in the path and returns the case-sensitive path.
Thus guestfs_case_sensitive_path
("/Windows/System32")
might return "/WINDOWS/system32"
(the exact return value
would depend on details of how the directories were originally
created under Windows).
Note: This function does not handle drive names, backslashes etc.
See also guestfs_realpath
.
This function returns a string, or NULL on error. The caller must free the returned string after use.
char * guestfs_cat (guestfs_h *g, const char *path);
Return the contents of the file named path
.
Note that this function cannot correctly handle binary files
(specifically, files containing \0
character which is treated
as end of string). For those you need to use the guestfs_read_file
or guestfs_download
functions which have a more complex interface.
This function returns a string, or NULL on error. The caller must free the returned string after use.
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See guestfs(3)/PROTOCOL LIMITS.
char * guestfs_checksum (guestfs_h *g, const char *csumtype, const char *path);
This call computes the MD5, SHAx or CRC checksum of the
file named path
.
The type of checksum to compute is given by the csumtype
parameter which must have one of the following values:
crc
Compute the cyclic redundancy check (CRC) specified by POSIX
for the cksum
command.
md5
Compute the MD5 hash (using the md5sum
program).
sha1
Compute the SHA1 hash (using the sha1sum
program).
sha224
Compute the SHA224 hash (using the sha224sum
program).
sha256
Compute the SHA256 hash (using the sha256sum
program).
sha384
Compute the SHA384 hash (using the sha384sum
program).
sha512
Compute the SHA512 hash (using the sha512sum
program).
The checksum is returned as a printable string.
To get the checksum for a device, use guestfs_checksum_device
.
To get the checksums for many files, use guestfs_checksums_out
.
This function returns a string, or NULL on error. The caller must free the returned string after use.
char * guestfs_checksum_device (guestfs_h *g, const char *csumtype, const char *device);
This call computes the MD5, SHAx or CRC checksum of the
contents of the device named device
. For the types of
checksums supported see the guestfs_checksum
command.
This function returns a string, or NULL on error. The caller must free the returned string after use.
int guestfs_checksums_out (guestfs_h *g, const char *csumtype, const char *directory, const char *sumsfile);
This command computes the checksums of all regular files in
directory
and then emits a list of those checksums to
the local output file sumsfile
.
This can be used for verifying the integrity of a virtual machine. However to be properly secure you should pay attention to the output of the checksum command (it uses the ones from GNU coreutils). In particular when the filename is not printable, coreutils uses a special backslash syntax. For more information, see the GNU coreutils info file.
This function returns 0 on success or -1 on error.
int guestfs_chmod (guestfs_h *g, int mode, const char *path);
Change the mode (permissions) of path
to mode
. Only
numeric modes are supported.
Note: When using this command from guestfish, mode
by default would be decimal, unless you prefix it with
0
to get octal, ie. use 0700
not 700
.
The mode actually set is affected by the umask.
This function returns 0 on success or -1 on error.
int guestfs_chown (guestfs_h *g, int owner, int group, const char *path);
Change the file owner to owner
and group to group
.
Only numeric uid and gid are supported. If you want to use names, you will need to locate and parse the password file yourself (Augeas support makes this relatively easy).
This function returns 0 on success or -1 on error.
char * guestfs_command (guestfs_h *g, char *const *arguments);
This call runs a command from the guest filesystem. The filesystem must be mounted, and must contain a compatible operating system (ie. something Linux, with the same or compatible processor architecture).
The single parameter is an argv-style list of arguments.
The first element is the name of the program to run.
Subsequent elements are parameters. The list must be
non-empty (ie. must contain a program name). Note that
the command runs directly, and is not invoked via
the shell (see guestfs_sh
).
The return value is anything printed to stdout by the command.
If the command returns a non-zero exit status, then this function returns an error message. The error message string is the content of stderr from the command.
The $PATH
environment variable will contain at least
/usr/bin
and /bin
. If you require a program from
another location, you should provide the full path in the
first parameter.
Shared libraries and data files required by the program must be available on filesystems which are mounted in the correct places. It is the caller's responsibility to ensure all filesystems that are needed are mounted at the right locations.
This function returns a string, or NULL on error. The caller must free the returned string after use.
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See guestfs(3)/PROTOCOL LIMITS.
char ** guestfs_command_lines (guestfs_h *g, char *const *arguments);
This is the same as guestfs_command
, but splits the
result into a list of lines.
See also: guestfs_sh_lines
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See guestfs(3)/PROTOCOL LIMITS.
int guestfs_config (guestfs_h *g, const char *qemuparam, const char *qemuvalue);
This can be used to add arbitrary qemu command line parameters
of the form -param value
. Actually it's not quite arbitrary - we
prevent you from setting some parameters which would interfere with
parameters that we use.
The first character of param
string must be a -
(dash).
value
can be NULL.
This function returns 0 on success or -1 on error.
int guestfs_copy_size (guestfs_h *g, const char *src, const char *dest, int64_t size);
This command copies exactly size
bytes from one source device
or file src
to another destination device or file dest
.
Note this will fail if the source is too short or if the destination is not large enough.
This function returns 0 on success or -1 on error.
This long-running command can generate progress notification messages so that the caller can display a progress bar or indicator. To receive these messages, the caller must register a progress callback. See guestfs(3)/guestfs_set_progress_callback.
int guestfs_cp (guestfs_h *g, const char *src, const char *dest);
This copies a file from src
to dest
where dest
is
either a destination filename or destination directory.
This function returns 0 on success or -1 on error.
int guestfs_cp_a (guestfs_h *g, const char *src, const char *dest);
This copies a file or directory from src
to dest
recursively using the cp -a
command.
This function returns 0 on success or -1 on error.
int guestfs_dd (guestfs_h *g, const char *src, const char *dest);
This command copies from one source device or file src
to another destination device or file dest
. Normally you
would use this to copy to or from a device or partition, for
example to duplicate a filesystem.
If the destination is a device, it must be as large or larger
than the source file or device, otherwise the copy will fail.
This command cannot do partial copies (see guestfs_copy_size
).
This function returns 0 on success or -1 on error.
char * guestfs_debug (guestfs_h *g, const char *subcmd, char *const *extraargs);
The guestfs_debug
command exposes some internals of
guestfsd
(the guestfs daemon) that runs inside the
qemu subprocess.
There is no comprehensive help for this command. You have
to look at the file daemon/debug.c
in the libguestfs source
to find out what you can do.
This function returns a string, or NULL on error. The caller must free the returned string after use.
int guestfs_debug_upload (guestfs_h *g, const char *filename, const char *tmpname, int mode);
The guestfs_debug_upload
command uploads a file to
the libguestfs appliance.
There is no comprehensive help for this command. You have
to look at the file daemon/debug.c
in the libguestfs source
to find out what it is for.
This function returns 0 on success or -1 on error.
char * guestfs_df (guestfs_h *g);
This command runs the df
command to report disk space used.
This command is mostly useful for interactive sessions. It
is not intended that you try to parse the output string.
Use statvfs
from programs.
This function returns a string, or NULL on error. The caller must free the returned string after use.
char * guestfs_df_h (guestfs_h *g);
This command runs the df -h
command to report disk space used
in human-readable format.
This command is mostly useful for interactive sessions. It
is not intended that you try to parse the output string.
Use statvfs
from programs.
This function returns a string, or NULL on error. The caller must free the returned string after use.
char * guestfs_dmesg (guestfs_h *g);
This returns the kernel messages (dmesg
output) from
the guest kernel. This is sometimes useful for extended
debugging of problems.
Another way to get the same information is to enable
verbose messages with guestfs_set_verbose
or by setting
the environment variable LIBGUESTFS_DEBUG=1
before
running the program.
This function returns a string, or NULL on error. The caller must free the returned string after use.
int guestfs_download (guestfs_h *g, const char *remotefilename, const char *filename);
Download file remotefilename
and save it as filename
on the local machine.
filename
can also be a named pipe.
See also guestfs_upload
, guestfs_cat
.
This function returns 0 on success or -1 on error.
This long-running command can generate progress notification messages so that the caller can display a progress bar or indicator. To receive these messages, the caller must register a progress callback. See guestfs(3)/guestfs_set_progress_callback.
int guestfs_download_offset (guestfs_h *g, const char *remotefilename, const char *filename, int64_t offset, int64_t size);
Download file remotefilename
and save it as filename
on the local machine.
remotefilename
is read for size
bytes starting at offset
(this region must be within the file or device).
Note that there is no limit on the amount of data that
can be downloaded with this call, unlike with guestfs_pread
,
and this call always reads the full amount unless an
error occurs.
See also guestfs_download
, guestfs_pread
.
This function returns 0 on success or -1 on error.
This long-running command can generate progress notification messages so that the caller can display a progress bar or indicator. To receive these messages, the caller must register a progress callback. See guestfs(3)/guestfs_set_progress_callback.
int guestfs_drop_caches (guestfs_h *g, int whattodrop);
This instructs the guest kernel to drop its page cache,
and/or dentries and inode caches. The parameter whattodrop
tells the kernel what precisely to drop, see
http://linux-mm.org/Drop_Caches
Setting whattodrop
to 3 should drop everything.
This automatically calls sync(2) before the operation, so that the maximum guest memory is freed.
This function returns 0 on success or -1 on error.
int64_t guestfs_du (guestfs_h *g, const char *path);
This command runs the du -s
command to estimate file space
usage for path
.
path
can be a file or a directory. If path
is a directory
then the estimate includes the contents of the directory and all
subdirectories (recursively).
The result is the estimated size in kilobytes (ie. units of 1024 bytes).
On error this function returns -1.
int guestfs_e2fsck_f (guestfs_h *g, const char *device);
This runs e2fsck -p -f device
, ie. runs the ext2/ext3
filesystem checker on device
, noninteractively (-p
),
even if the filesystem appears to be clean (-f
).
This command is only needed because of guestfs_resize2fs
(q.v.). Normally you should use guestfs_fsck
.
This function returns 0 on success or -1 on error.
char * guestfs_echo_daemon (guestfs_h *g, char *const *words);
This command concatenates the list of words
passed with single spaces
between them and returns the resulting string.
You can use this command to test the connection through to the daemon.
See also guestfs_ping_daemon
.
This function returns a string, or NULL on error. The caller must free the returned string after use.
char ** guestfs_egrep (guestfs_h *g, const char *regex, const char *path);
This calls the external egrep
program and returns the
matching lines.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See guestfs(3)/PROTOCOL LIMITS.
char ** guestfs_egrepi (guestfs_h *g, const char *regex, const char *path);
This calls the external egrep -i
program and returns the
matching lines.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See guestfs(3)/PROTOCOL LIMITS.
int guestfs_equal (guestfs_h *g, const char *file1, const char *file2);
This compares the two files file1
and file2
and returns
true if their content is exactly equal, or false otherwise.
The external cmp(1) program is used for the comparison.
This function returns a C truth value on success or -1 on error.
int guestfs_exists (guestfs_h *g, const char *path);
This returns true
if and only if there is a file, directory
(or anything) with the given path
name.
See also guestfs_is_file
, guestfs_is_dir
, guestfs_stat
.
This function returns a C truth value on success or -1 on error.
int guestfs_fallocate (guestfs_h *g, const char *path, int len);
This command preallocates a file (containing zero bytes) named
path
of size len
bytes. If the file exists already, it
is overwritten.
Do not confuse this with the guestfish-specific
alloc
command which allocates a file in the host and
attaches it as a device.
This function returns 0 on success or -1 on error.
This function is deprecated.
In new code, use the fallocate64
call instead.
Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.
int guestfs_fallocate64 (guestfs_h *g, const char *path, int64_t len);
This command preallocates a file (containing zero bytes) named
path
of size len
bytes. If the file exists already, it
is overwritten.
Note that this call allocates disk blocks for the file.
To create a sparse file use guestfs_truncate_size
instead.
The deprecated call guestfs_fallocate
does the same,
but owing to an oversight it only allowed 30 bit lengths
to be specified, effectively limiting the maximum size
of files created through that call to 1GB.
Do not confuse this with the guestfish-specific
alloc
and sparse
commands which create
a file in the host and attach it as a device.
This function returns 0 on success or -1 on error.
char ** guestfs_fgrep (guestfs_h *g, const char *pattern, const char *path);
This calls the external fgrep
program and returns the
matching lines.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See guestfs(3)/PROTOCOL LIMITS.
char ** guestfs_fgrepi (guestfs_h *g, const char *pattern, const char *path);
This calls the external fgrep -i
program and returns the
matching lines.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See guestfs(3)/PROTOCOL LIMITS.
char * guestfs_file (guestfs_h *g, const char *path);
This call uses the standard file(1) command to determine the type or contents of the file.
This call will also transparently look inside various types of compressed file.
The exact command which runs is file -zb path
. Note in
particular that the filename is not prepended to the output
(the -b
option).
This command can also be used on /dev/
devices
(and partitions, LV names). You can for example use this
to determine if a device contains a filesystem, although
it's usually better to use guestfs_vfs_type
.
If the path
does not begin with /dev/
then
this command only works for the content of regular files.
For other file types (directory, symbolic link etc) it
will just return the string directory
etc.
This function returns a string, or NULL on error. The caller must free the returned string after use.
char * guestfs_file_architecture (guestfs_h *g, const char *filename);
This detects the architecture of the binary filename
,
and returns it if known.
Currently defined architectures are:
This string is returned for all 32 bit i386, i486, i586, i686 binaries irrespective of the precise processor requirements of the binary.
64 bit x86-64.
32 bit SPARC.
64 bit SPARC V9 and above.
Intel Itanium.
32 bit Power PC.
64 bit Power PC.
Libguestfs may return other architecture strings in future.
The function works on at least the following types of files:
many types of Un*x and Linux binary
many types of Un*x and Linux shared library
Windows Win32 and Win64 binaries
Windows Win32 and Win64 DLLs
Win32 binaries and DLLs return i386
.
Win64 binaries and DLLs return x86_64
.
Linux kernel modules
Linux new-style initrd images
some non-x86 Linux vmlinuz kernels
What it can't do currently:
static libraries (libfoo.a)
Linux old-style initrd as compressed ext2 filesystem (RHEL 3)
x86 Linux vmlinuz kernels
x86 vmlinuz images (bzImage format) consist of a mix of 16-, 32- and compressed code, and are horribly hard to unpack. If you want to find the architecture of a kernel, use the architecture of the associated initrd or kernel module(s) instead.
This function returns a string, or NULL on error. The caller must free the returned string after use.
int64_t guestfs_filesize (guestfs_h *g, const char *file);
This command returns the size of file
in bytes.
To get other stats about a file, use guestfs_stat
, guestfs_lstat
,
guestfs_is_dir
, guestfs_is_file
etc.
To get the size of block devices, use guestfs_blockdev_getsize64
.
On error this function returns -1.
int guestfs_fill (guestfs_h *g, int c, int len, const char *path);
This command creates a new file called path
. The initial
content of the file is len
octets of c
, where c
must be a number in the range [0..255]
.
To fill a file with zero bytes (sparsely), it is
much more efficient to use guestfs_truncate_size
.
To create a file with a pattern of repeating bytes
use guestfs_fill_pattern
.
This function returns 0 on success or -1 on error.
This long-running command can generate progress notification messages so that the caller can display a progress bar or indicator. To receive these messages, the caller must register a progress callback. See guestfs(3)/guestfs_set_progress_callback.
int guestfs_fill_pattern (guestfs_h *g, const char *pattern, int len, const char *path);
This function is like guestfs_fill
except that it creates
a new file of length len
containing the repeating pattern
of bytes in pattern
. The pattern is truncated if necessary
to ensure the length of the file is exactly len
bytes.
This function returns 0 on success or -1 on error.
This long-running command can generate progress notification messages so that the caller can display a progress bar or indicator. To receive these messages, the caller must register a progress callback. See guestfs(3)/guestfs_set_progress_callback.
char ** guestfs_find (guestfs_h *g, const char *directory);
This command lists out all files and directories, recursively,
starting at directory
. It is essentially equivalent to
running the shell command find directory -print
but some
post-processing happens on the output, described below.
This returns a list of strings without any prefix. Thus if the directory structure was:
/tmp/a /tmp/b /tmp/c/d
then the returned list from guestfs_find
/tmp
would be
4 elements:
a b c c/d
If directory
is not a directory, then this command returns
an error.
The returned list is sorted.
See also guestfs_find0
.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See guestfs(3)/PROTOCOL LIMITS.
int guestfs_find0 (guestfs_h *g, const char *directory, const char *files);
This command lists out all files and directories, recursively,
starting at directory
, placing the resulting list in the
external file called files
.
This command works the same way as guestfs_find
with the
following exceptions:
The resulting list is written to an external file.
Items (filenames) in the result are separated
by \0
characters. See find(1) option -print0.
This command is not limited in the number of names that it can return.
The result list is not sorted.
This function returns 0 on success or -1 on error.
char * guestfs_findfs_label (guestfs_h *g, const char *label);
This command searches the filesystems and returns the one which has the given label. An error is returned if no such filesystem can be found.
To find the label of a filesystem, use guestfs_vfs_label
.
This function returns a string, or NULL on error. The caller must free the returned string after use.
char * guestfs_findfs_uuid (guestfs_h *g, const char *uuid);
This command searches the filesystems and returns the one which has the given UUID. An error is returned if no such filesystem can be found.
To find the UUID of a filesystem, use guestfs_vfs_uuid
.
This function returns a string, or NULL on error. The caller must free the returned string after use.
int guestfs_fsck (guestfs_h *g, const char *fstype, const char *device);
This runs the filesystem checker (fsck) on device
which
should have filesystem type fstype
.
The returned integer is the status. See fsck(8) for the
list of status codes from fsck
.
Notes:
Multiple status codes can be summed together.
A non-zero return code can mean "success", for example if errors have been corrected on the filesystem.
Checking or repairing NTFS volumes is not supported (by linux-ntfs).
This command is entirely equivalent to running fsck -a -t fstype device
.
On error this function returns -1.
const char * guestfs_get_append (guestfs_h *g);
Return the additional kernel options which are added to the guest kernel command line.
If NULL
then no options are added.
This function returns a string which may be NULL. There is no way to return an error from this function. The string is owned by the guest handle and must not be freed.
int guestfs_get_autosync (guestfs_h *g);
Get the autosync flag.
This function returns a C truth value on success or -1 on error.
int guestfs_get_direct (guestfs_h *g);
Return the direct appliance mode flag.
This function returns a C truth value on success or -1 on error.
char * guestfs_get_e2label (guestfs_h *g, const char *device);
This returns the ext2/3/4 filesystem label of the filesystem on
device
.
This function returns a string, or NULL on error. The caller must free the returned string after use.
This function is deprecated.
In new code, use the vfs_label
call instead.
Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.
char * guestfs_get_e2uuid (guestfs_h *g, const char *device);
This returns the ext2/3/4 filesystem UUID of the filesystem on
device
.
This function returns a string, or NULL on error. The caller must free the returned string after use.
This function is deprecated.
In new code, use the vfs_uuid
call instead.
Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.
int guestfs_get_memsize (guestfs_h *g);
This gets the memory size in megabytes allocated to the qemu subprocess.
If guestfs_set_memsize
was not called
on this handle, and if LIBGUESTFS_MEMSIZE
was not set,
then this returns the compiled-in default value for memsize.
For more information on the architecture of libguestfs, see guestfs(3).
On error this function returns -1.
int guestfs_get_network (guestfs_h *g);
This returns the enable network flag.
This function returns a C truth value on success or -1 on error.
const char * guestfs_get_path (guestfs_h *g);
Return the current search path.
This is always non-NULL. If it wasn't set already, then this will return the default path.
This function returns a string, or NULL on error. The string is owned by the guest handle and must not be freed.
int guestfs_get_pid (guestfs_h *g);
Return the process ID of the qemu subprocess. If there is no qemu subprocess, then this will return an error.
This is an internal call used for debugging and testing.
On error this function returns -1.
const char * guestfs_get_qemu (guestfs_h *g);
Return the current qemu binary.
This is always non-NULL. If it wasn't set already, then this will return the default qemu binary name.
This function returns a string, or NULL on error. The string is owned by the guest handle and must not be freed.
int guestfs_get_recovery_proc (guestfs_h *g);
Return the recovery process enabled flag.
This function returns a C truth value on success or -1 on error.
int guestfs_get_selinux (guestfs_h *g);
This returns the current setting of the selinux flag which
is passed to the appliance at boot time. See guestfs_set_selinux
.
For more information on the architecture of libguestfs, see guestfs(3).
This function returns a C truth value on success or -1 on error.
int guestfs_get_state (guestfs_h *g);
This returns the current state as an opaque integer. This is only useful for printing debug and internal error messages.
For more information on states, see guestfs(3).
On error this function returns -1.
int guestfs_get_trace (guestfs_h *g);
Return the command trace flag.
This function returns a C truth value on success or -1 on error.
int guestfs_get_umask (guestfs_h *g);
Return the current umask. By default the umask is 022
unless it has been set by calling guestfs_umask
.
On error this function returns -1.
int guestfs_get_verbose (guestfs_h *g);
This returns the verbose messages flag.
This function returns a C truth value on success or -1 on error.
char * guestfs_getcon (guestfs_h *g);
This gets the SELinux security context of the daemon.
See the documentation about SELINUX in guestfs(3),
and guestfs_setcon
This function returns a string, or NULL on error. The caller must free the returned string after use.
struct guestfs_xattr_list * guestfs_getxattrs (guestfs_h *g, const char *path);
This call lists the extended attributes of the file or directory
path
.
At the system call level, this is a combination of the listxattr(2) and getxattr(2) calls.
See also: guestfs_lgetxattrs
, attr(5).
This function returns a struct guestfs_xattr_list *
(see <guestfs-structs.h>),
or NULL if there was an error.
The caller must call guestfs_free_xattr_list
after use.
char ** guestfs_glob_expand (guestfs_h *g, const char *pattern);
This command searches for all the pathnames matching
pattern
according to the wildcard expansion rules
used by the shell.
If no paths match, then this returns an empty list (note: not an error).
It is just a wrapper around the C glob(3) function
with flags GLOB_MARK|GLOB_BRACE
.
See that manual page for more details.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
char ** guestfs_grep (guestfs_h *g, const char *regex, const char *path);
This calls the external grep
program and returns the
matching lines.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See guestfs(3)/PROTOCOL LIMITS.
char ** guestfs_grepi (guestfs_h *g, const char *regex, const char *path);
This calls the external grep -i
program and returns the
matching lines.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See guestfs(3)/PROTOCOL LIMITS.
int guestfs_grub_install (guestfs_h *g, const char *root, const char *device);
This command installs GRUB (the Grand Unified Bootloader) on
device
, with the root directory being root
.
Note: If grub-install reports the error
"No suitable drive was found in the generated device map."
it may be that you need to create a /boot/grub/device.map
file first that contains the mapping between grub device names
and Linux device names. It is usually sufficient to create
a file containing:
(hd0) /dev/vda
replacing /dev/vda
with the name of the installation device.
This function returns 0 on success or -1 on error.
char ** guestfs_head (guestfs_h *g, const char *path);
This command returns up to the first 10 lines of a file as a list of strings.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See guestfs(3)/PROTOCOL LIMITS.
char ** guestfs_head_n (guestfs_h *g, int nrlines, const char *path);
If the parameter nrlines
is a positive number, this returns the first
nrlines
lines of the file path
.
If the parameter nrlines
is a negative number, this returns lines
from the file path
, excluding the last nrlines
lines.
If the parameter nrlines
is zero, this returns an empty list.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See guestfs(3)/PROTOCOL LIMITS.
char * guestfs_hexdump (guestfs_h *g, const char *path);
This runs hexdump -C
on the given path
. The result is
the human-readable, canonical hex dump of the file.
This function returns a string, or NULL on error. The caller must free the returned string after use.
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See guestfs(3)/PROTOCOL LIMITS.
char * guestfs_initrd_cat (guestfs_h *g, const char *initrdpath, const char *filename, size_t *size_r);
This command unpacks the file filename
from the initrd file
called initrdpath
. The filename must be given without the
initial /
character.
For example, in guestfish you could use the following command
to examine the boot script (usually called /init
)
contained in a Linux initrd or initramfs image:
initrd-cat /boot/initrd-<version>.img init
See also guestfs_initrd_list
.
This function returns a buffer, or NULL on error.
The size of the returned buffer is written to *size_r
.
The caller must free the returned buffer after use.
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See guestfs(3)/PROTOCOL LIMITS.
char ** guestfs_initrd_list (guestfs_h *g, const char *path);
This command lists out files contained in an initrd.
The files are listed without any initial /
character. The
files are listed in the order they appear (not necessarily
alphabetical). Directory names are listed as separate items.
Old Linux kernels (2.4 and earlier) used a compressed ext2 filesystem as initrd. We only support the newer initramfs format (compressed cpio files).
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
int64_t guestfs_inotify_add_watch (guestfs_h *g, const char *path, int mask);
Watch path
for the events listed in mask
.
Note that if path
is a directory then events within that
directory are watched, but this does not happen recursively
(in subdirectories).
Note for non-C or non-Linux callers: the inotify events are
defined by the Linux kernel ABI and are listed in
/usr/include/sys/inotify.h
.
On error this function returns -1.
int guestfs_inotify_close (guestfs_h *g);
This closes the inotify handle which was previously opened by inotify_init. It removes all watches, throws away any pending events, and deallocates all resources.
This function returns 0 on success or -1 on error.
char ** guestfs_inotify_files (guestfs_h *g);
This function is a helpful wrapper around guestfs_inotify_read
which just returns a list of pathnames of objects that were
touched. The returned pathnames are sorted and deduplicated.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
int guestfs_inotify_init (guestfs_h *g, int maxevents);
This command creates a new inotify handle. The inotify subsystem can be used to notify events which happen to objects in the guest filesystem.
maxevents
is the maximum number of events which will be
queued up between calls to guestfs_inotify_read
or
guestfs_inotify_files
.
If this is passed as 0
, then the kernel (or previously set)
default is used. For Linux 2.6.29 the default was 16384 events.
Beyond this limit, the kernel throws away events, but records
the fact that it threw them away by setting a flag
IN_Q_OVERFLOW
in the returned structure list (see
guestfs_inotify_read
).
Before any events are generated, you have to add some
watches to the internal watch list. See:
guestfs_inotify_add_watch
,
guestfs_inotify_rm_watch
and
guestfs_inotify_watch_all
.
Queued up events should be read periodically by calling
guestfs_inotify_read
(or guestfs_inotify_files
which is just a helpful
wrapper around guestfs_inotify_read
). If you don't
read the events out often enough then you risk the internal
queue overflowing.
The handle should be closed after use by calling
guestfs_inotify_close
. This also removes any
watches automatically.
See also inotify(7) for an overview of the inotify interface as exposed by the Linux kernel, which is roughly what we expose via libguestfs. Note that there is one global inotify handle per libguestfs instance.
This function returns 0 on success or -1 on error.
struct guestfs_inotify_event_list * guestfs_inotify_read (guestfs_h *g);
Return the complete queue of events that have happened since the previous read call.
If no events have happened, this returns an empty list.
Note: In order to make sure that all events have been read, you must call this function repeatedly until it returns an empty list. The reason is that the call will read events up to the maximum appliance-to-host message size and leave remaining events in the queue.
This function returns a struct guestfs_inotify_event_list *
(see <guestfs-structs.h>),
or NULL if there was an error.
The caller must call guestfs_free_inotify_event_list
after use.
int guestfs_inotify_rm_watch (guestfs_h *g, int wd);
Remove a previously defined inotify watch.
See guestfs_inotify_add_watch
.
This function returns 0 on success or -1 on error.
char * guestfs_inspect_get_arch (guestfs_h *g, const char *root);
This function should only be called with a root device string
as returned by guestfs_inspect_os
.
This returns the architecture of the inspected operating system.
The possible return values are listed under
guestfs_file_architecture
.
If the architecture could not be determined, then the
string unknown
is returned.
Please read guestfs(3)/INSPECTION for more details.
This function returns a string, or NULL on error. The caller must free the returned string after use.
char * guestfs_inspect_get_distro (guestfs_h *g, const char *root);
This function should only be called with a root device string
as returned by guestfs_inspect_os
.
This returns the distro (distribution) of the inspected operating system.
Currently defined distros are:
Arch Linux.
Debian.
Fedora.
Gentoo.
MeeGo.
Pardus.
Some Red Hat-derived distro.
Red Hat Enterprise Linux and some derivatives.
Ubuntu.
The distro could not be determined.
Windows does not have distributions. This string is returned if the OS type is Windows.
Future versions of libguestfs may return other strings here. The caller should be prepared to handle any string.
Please read guestfs(3)/INSPECTION for more details.
This function returns a string, or NULL on error. The caller must free the returned string after use.
char ** guestfs_inspect_get_filesystems (guestfs_h *g, const char *root);
This function should only be called with a root device string
as returned by guestfs_inspect_os
.
This returns a list of all the filesystems that we think are associated with this operating system. This includes the root filesystem, other ordinary filesystems, and non-mounted devices like swap partitions.
In the case of a multi-boot virtual machine, it is possible for a filesystem to be shared between operating systems.
Please read guestfs(3)/INSPECTION for more details.
See also guestfs_inspect_get_mountpoints
.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
int guestfs_inspect_get_major_version (guestfs_h *g, const char *root);
This function should only be called with a root device string
as returned by guestfs_inspect_os
.
This returns the major version number of the inspected operating system.
Windows uses a consistent versioning scheme which is not reflected in the popular public names used by the operating system. Notably the operating system known as "Windows 7" is really version 6.1 (ie. major = 6, minor = 1). You can find out the real versions corresponding to releases of Windows by consulting Wikipedia or MSDN.
If the version could not be determined, then 0
is returned.
Please read guestfs(3)/INSPECTION for more details.
On error this function returns -1.
int guestfs_inspect_get_minor_version (guestfs_h *g, const char *root);
This function should only be called with a root device string
as returned by guestfs_inspect_os
.
This returns the minor version number of the inspected operating system.
If the version could not be determined, then 0
is returned.
Please read guestfs(3)/INSPECTION for more details.
See also guestfs_inspect_get_major_version
.
On error this function returns -1.
char ** guestfs_inspect_get_mountpoints (guestfs_h *g, const char *root);
This function should only be called with a root device string
as returned by guestfs_inspect_os
.
This returns a hash of where we think the filesystems
associated with this operating system should be mounted.
Callers should note that this is at best an educated guess
made by reading configuration files such as /etc/fstab
.
Each element in the returned hashtable has a key which
is the path of the mountpoint (eg. /boot
) and a value
which is the filesystem that would be mounted there
(eg. /dev/sda1
).
Non-mounted devices such as swap devices are not returned in this list.
Please read guestfs(3)/INSPECTION for more details.
See also guestfs_inspect_get_filesystems
.
This function returns a NULL-terminated array of
strings, or NULL if there was an error.
The array of strings will always have length 2n+1
, where
n
keys and values alternate, followed by the trailing NULL entry.
The caller must free the strings and the array after use.
char * guestfs_inspect_get_product_name (guestfs_h *g, const char *root);
This function should only be called with a root device string
as returned by guestfs_inspect_os
.
This returns the product name of the inspected operating system. The product name is generally some freeform string which can be displayed to the user, but should not be parsed by programs.
If the product name could not be determined, then the
string unknown
is returned.
Please read guestfs(3)/INSPECTION for more details.
This function returns a string, or NULL on error. The caller must free the returned string after use.
char * guestfs_inspect_get_type (guestfs_h *g, const char *root);
This function should only be called with a root device string
as returned by guestfs_inspect_os
.
This returns the type of the inspected operating system. Currently defined types are:
Any Linux-based operating system.
Any Microsoft Windows operating system.
The operating system type could not be determined.
Future versions of libguestfs may return other strings here. The caller should be prepared to handle any string.
Please read guestfs(3)/INSPECTION for more details.
This function returns a string, or NULL on error. The caller must free the returned string after use.
char * guestfs_inspect_get_windows_systemroot (guestfs_h *g, const char *root);
This function should only be called with a root device string
as returned by guestfs_inspect_os
.
This returns the Windows systemroot of the inspected guest.
The systemroot is a directory path such as /WINDOWS
.
This call assumes that the guest is Windows and that the systemroot could be determined by inspection. If this is not the case then an error is returned.
Please read guestfs(3)/INSPECTION for more details.
This function returns a string, or NULL on error. The caller must free the returned string after use.
char ** guestfs_inspect_os (guestfs_h *g);
This function uses other libguestfs functions and certain heuristics to inspect the disk(s) (usually disks belonging to a virtual machine), looking for operating systems.
The list returned is empty if no operating systems were found.
If one operating system was found, then this returns a list with a single element, which is the name of the root filesystem of this operating system. It is also possible for this function to return a list containing more than one element, indicating a dual-boot or multi-boot virtual machine, with each element being the root filesystem of one of the operating systems.
You can pass the root string(s) returned to other
guestfs_inspect_get_*
functions in order to query further
information about each operating system, such as the name
and version.
This function uses other libguestfs features such as
guestfs_mount_ro
and guestfs_umount_all
in order to mount
and unmount filesystems and look at the contents. This should
be called with no disks currently mounted. The function may also
use Augeas, so any existing Augeas handle will be closed.
This function cannot decrypt encrypted disks. The caller must do that first (supplying the necessary keys) if the disk is encrypted.
Please read guestfs(3)/INSPECTION for more details.
See also guestfs_list_filesystems
.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
int guestfs_is_blockdev (guestfs_h *g, const char *path);
This returns true
if and only if there is a block device
with the given path
name.
See also guestfs_stat
.
This function returns a C truth value on success or -1 on error.
int guestfs_is_busy (guestfs_h *g);
This returns true iff this handle is busy processing a command
(in the BUSY
state).
For more information on states, see guestfs(3).
This function returns a C truth value on success or -1 on error.
int guestfs_is_chardev (guestfs_h *g, const char *path);
This returns true
if and only if there is a character device
with the given path
name.
See also guestfs_stat
.
This function returns a C truth value on success or -1 on error.
int guestfs_is_config (guestfs_h *g);
This returns true iff this handle is being configured
(in the CONFIG
state).
For more information on states, see guestfs(3).
This function returns a C truth value on success or -1 on error.
int guestfs_is_dir (guestfs_h *g, const char *path);
This returns true
if and only if there is a directory
with the given path
name. Note that it returns false for
other objects like files.
See also guestfs_stat
.
This function returns a C truth value on success or -1 on error.
int guestfs_is_fifo (guestfs_h *g, const char *path);
This returns true
if and only if there is a FIFO (named pipe)
with the given path
name.
See also guestfs_stat
.
This function returns a C truth value on success or -1 on error.
int guestfs_is_file (guestfs_h *g, const char *path);
This returns true
if and only if there is a regular file
with the given path
name. Note that it returns false for
other objects like directories.
See also guestfs_stat
.
This function returns a C truth value on success or -1 on error.
int guestfs_is_launching (guestfs_h *g);
This returns true iff this handle is launching the subprocess
(in the LAUNCHING
state).
For more information on states, see guestfs(3).
This function returns a C truth value on success or -1 on error.
int guestfs_is_lv (guestfs_h *g, const char *device);
This command tests whether device
is a logical volume, and
returns true iff this is the case.
This function returns a C truth value on success or -1 on error.
int guestfs_is_ready (guestfs_h *g);
This returns true iff this handle is ready to accept commands
(in the READY
state).
For more information on states, see guestfs(3).
This function returns a C truth value on success or -1 on error.
int guestfs_is_socket (guestfs_h *g, const char *path);
This returns true
if and only if there is a Unix domain socket
with the given path
name.
See also guestfs_stat
.
This function returns a C truth value on success or -1 on error.
int guestfs_is_symlink (guestfs_h *g, const char *path);
This returns true
if and only if there is a symbolic link
with the given path
name.
See also guestfs_stat
.
This function returns a C truth value on success or -1 on error.
int guestfs_kill_subprocess (guestfs_h *g);
This kills the qemu subprocess. You should never need to call this.
This function returns 0 on success or -1 on error.
int guestfs_launch (guestfs_h *g);
Internally libguestfs is implemented by running a virtual machine using qemu(1).
You should call this after configuring the handle (eg. adding drives) but before performing any actions.
This function returns 0 on success or -1 on error.
int guestfs_lchown (guestfs_h *g, int owner, int group, const char *path);
Change the file owner to owner
and group to group
.
This is like guestfs_chown
but if path
is a symlink then
the link itself is changed, not the target.
Only numeric uid and gid are supported. If you want to use names, you will need to locate and parse the password file yourself (Augeas support makes this relatively easy).
This function returns 0 on success or -1 on error.
struct guestfs_xattr_list * guestfs_lgetxattrs (guestfs_h *g, const char *path);
This is the same as guestfs_getxattrs
, but if path
is a symbolic link, then it returns the extended attributes
of the link itself.
This function returns a struct guestfs_xattr_list *
(see <guestfs-structs.h>),
or NULL if there was an error.
The caller must call guestfs_free_xattr_list
after use.
char ** guestfs_list_devices (guestfs_h *g);
List all the block devices.
The full block device names are returned, eg. /dev/sda
.
See also guestfs_list_filesystems
.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
char ** guestfs_list_filesystems (guestfs_h *g);
This inspection command looks for filesystems on partitions, block devices and logical volumes, returning a list of devices containing filesystems and their type.
The return value is a hash, where the keys are the devices containing filesystems, and the values are the filesystem types. For example:
"/dev/sda1" => "ntfs" "/dev/sda2" => "ext2" "/dev/vg_guest/lv_root" => "ext4" "/dev/vg_guest/lv_swap" => "swap"
The value can have the special value "unknown", meaning the content of the device is undetermined or empty. "swap" means a Linux swap partition.
This command runs other libguestfs commands, which might include
guestfs_mount
and guestfs_umount
, and therefore you should
use this soon after launch and only when nothing is mounted.
Not all of the filesystems returned will be mountable. In
particular, swap partitions are returned in the list. Also
this command does not check that each filesystem
found is valid and mountable, and some filesystems might
be mountable but require special options. Filesystems may
not all belong to a single logical operating system
(use guestfs_inspect_os
to look for OSes).
This function returns a NULL-terminated array of
strings, or NULL if there was an error.
The array of strings will always have length 2n+1
, where
n
keys and values alternate, followed by the trailing NULL entry.
The caller must free the strings and the array after use.
char ** guestfs_list_partitions (guestfs_h *g);
List all the partitions detected on all block devices.
The full partition device names are returned, eg. /dev/sda1
This does not return logical volumes. For that you will need to
call guestfs_lvs
.
See also guestfs_list_filesystems
.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
char * guestfs_ll (guestfs_h *g, const char *directory);
List the files in directory
(relative to the root directory,
there is no cwd) in the format of 'ls -la'.
This command is mostly useful for interactive sessions. It is not intended that you try to parse the output string.
This function returns a string, or NULL on error. The caller must free the returned string after use.
int guestfs_ln (guestfs_h *g, const char *target, const char *linkname);
This command creates a hard link using the ln
command.
This function returns 0 on success or -1 on error.
int guestfs_ln_f (guestfs_h *g, const char *target, const char *linkname);
This command creates a hard link using the ln -f
command.
The -f
option removes the link (linkname
) if it exists already.
This function returns 0 on success or -1 on error.
int guestfs_ln_s (guestfs_h *g, const char *target, const char *linkname);
This command creates a symbolic link using the ln -s
command.
This function returns 0 on success or -1 on error.
int guestfs_ln_sf (guestfs_h *g, const char *target, const char *linkname);
This command creates a symbolic link using the ln -sf
command,
The -f
option removes the link (linkname
) if it exists already.
This function returns 0 on success or -1 on error.
int guestfs_lremovexattr (guestfs_h *g, const char *xattr, const char *path);
This is the same as guestfs_removexattr
, but if path
is a symbolic link, then it removes an extended attribute
of the link itself.
This function returns 0 on success or -1 on error.
char ** guestfs_ls (guestfs_h *g, const char *directory);
List the files in directory
(relative to the root directory,
there is no cwd). The '.' and '..' entries are not returned, but
hidden files are shown.
This command is mostly useful for interactive sessions. Programs
should probably use guestfs_readdir
instead.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
int guestfs_lsetxattr (guestfs_h *g, const char *xattr, const char *val, int vallen, const char *path);
This is the same as guestfs_setxattr
, but if path
is a symbolic link, then it sets an extended attribute
of the link itself.
This function returns 0 on success or -1 on error.
struct guestfs_stat * guestfs_lstat (guestfs_h *g, const char *path);
Returns file information for the given path
.
This is the same as guestfs_stat
except that if path
is a symbolic link, then the link is stat-ed, not the file it
refers to.
This is the same as the lstat(2)
system call.
This function returns a struct guestfs_stat *
,
or NULL if there was an error.
The caller must call guestfs_free_stat
after use.
struct guestfs_stat_list * guestfs_lstatlist (guestfs_h *g, const char *path, char *const *names);
This call allows you to perform the guestfs_lstat
operation
on multiple files, where all files are in the directory path
.
names
is the list of files from this directory.
On return you get a list of stat structs, with a one-to-one
correspondence to the names
list. If any name did not exist
or could not be lstat'd, then the ino
field of that structure
is set to -1
.
This call is intended for programs that want to efficiently
list a directory contents without making many round-trips.
See also guestfs_lxattrlist
for a similarly efficient call
for getting extended attributes. Very long directory listings
might cause the protocol message size to be exceeded, causing
this call to fail. The caller must split up such requests
into smaller groups of names.
This function returns a struct guestfs_stat_list *
(see <guestfs-structs.h>),
or NULL if there was an error.
The caller must call guestfs_free_stat_list
after use.
int guestfs_luks_add_key (guestfs_h *g, const char *device, const char *key, const char *newkey, int keyslot);
This command adds a new key on LUKS device device
.
key
is any existing key, and is used to access the device.
newkey
is the new key to add. keyslot
is the key slot
that will be replaced.
Note that if keyslot
already contains a key, then this
command will fail. You have to use guestfs_luks_kill_slot
first to remove that key.
This function returns 0 on success or -1 on error.
This function takes a key or passphrase parameter which could contain sensitive material. Read the section KEYS AND PASSPHRASES for more information.
int guestfs_luks_close (guestfs_h *g, const char *device);
This closes a LUKS device that was created earlier by
guestfs_luks_open
or guestfs_luks_open_ro
. The
device
parameter must be the name of the LUKS mapping
device (ie. /dev/mapper/mapname
) and not the name
of the underlying block device.
This function returns 0 on success or -1 on error.
int guestfs_luks_format (guestfs_h *g, const char *device, const char *key, int keyslot);
This command erases existing data on device
and formats
the device as a LUKS encrypted device. key
is the
initial key, which is added to key slot slot
. (LUKS
supports 8 key slots, numbered 0-7).
This function returns 0 on success or -1 on error.
This command is dangerous. Without careful use you can easily destroy all your data.
This function takes a key or passphrase parameter which could contain sensitive material. Read the section KEYS AND PASSPHRASES for more information.
int guestfs_luks_format_cipher (guestfs_h *g, const char *device, const char *key, int keyslot, const char *cipher);
This command is the same as guestfs_luks_format
but
it also allows you to set the cipher
used.
This function returns 0 on success or -1 on error.
This command is dangerous. Without careful use you can easily destroy all your data.
This function takes a key or passphrase parameter which could contain sensitive material. Read the section KEYS AND PASSPHRASES for more information.
int guestfs_luks_kill_slot (guestfs_h *g, const char *device, const char *key, int keyslot);
This command deletes the key in key slot keyslot
from the
encrypted LUKS device device
. key
must be one of the
other keys.
This function returns 0 on success or -1 on error.
This function takes a key or passphrase parameter which could contain sensitive material. Read the section KEYS AND PASSPHRASES for more information.
int guestfs_luks_open (guestfs_h *g, const char *device, const char *key, const char *mapname);
This command opens a block device which has been encrypted according to the Linux Unified Key Setup (LUKS) standard.
device
is the encrypted block device or partition.
The caller must supply one of the keys associated with the
LUKS block device, in the key
parameter.
This creates a new block device called /dev/mapper/mapname
.
Reads and writes to this block device are decrypted from and
encrypted to the underlying device
respectively.
If this block device contains LVM volume groups, then
calling guestfs_vgscan
followed by guestfs_vg_activate_all
will make them visible.
This function returns 0 on success or -1 on error.
This function takes a key or passphrase parameter which could contain sensitive material. Read the section KEYS AND PASSPHRASES for more information.
int guestfs_luks_open_ro (guestfs_h *g, const char *device, const char *key, const char *mapname);
This is the same as guestfs_luks_open
except that a read-only
mapping is created.
This function returns 0 on success or -1 on error.
This function takes a key or passphrase parameter which could contain sensitive material. Read the section KEYS AND PASSPHRASES for more information.
int guestfs_lvcreate (guestfs_h *g, const char *logvol, const char *volgroup, int mbytes);
This creates an LVM logical volume called logvol
on the volume group volgroup
, with size
megabytes.
This function returns 0 on success or -1 on error.
char * guestfs_lvm_canonical_lv_name (guestfs_h *g, const char *lvname);
This converts alternative naming schemes for LVs that you
might find to the canonical name. For example, /dev/mapper/VG-LV
is converted to /dev/VG/LV
.
This command returns an error if the lvname
parameter does
not refer to a logical volume.
See also guestfs_is_lv
.
This function returns a string, or NULL on error. The caller must free the returned string after use.
int guestfs_lvm_clear_filter (guestfs_h *g);
This undoes the effect of guestfs_lvm_set_filter
. LVM
will be able to see every block device.
This command also clears the LVM cache and performs a volume group scan.
This function returns 0 on success or -1 on error.
int guestfs_lvm_remove_all (guestfs_h *g);
This command removes all LVM logical volumes, volume groups and physical volumes.
This function returns 0 on success or -1 on error.
This command is dangerous. Without careful use you can easily destroy all your data.
int guestfs_lvm_set_filter (guestfs_h *g, char *const *devices);
This sets the LVM device filter so that LVM will only be
able to "see" the block devices in the list devices
,
and will ignore all other attached block devices.
Where disk image(s) contain duplicate PVs or VGs, this command is useful to get LVM to ignore the duplicates, otherwise LVM can get confused. Note also there are two types of duplication possible: either cloned PVs/VGs which have identical UUIDs; or VGs that are not cloned but just happen to have the same name. In normal operation you cannot create this situation, but you can do it outside LVM, eg. by cloning disk images or by bit twiddling inside the LVM metadata.
This command also clears the LVM cache and performs a volume group scan.
You can filter whole block devices or individual partitions.
You cannot use this if any VG is currently in use (eg. contains a mounted filesystem), even if you are not filtering out that VG.
This function returns 0 on success or -1 on error.
int guestfs_lvremove (guestfs_h *g, const char *device);
Remove an LVM logical volume device
, where device
is
the path to the LV, such as /dev/VG/LV
.
You can also remove all LVs in a volume group by specifying
the VG name, /dev/VG
.
This function returns 0 on success or -1 on error.
int guestfs_lvrename (guestfs_h *g, const char *logvol, const char *newlogvol);
Rename a logical volume logvol
with the new name newlogvol
.
This function returns 0 on success or -1 on error.
int guestfs_lvresize (guestfs_h *g, const char *device, int mbytes);
This resizes (expands or shrinks) an existing LVM logical
volume to mbytes
. When reducing, data in the reduced part
is lost.
This function returns 0 on success or -1 on error.
int guestfs_lvresize_free (guestfs_h *g, const char *lv, int percent);
This expands an existing logical volume lv
so that it fills
pc
% of the remaining free space in the volume group. Commonly
you would call this with pc = 100 which expands the logical volume
as much as possible, using all remaining free space in the volume
group.
This function returns 0 on success or -1 on error.
char ** guestfs_lvs (guestfs_h *g);
List all the logical volumes detected. This is the equivalent of the lvs(8) command.
This returns a list of the logical volume device names
(eg. /dev/VolGroup00/LogVol00
).
See also guestfs_lvs_full
, guestfs_list_filesystems
.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
struct guestfs_lvm_lv_list * guestfs_lvs_full (guestfs_h *g);
List all the logical volumes detected. This is the equivalent of the lvs(8) command. The "full" version includes all fields.
This function returns a struct guestfs_lvm_lv_list *
(see <guestfs-structs.h>),
or NULL if there was an error.
The caller must call guestfs_free_lvm_lv_list
after use.
char * guestfs_lvuuid (guestfs_h *g, const char *device);
This command returns the UUID of the LVM LV device
.
This function returns a string, or NULL on error. The caller must free the returned string after use.
struct guestfs_xattr_list * guestfs_lxattrlist (guestfs_h *g, const char *path, char *const *names);
This call allows you to get the extended attributes
of multiple files, where all files are in the directory path
.
names
is the list of files from this directory.
On return you get a flat list of xattr structs which must be
interpreted sequentially. The first xattr struct always has a zero-length
attrname
. attrval
in this struct is zero-length
to indicate there was an error doing lgetxattr
for this
file, or is a C string which is a decimal number
(the number of following attributes for this file, which could
be "0"
). Then after the first xattr struct are the
zero or more attributes for the first named file.
This repeats for the second and subsequent files.
This call is intended for programs that want to efficiently
list a directory contents without making many round-trips.
See also guestfs_lstatlist
for a similarly efficient call
for getting standard stats. Very long directory listings
might cause the protocol message size to be exceeded, causing
this call to fail. The caller must split up such requests
into smaller groups of names.
This function returns a struct guestfs_xattr_list *
(see <guestfs-structs.h>),
or NULL if there was an error.
The caller must call guestfs_free_xattr_list
after use.
int guestfs_mkdir (guestfs_h *g, const char *path);
Create a directory named path
.
This function returns 0 on success or -1 on error.
int guestfs_mkdir_mode (guestfs_h *g, const char *path, int mode);
This command creates a directory, setting the initial permissions
of the directory to mode
.
For common Linux filesystems, the actual mode which is set will
be mode & ~umask & 01777
. Non-native-Linux filesystems may
interpret the mode in other ways.
See also guestfs_mkdir
, guestfs_umask
This function returns 0 on success or -1 on error.
int guestfs_mkdir_p (guestfs_h *g, const char *path);
Create a directory named path
, creating any parent directories
as necessary. This is like the mkdir -p
shell command.
This function returns 0 on success or -1 on error.
char * guestfs_mkdtemp (guestfs_h *g, const char *template);
This command creates a temporary directory. The
template
parameter should be a full pathname for the
temporary directory name with the final six characters being
"XXXXXX".
For example: "/tmp/myprogXXXXXX" or "/Temp/myprogXXXXXX", the second one being suitable for Windows filesystems.
The name of the temporary directory that was created is returned.
The temporary directory is created with mode 0700 and is owned by root.
The caller is responsible for deleting the temporary directory and its contents after use.
See also: mkdtemp(3)
This function returns a string, or NULL on error. The caller must free the returned string after use.
int guestfs_mke2fs_J (guestfs_h *g, const char *fstype, int blocksize, const char *device, const char *journal);
This creates an ext2/3/4 filesystem on device
with
an external journal on journal
. It is equivalent
to the command:
mke2fs -t fstype -b blocksize -J device=<journal> <device>
See also guestfs_mke2journal
.
This function returns 0 on success or -1 on error.
int guestfs_mke2fs_JL (guestfs_h *g, const char *fstype, int blocksize, const char *device, const char *label);
This creates an ext2/3/4 filesystem on device
with
an external journal on the journal labeled label
.
See also guestfs_mke2journal_L
.
This function returns 0 on success or -1 on error.
int guestfs_mke2fs_JU (guestfs_h *g, const char *fstype, int blocksize, const char *device, const char *uuid);
This creates an ext2/3/4 filesystem on device
with
an external journal on the journal with UUID uuid
.
See also guestfs_mke2journal_U
.
This function returns 0 on success or -1 on error.
int guestfs_mke2journal (guestfs_h *g, int blocksize, const char *device);
This creates an ext2 external journal on device
. It is equivalent
to the command:
mke2fs -O journal_dev -b blocksize device
This function returns 0 on success or -1 on error.
int guestfs_mke2journal_L (guestfs_h *g, int blocksize, const char *label, const char *device);
This creates an ext2 external journal on device
with label label
.
This function returns 0 on success or -1 on error.
int guestfs_mke2journal_U (guestfs_h *g, int blocksize, const char *uuid, const char *device);
This creates an ext2 external journal on device
with UUID uuid
.
This function returns 0 on success or -1 on error.
int guestfs_mkfifo (guestfs_h *g, int mode, const char *path);
This call creates a FIFO (named pipe) called path
with
mode mode
. It is just a convenient wrapper around
guestfs_mknod
.
The mode actually set is affected by the umask.
This function returns 0 on success or -1 on error.
int guestfs_mkfs (guestfs_h *g, const char *fstype, const char *device);
This creates a filesystem on device
(usually a partition
or LVM logical volume). The filesystem type is fstype
, for
example ext3
.
This function returns 0 on success or -1 on error.
int guestfs_mkfs_b (guestfs_h *g, const char *fstype, int blocksize, const char *device);
This call is similar to guestfs_mkfs
, but it allows you to
control the block size of the resulting filesystem. Supported
block sizes depend on the filesystem type, but typically they
are 1024
, 2048
or 4096
only.
For VFAT and NTFS the blocksize
parameter is treated as
the requested cluster size.
This function returns 0 on success or -1 on error.
int guestfs_mkmountpoint (guestfs_h *g, const char *exemptpath);
guestfs_mkmountpoint
and guestfs_rmmountpoint
are
specialized calls that can be used to create extra mountpoints
before mounting the first filesystem.
These calls are only necessary in some very limited circumstances, mainly the case where you want to mount a mix of unrelated and/or read-only filesystems together.
For example, live CDs often contain a "Russian doll" nest of filesystems, an ISO outer layer, with a squashfs image inside, with an ext2/3 image inside that. You can unpack this as follows in guestfish:
add-ro Fedora-11-i686-Live.iso run mkmountpoint /cd mkmountpoint /sqsh mkmountpoint /ext3fs mount /dev/sda /cd mount-loop /cd/LiveOS/squashfs.img /sqsh mount-loop /sqsh/LiveOS/ext3fs.img /ext3fs
The inner filesystem is now unpacked under the /ext3fs mountpoint.
guestfs_mkmountpoint
is not compatible with guestfs_umount_all
.
You may get unexpected errors if you try to mix these calls. It is
safest to manually unmount filesystems and remove mountpoints after use.
guestfs_umount_all
unmounts filesystems by sorting the paths
longest first, so for this to work for manual mountpoints, you
must ensure that the innermost mountpoints have the longest
pathnames, as in the example code above.
For more details see https://bugzilla.redhat.com/show_bug.cgi?id=599503
Autosync [see guestfs_set_autosync
, this is set by default on
handles] means that guestfs_umount_all
is called when the handle
is closed which can also trigger these issues.
This function returns 0 on success or -1 on error.
int guestfs_mknod (guestfs_h *g, int mode, int devmajor, int devminor, const char *path);
This call creates block or character special devices, or named pipes (FIFOs).
The mode
parameter should be the mode, using the standard
constants. devmajor
and devminor
are the
device major and minor numbers, only used when creating block
and character special devices.
Note that, just like mknod(2), the mode must be bitwise
OR'd with S_IFBLK, S_IFCHR, S_IFIFO or S_IFSOCK (otherwise this call
just creates a regular file). These constants are
available in the standard Linux header files, or you can use
guestfs_mknod_b
, guestfs_mknod_c
or guestfs_mkfifo
which are wrappers around this command which bitwise OR
in the appropriate constant for you.
The mode actually set is affected by the umask.
This function returns 0 on success or -1 on error.
int guestfs_mknod_b (guestfs_h *g, int mode, int devmajor, int devminor, const char *path);
This call creates a block device node called path
with
mode mode
and device major/minor devmajor
and devminor
.
It is just a convenient wrapper around guestfs_mknod
.
The mode actually set is affected by the umask.
This function returns 0 on success or -1 on error.
int guestfs_mknod_c (guestfs_h *g, int mode, int devmajor, int devminor, const char *path);
This call creates a char device node called path
with
mode mode
and device major/minor devmajor
and devminor
.
It is just a convenient wrapper around guestfs_mknod
.
The mode actually set is affected by the umask.
This function returns 0 on success or -1 on error.
int guestfs_mkswap (guestfs_h *g, const char *device);
Create a swap partition on device
.
This function returns 0 on success or -1 on error.
int guestfs_mkswap_L (guestfs_h *g, const char *label, const char *device);
Create a swap partition on device
with label label
.
Note that you cannot attach a swap label to a block device
(eg. /dev/sda
), just to a partition. This appears to be
a limitation of the kernel or swap tools.
This function returns 0 on success or -1 on error.
int guestfs_mkswap_U (guestfs_h *g, const char *uuid, const char *device);
Create a swap partition on device
with UUID uuid
.
This function returns 0 on success or -1 on error.
int guestfs_mkswap_file (guestfs_h *g, const char *path);
Create a swap file.
This command just writes a swap file signature to an existing
file. To create the file itself, use something like guestfs_fallocate
.
This function returns 0 on success or -1 on error.
int guestfs_modprobe (guestfs_h *g, const char *modulename);
This loads a kernel module in the appliance.
The kernel module must have been whitelisted when libguestfs
was built (see appliance/kmod.whitelist.in
in the source).
This function returns 0 on success or -1 on error.
int guestfs_mount (guestfs_h *g, const char *device, const char *mountpoint);
Mount a guest disk at a position in the filesystem. Block devices
are named /dev/sda
, /dev/sdb
and so on, as they were added to
the guest. If those block devices contain partitions, they will have
the usual names (eg. /dev/sda1
). Also LVM /dev/VG/LV
-style
names can be used.
The rules are the same as for mount(2): A filesystem must
first be mounted on /
before others can be mounted. Other
filesystems can only be mounted on directories which already
exist.
The mounted filesystem is writable, if we have sufficient permissions on the underlying device.
Important note:
When you use this call, the filesystem options sync
and noatime
are set implicitly. This was originally done because we thought it
would improve reliability, but it turns out that -o sync has a
very large negative performance impact and negligible effect on
reliability. Therefore we recommend that you avoid using
guestfs_mount
in any code that needs performance, and instead
use guestfs_mount_options
(use an empty string for the first
parameter if you don't want any options).
This function returns 0 on success or -1 on error.
int guestfs_mount_loop (guestfs_h *g, const char *file, const char *mountpoint);
This command lets you mount file
(a filesystem image
in a file) on a mount point. It is entirely equivalent to
the command mount -o loop file mountpoint
.
This function returns 0 on success or -1 on error.
int guestfs_mount_options (guestfs_h *g, const char *options, const char *device, const char *mountpoint);
This is the same as the guestfs_mount
command, but it
allows you to set the mount options as for the
mount(8) -o flag.
If the options
parameter is an empty string, then
no options are passed (all options default to whatever
the filesystem uses).
This function returns 0 on success or -1 on error.
int guestfs_mount_ro (guestfs_h *g, const char *device, const char *mountpoint);
This is the same as the guestfs_mount
command, but it
mounts the filesystem with the read-only (-o ro) flag.
This function returns 0 on success or -1 on error.
int guestfs_mount_vfs (guestfs_h *g, const char *options, const char *vfstype, const char *device, const char *mountpoint);
This is the same as the guestfs_mount
command, but it
allows you to set both the mount options and the vfstype
as for the mount(8) -o and -t flags.
This function returns 0 on success or -1 on error.
char ** guestfs_mountpoints (guestfs_h *g);
This call is similar to guestfs_mounts
. That call returns
a list of devices. This one returns a hash table (map) of
device name to directory where the device is mounted.
This function returns a NULL-terminated array of
strings, or NULL if there was an error.
The array of strings will always have length 2n+1
, where
n
keys and values alternate, followed by the trailing NULL entry.
The caller must free the strings and the array after use.
char ** guestfs_mounts (guestfs_h *g);
This returns the list of currently mounted filesystems. It returns
the list of devices (eg. /dev/sda1
, /dev/VG/LV
).
Some internal mounts are not shown.
See also: guestfs_mountpoints
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
int guestfs_mv (guestfs_h *g, const char *src, const char *dest);
This moves a file from src
to dest
where dest
is
either a destination filename or destination directory.
This function returns 0 on success or -1 on error.
int guestfs_ntfs_3g_probe (guestfs_h *g, int rw, const char *device);
This command runs the ntfs-3g.probe(8) command which probes
an NTFS device
for mountability. (Not all NTFS volumes can
be mounted read-write, and some cannot be mounted at all).
rw
is a boolean flag. Set it to true if you want to test
if the volume can be mounted read-write. Set it to false if
you want to test if the volume can be mounted read-only.
The return value is an integer which 0
if the operation
would succeed, or some non-zero value documented in the
ntfs-3g.probe(8) manual page.
On error this function returns -1.
int guestfs_ntfsresize (guestfs_h *g, const char *device);
This command resizes an NTFS filesystem, expanding or shrinking it to the size of the underlying device. See also ntfsresize(8).
This function returns 0 on success or -1 on error.
int guestfs_ntfsresize_size (guestfs_h *g, const char *device, int64_t size);
This command is the same as guestfs_ntfsresize
except that it
allows you to specify the new size (in bytes) explicitly.
This function returns 0 on success or -1 on error.
int guestfs_part_add (guestfs_h *g, const char *device, const char *prlogex, int64_t startsect, int64_t endsect);
This command adds a partition to device
. If there is no partition
table on the device, call guestfs_part_init
first.
The prlogex
parameter is the type of partition. Normally you
should pass p
or primary
here, but MBR partition tables also
support l
(or logical
) and e
(or extended
) partition
types.
startsect
and endsect
are the start and end of the partition
in sectors. endsect
may be negative, which means it counts
backwards from the end of the disk (-1
is the last sector).
Creating a partition which covers the whole disk is not so easy.
Use guestfs_part_disk
to do that.
This function returns 0 on success or -1 on error.
int guestfs_part_del (guestfs_h *g, const char *device, int partnum);
This command deletes the partition numbered partnum
on device
.
Note that in the case of MBR partitioning, deleting an extended partition also deletes any logical partitions it contains.
This function returns 0 on success or -1 on error.
int guestfs_part_disk (guestfs_h *g, const char *device, const char *parttype);
This command is simply a combination of guestfs_part_init
followed by guestfs_part_add
to create a single primary partition
covering the whole disk.
parttype
is the partition table type, usually mbr
or gpt
,
but other possible values are described in guestfs_part_init
.
This function returns 0 on success or -1 on error.
This command is dangerous. Without careful use you can easily destroy all your data.
int guestfs_part_get_bootable (guestfs_h *g, const char *device, int partnum);
This command returns true if the partition partnum
on
device
has the bootable flag set.
See also guestfs_part_set_bootable
.
This function returns a C truth value on success or -1 on error.
int guestfs_part_get_mbr_id (guestfs_h *g, const char *device, int partnum);
Returns the MBR type byte (also known as the ID byte) from
the numbered partition partnum
.
Note that only MBR (old DOS-style) partitions have type bytes.
You will get undefined results for other partition table
types (see guestfs_part_get_parttype
).
On error this function returns -1.
char * guestfs_part_get_parttype (guestfs_h *g, const char *device);
This command examines the partition table on device
and
returns the partition table type (format) being used.
Common return values include: msdos
(a DOS/Windows style MBR
partition table), gpt
(a GPT/EFI-style partition table). Other
values are possible, although unusual. See guestfs_part_init
for a full list.
This function returns a string, or NULL on error. The caller must free the returned string after use.
int guestfs_part_init (guestfs_h *g, const char *device, const char *parttype);
This creates an empty partition table on device
of one of the
partition types listed below. Usually parttype
should be
either msdos
or gpt
(for large disks).
Initially there are no partitions. Following this, you should
call guestfs_part_add
for each partition required.
Possible values for parttype
are:
Intel EFI / GPT partition table.
This is recommended for >= 2 TB partitions that will be accessed
from Linux and Intel-based Mac OS X. It also has limited backwards
compatibility with the mbr
format.
The standard PC "Master Boot Record" (MBR) format used
by MS-DOS and Windows. This partition type will only work
for device sizes up to 2 TB. For large disks we recommend
using gpt
.
Other partition table types that may work but are not supported include:
AIX disk labels.
Amiga "Rigid Disk Block" format.
BSD disk labels.
DASD, used on IBM mainframes.
MIPS/SGI volumes.
Old Mac partition format. Modern Macs use gpt
.
NEC PC-98 format, common in Japan apparently.
Sun disk labels.
This function returns 0 on success or -1 on error.
struct guestfs_partition_list * guestfs_part_list (guestfs_h *g, const char *device);
This command parses the partition table on device
and
returns the list of partitions found.
The fields in the returned structure are:
Partition number, counting from 1.
Start of the partition in bytes. To get sectors you have to
divide by the device's sector size, see guestfs_blockdev_getss
.
End of the partition in bytes.
Size of the partition in bytes.
This function returns a struct guestfs_partition_list *
(see <guestfs-structs.h>),
or NULL if there was an error.
The caller must call guestfs_free_partition_list
after use.
int guestfs_part_set_bootable (guestfs_h *g, const char *device, int partnum, int bootable);
This sets the bootable flag on partition numbered partnum
on
device device
. Note that partitions are numbered from 1.
The bootable flag is used by some operating systems (notably Windows) to determine which partition to boot from. It is by no means universally recognized.
This function returns 0 on success or -1 on error.
int guestfs_part_set_mbr_id (guestfs_h *g, const char *device, int partnum, int idbyte);
Sets the MBR type byte (also known as the ID byte) of
the numbered partition partnum
to idbyte
. Note
that the type bytes quoted in most documentation are
in fact hexadecimal numbers, but usually documented
without any leading "0x" which might be confusing.
Note that only MBR (old DOS-style) partitions have type bytes.
You will get undefined results for other partition table
types (see guestfs_part_get_parttype
).
This function returns 0 on success or -1 on error.
int guestfs_part_set_name (guestfs_h *g, const char *device, int partnum, const char *name);
This sets the partition name on partition numbered partnum
on
device device
. Note that partitions are numbered from 1.
The partition name can only be set on certain types of partition
table. This works on gpt
but not on mbr
partitions.
This function returns 0 on success or -1 on error.
char * guestfs_part_to_dev (guestfs_h *g, const char *partition);
This function takes a partition name (eg. "/dev/sdb1") and removes the partition number, returning the device name (eg. "/dev/sdb").
The named partition must exist, for example as a string returned
from guestfs_list_partitions
.
This function returns a string, or NULL on error. The caller must free the returned string after use.
int guestfs_ping_daemon (guestfs_h *g);
This is a test probe into the guestfs daemon running inside the qemu subprocess. Calling this function checks that the daemon responds to the ping message, without affecting the daemon or attached block device(s) in any other way.
This function returns 0 on success or -1 on error.
char * guestfs_pread (guestfs_h *g, const char *path, int count, int64_t offset, size_t *size_r);
This command lets you read part of a file. It reads count
bytes of the file, starting at offset
, from file path
.
This may read fewer bytes than requested. For further details see the pread(2) system call.
See also guestfs_pwrite
, guestfs_pread_device
.
This function returns a buffer, or NULL on error.
The size of the returned buffer is written to *size_r
.
The caller must free the returned buffer after use.
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See guestfs(3)/PROTOCOL LIMITS.
char * guestfs_pread_device (guestfs_h *g, const char *device, int count, int64_t offset, size_t *size_r);
This command lets you read part of a file. It reads count
bytes of device
, starting at offset
.
This may read fewer bytes than requested. For further details see the pread(2) system call.
See also guestfs_pread
.
This function returns a buffer, or NULL on error.
The size of the returned buffer is written to *size_r
.
The caller must free the returned buffer after use.
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See guestfs(3)/PROTOCOL LIMITS.
int guestfs_pvcreate (guestfs_h *g, const char *device);
This creates an LVM physical volume on the named device
,
where device
should usually be a partition name such
as /dev/sda1
.
This function returns 0 on success or -1 on error.
int guestfs_pvremove (guestfs_h *g, const char *device);
This wipes a physical volume device
so that LVM will no longer
recognise it.
The implementation uses the pvremove
command which refuses to
wipe physical volumes that contain any volume groups, so you have
to remove those first.
This function returns 0 on success or -1 on error.
int guestfs_pvresize (guestfs_h *g, const char *device);
This resizes (expands or shrinks) an existing LVM physical volume to match the new size of the underlying device.
This function returns 0 on success or -1 on error.
int guestfs_pvresize_size (guestfs_h *g, const char *device, int64_t size);
This command is the same as guestfs_pvresize
except that it
allows you to specify the new size (in bytes) explicitly.
This function returns 0 on success or -1 on error.
char ** guestfs_pvs (guestfs_h *g);
List all the physical volumes detected. This is the equivalent of the pvs(8) command.
This returns a list of just the device names that contain
PVs (eg. /dev/sda2
).
See also guestfs_pvs_full
.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
struct guestfs_lvm_pv_list * guestfs_pvs_full (guestfs_h *g);
List all the physical volumes detected. This is the equivalent of the pvs(8) command. The "full" version includes all fields.
This function returns a struct guestfs_lvm_pv_list *
(see <guestfs-structs.h>),
or NULL if there was an error.
The caller must call guestfs_free_lvm_pv_list
after use.
char * guestfs_pvuuid (guestfs_h *g, const char *device);
This command returns the UUID of the LVM PV device
.
This function returns a string, or NULL on error. The caller must free the returned string after use.
int guestfs_pwrite (guestfs_h *g, const char *path, const char *content, size_t content_size, int64_t offset);
This command writes to part of a file. It writes the data
buffer content
to the file path
starting at offset offset
.
This command implements the pwrite(2) system call, and like that system call it may not write the full data requested. The return value is the number of bytes that were actually written to the file. This could even be 0, although short writes are unlikely for regular files in ordinary circumstances.
See also guestfs_pread
, guestfs_pwrite_device
.
On error this function returns -1.
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See guestfs(3)/PROTOCOL LIMITS.
int guestfs_pwrite_device (guestfs_h *g, const char *device, const char *content, size_t content_size, int64_t offset);
This command writes to part of a device. It writes the data
buffer content
to device
starting at offset offset
.
This command implements the pwrite(2) system call, and like that system call it may not write the full data requested (although short writes to disk devices and partitions are probably impossible with standard Linux kernels).
See also guestfs_pwrite
.
On error this function returns -1.
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See guestfs(3)/PROTOCOL LIMITS.
char * guestfs_read_file (guestfs_h *g, const char *path, size_t *size_r);
This calls returns the contents of the file path
as a
buffer.
Unlike guestfs_cat
, this function can correctly
handle files that contain embedded ASCII NUL characters.
However unlike guestfs_download
, this function is limited
in the total size of file that can be handled.
This function returns a buffer, or NULL on error.
The size of the returned buffer is written to *size_r
.
The caller must free the returned buffer after use.
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See guestfs(3)/PROTOCOL LIMITS.
char ** guestfs_read_lines (guestfs_h *g, const char *path);
Return the contents of the file named path
.
The file contents are returned as a list of lines. Trailing
LF
and CRLF
character sequences are not returned.
Note that this function cannot correctly handle binary files
(specifically, files containing \0
character which is treated
as end of line). For those you need to use the guestfs_read_file
function which has a more complex interface.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
struct guestfs_dirent_list * guestfs_readdir (guestfs_h *g, const char *dir);
This returns the list of directory entries in directory dir
.
All entries in the directory are returned, including .
and
..
. The entries are not sorted, but returned in the same
order as the underlying filesystem.
Also this call returns basic file type information about each
file. The ftyp
field will contain one of the following characters:
Block special
Char special
Directory
FIFO (named pipe)
Symbolic link
Regular file
Socket
Unknown file type
The readdir(3) call returned a d_type
field with an
unexpected value
This function is primarily intended for use by programs. To
get a simple list of names, use guestfs_ls
. To get a printable
directory for human consumption, use guestfs_ll
.
This function returns a struct guestfs_dirent_list *
(see <guestfs-structs.h>),
or NULL if there was an error.
The caller must call guestfs_free_dirent_list
after use.
char * guestfs_readlink (guestfs_h *g, const char *path);
This command reads the target of a symbolic link.
This function returns a string, or NULL on error. The caller must free the returned string after use.
char ** guestfs_readlinklist (guestfs_h *g, const char *path, char *const *names);
This call allows you to do a readlink
operation
on multiple files, where all files are in the directory path
.
names
is the list of files from this directory.
On return you get a list of strings, with a one-to-one
correspondence to the names
list. Each string is the
value of the symbolic link.
If the readlink(2)
operation fails on any name, then
the corresponding result string is the empty string ""
.
However the whole operation is completed even if there
were readlink(2)
errors, and so you can call this
function with names where you don't know if they are
symbolic links already (albeit slightly less efficient).
This call is intended for programs that want to efficiently list a directory contents without making many round-trips. Very long directory listings might cause the protocol message size to be exceeded, causing this call to fail. The caller must split up such requests into smaller groups of names.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
char * guestfs_realpath (guestfs_h *g, const char *path);
Return the canonicalized absolute pathname of path
. The
returned path has no .
, ..
or symbolic link path elements.
This function returns a string, or NULL on error. The caller must free the returned string after use.
int guestfs_removexattr (guestfs_h *g, const char *xattr, const char *path);
This call removes the extended attribute named xattr
of the file path
.
See also: guestfs_lremovexattr
, attr(5).
This function returns 0 on success or -1 on error.
int guestfs_resize2fs (guestfs_h *g, const char *device);
This resizes an ext2, ext3 or ext4 filesystem to match the size of the underlying device.
Note: It is sometimes required that you run guestfs_e2fsck_f
on the device
before calling this command. For unknown reasons
resize2fs
sometimes gives an error about this and sometimes not.
In any case, it is always safe to call guestfs_e2fsck_f
before
calling this function.
This function returns 0 on success or -1 on error.
int guestfs_resize2fs_size (guestfs_h *g, const char *device, int64_t size);
This command is the same as guestfs_resize2fs
except that it
allows you to specify the new size (in bytes) explicitly.
This function returns 0 on success or -1 on error.
int guestfs_rm (guestfs_h *g, const char *path);
Remove the single file path
.
This function returns 0 on success or -1 on error.
int guestfs_rm_rf (guestfs_h *g, const char *path);
Remove the file or directory path
, recursively removing the
contents if its a directory. This is like the rm -rf
shell
command.
This function returns 0 on success or -1 on error.
int guestfs_rmdir (guestfs_h *g, const char *path);
Remove the single directory path
.
This function returns 0 on success or -1 on error.
int guestfs_rmmountpoint (guestfs_h *g, const char *exemptpath);
This calls removes a mountpoint that was previously created
with guestfs_mkmountpoint
. See guestfs_mkmountpoint
for full details.
This function returns 0 on success or -1 on error.
int guestfs_scrub_device (guestfs_h *g, const char *device);
This command writes patterns over device
to make data retrieval
more difficult.
It is an interface to the scrub(1) program. See that manual page for more details.
This function returns 0 on success or -1 on error.
This command is dangerous. Without careful use you can easily destroy all your data.
int guestfs_scrub_file (guestfs_h *g, const char *file);
This command writes patterns over a file to make data retrieval more difficult.
The file is removed after scrubbing.
It is an interface to the scrub(1) program. See that manual page for more details.
This function returns 0 on success or -1 on error.
int guestfs_scrub_freespace (guestfs_h *g, const char *dir);
This command creates the directory dir
and then fills it
with files until the filesystem is full, and scrubs the files
as for guestfs_scrub_file
, and deletes them.
The intention is to scrub any free space on the partition
containing dir
.
It is an interface to the scrub(1) program. See that manual page for more details.
This function returns 0 on success or -1 on error.
int guestfs_set_append (guestfs_h *g, const char *append);
This function is used to add additional options to the guest kernel command line.
The default is NULL
unless overridden by setting
LIBGUESTFS_APPEND
environment variable.
Setting append
to NULL
means no additional options
are passed (libguestfs always adds a few of its own).
This function returns 0 on success or -1 on error.
int guestfs_set_autosync (guestfs_h *g, int autosync);
If autosync
is true, this enables autosync. Libguestfs will make a
best effort attempt to run guestfs_umount_all
followed by
guestfs_sync
when the handle is closed
(also if the program exits without closing handles).
This is enabled by default (since libguestfs 1.5.24, previously it was disabled by default).
This function returns 0 on success or -1 on error.
int guestfs_set_direct (guestfs_h *g, int direct);
If the direct appliance mode flag is enabled, then stdin and stdout are passed directly through to the appliance once it is launched.
One consequence of this is that log messages aren't caught
by the library and handled by guestfs_set_log_message_callback
,
but go straight to stdout.
You probably don't want to use this unless you know what you are doing.
The default is disabled.
This function returns 0 on success or -1 on error.
int guestfs_set_e2label (guestfs_h *g, const char *device, const char *label);
This sets the ext2/3/4 filesystem label of the filesystem on
device
to label
. Filesystem labels are limited to
16 characters.
You can use either guestfs_tune2fs_l
or guestfs_get_e2label
to return the existing label on a filesystem.
This function returns 0 on success or -1 on error.
int guestfs_set_e2uuid (guestfs_h *g, const char *device, const char *uuid);
This sets the ext2/3/4 filesystem UUID of the filesystem on
device
to uuid
. The format of the UUID and alternatives
such as clear
, random
and time
are described in the
tune2fs(8) manpage.
You can use either guestfs_tune2fs_l
or guestfs_get_e2uuid
to return the existing UUID of a filesystem.
This function returns 0 on success or -1 on error.
int guestfs_set_memsize (guestfs_h *g, int memsize);
This sets the memory size in megabytes allocated to the
qemu subprocess. This only has any effect if called before
guestfs_launch
.
You can also change this by setting the environment
variable LIBGUESTFS_MEMSIZE
before the handle is
created.
For more information on the architecture of libguestfs, see guestfs(3).
This function returns 0 on success or -1 on error.
int guestfs_set_network (guestfs_h *g, int network);
If network
is true, then the network is enabled in the
libguestfs appliance. The default is false.
This affects whether commands are able to access the network (see guestfs(3)/RUNNING COMMANDS).
You must call this before calling guestfs_launch
, otherwise
it has no effect.
This function returns 0 on success or -1 on error.
int guestfs_set_path (guestfs_h *g, const char *searchpath);
Set the path that libguestfs searches for kernel and initrd.img.
The default is $libdir/guestfs
unless overridden by setting
LIBGUESTFS_PATH
environment variable.
Setting path
to NULL
restores the default path.
This function returns 0 on success or -1 on error.
int guestfs_set_qemu (guestfs_h *g, const char *qemu);
Set the qemu binary that we will use.
The default is chosen when the library was compiled by the configure script.
You can also override this by setting the LIBGUESTFS_QEMU
environment variable.
Setting qemu
to NULL
restores the default qemu binary.
Note that you should call this function as early as possible
after creating the handle. This is because some pre-launch
operations depend on testing qemu features (by running qemu -help
).
If the qemu binary changes, we don't retest features, and
so you might see inconsistent results. Using the environment
variable LIBGUESTFS_QEMU
is safest of all since that picks
the qemu binary at the same time as the handle is created.
This function returns 0 on success or -1 on error.
int guestfs_set_recovery_proc (guestfs_h *g, int recoveryproc);
If this is called with the parameter false
then
guestfs_launch
does not create a recovery process. The
purpose of the recovery process is to stop runaway qemu
processes in the case where the main program aborts abruptly.
This only has any effect if called before guestfs_launch
,
and the default is true.
About the only time when you would want to disable this is if the main process will fork itself into the background ("daemonize" itself). In this case the recovery process thinks that the main program has disappeared and so kills qemu, which is not very helpful.
This function returns 0 on success or -1 on error.
int guestfs_set_selinux (guestfs_h *g, int selinux);
This sets the selinux flag that is passed to the appliance
at boot time. The default is selinux=0
(disabled).
Note that if SELinux is enabled, it is always in
Permissive mode (enforcing=0
).
For more information on the architecture of libguestfs, see guestfs(3).
This function returns 0 on success or -1 on error.
int guestfs_set_trace (guestfs_h *g, int trace);
If the command trace flag is set to 1, then commands are printed on stderr before they are executed in a format which is very similar to the one used by guestfish. In other words, you can run a program with this enabled, and you will get out a script which you can feed to guestfish to perform the same set of actions.
If you want to trace C API calls into libguestfs (and
other libraries) then possibly a better way is to use
the external ltrace(1)
command.
Command traces are disabled unless the environment variable
LIBGUESTFS_TRACE
is defined and set to 1
.
This function returns 0 on success or -1 on error.
int guestfs_set_verbose (guestfs_h *g, int verbose);
If verbose
is true, this turns on verbose messages (to stderr
).
Verbose messages are disabled unless the environment variable
LIBGUESTFS_DEBUG
is defined and set to 1
.
This function returns 0 on success or -1 on error.
int guestfs_setcon (guestfs_h *g, const char *context);
This sets the SELinux security context of the daemon
to the string context
.
See the documentation about SELINUX in guestfs(3).
This function returns 0 on success or -1 on error.
int guestfs_setxattr (guestfs_h *g, const char *xattr, const char *val, int vallen, const char *path);
This call sets the extended attribute named xattr
of the file path
to the value val
(of length vallen
).
The value is arbitrary 8 bit data.
See also: guestfs_lsetxattr
, attr(5).
This function returns 0 on success or -1 on error.
int guestfs_sfdisk (guestfs_h *g, const char *device, int cyls, int heads, int sectors, char *const *lines);
This is a direct interface to the sfdisk(8) program for creating partitions on block devices.
device
should be a block device, for example /dev/sda
.
cyls
, heads
and sectors
are the number of cylinders, heads
and sectors on the device, which are passed directly to sfdisk as
the -C, -H and -S parameters. If you pass 0
for any
of these, then the corresponding parameter is omitted. Usually for
'large' disks, you can just pass 0
for these, but for small
(floppy-sized) disks, sfdisk (or rather, the kernel) cannot work
out the right geometry and you will need to tell it.
lines
is a list of lines that we feed to sfdisk
. For more
information refer to the sfdisk(8) manpage.
To create a single partition occupying the whole disk, you would
pass lines
as a single element list, when the single element being
the string ,
(comma).
See also: guestfs_sfdisk_l
, guestfs_sfdisk_N
,
guestfs_part_init
This function returns 0 on success or -1 on error.
This command is dangerous. Without careful use you can easily destroy all your data.
int guestfs_sfdiskM (guestfs_h *g, const char *device, char *const *lines);
This is a simplified interface to the guestfs_sfdisk
command, where partition sizes are specified in megabytes
only (rounded to the nearest cylinder) and you don't need
to specify the cyls, heads and sectors parameters which
were rarely if ever used anyway.
See also: guestfs_sfdisk
, the sfdisk(8) manpage
and guestfs_part_disk
This function returns 0 on success or -1 on error.
This command is dangerous. Without careful use you can easily destroy all your data.
int guestfs_sfdisk_N (guestfs_h *g, const char *device, int partnum, int cyls, int heads, int sectors, const char *line);
This runs sfdisk(8) option to modify just the single
partition n
(note: n
counts from 1).
For other parameters, see guestfs_sfdisk
. You should usually
pass 0
for the cyls/heads/sectors parameters.
See also: guestfs_part_add
This function returns 0 on success or -1 on error.
This command is dangerous. Without careful use you can easily destroy all your data.
char * guestfs_sfdisk_disk_geometry (guestfs_h *g, const char *device);
This displays the disk geometry of device
read from the
partition table. Especially in the case where the underlying
block device has been resized, this can be different from the
kernel's idea of the geometry (see guestfs_sfdisk_kernel_geometry
).
The result is in human-readable format, and not designed to be parsed.
This function returns a string, or NULL on error. The caller must free the returned string after use.
char * guestfs_sfdisk_kernel_geometry (guestfs_h *g, const char *device);
This displays the kernel's idea of the geometry of device
.
The result is in human-readable format, and not designed to be parsed.
This function returns a string, or NULL on error. The caller must free the returned string after use.
char * guestfs_sfdisk_l (guestfs_h *g, const char *device);
This displays the partition table on device
, in the
human-readable output of the sfdisk(8) command. It is
not intended to be parsed.
See also: guestfs_part_list
This function returns a string, or NULL on error. The caller must free the returned string after use.
char * guestfs_sh (guestfs_h *g, const char *command);
This call runs a command from the guest filesystem via the
guest's /bin/sh
.
This is like guestfs_command
, but passes the command to:
/bin/sh -c "command"
Depending on the guest's shell, this usually results in wildcards being expanded, shell expressions being interpolated and so on.
All the provisos about guestfs_command
apply to this call.
This function returns a string, or NULL on error. The caller must free the returned string after use.
char ** guestfs_sh_lines (guestfs_h *g, const char *command);
This is the same as guestfs_sh
, but splits the result
into a list of lines.
See also: guestfs_command_lines
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
int guestfs_sleep (guestfs_h *g, int secs);
Sleep for secs
seconds.
This function returns 0 on success or -1 on error.
struct guestfs_stat * guestfs_stat (guestfs_h *g, const char *path);
Returns file information for the given path
.
This is the same as the stat(2)
system call.
This function returns a struct guestfs_stat *
,
or NULL if there was an error.
The caller must call guestfs_free_stat
after use.
struct guestfs_statvfs * guestfs_statvfs (guestfs_h *g, const char *path);
Returns file system statistics for any mounted file system.
path
should be a file or directory in the mounted file system
(typically it is the mount point itself, but it doesn't need to be).
This is the same as the statvfs(2)
system call.
This function returns a struct guestfs_statvfs *
,
or NULL if there was an error.
The caller must call guestfs_free_statvfs
after use.
char ** guestfs_strings (guestfs_h *g, const char *path);
This runs the strings(1) command on a file and returns the list of printable strings found.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See guestfs(3)/PROTOCOL LIMITS.
char ** guestfs_strings_e (guestfs_h *g, const char *encoding, const char *path);
This is like the guestfs_strings
command, but allows you to
specify the encoding of strings that are looked for in
the source file path
.
Allowed encodings are:
Single 7-bit-byte characters like ASCII and the ASCII-compatible
parts of ISO-8859-X (this is what guestfs_strings
uses).
Single 8-bit-byte characters.
16-bit big endian strings such as those encoded in UTF-16BE or UCS-2BE.
16-bit little endian such as UTF-16LE and UCS-2LE. This is useful for examining binaries in Windows guests.
32-bit big endian such as UCS-4BE.
32-bit little endian such as UCS-4LE.
The returned strings are transcoded to UTF-8.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See guestfs(3)/PROTOCOL LIMITS.
int guestfs_swapoff_device (guestfs_h *g, const char *device);
This command disables the libguestfs appliance swap
device or partition named device
.
See guestfs_swapon_device
.
This function returns 0 on success or -1 on error.
int guestfs_swapoff_file (guestfs_h *g, const char *file);
This command disables the libguestfs appliance swap on file.
This function returns 0 on success or -1 on error.
int guestfs_swapoff_label (guestfs_h *g, const char *label);
This command disables the libguestfs appliance swap on labeled swap partition.
This function returns 0 on success or -1 on error.
int guestfs_swapoff_uuid (guestfs_h *g, const char *uuid);
This command disables the libguestfs appliance swap partition with the given UUID.
This function returns 0 on success or -1 on error.
int guestfs_swapon_device (guestfs_h *g, const char *device);
This command enables the libguestfs appliance to use the
swap device or partition named device
. The increased
memory is made available for all commands, for example
those run using guestfs_command
or guestfs_sh
.
Note that you should not swap to existing guest swap partitions unless you know what you are doing. They may contain hibernation information, or other information that the guest doesn't want you to trash. You also risk leaking information about the host to the guest this way. Instead, attach a new host device to the guest and swap on that.
This function returns 0 on success or -1 on error.
int guestfs_swapon_file (guestfs_h *g, const char *file);
This command enables swap to a file.
See guestfs_swapon_device
for other notes.
This function returns 0 on success or -1 on error.
int guestfs_swapon_label (guestfs_h *g, const char *label);
This command enables swap to a labeled swap partition.
See guestfs_swapon_device
for other notes.
This function returns 0 on success or -1 on error.
int guestfs_swapon_uuid (guestfs_h *g, const char *uuid);
This command enables swap to a swap partition with the given UUID.
See guestfs_swapon_device
for other notes.
This function returns 0 on success or -1 on error.
int guestfs_sync (guestfs_h *g);
This syncs the disk, so that any writes are flushed through to the underlying disk image.
You should always call this if you have modified a disk image, before closing the handle.
This function returns 0 on success or -1 on error.
char ** guestfs_tail (guestfs_h *g, const char *path);
This command returns up to the last 10 lines of a file as a list of strings.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See guestfs(3)/PROTOCOL LIMITS.
char ** guestfs_tail_n (guestfs_h *g, int nrlines, const char *path);
If the parameter nrlines
is a positive number, this returns the last
nrlines
lines of the file path
.
If the parameter nrlines
is a negative number, this returns lines
from the file path
, starting with the -nrlines
th line.
If the parameter nrlines
is zero, this returns an empty list.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See guestfs(3)/PROTOCOL LIMITS.
int guestfs_tar_in (guestfs_h *g, const char *tarfile, const char *directory);
This command uploads and unpacks local file tarfile
(an
uncompressed tar file) into directory
.
To upload a compressed tarball, use guestfs_tgz_in
or guestfs_txz_in
.
This function returns 0 on success or -1 on error.
int guestfs_tar_out (guestfs_h *g, const char *directory, const char *tarfile);
This command packs the contents of directory
and downloads
it to local file tarfile
.
To download a compressed tarball, use guestfs_tgz_out
or guestfs_txz_out
.
This function returns 0 on success or -1 on error.
int guestfs_tgz_in (guestfs_h *g, const char *tarball, const char *directory);
This command uploads and unpacks local file tarball
(a
gzip compressed tar file) into directory
.
To upload an uncompressed tarball, use guestfs_tar_in
.
This function returns 0 on success or -1 on error.
int guestfs_tgz_out (guestfs_h *g, const char *directory, const char *tarball);
This command packs the contents of directory
and downloads
it to local file tarball
.
To download an uncompressed tarball, use guestfs_tar_out
.
This function returns 0 on success or -1 on error.
int guestfs_touch (guestfs_h *g, const char *path);
Touch acts like the touch(1) command. It can be used to update the timestamps on a file, or, if the file does not exist, to create a new zero-length file.
This command only works on regular files, and will fail on other file types such as directories, symbolic links, block special etc.
This function returns 0 on success or -1 on error.
int guestfs_truncate (guestfs_h *g, const char *path);
This command truncates path
to a zero-length file. The
file must exist already.
This function returns 0 on success or -1 on error.
int guestfs_truncate_size (guestfs_h *g, const char *path, int64_t size);
This command truncates path
to size size
bytes. The file
must exist already.
If the current file size is less than size
then
the file is extended to the required size with zero bytes.
This creates a sparse file (ie. disk blocks are not allocated
for the file until you write to it). To create a non-sparse
file of zeroes, use guestfs_fallocate64
instead.
This function returns 0 on success or -1 on error.
char ** guestfs_tune2fs_l (guestfs_h *g, const char *device);
This returns the contents of the ext2, ext3 or ext4 filesystem
superblock on device
.
It is the same as running tune2fs -l device
. See tune2fs(8)
manpage for more details. The list of fields returned isn't
clearly defined, and depends on both the version of tune2fs
that libguestfs was built against, and the filesystem itself.
This function returns a NULL-terminated array of
strings, or NULL if there was an error.
The array of strings will always have length 2n+1
, where
n
keys and values alternate, followed by the trailing NULL entry.
The caller must free the strings and the array after use.
int guestfs_txz_in (guestfs_h *g, const char *tarball, const char *directory);
This command uploads and unpacks local file tarball
(an
xz compressed tar file) into directory
.
This function returns 0 on success or -1 on error.
int guestfs_txz_out (guestfs_h *g, const char *directory, const char *tarball);
This command packs the contents of directory
and downloads
it to local file tarball
(as an xz compressed tar archive).
This function returns 0 on success or -1 on error.
int guestfs_umask (guestfs_h *g, int mask);
This function sets the mask used for creating new files and
device nodes to mask & 0777
.
Typical umask values would be 022
which creates new files
with permissions like "-rw-r--r--" or "-rwxr-xr-x", and
002
which creates new files with permissions like
"-rw-rw-r--" or "-rwxrwxr-x".
The default umask is 022
. This is important because it
means that directories and device nodes will be created with
0644
or 0755
mode even if you specify 0777
.
See also guestfs_get_umask
,
umask(2), guestfs_mknod
, guestfs_mkdir
.
This call returns the previous umask.
On error this function returns -1.
int guestfs_umount (guestfs_h *g, const char *pathordevice);
This unmounts the given filesystem. The filesystem may be specified either by its mountpoint (path) or the device which contains the filesystem.
This function returns 0 on success or -1 on error.
int guestfs_umount_all (guestfs_h *g);
This unmounts all mounted filesystems.
Some internal mounts are not unmounted by this call.
This function returns 0 on success or -1 on error.
int guestfs_upload (guestfs_h *g, const char *filename, const char *remotefilename);
Upload local file filename
to remotefilename
on the
filesystem.
filename
can also be a named pipe.
See also guestfs_download
.
This function returns 0 on success or -1 on error.
int guestfs_upload_offset (guestfs_h *g, const char *filename, const char *remotefilename, int64_t offset);
Upload local file filename
to remotefilename
on the
filesystem.
remotefilename
is overwritten starting at the byte offset
specified. The intention is to overwrite parts of existing
files or devices, although if a non-existant file is specified
then it is created with a "hole" before offset
. The
size of the data written is implicit in the size of the
source filename
.
Note that there is no limit on the amount of data that
can be uploaded with this call, unlike with guestfs_pwrite
,
and this call always writes the full amount unless an
error occurs.
See also guestfs_upload
, guestfs_pwrite
.
This function returns 0 on success or -1 on error.
int guestfs_utimens (guestfs_h *g, const char *path, int64_t atsecs, int64_t atnsecs, int64_t mtsecs, int64_t mtnsecs);
This command sets the timestamps of a file with nanosecond precision.
atsecs, atnsecs
are the last access time (atime) in secs and
nanoseconds from the epoch.
mtsecs, mtnsecs
are the last modification time (mtime) in
secs and nanoseconds from the epoch.
If the *nsecs
field contains the special value -1
then
the corresponding timestamp is set to the current time. (The
*secs
field is ignored in this case).
If the *nsecs
field contains the special value -2
then
the corresponding timestamp is left unchanged. (The
*secs
field is ignored in this case).
This function returns 0 on success or -1 on error.
struct guestfs_version * guestfs_version (guestfs_h *g);
Return the libguestfs version number that the program is linked against.
Note that because of dynamic linking this is not necessarily
the version of libguestfs that you compiled against. You can
compile the program, and then at runtime dynamically link
against a completely different libguestfs.so
library.
This call was added in version 1.0.58
. In previous
versions of libguestfs there was no way to get the version
number. From C code you can use dynamic linker functions
to find out if this symbol exists (if it doesn't, then
it's an earlier version).
The call returns a structure with four elements. The first
three (major
, minor
and release
) are numbers and
correspond to the usual version triplet. The fourth element
(extra
) is a string and is normally empty, but may be
used for distro-specific information.
To construct the original version string:
$major.$minor.$release$extra
See also: guestfs(3)/LIBGUESTFS VERSION NUMBERS.
Note: Don't use this call to test for availability
of features. In enterprise distributions we backport
features from later versions into earlier versions,
making this an unreliable way to test for features.
Use guestfs_available
instead.
This function returns a struct guestfs_version *
,
or NULL if there was an error.
The caller must call guestfs_free_version
after use.
char * guestfs_vfs_label (guestfs_h *g, const char *device);
This returns the filesystem label of the filesystem on
device
.
If the filesystem is unlabeled, this returns the empty string.
To find a filesystem from the label, use guestfs_findfs_label
.
This function returns a string, or NULL on error. The caller must free the returned string after use.
char * guestfs_vfs_type (guestfs_h *g, const char *device);
This command gets the filesystem type corresponding to
the filesystem on device
.
For most filesystems, the result is the name of the Linux
VFS module which would be used to mount this filesystem
if you mounted it without specifying the filesystem type.
For example a string such as ext3
or ntfs
.
This function returns a string, or NULL on error. The caller must free the returned string after use.
char * guestfs_vfs_uuid (guestfs_h *g, const char *device);
This returns the filesystem UUID of the filesystem on
device
.
If the filesystem does not have a UUID, this returns the empty string.
To find a filesystem from the UUID, use guestfs_findfs_uuid
.
This function returns a string, or NULL on error. The caller must free the returned string after use.
int guestfs_vg_activate (guestfs_h *g, int activate, char *const *volgroups);
This command activates or (if activate
is false) deactivates
all logical volumes in the listed volume groups volgroups
.
If activated, then they are made known to the
kernel, ie. they appear as /dev/mapper
devices. If deactivated,
then those devices disappear.
This command is the same as running vgchange -a y|n volgroups...
Note that if volgroups
is an empty list then all volume groups
are activated or deactivated.
This function returns 0 on success or -1 on error.
int guestfs_vg_activate_all (guestfs_h *g, int activate);
This command activates or (if activate
is false) deactivates
all logical volumes in all volume groups.
If activated, then they are made known to the
kernel, ie. they appear as /dev/mapper
devices. If deactivated,
then those devices disappear.
This command is the same as running vgchange -a y|n
This function returns 0 on success or -1 on error.
int guestfs_vgcreate (guestfs_h *g, const char *volgroup, char *const *physvols);
This creates an LVM volume group called volgroup
from the non-empty list of physical volumes physvols
.
This function returns 0 on success or -1 on error.
char ** guestfs_vglvuuids (guestfs_h *g, const char *vgname);
Given a VG called vgname
, this returns the UUIDs of all
the logical volumes created in this volume group.
You can use this along with guestfs_lvs
and guestfs_lvuuid
calls to associate logical volumes and volume groups.
See also guestfs_vgpvuuids
.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
char ** guestfs_vgpvuuids (guestfs_h *g, const char *vgname);
Given a VG called vgname
, this returns the UUIDs of all
the physical volumes that this volume group resides on.
You can use this along with guestfs_pvs
and guestfs_pvuuid
calls to associate physical volumes and volume groups.
See also guestfs_vglvuuids
.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
int guestfs_vgremove (guestfs_h *g, const char *vgname);
Remove an LVM volume group vgname
, (for example VG
).
This also forcibly removes all logical volumes in the volume group (if any).
This function returns 0 on success or -1 on error.
int guestfs_vgrename (guestfs_h *g, const char *volgroup, const char *newvolgroup);
Rename a volume group volgroup
with the new name newvolgroup
.
This function returns 0 on success or -1 on error.
char ** guestfs_vgs (guestfs_h *g);
List all the volumes groups detected. This is the equivalent of the vgs(8) command.
This returns a list of just the volume group names that were
detected (eg. VolGroup00
).
See also guestfs_vgs_full
.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
struct guestfs_lvm_vg_list * guestfs_vgs_full (guestfs_h *g);
List all the volumes groups detected. This is the equivalent of the vgs(8) command. The "full" version includes all fields.
This function returns a struct guestfs_lvm_vg_list *
(see <guestfs-structs.h>),
or NULL if there was an error.
The caller must call guestfs_free_lvm_vg_list
after use.
int guestfs_vgscan (guestfs_h *g);
This rescans all block devices and rebuilds the list of LVM physical volumes, volume groups and logical volumes.
This function returns 0 on success or -1 on error.
char * guestfs_vguuid (guestfs_h *g, const char *vgname);
This command returns the UUID of the LVM VG named vgname
.
This function returns a string, or NULL on error. The caller must free the returned string after use.
int guestfs_wait_ready (guestfs_h *g);
This function is a no op.
In versions of the API < 1.0.71 you had to call this function
just after calling guestfs_launch
to wait for the launch
to complete. However this is no longer necessary because
guestfs_launch
now does the waiting.
If you see any calls to this function in code then you can just remove them, unless you want to retain compatibility with older versions of the API.
This function returns 0 on success or -1 on error.
int guestfs_wc_c (guestfs_h *g, const char *path);
This command counts the characters in a file, using the
wc -c
external command.
On error this function returns -1.
int guestfs_wc_l (guestfs_h *g, const char *path);
This command counts the lines in a file, using the
wc -l
external command.
On error this function returns -1.
int guestfs_wc_w (guestfs_h *g, const char *path);
This command counts the words in a file, using the
wc -w
external command.
On error this function returns -1.
int guestfs_write (guestfs_h *g, const char *path, const char *content, size_t content_size);
This call creates a file called path
. The content of the
file is the string content
(which can contain any 8 bit data).
This function returns 0 on success or -1 on error.
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See guestfs(3)/PROTOCOL LIMITS.
int guestfs_write_file (guestfs_h *g, const char *path, const char *content, int size);
This call creates a file called path
. The contents of the
file is the string content
(which can contain any 8 bit data),
with length size
.
As a special case, if size
is 0
then the length is calculated using strlen
(so in this case
the content cannot contain embedded ASCII NULs).
NB. Owing to a bug, writing content containing ASCII NUL characters does not work, even if the length is specified.
This function returns 0 on success or -1 on error.
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See guestfs(3)/PROTOCOL LIMITS.
This function is deprecated.
In new code, use the write
call instead.
Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.
char ** guestfs_zegrep (guestfs_h *g, const char *regex, const char *path);
This calls the external zegrep
program and returns the
matching lines.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See guestfs(3)/PROTOCOL LIMITS.
char ** guestfs_zegrepi (guestfs_h *g, const char *regex, const char *path);
This calls the external zegrep -i
program and returns the
matching lines.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See guestfs(3)/PROTOCOL LIMITS.
int guestfs_zero (guestfs_h *g, const char *device);
This command writes zeroes over the first few blocks of device
.
How many blocks are zeroed isn't specified (but it's not enough to securely wipe the device). It should be sufficient to remove any partition tables, filesystem superblocks and so on.
See also: guestfs_zero_device
, guestfs_scrub_device
.
This function returns 0 on success or -1 on error.
This long-running command can generate progress notification messages so that the caller can display a progress bar or indicator. To receive these messages, the caller must register a progress callback. See guestfs(3)/guestfs_set_progress_callback.
int guestfs_zero_device (guestfs_h *g, const char *device);
This command writes zeroes over the entire device
. Compare
with guestfs_zero
which just zeroes the first few blocks of
a device.
This function returns 0 on success or -1 on error.
This long-running command can generate progress notification messages so that the caller can display a progress bar or indicator. To receive these messages, the caller must register a progress callback. See guestfs(3)/guestfs_set_progress_callback.
This command is dangerous. Without careful use you can easily destroy all your data.
int guestfs_zerofree (guestfs_h *g, const char *device);
This runs the zerofree program on device
. This program
claims to zero unused inodes and disk blocks on an ext2/3
filesystem, thus making it possible to compress the filesystem
more effectively.
You should not run this program if the filesystem is mounted.
It is possible that using this program can damage the filesystem or data on the filesystem.
This function returns 0 on success or -1 on error.
char ** guestfs_zfgrep (guestfs_h *g, const char *pattern, const char *path);
This calls the external zfgrep
program and returns the
matching lines.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See guestfs(3)/PROTOCOL LIMITS.
char ** guestfs_zfgrepi (guestfs_h *g, const char *pattern, const char *path);
This calls the external zfgrep -i
program and returns the
matching lines.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See guestfs(3)/PROTOCOL LIMITS.
char * guestfs_zfile (guestfs_h *g, const char *meth, const char *path);
This command runs file
after first decompressing path
using method
.
method
must be one of gzip
, compress
or bzip2
.
Since 1.0.63, use guestfs_file
instead which can now
process compressed files.
This function returns a string, or NULL on error. The caller must free the returned string after use.
This function is deprecated.
In new code, use the file
call instead.
Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.
char ** guestfs_zgrep (guestfs_h *g, const char *regex, const char *path);
This calls the external zgrep
program and returns the
matching lines.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See guestfs(3)/PROTOCOL LIMITS.
char ** guestfs_zgrepi (guestfs_h *g, const char *regex, const char *path);
This calls the external zgrep -i
program and returns the
matching lines.
This function returns a NULL-terminated array of strings (like environ(3)), or NULL if there was an error. The caller must free the strings and the array after use.
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See guestfs(3)/PROTOCOL LIMITS.
struct guestfs_int_bool { int32_t i; int32_t b; }; struct guestfs_int_bool_list { uint32_t len; /* Number of elements in list. */ struct guestfs_int_bool *val; /* Elements. */ }; void guestfs_free_int_bool (struct guestfs_free_int_bool *); void guestfs_free_int_bool_list (struct guestfs_free_int_bool_list *);
struct guestfs_lvm_pv { char *pv_name; /* The next field is NOT nul-terminated, be careful when printing it: */ char pv_uuid[32]; char *pv_fmt; uint64_t pv_size; uint64_t dev_size; uint64_t pv_free; uint64_t pv_used; char *pv_attr; int64_t pv_pe_count; int64_t pv_pe_alloc_count; char *pv_tags; uint64_t pe_start; int64_t pv_mda_count; uint64_t pv_mda_free; }; struct guestfs_lvm_pv_list { uint32_t len; /* Number of elements in list. */ struct guestfs_lvm_pv *val; /* Elements. */ }; void guestfs_free_lvm_pv (struct guestfs_free_lvm_pv *); void guestfs_free_lvm_pv_list (struct guestfs_free_lvm_pv_list *);
struct guestfs_lvm_vg { char *vg_name; /* The next field is NOT nul-terminated, be careful when printing it: */ char vg_uuid[32]; char *vg_fmt; char *vg_attr; uint64_t vg_size; uint64_t vg_free; char *vg_sysid; uint64_t vg_extent_size; int64_t vg_extent_count; int64_t vg_free_count; int64_t max_lv; int64_t max_pv; int64_t pv_count; int64_t lv_count; int64_t snap_count; int64_t vg_seqno; char *vg_tags; int64_t vg_mda_count; uint64_t vg_mda_free; }; struct guestfs_lvm_vg_list { uint32_t len; /* Number of elements in list. */ struct guestfs_lvm_vg *val; /* Elements. */ }; void guestfs_free_lvm_vg (struct guestfs_free_lvm_vg *); void guestfs_free_lvm_vg_list (struct guestfs_free_lvm_vg_list *);
struct guestfs_lvm_lv { char *lv_name; /* The next field is NOT nul-terminated, be careful when printing it: */ char lv_uuid[32]; char *lv_attr; int64_t lv_major; int64_t lv_minor; int64_t lv_kernel_major; int64_t lv_kernel_minor; uint64_t lv_size; int64_t seg_count; char *origin; /* The next field is [0..100] or -1 meaning 'not present': */ float snap_percent; /* The next field is [0..100] or -1 meaning 'not present': */ float copy_percent; char *move_pv; char *lv_tags; char *mirror_log; char *modules; }; struct guestfs_lvm_lv_list { uint32_t len; /* Number of elements in list. */ struct guestfs_lvm_lv *val; /* Elements. */ }; void guestfs_free_lvm_lv (struct guestfs_free_lvm_lv *); void guestfs_free_lvm_lv_list (struct guestfs_free_lvm_lv_list *);
struct guestfs_stat { int64_t dev; int64_t ino; int64_t mode; int64_t nlink; int64_t uid; int64_t gid; int64_t rdev; int64_t size; int64_t blksize; int64_t blocks; int64_t atime; int64_t mtime; int64_t ctime; }; struct guestfs_stat_list { uint32_t len; /* Number of elements in list. */ struct guestfs_stat *val; /* Elements. */ }; void guestfs_free_stat (struct guestfs_free_stat *); void guestfs_free_stat_list (struct guestfs_free_stat_list *);
struct guestfs_statvfs { int64_t bsize; int64_t frsize; int64_t blocks; int64_t bfree; int64_t bavail; int64_t files; int64_t ffree; int64_t favail; int64_t fsid; int64_t flag; int64_t namemax; }; struct guestfs_statvfs_list { uint32_t len; /* Number of elements in list. */ struct guestfs_statvfs *val; /* Elements. */ }; void guestfs_free_statvfs (struct guestfs_free_statvfs *); void guestfs_free_statvfs_list (struct guestfs_free_statvfs_list *);
struct guestfs_dirent { int64_t ino; char ftyp; char *name; }; struct guestfs_dirent_list { uint32_t len; /* Number of elements in list. */ struct guestfs_dirent *val; /* Elements. */ }; void guestfs_free_dirent (struct guestfs_free_dirent *); void guestfs_free_dirent_list (struct guestfs_free_dirent_list *);
struct guestfs_version { int64_t major; int64_t minor; int64_t release; char *extra; }; struct guestfs_version_list { uint32_t len; /* Number of elements in list. */ struct guestfs_version *val; /* Elements. */ }; void guestfs_free_version (struct guestfs_free_version *); void guestfs_free_version_list (struct guestfs_free_version_list *);
struct guestfs_xattr { char *attrname; /* The next two fields describe a byte array. */ uint32_t attrval_len; char *attrval; }; struct guestfs_xattr_list { uint32_t len; /* Number of elements in list. */ struct guestfs_xattr *val; /* Elements. */ }; void guestfs_free_xattr (struct guestfs_free_xattr *); void guestfs_free_xattr_list (struct guestfs_free_xattr_list *);
struct guestfs_inotify_event { int64_t in_wd; uint32_t in_mask; uint32_t in_cookie; char *in_name; }; struct guestfs_inotify_event_list { uint32_t len; /* Number of elements in list. */ struct guestfs_inotify_event *val; /* Elements. */ }; void guestfs_free_inotify_event (struct guestfs_free_inotify_event *); void guestfs_free_inotify_event_list (struct guestfs_free_inotify_event_list *);
struct guestfs_partition { int32_t part_num; uint64_t part_start; uint64_t part_end; uint64_t part_size; }; struct guestfs_partition_list { uint32_t len; /* Number of elements in list. */ struct guestfs_partition *val; /* Elements. */ }; void guestfs_free_partition (struct guestfs_free_partition *); void guestfs_free_partition_list (struct guestfs_free_partition_list *);
Using guestfs_available you can test availability of the following groups of functions. This test queries the appliance to see if the appliance you are currently using supports the functionality.
The following functions: guestfs_aug_clear guestfs_aug_close guestfs_aug_defnode guestfs_aug_defvar guestfs_aug_get guestfs_aug_init guestfs_aug_insert guestfs_aug_load guestfs_aug_ls guestfs_aug_match guestfs_aug_mv guestfs_aug_rm guestfs_aug_save guestfs_aug_set
The following functions: guestfs_inotify_add_watch guestfs_inotify_close guestfs_inotify_files guestfs_inotify_init guestfs_inotify_read guestfs_inotify_rm_watch
The following functions: guestfs_mke2fs_JU guestfs_mke2journal_U guestfs_mkswap_U guestfs_swapoff_uuid guestfs_swapon_uuid
The following functions: guestfs_modprobe
The following functions: guestfs_getxattrs guestfs_lgetxattrs guestfs_lremovexattr guestfs_lsetxattr guestfs_lxattrlist guestfs_removexattr guestfs_setxattr
The following functions: guestfs_luks_add_key guestfs_luks_close guestfs_luks_format guestfs_luks_format_cipher guestfs_luks_kill_slot guestfs_luks_open guestfs_luks_open_ro
The following functions: guestfs_is_lv guestfs_lvcreate guestfs_lvm_remove_all guestfs_lvm_set_filter guestfs_lvremove guestfs_lvresize guestfs_lvresize_free guestfs_lvs guestfs_lvs_full guestfs_pvcreate guestfs_pvremove guestfs_pvresize guestfs_pvresize_size guestfs_pvs guestfs_pvs_full guestfs_vg_activate guestfs_vg_activate_all guestfs_vgcreate guestfs_vgremove guestfs_vgs guestfs_vgs_full
The following functions: guestfs_mkfifo guestfs_mknod guestfs_mknod_b guestfs_mknod_c
The following functions: guestfs_ntfs_3g_probe
The following functions: guestfs_ntfsresize guestfs_ntfsresize_size
The following functions: guestfs_realpath
The following functions: guestfs_scrub_device guestfs_scrub_file guestfs_scrub_freespace
The following functions: guestfs_getcon guestfs_setcon
The following functions: guestfs_txz_in guestfs_txz_out
The following functions: guestfs_zerofree
In guestfish(3) there is a handy interactive command
supported
which prints out the available groups and
whether they are supported by this build of libguestfs.
Note however that you have to do run
first.
Since version 1.5.8, <guestfs.h>
defines symbols
for each C API function, such as:
#define LIBGUESTFS_HAVE_DD 1
if guestfs_dd is available.
Before version 1.5.8, if you needed to test whether a single libguestfs function is available at compile time, we recommended using build tools such as autoconf or cmake. For example in autotools you could use:
AC_CHECK_LIB([guestfs],[guestfs_create]) AC_CHECK_FUNCS([guestfs_dd])
which would result in HAVE_GUESTFS_DD
being either defined
or not defined in your program.
Testing at compile time doesn't guarantee that a function really exists in the library. The reason is that you might be dynamically linked against a previous libguestfs.so (dynamic library) which doesn't have the call. This situation unfortunately results in a segmentation fault, which is a shortcoming of the C dynamic linking system itself.
You can use dlopen(3) to test if a function is available at run time, as in this example program (note that you still need the compile time check as well):
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <dlfcn.h> #include <guestfs.h> main () { #ifdef LIBGUESTFS_HAVE_DD void *dl; int has_function; /* Test if the function guestfs_dd is really available. */ dl = dlopen (NULL, RTLD_LAZY); if (!dl) { fprintf (stderr, "dlopen: %s\n", dlerror ()); exit (EXIT_FAILURE); } has_function = dlsym (dl, "guestfs_dd") != NULL; dlclose (dl); if (!has_function) printf ("this libguestfs.so does NOT have guestfs_dd function\n"); else { printf ("this libguestfs.so has guestfs_dd function\n"); /* Now it's safe to call guestfs_dd (g, "foo", "bar"); */ } #else printf ("guestfs_dd function was not found at compile time\n"); #endif }
You may think the above is an awful lot of hassle, and it is. There are other ways outside of the C linking system to ensure that this kind of incompatibility never arises, such as using package versioning:
Requires: libguestfs >= 1.0.80
A recent feature of the API is the introduction of calls which take
optional arguments. In C these are declared 3 ways. The main way is
as a call which takes variable arguments (ie. ...
), as in this
example:
int guestfs_add_drive_opts (guestfs_h *g, const char *filename, ...);
Call this with a list of optional arguments, terminated by -1
.
So to call with no optional arguments specified:
guestfs_add_drive_opts (g, filename, -1);
With a single optional argument:
guestfs_add_drive_opts (g, filename, GUESTFS_ADD_DRIVE_OPTS_FORMAT, "qcow2", -1);
With two:
guestfs_add_drive_opts (g, filename, GUESTFS_ADD_DRIVE_OPTS_FORMAT, "qcow2", GUESTFS_ADD_DRIVE_OPTS_READONLY, 1, -1);
and so forth. Don't forget the terminating -1
otherwise
Bad Things will happen!
The second variant has the same name with the suffix _va
, which
works the same way but takes a va_list
. See the C manual for
details. For the example function, this is declared:
int guestfs_add_drive_opts_va (guestfs_h *g, const char *filename, va_list args);
The third variant is useful where you need to construct these calls. You pass in a structure where you fill in the optional fields. The structure has a bitmask as the first element which you must set to indicate which fields you have filled in. For our example function the structure and call are declared:
struct guestfs_add_drive_opts_argv { uint64_t bitmask; int readonly; const char *format; /* ... */ }; int guestfs_add_drive_opts_argv (guestfs_h *g, const char *filename, const struct guestfs_add_drive_opts_argv *optargs);
You could call it like this:
struct guestfs_add_drive_opts_argv optargs = { .bitmask = GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK | GUESTFS_ADD_DRIVE_OPTS_FORMAT_BITMASK, .readonly = 1, .format = "qcow2" }; guestfs_add_drive_opts_argv (g, filename, &optargs);
Notes:
The _BITMASK
suffix on each option name when specifying the
bitmask.
You do not need to fill in all fields of the structure.
There must be a one-to-one correspondence between fields of the structure that are filled in, and bits set in the bitmask.
In other languages, optional arguments are expressed in the way that is natural for that language. We refer you to the language-specific documentation for more details on that.
For guestfish, see guestfish(1)/OPTIONAL ARGUMENTS.
The child process generates events in some situations. Current events include: receiving a log message, the child process exits.
Use the guestfs_set_*_callback
functions to set a callback for
different types of events.
Only one callback of each type can be registered for each handle.
Calling guestfs_set_*_callback
again overwrites the previous
callback of that type. Cancel all callbacks of this type by calling
this function with cb
set to NULL
.
typedef void (*guestfs_log_message_cb) (guestfs_h *g, void *opaque, char *buf, int len); void guestfs_set_log_message_callback (guestfs_h *g, guestfs_log_message_cb cb, void *opaque);
The callback function cb
will be called whenever qemu or the guest
writes anything to the console.
Use this function to capture kernel messages and similar.
Normally there is no log message handler, and log messages are just discarded.
typedef void (*guestfs_subprocess_quit_cb) (guestfs_h *g, void *opaque); void guestfs_set_subprocess_quit_callback (guestfs_h *g, guestfs_subprocess_quit_cb cb, void *opaque);
The callback function cb
will be called when the child process
quits, either asynchronously or if killed by
guestfs_kill_subprocess. (This corresponds to a transition from
any state to the CONFIG state).
typedef void (*guestfs_launch_done_cb) (guestfs_h *g, void *opaque); void guestfs_set_launch_done_callback (guestfs_h *g, guestfs_launch_done_cb cb, void *opaque);
The callback function cb
will be called when the child process
becomes ready first time after it has been launched. (This
corresponds to a transition from LAUNCHING to the READY state).
typedef void (*guestfs_close_cb) (guestfs_h *g, void *opaque); void guestfs_set_close_callback (guestfs_h *g, guestfs_close_cb cb, void *opaque);
The callback function cb
will be called while the handle
is being closed (synchronously from guestfs_close).
Note that libguestfs installs an atexit(3) handler to try to clean up handles that are open when the program exits. This means that this callback might be called indirectly from exit(3), which can cause unexpected problems in higher-level languages (eg. if your HLL interpreter has already been cleaned up by the time this is called, and if your callback then jumps into some HLL function).
typedef void (*guestfs_progress_cb) (guestfs_h *g, void *opaque, int proc_nr, int serial, uint64_t position, uint64_t total); void guestfs_set_progress_callback (guestfs_h *g, guestfs_progress_cb cb, void *opaque);
Some long-running operations can generate progress messages. If this callback is registered, then it will be called each time a progress message is generated (usually two seconds after the operation started, and three times per second thereafter until it completes, although the frequency may change in future versions).
The callback receives two numbers: position
and total
.
The units of total
are not defined, although for some
operations total
may relate in some way to the amount of
data to be transferred (eg. in bytes or megabytes), and
position
may be the portion which has been transferred.
The only defined and stable parts of the API are:
The callback can display to the user some type of progress bar or
indicator which shows the ratio of position
:total
.
0 <= position
<= total
If any progress notification is sent during a call, then a final
progress notification is always sent when position
= total
.
This is to simplify caller code, so callers can easily set the progress indicator to "100%" at the end of the operation, without requiring special code to detect this case.
The callback also receives the procedure number and serial number of the call. These are only useful for debugging protocol issues, and the callback can normally ignore them. The callback may want to print these numbers in error messages or debugging messages.
You can attach named pieces of private data to the libguestfs handle, and fetch them by name for the lifetime of the handle. This is called the private data area and is only available from the C API.
To attach a named piece of data, use the following call:
void guestfs_set_private (guestfs_h *g, const char *key, void *data);
key
is the name to associate with this data, and data
is an
arbitrary pointer (which can be NULL
). Any previous item with the
same name is overwritten.
You can use any key
you want, but names beginning with an
underscore character are reserved for internal libguestfs purposes
(for implementing language bindings). It is recommended to prefix the
name with some unique string to avoid collisions with other users.
To retrieve the pointer, use:
void *guestfs_get_private (guestfs_h *g, const char *key);
This function returns NULL
if either no data is found associated
with key
, or if the user previously set the key
's data
pointer to NULL
.
Libguestfs does not try to look at or interpret the data
pointer in
any way. As far as libguestfs is concerned, it need not be a valid
pointer at all. In particular, libguestfs does not try to free the
data when the handle is closed. If the data must be freed, then the
caller must either free it before calling guestfs_close or must
set up a close callback to do it (see guestfs_set_close_callback,
and note that only one callback can be registered for a handle).
The private data area is implemented using a hash table, and should be reasonably efficient for moderate numbers of keys.
Internally, libguestfs is implemented by running an appliance (a special type of small virtual machine) using qemu(1). Qemu runs as a child process of the main program.
___________________ / \ | main program | | | | | child process / appliance | | __________________________ | | / qemu \ +-------------------+ RPC | +-----------------+ | | libguestfs <--------------------> guestfsd | | | | | +-----------------+ | \___________________/ | | Linux kernel | | | +--^--------------+ | \_________|________________/ | _______v______ / \ | Device or | | disk image | \______________/
The library, linked to the main program, creates the child process and hence the appliance in the guestfs_launch function.
Inside the appliance is a Linux kernel and a complete stack of userspace tools (such as LVM and ext2 programs) and a small controlling daemon called guestfsd. The library talks to guestfsd using remote procedure calls (RPC). There is a mostly one-to-one correspondence between libguestfs API calls and RPC calls to the daemon. Lastly the disk image(s) are attached to the qemu process which translates device access by the appliance's Linux kernel into accesses to the image.
A common misunderstanding is that the appliance "is" the virtual machine. Although the disk image you are attached to might also be used by some virtual machine, libguestfs doesn't know or care about this. (But you will care if both libguestfs's qemu process and your virtual machine are trying to update the disk image at the same time, since these usually results in massive disk corruption).
libguestfs uses a state machine to model the child process:
| guestfs_create | | ____V_____ / \ | CONFIG | \__________/ ^ ^ ^ \ / | \ \ guestfs_launch / | _\__V______ / | / \ / | | LAUNCHING | / | \___________/ / | / / | guestfs_launch / | / ______ / __|____V / \ ------> / \ | BUSY | | READY | \______/ <------ \________/
The normal transitions are (1) CONFIG (when the handle is created, but there is no child process), (2) LAUNCHING (when the child process is booting up), (3) alternating between READY and BUSY as commands are issued to, and carried out by, the child process.
The guest may be killed by guestfs_kill_subprocess, or may die asynchronously at any time (eg. due to some internal error), and that causes the state to transition back to CONFIG.
Configuration commands for qemu such as guestfs_add_drive can only be issued when in the CONFIG state.
The API offers one call that goes from CONFIG through LAUNCHING to READY. guestfs_launch blocks until the child process is READY to accept commands (or until some failure or timeout). guestfs_launch internally moves the state from CONFIG to LAUNCHING while it is running.
API actions such as guestfs_mount can only be issued when in the READY state. These API calls block waiting for the command to be carried out (ie. the state to transition to BUSY and then back to READY). There are no non-blocking versions, and no way to issue more than one command per handle at the same time.
Finally, the child process sends asynchronous messages back to the main program, such as kernel log messages. You can register a callback to receive these messages.
Don't rely on using this protocol directly. This section documents how it currently works, but it may change at any time.
The protocol used to talk between the library and the daemon running inside the qemu virtual machine is a simple RPC mechanism built on top of XDR (RFC 1014, RFC 1832, RFC 4506).
The detailed format of structures is in src/guestfs_protocol.x
(note: this file is automatically generated).
There are two broad cases, ordinary functions that don't have any
FileIn
and FileOut
parameters, which are handled with very
simple request/reply messages. Then there are functions that have any
FileIn
or FileOut
parameters, which use the same request and
reply messages, but they may also be followed by files sent using a
chunked encoding.
For ordinary functions, the request message is:
total length (header + arguments, but not including the length word itself) struct guestfs_message_header (encoded as XDR) struct guestfs_<foo>_args (encoded as XDR)
The total length field allows the daemon to allocate a fixed size
buffer into which it slurps the rest of the message. As a result, the
total length is limited to GUESTFS_MESSAGE_MAX
bytes (currently
4MB), which means the effective size of any request is limited to
somewhere under this size.
Note also that many functions don't take any arguments, in which case
the guestfs_foo_args
is completely omitted.
The header contains the procedure number (guestfs_proc
) which is
how the receiver knows what type of args structure to expect, or none
at all.
The reply message for ordinary functions is:
total length (header + ret, but not including the length word itself) struct guestfs_message_header (encoded as XDR) struct guestfs_<foo>_ret (encoded as XDR)
As above the guestfs_foo_ret
structure may be completely omitted
for functions that return no formal return values.
As above the total length of the reply is limited to
GUESTFS_MESSAGE_MAX
.
In the case of an error, a flag is set in the header, and the reply message is slightly changed:
total length (header + error, but not including the length word itself) struct guestfs_message_header (encoded as XDR) struct guestfs_message_error (encoded as XDR)
The guestfs_message_error
structure contains the error message as a
string.
A FileIn
parameter indicates that we transfer a file into the
guest. The normal request message is sent (see above). However this
is followed by a sequence of file chunks.
total length (header + arguments, but not including the length word itself, and not including the chunks) struct guestfs_message_header (encoded as XDR) struct guestfs_<foo>_args (encoded as XDR) sequence of chunks for FileIn param #0 sequence of chunks for FileIn param #1 etc.
The "sequence of chunks" is:
length of chunk (not including length word itself) struct guestfs_chunk (encoded as XDR) length of chunk struct guestfs_chunk (encoded as XDR) ... length of chunk struct guestfs_chunk (with data.data_len == 0)
The final chunk has the data_len
field set to zero. Additionally a
flag is set in the final chunk to indicate either successful
completion or early cancellation.
At time of writing there are no functions that have more than one FileIn parameter. However this is (theoretically) supported, by sending the sequence of chunks for each FileIn parameter one after another (from left to right).
Both the library (sender) and the daemon (receiver) may cancel the transfer. The library does this by sending a chunk with a special flag set to indicate cancellation. When the daemon sees this, it cancels the whole RPC, does not send any reply, and goes back to reading the next request.
The daemon may also cancel. It does this by writing a special word
GUESTFS_CANCEL_FLAG
to the socket. The library listens for this
during the transfer, and if it gets it, it will cancel the transfer
(it sends a cancel chunk). The special word is chosen so that even if
cancellation happens right at the end of the transfer (after the
library has finished writing and has started listening for the reply),
the "spurious" cancel flag will not be confused with the reply
message.
This protocol allows the transfer of arbitrary sized files (no 32 bit
limit), and also files where the size is not known in advance
(eg. from pipes or sockets). However the chunks are rather small
(GUESTFS_MAX_CHUNK_SIZE
), so that neither the library nor the
daemon need to keep much in memory.
The protocol for FileOut parameters is exactly the same as for FileIn parameters, but with the roles of daemon and library reversed.
total length (header + ret, but not including the length word itself, and not including the chunks) struct guestfs_message_header (encoded as XDR) struct guestfs_<foo>_ret (encoded as XDR) sequence of chunks for FileOut param #0 sequence of chunks for FileOut param #1 etc.
When the daemon launches it sends an initial word
(GUESTFS_LAUNCH_FLAG
) which indicates that the guest and daemon is
alive. This is what guestfs_launch waits for.
The daemon may send progress notification messages at any time. These
are distinguished by the normal length word being replaced by
GUESTFS_PROGRESS_FLAG
, followed by a fixed size progress message.
The library turns them into progress callbacks (see
guestfs_set_progress_callback
) if there is a callback registered,
or discards them if not.
The daemon self-limits the frequency of progress messages it sends
(see daemon/proto.c:notify_progress
). Not all calls generate
progress messages.
Since April 2010, libguestfs has started to make separate development and stable releases, along with corresponding branches in our git repository. These separate releases can be identified by version number:
even numbers for stable: 1.2.x, 1.4.x, ... .-------- odd numbers for development: 1.3.x, 1.5.x, ... | v 1 . 3 . 5 ^ ^ | | | `-------- sub-version | `------ always '1' because we don't change the ABI
Thus "1.3.5" is the 5th update to the development branch "1.3".
As time passes we cherry pick fixes from the development branch and backport those into the stable branch, the effect being that the stable branch should get more stable and less buggy over time. So the stable releases are ideal for people who don't need new features but would just like the software to work.
Our criteria for backporting changes are:
Documentation changes which don't affect any code are backported unless the documentation refers to a future feature which is not in stable.
Bug fixes which are not controversial, fix obvious problems, and have been well tested are backported.
Simple rearrangements of code which shouldn't affect how it works get backported. This is so that the code in the two branches doesn't get too far out of step, allowing us to backport future fixes more easily.
We don't backport new features, new APIs, new tools etc, except in one exceptional case: the new feature is required in order to implement an important bug fix.
A new stable branch starts when we think the new features in development are substantial and compelling enough over the current stable branch to warrant it. When that happens we create new stable and development versions 1.N.0 and 1.(N+1).0 [N is even]. The new dot-oh release won't necessarily be so stable at this point, but by backporting fixes from development, that branch will stabilize over time.
Pass additional options to the guest kernel.
Set LIBGUESTFS_DEBUG=1
to enable verbose messages. This
has the same effect as calling guestfs_set_verbose (g, 1)
.
Set the memory allocated to the qemu process, in megabytes. For example:
LIBGUESTFS_MEMSIZE=700
Set the path that libguestfs uses to search for kernel and initrd.img. See the discussion of paths in section PATH above.
Set the default qemu binary that libguestfs uses. If not set, then the qemu which was found at compile time by the configure script is used.
See also QEMU WRAPPERS above.
Set LIBGUESTFS_TRACE=1
to enable command traces. This
has the same effect as calling guestfs_set_trace (g, 1)
.
Location of temporary directory, defaults to /tmp
.
If libguestfs was compiled to use the supermin appliance then the
real appliance is cached in this directory, shared between all
handles belonging to the same EUID. You can use $TMPDIR
to
configure another directory to use in case /tmp
is not large
enough.
guestfish(1), guestmount(1), virt-cat(1), virt-df(1), virt-edit(1), virt-inspector(1), virt-list-filesystems(1), virt-list-partitions(1), virt-ls(1), virt-make-fs(1), virt-rescue(1), virt-tar(1), virt-win-reg(1), qemu(1), febootstrap(1), hivex(3), http://libguestfs.org/.
Tools with a similar purpose: fdisk(8), parted(8), kpartx(8), lvm(8), disktype(1).
To get a list of bugs against libguestfs use this link:
https://bugzilla.redhat.com/buglist.cgi?component=libguestfs&product=Virtualization+Tools
To report a new bug against libguestfs use this link:
https://bugzilla.redhat.com/enter_bug.cgi?component=libguestfs&product=Virtualization+Tools
When reporting a bug, please check:
That the bug hasn't been reported already.
That you are testing a recent version.
Describe the bug accurately, and give a way to reproduce it.
Run libguestfs-test-tool and paste the complete, unedited output into the bug report.
Richard W.M. Jones (rjones at redhat dot com
)
Copyright (C) 2009-2010 Red Hat Inc. http://libguestfs.org/
This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA