2 * Copyright (C) 2009-2011 Red Hat Inc.
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 #define _BSD_SOURCE /* for mkdtemp, usleep */
34 #include <sys/select.h>
38 #include <rpc/types.h>
45 #ifdef HAVE_SYS_TYPES_H
46 #include <sys/types.h>
49 #ifdef HAVE_SYS_WAIT_H
53 #ifdef HAVE_SYS_SOCKET_H
54 #include <sys/socket.h>
61 #include <arpa/inet.h>
62 #include <netinet/in.h>
65 #include "glthread/lock.h"
70 #include "guestfs-internal.h"
71 #include "guestfs-internal-actions.h"
72 #include "guestfs_protocol.h"
74 static void default_error_cb (guestfs_h *g, void *data, const char *msg);
75 static void remove_tmpdir (guestfs_h *g);
76 static void close_handles (void);
78 gl_lock_define_initialized (static, handles_lock);
79 static guestfs_h *handles = NULL;
80 static int atexit_handler_set = 0;
88 g = malloc (sizeof (*g));
91 memset (g, 0, sizeof (*g));
100 g->error_cb = default_error_cb;
101 g->error_cb_data = NULL;
103 g->recovery_proc = 1;
106 str = getenv ("LIBGUESTFS_DEBUG");
107 g->verbose = str != NULL && STREQ (str, "1");
109 str = getenv ("LIBGUESTFS_TRACE");
110 g->trace = str != NULL && STREQ (str, "1");
112 str = getenv ("LIBGUESTFS_PATH");
113 g->path = str != NULL ? strdup (str) : strdup (GUESTFS_DEFAULT_PATH);
114 if (!g->path) goto error;
116 str = getenv ("LIBGUESTFS_QEMU");
117 g->qemu = str != NULL ? strdup (str) : strdup (QEMU);
118 if (!g->qemu) goto error;
120 str = getenv ("LIBGUESTFS_APPEND");
122 g->append = strdup (str);
123 if (!g->append) goto error;
126 /* Choose a suitable memory size. Previously we tried to choose
127 * a minimal memory size, but this isn't really necessary since
128 * recent QEMU and KVM don't do anything nasty like locking
129 * memory into core any more. Thus we can safely choose a
130 * large, generous amount of memory, and it'll just get swapped
131 * on smaller systems.
133 str = getenv ("LIBGUESTFS_MEMSIZE");
135 if (sscanf (str, "%d", &g->memsize) != 1 || g->memsize <= 256) {
136 warning (g, "non-numeric or too small value for LIBGUESTFS_MEMSIZE");
142 /* Start with large serial numbers so they are easy to spot
143 * inside the protocol.
145 g->msg_next_serial = 0x00123400;
147 /* Default is uniprocessor appliance. */
150 /* Link the handles onto a global list. */
151 gl_lock_lock (handles_lock);
154 if (!atexit_handler_set) {
155 atexit (close_handles);
156 atexit_handler_set = 1;
158 gl_lock_unlock (handles_lock);
160 debug (g, "new guestfs handle %p", g);
173 guestfs_close (guestfs_h *g)
175 if (g->state == NO_HANDLE) {
176 /* Not safe to call ANY callbacks here, so ... */
177 fprintf (stderr, _("guestfs_close: called twice on the same handle\n"));
182 const char trace_msg[] = "close";
184 guestfs___call_callbacks_message (g, GUESTFS_EVENT_TRACE,
185 trace_msg, strlen (trace_msg));
188 debug (g, "closing guestfs handle %p (state %d)", g, g->state);
190 /* Try to sync if autosync flag is set. */
191 if (g->autosync && g->state == READY)
192 guestfs_internal_autosync (g);
194 /* Kill the qemu subprocess. */
195 if (g->state != CONFIG)
196 guestfs_kill_subprocess (g);
198 /* Run user close callbacks. */
199 guestfs___call_callbacks_void (g, GUESTFS_EVENT_CLOSE);
201 /* Remove all other registered callbacks. Since we've already
202 * called the close callbacks, we shouldn't call any others.
208 guestfs___free_inspect_info (g);
221 /* Wait for subprocess(es) to exit. */
222 if (g->pid > 0) waitpid (g->pid, NULL, 0);
223 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
225 /* Remove whole temporary directory. */
231 for (i = 0; i < g->cmdline_size; ++i)
232 free (g->cmdline[i]);
236 /* Mark the handle as dead before freeing it. */
237 g->state = NO_HANDLE;
239 gl_lock_lock (handles_lock);
245 for (gg = handles; gg->next != g; gg = gg->next)
249 gl_lock_unlock (handles_lock);
253 free (g->last_error);
258 free (g->qemu_version);
262 /* g->tmpdir can contain any files (but not subdirectories). Remove
263 * those and the directory itself. Note that errors in this function
264 * aren't really that important: if we end up not deleting temporary
265 * files it's only annoying.
268 remove_tmpdir (guestfs_h *g)
276 dir = opendir (g->tmpdir);
282 while ((d = readdir (dir)) != NULL) {
283 if (STRNEQ (d->d_name, ".") && STRNEQ (d->d_name, "..")) {
284 if (unlinkat (dirfd (dir), d->d_name, 0) == -1)
289 if (closedir (dir) == -1)
292 if (rmdir (g->tmpdir) == -1)
299 /* Close all open handles (called from atexit(3)). */
303 while (handles) guestfs_close (handles);
307 guestfs_last_error (guestfs_h *g)
309 return g->last_error;
313 guestfs_last_errno (guestfs_h *g)
315 return g->last_errnum;
319 set_last_error (guestfs_h *g, int errnum, const char *msg)
321 free (g->last_error);
322 g->last_error = strdup (msg);
323 g->last_errnum = errnum;
326 /* Warning are printed unconditionally. We try to make these rare.
327 * Generally speaking, a warning should either be an error, or if it's
328 * not important for end users then it should be a debug message.
331 guestfs___warning (guestfs_h *g, const char *fs, ...)
338 len = vasprintf (&msg, fs, args);
343 len = asprintf (&msg2, _("warning: %s"), msg);
348 guestfs___call_callbacks_message (g, GUESTFS_EVENT_LIBRARY, msg2, len);
353 /* Debug messages. */
355 guestfs___debug (guestfs_h *g, const char *fs, ...)
361 /* The cpp macro "debug" has already checked that g->verbose is true
362 * before calling this function, but we check it again just in case
363 * anyone calls this function directly.
369 len = vasprintf (&msg, fs, args);
374 guestfs___call_callbacks_message (g, GUESTFS_EVENT_LIBRARY, msg, len);
377 /* Call trace messages. These are enabled by setting g->trace, and
378 * calls to this function should only happen from the generated code
382 guestfs___trace (guestfs_h *g, const char *fs, ...)
389 len = vasprintf (&msg, fs, args);
394 guestfs___call_callbacks_message (g, GUESTFS_EVENT_TRACE, msg, len);
400 default_error_cb (guestfs_h *g, void *data, const char *msg)
402 fprintf (stderr, _("libguestfs: error: %s\n"), msg);
406 guestfs_error_errno (guestfs_h *g, int errnum, const char *fs, ...)
412 int err = vasprintf (&msg, fs, args);
417 /* set_last_error first so that the callback can access the error
418 * message and errno through the handle if it wishes.
420 set_last_error (g, errnum, msg);
421 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
427 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
434 int err = vasprintf (&msg, fs, args);
440 strerror_r (errnum, buf, sizeof buf);
442 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
446 /* set_last_error first so that the callback can access the error
447 * message and errno through the handle if it wishes.
449 set_last_error (g, errnum, msg);
450 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
456 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
458 void *ptr = malloc (nbytes);
459 if (nbytes > 0 && !ptr) g->abort_cb ();
463 /* Return 1 if an array of N objects, each of size S, cannot exist due
464 to size arithmetic overflow. S must be positive and N must be
465 nonnegative. This is a macro, not an inline function, so that it
466 works correctly even when SIZE_MAX < N.
468 By gnulib convention, SIZE_MAX represents overflow in size
469 calculations, so the conservative dividend to use here is
470 SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value.
471 However, malloc (SIZE_MAX) fails on all known hosts where
472 sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for
473 exactly-SIZE_MAX allocations on such hosts; this avoids a test and
474 branch when S is known to be 1. */
475 # define xalloc_oversized(n, s) \
476 ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
478 /* Technically we should add an autoconf test for this, testing for the desired
479 functionality, like what's done in gnulib, but for now, this is fine. */
480 #if defined(__GLIBC__)
481 #define HAVE_GNU_CALLOC (__GLIBC__ >= 2)
483 #define HAVE_GNU_CALLOC 0
486 /* Allocate zeroed memory for N elements of S bytes, with error
487 checking. S must be nonzero. */
489 guestfs_safe_calloc (guestfs_h *g, size_t n, size_t s)
491 /* From gnulib's calloc function in xmalloc.c. */
493 /* Test for overflow, since some calloc implementations don't have
494 proper overflow checks. But omit overflow and size-zero tests if
495 HAVE_GNU_CALLOC, since GNU calloc catches overflow and never
496 returns NULL if successful. */
497 if ((! HAVE_GNU_CALLOC && xalloc_oversized (n, s))
498 || (! (p = calloc (n, s)) && (HAVE_GNU_CALLOC || n != 0)))
504 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
506 void *p = realloc (ptr, nbytes);
507 if (nbytes > 0 && !p) g->abort_cb ();
512 guestfs_safe_strdup (guestfs_h *g, const char *str)
514 char *s = strdup (str);
515 if (!s) g->abort_cb ();
520 guestfs_safe_strndup (guestfs_h *g, const char *str, size_t n)
522 char *s = strndup (str, n);
523 if (!s) g->abort_cb ();
528 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
530 void *p = malloc (size);
531 if (!p) g->abort_cb ();
532 memcpy (p, ptr, size);
537 guestfs_safe_asprintf (guestfs_h *g, const char *fs, ...)
543 int err = vasprintf (&msg, fs, args);
553 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
559 guestfs_get_out_of_memory_handler (guestfs_h *g)
565 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
568 g->error_cb_data = data;
571 guestfs_error_handler_cb
572 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
574 if (data_rtn) *data_rtn = g->error_cb_data;
579 guestfs_user_cancel (guestfs_h *g)
585 guestfs__set_verbose (guestfs_h *g, int v)
592 guestfs__get_verbose (guestfs_h *g)
598 guestfs__set_autosync (guestfs_h *g, int a)
605 guestfs__get_autosync (guestfs_h *g)
611 guestfs__set_path (guestfs_h *g, const char *path)
618 safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
623 guestfs__get_path (guestfs_h *g)
629 guestfs__set_qemu (guestfs_h *g, const char *qemu)
634 g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
639 guestfs__get_qemu (guestfs_h *g)
645 guestfs__set_append (guestfs_h *g, const char *append)
650 g->append = append ? safe_strdup (g, append) : NULL;
655 guestfs__get_append (guestfs_h *g)
661 guestfs__set_memsize (guestfs_h *g, int memsize)
663 g->memsize = memsize;
668 guestfs__get_memsize (guestfs_h *g)
674 guestfs__set_selinux (guestfs_h *g, int selinux)
676 g->selinux = selinux;
681 guestfs__get_selinux (guestfs_h *g)
687 guestfs__get_pid (guestfs_h *g)
692 error (g, "get_pid: no qemu subprocess");
697 struct guestfs_version *
698 guestfs__version (guestfs_h *g)
700 struct guestfs_version *r;
702 r = safe_malloc (g, sizeof *r);
703 r->major = PACKAGE_VERSION_MAJOR;
704 r->minor = PACKAGE_VERSION_MINOR;
705 r->release = PACKAGE_VERSION_RELEASE;
706 r->extra = safe_strdup (g, PACKAGE_VERSION_EXTRA);
711 guestfs__set_trace (guestfs_h *g, int t)
718 guestfs__get_trace (guestfs_h *g)
724 guestfs__set_direct (guestfs_h *g, int d)
731 guestfs__get_direct (guestfs_h *g)
737 guestfs__set_recovery_proc (guestfs_h *g, int f)
739 g->recovery_proc = !!f;
744 guestfs__get_recovery_proc (guestfs_h *g)
746 return g->recovery_proc;
750 guestfs__set_network (guestfs_h *g, int v)
752 g->enable_network = !!v;
757 guestfs__get_network (guestfs_h *g)
759 return g->enable_network;
763 guestfs__set_attach_method (guestfs_h *g, const char *method)
765 if (STREQ (method, "appliance")) {
766 g->attach_method = ATTACH_METHOD_APPLIANCE;
767 free (g->attach_method_arg);
768 g->attach_method_arg = NULL;
770 else if (STRPREFIX (method, "unix:") && strlen (method) > 5) {
771 g->attach_method = ATTACH_METHOD_UNIX;
772 free (g->attach_method_arg);
773 g->attach_method_arg = safe_strdup (g, method + 5);
774 /* Note that we don't check the path exists until launch is called. */
777 error (g, "invalid attach method: %s", method);
785 guestfs__get_attach_method (guestfs_h *g)
789 switch (g->attach_method) {
790 case ATTACH_METHOD_APPLIANCE:
791 ret = safe_strdup (g, "appliance");
794 case ATTACH_METHOD_UNIX:
795 ret = safe_malloc (g, strlen (g->attach_method_arg) + 5 + 1);
796 strcpy (ret, "unix:");
797 strcat (ret, g->attach_method_arg);
800 default: /* keep GCC happy - this is not reached */
808 guestfs__set_pgroup (guestfs_h *g, int v)
815 guestfs__get_pgroup (guestfs_h *g)
821 guestfs__set_smp (guestfs_h *g, int v)
827 error (g, "invalid smp parameter: %d", v);
833 guestfs__get_smp (guestfs_h *g)
838 /* Note the private data area is allocated lazily, since the vast
839 * majority of callers will never use it. This means g->pda is
844 void *data; /* opaque user data pointer */
848 hasher (void const *x, size_t table_size)
850 struct pda_entry const *p = x;
851 return hash_pjw (p->key, table_size);
855 comparator (void const *x, void const *y)
857 struct pda_entry const *a = x;
858 struct pda_entry const *b = y;
859 return STREQ (a->key, b->key);
866 struct pda_entry *p = x;
873 guestfs_set_private (guestfs_h *g, const char *key, void *data)
875 if (g->pda == NULL) {
876 g->pda = hash_initialize (16, NULL, hasher, comparator, freer);
881 struct pda_entry *new_entry = safe_malloc (g, sizeof *new_entry);
882 new_entry->key = safe_strdup (g, key);
883 new_entry->data = data;
885 struct pda_entry *old_entry = hash_delete (g->pda, new_entry);
888 struct pda_entry *entry = hash_insert (g->pda, new_entry);
891 assert (entry == new_entry);
895 bad_cast (char const *s)
901 guestfs_get_private (guestfs_h *g, const char *key)
904 return NULL; /* no keys have been set */
906 const struct pda_entry k = { .key = bad_cast (key) };
907 struct pda_entry *entry = hash_lookup (g->pda, &k);
916 guestfs_first_private (guestfs_h *g, const char **key_rtn)
921 g->pda_next = hash_get_first (g->pda);
923 /* Ignore any keys with NULL data pointers. */
924 while (g->pda_next && g->pda_next->data == NULL)
925 g->pda_next = hash_get_next (g->pda, g->pda_next);
927 if (g->pda_next == NULL)
930 *key_rtn = g->pda_next->key;
931 return g->pda_next->data;
935 guestfs_next_private (guestfs_h *g, const char **key_rtn)
940 if (g->pda_next == NULL)
943 /* Walk to the next key with a non-NULL data pointer. */
945 g->pda_next = hash_get_next (g->pda, g->pda_next);
946 } while (g->pda_next && g->pda_next->data == NULL);
948 if (g->pda_next == NULL)
951 *key_rtn = g->pda_next->key;
952 return g->pda_next->data;
955 /* When tracing, be careful how we print BufferIn parameters which
956 * usually contain large amounts of binary data (RHBZ#646822).
959 guestfs___print_BufferIn (FILE *out, const char *buf, size_t buf_size)
962 size_t orig_size = buf_size;
969 for (i = 0; i < buf_size; ++i) {
970 if (c_isprint (buf[i]))
973 fprintf (out, "\\x%02x", (unsigned char) buf[i]);
978 if (orig_size > buf_size)
980 _("<truncated, original size %zu bytes>"), orig_size);
984 guestfs___print_BufferOut (FILE *out, const char *buf, size_t buf_size)
986 guestfs___print_BufferIn (out, buf, buf_size);
990 guestfs___free_string_list (char **argv)
993 for (i = 0; argv[i] != NULL; ++i)