2 * Copyright (C) 2009-2010 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 close_handles (void);
77 gl_lock_define_initialized (static, handles_lock);
78 static guestfs_h *handles = NULL;
79 static int atexit_handler_set = 0;
87 g = malloc (sizeof (*g));
90 memset (g, 0, sizeof (*g));
99 g->error_cb = default_error_cb;
100 g->error_cb_data = NULL;
102 g->recovery_proc = 1;
105 str = getenv ("LIBGUESTFS_DEBUG");
106 g->verbose = str != NULL && STREQ (str, "1");
108 str = getenv ("LIBGUESTFS_TRACE");
109 g->trace = str != NULL && STREQ (str, "1");
111 str = getenv ("LIBGUESTFS_PATH");
112 g->path = str != NULL ? strdup (str) : strdup (GUESTFS_DEFAULT_PATH);
113 if (!g->path) goto error;
115 str = getenv ("LIBGUESTFS_QEMU");
116 g->qemu = str != NULL ? strdup (str) : strdup (QEMU);
117 if (!g->qemu) goto error;
119 str = getenv ("LIBGUESTFS_APPEND");
121 g->append = strdup (str);
122 if (!g->append) goto error;
125 /* Choose a suitable memory size. Previously we tried to choose
126 * a minimal memory size, but this isn't really necessary since
127 * recent QEMU and KVM don't do anything nasty like locking
128 * memory into core any more. Thus we can safely choose a
129 * large, generous amount of memory, and it'll just get swapped
130 * on smaller systems.
132 str = getenv ("LIBGUESTFS_MEMSIZE");
134 if (sscanf (str, "%d", &g->memsize) != 1 || g->memsize <= 256) {
135 fprintf (stderr, "libguestfs: non-numeric or too small value for LIBGUESTFS_MEMSIZE\n");
141 /* Start with large serial numbers so they are easy to spot
142 * inside the protocol.
144 g->msg_next_serial = 0x00123400;
146 /* Link the handles onto a global list. */
147 gl_lock_lock (handles_lock);
150 if (!atexit_handler_set) {
151 atexit (close_handles);
152 atexit_handler_set = 1;
154 gl_lock_unlock (handles_lock);
157 fprintf (stderr, "new guestfs handle %p\n", g);
170 guestfs_close (guestfs_h *g)
176 if (g->state == NO_HANDLE) {
177 /* Not safe to call 'error' here, so ... */
178 fprintf (stderr, _("guestfs_close: called twice on the same handle\n"));
183 fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
185 /* Run user close callback before anything else. */
187 g->close_cb (g, g->close_cb_data);
189 guestfs___free_inspect_info (g);
191 /* Try to sync if autosync flag is set. */
192 if (g->autosync && g->state == READY) {
193 guestfs_umount_all (g);
197 /* Remove any handlers that might be called back before we kill the
200 g->log_message_cb = NULL;
202 if (g->state != CONFIG)
203 guestfs_kill_subprocess (g);
216 /* Wait for subprocess(es) to exit. */
217 waitpid (g->pid, NULL, 0);
218 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
220 /* Remove tmpfiles. */
222 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
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);
243 for (gg = handles; gg->next != g; gg = gg->next)
247 gl_lock_unlock (handles_lock);
251 free (g->last_error);
256 free (g->qemu_version);
260 /* Close all open handles (called from atexit(3)). */
264 while (handles) guestfs_close (handles);
268 guestfs_last_error (guestfs_h *g)
270 return g->last_error;
274 guestfs_last_errno (guestfs_h *g)
276 return g->last_errnum;
280 set_last_error (guestfs_h *g, int errnum, const char *msg)
282 free (g->last_error);
283 g->last_error = strdup (msg);
284 g->last_errnum = errnum;
288 default_error_cb (guestfs_h *g, void *data, const char *msg)
290 fprintf (stderr, _("libguestfs: error: %s\n"), msg);
294 guestfs_error_errno (guestfs_h *g, int errnum, const char *fs, ...)
300 int err = vasprintf (&msg, fs, args);
305 /* set_last_error first so that the callback can access the error
306 * message and errno through the handle if it wishes.
308 set_last_error (g, errnum, msg);
309 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
315 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
322 int err = vasprintf (&msg, fs, args);
327 #if !defined(_GNU_SOURCE) || defined(__APPLE__)
329 strerror_r (errnum, buf, sizeof buf);
333 buf = strerror_r (errnum, _buf, sizeof _buf);
336 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
340 /* set_last_error first so that the callback can access the error
341 * message and errno through the handle if it wishes.
343 set_last_error (g, errnum, msg);
344 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
350 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
352 void *ptr = malloc (nbytes);
353 if (nbytes > 0 && !ptr) g->abort_cb ();
357 /* Return 1 if an array of N objects, each of size S, cannot exist due
358 to size arithmetic overflow. S must be positive and N must be
359 nonnegative. This is a macro, not an inline function, so that it
360 works correctly even when SIZE_MAX < N.
362 By gnulib convention, SIZE_MAX represents overflow in size
363 calculations, so the conservative dividend to use here is
364 SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value.
365 However, malloc (SIZE_MAX) fails on all known hosts where
366 sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for
367 exactly-SIZE_MAX allocations on such hosts; this avoids a test and
368 branch when S is known to be 1. */
369 # define xalloc_oversized(n, s) \
370 ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
372 /* Technically we should add an autoconf test for this, testing for the desired
373 functionality, like what's done in gnulib, but for now, this is fine. */
374 #if defined(__GLIBC__)
375 #define HAVE_GNU_CALLOC (__GLIBC__ >= 2)
377 #define HAVE_GNU_CALLOC 0
380 /* Allocate zeroed memory for N elements of S bytes, with error
381 checking. S must be nonzero. */
383 guestfs_safe_calloc (guestfs_h *g, size_t n, size_t s)
385 /* From gnulib's calloc function in xmalloc.c. */
387 /* Test for overflow, since some calloc implementations don't have
388 proper overflow checks. But omit overflow and size-zero tests if
389 HAVE_GNU_CALLOC, since GNU calloc catches overflow and never
390 returns NULL if successful. */
391 if ((! HAVE_GNU_CALLOC && xalloc_oversized (n, s))
392 || (! (p = calloc (n, s)) && (HAVE_GNU_CALLOC || n != 0)))
398 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
400 void *p = realloc (ptr, nbytes);
401 if (nbytes > 0 && !p) g->abort_cb ();
406 guestfs_safe_strdup (guestfs_h *g, const char *str)
408 char *s = strdup (str);
409 if (!s) g->abort_cb ();
414 guestfs_safe_strndup (guestfs_h *g, const char *str, size_t n)
416 char *s = strndup (str, n);
417 if (!s) g->abort_cb ();
422 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
424 void *p = malloc (size);
425 if (!p) g->abort_cb ();
426 memcpy (p, ptr, size);
431 guestfs_safe_asprintf (guestfs_h *g, const char *fs, ...)
437 int err = vasprintf (&msg, fs, args);
447 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
453 guestfs_get_out_of_memory_handler (guestfs_h *g)
459 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
462 g->error_cb_data = data;
465 guestfs_error_handler_cb
466 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
468 if (data_rtn) *data_rtn = g->error_cb_data;
473 guestfs__set_verbose (guestfs_h *g, int v)
480 guestfs__get_verbose (guestfs_h *g)
486 guestfs__set_autosync (guestfs_h *g, int a)
493 guestfs__get_autosync (guestfs_h *g)
499 guestfs__set_path (guestfs_h *g, const char *path)
506 safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
511 guestfs__get_path (guestfs_h *g)
517 guestfs__set_qemu (guestfs_h *g, const char *qemu)
522 g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
527 guestfs__get_qemu (guestfs_h *g)
533 guestfs__set_append (guestfs_h *g, const char *append)
538 g->append = append ? safe_strdup (g, append) : NULL;
543 guestfs__get_append (guestfs_h *g)
549 guestfs__set_memsize (guestfs_h *g, int memsize)
551 g->memsize = memsize;
556 guestfs__get_memsize (guestfs_h *g)
562 guestfs__set_selinux (guestfs_h *g, int selinux)
564 g->selinux = selinux;
569 guestfs__get_selinux (guestfs_h *g)
575 guestfs__get_pid (guestfs_h *g)
580 error (g, "get_pid: no qemu subprocess");
585 struct guestfs_version *
586 guestfs__version (guestfs_h *g)
588 struct guestfs_version *r;
590 r = safe_malloc (g, sizeof *r);
591 r->major = PACKAGE_VERSION_MAJOR;
592 r->minor = PACKAGE_VERSION_MINOR;
593 r->release = PACKAGE_VERSION_RELEASE;
594 r->extra = safe_strdup (g, PACKAGE_VERSION_EXTRA);
599 guestfs__set_trace (guestfs_h *g, int t)
606 guestfs__get_trace (guestfs_h *g)
612 guestfs__set_direct (guestfs_h *g, int d)
619 guestfs__get_direct (guestfs_h *g)
625 guestfs__set_recovery_proc (guestfs_h *g, int f)
627 g->recovery_proc = !!f;
632 guestfs__get_recovery_proc (guestfs_h *g)
634 return g->recovery_proc;
638 guestfs__set_network (guestfs_h *g, int v)
640 g->enable_network = !!v;
645 guestfs__get_network (guestfs_h *g)
647 return g->enable_network;
651 guestfs_set_log_message_callback (guestfs_h *g,
652 guestfs_log_message_cb cb, void *opaque)
654 g->log_message_cb = cb;
655 g->log_message_cb_data = opaque;
659 guestfs_set_subprocess_quit_callback (guestfs_h *g,
660 guestfs_subprocess_quit_cb cb, void *opaque)
662 g->subprocess_quit_cb = cb;
663 g->subprocess_quit_cb_data = opaque;
667 guestfs_set_launch_done_callback (guestfs_h *g,
668 guestfs_launch_done_cb cb, void *opaque)
670 g->launch_done_cb = cb;
671 g->launch_done_cb_data = opaque;
675 guestfs_set_close_callback (guestfs_h *g,
676 guestfs_close_cb cb, void *opaque)
679 g->close_cb_data = opaque;
683 guestfs_set_progress_callback (guestfs_h *g,
684 guestfs_progress_cb cb, void *opaque)
687 g->progress_cb_data = opaque;
690 /* Note the private data area is allocated lazily, since the vast
691 * majority of callers will never use it. This means g->pda is
696 void *data; /* opaque user data pointer */
700 hasher (void const *x, size_t table_size)
702 struct pda_entry const *p = x;
703 return hash_pjw (p->key, table_size);
707 comparator (void const *x, void const *y)
709 struct pda_entry const *a = x;
710 struct pda_entry const *b = y;
711 return STREQ (a->key, b->key);
718 struct pda_entry *p = x;
725 guestfs_set_private (guestfs_h *g, const char *key, void *data)
727 if (g->pda == NULL) {
728 g->pda = hash_initialize (16, NULL, hasher, comparator, freer);
733 struct pda_entry *new_entry = safe_malloc (g, sizeof *new_entry);
734 new_entry->key = safe_strdup (g, key);
735 new_entry->data = data;
737 struct pda_entry *old_entry = hash_delete (g->pda, new_entry);
740 struct pda_entry *entry = hash_insert (g->pda, new_entry);
743 assert (entry == new_entry);
747 bad_cast (char const *s)
753 guestfs_get_private (guestfs_h *g, const char *key)
756 return NULL; /* no keys have been set */
758 const struct pda_entry k = { .key = bad_cast (key) };
759 struct pda_entry *entry = hash_lookup (g->pda, &k);
766 /* When tracing, be careful how we print BufferIn parameters which
767 * usually contain large amounts of binary data (RHBZ#646822).
770 guestfs___print_BufferIn (FILE *out, const char *buf, size_t buf_size)
773 size_t orig_size = buf_size;
780 for (i = 0; i < buf_size; ++i) {
781 if (c_isprint (buf[i]))
784 fprintf (out, "\\x%02x", (unsigned char) buf[i]);
789 if (orig_size > buf_size)
791 _("<truncated, original size %zu bytes>"), orig_size);
795 guestfs___print_BufferOut (FILE *out, const char *buf, size_t buf_size)
797 guestfs___print_BufferIn (out, buf, buf_size);
801 guestfs___free_string_list (char **argv)
804 for (i = 0; argv[i] != NULL; ++i)