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, 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.
You can add a disk read-only using guestfs_add_drive_ro, in which 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. 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.
For small, single files, use guestfs_write_file. This call currently contains a bug which limits the call to plain text files (not containing ASCII NUL characters).
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 a 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.
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.
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 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 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 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.
-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.
This limit is both rather small and quite unnecessary. We should be able to return error messages up to the length of the protocol message (2-4 MB).
Note that we cannot change the protocol without some breakage, because there are distributions that repackage the Fedora appliance.
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.
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)).
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 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.
The convention in all functions that return int
is that they 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.
The default error handler prints the information string to stderr
.
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.
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.
The error string is not localized (ie. is always in English), because this makes searching for error messages in search engines give the largest number of results.
typedef void (*guestfs_error_handler_cb) (guestfs_h *g, void *data, const char *msg); void guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data);
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 **data_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.
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
.
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.
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.
int guestfs_add_drive (guestfs_h *g, const char *filename);
This function adds a virtual machine disk image filename
to the
guest. The first time you call this function, the disk appears as IDE
disk 0 (/dev/sda
) in the guest, 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 is equivalent to the qemu parameter
-drive file=filename,cache=off,if=...
.
cache=off
is omitted in cases where it is not supported by
the underlying filesystem.
if=...
is set at compile time by the configuration option
./configure --with-drive-if=...
. In the rare case where you
might need to change this at run time, use guestfs_add_drive_with_if
or guestfs_add_drive_ro_with_if
.
Note that 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.
This function returns 0 on success or -1 on error.
int guestfs_add_drive_ro (guestfs_h *g, const char *filename);
This adds a drive in snapshot mode, making it effectively read-only.
Note that writes to the device are allowed, and will be seen for the duration of the guestfs handle, but they are written to a temporary file which is discarded as soon as the guestfs handle is closed. We don't currently have any method to enable changes to be committed, although qemu can support this.
This is equivalent to the qemu parameter
-drive file=filename,snapshot=on,if=...
.
if=...
is set at compile time by the configuration option
./configure --with-drive-if=...
. In the rare case where you
might need to change this at run time, use guestfs_add_drive_with_if
or guestfs_add_drive_ro_with_if
.
Note that 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.
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.
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.
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.
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.
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.
This function returns a string, or NULL on error. The caller must free the returned string after use.
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.
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.
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.
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 concatenate 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.
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 also works on devices, for example to find out whether a partition contains a filesystem.
This call will also transparently look inside various types of compressed file.
The exact command which runs is file -zbsL path
. Note in
particular that the filename is not prepended to the output
(the -b
option).
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
.
This function returns 0 on success or -1 on error.
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.
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 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.
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.
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.
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_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
.
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.
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_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_file (guestfs_h *g, const char *path);
This returns true
if and only if there is a 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_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
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_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
.
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_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.
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_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.
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
.
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 /squash mkmountpoint /ext3 mount /dev/sda /cd mount-loop /cd/LiveOS/squashfs.img /squash mount-loop /squash/LiveOS/ext3fs.img /ext3
The inner filesystem is now unpacked under the /ext3 mountpoint.
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_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.
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.
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.
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.
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) 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 symbol 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 or ext3 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_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 disabled by default (except in guestfish where it is enabled 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_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 stdout 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
.
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
.
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 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 file is smaller than size
then
the file is extended to the required size with null bytes.
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_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 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_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 ELF weak linking tricks 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
Note: Don't use this call to test for availability
of features. Distro backports makes this unreliable. 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_type (guestfs_h *g, const char *device);
This command gets the block device type corresponding to
a mounted device called device
.
Usually the result is the name of the Linux VFS module that
is used to mount this device (probably determined automatically
if you used the guestfs_mount
call).
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.
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_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.
We hope to resolve this bug in a future version. In the meantime
use guestfs_upload
.
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.
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_scrub_device
.
This function returns 0 on success or -1 on error.
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_is_lv guestfs_lvcreate guestfs_lvm_remove_all guestfs_lvremove guestfs_lvresize guestfs_lvs guestfs_lvs_full guestfs_pvcreate guestfs_pvremove guestfs_pvresize 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_realpath
The following functions: guestfs_scrub_device guestfs_scrub_file guestfs_scrub_freespace
The following functions: guestfs_getcon guestfs_setcon
The following functions: guestfs_zerofree
If you need to test whether a single libguestfs function is available at compile time, we recommend 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 <config.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <dlfcn.h> #include <guestfs.h> main () { #ifdef HAVE_GUESTFS_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
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 high-level API offers two calls that go 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.
High-level API actions such as guestfs_mount can only be issued when in the READY state. These high-level API calls block waiting for the command to be carried out (ie. the state to transition to BUSY and then back to READY). But using the low-level event API, you get non-blocking versions. (But you can still only carry out one operation per handle at a time - that is a limitation of the communications protocol we use).
Finally, the child process sends asynchronous messages back to the main program, such as kernel log messages. Mostly these are ignored by the high-level API, but using the low-level event API you can register to receive these messages.
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_ready_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).
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.
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.
Because the underlying channel (QEmu -net channel) doesn't have any
sort of connection control, 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.
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.
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.
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 each
handle will require rather a large amount of space in this directory
for short periods of time (~ 80 MB). 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