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>
39 #include <rpc/types.h>
46 #ifdef HAVE_SYS_TYPES_H
47 #include <sys/types.h>
50 #ifdef HAVE_SYS_WAIT_H
54 #ifdef HAVE_SYS_SOCKET_H
55 #include <sys/socket.h>
62 #include <arpa/inet.h>
63 #include <netinet/in.h>
66 #include "glthread/lock.h"
69 #include "ignore-value.h"
72 #include "guestfs-internal.h"
73 #include "guestfs-internal-actions.h"
74 #include "guestfs_protocol.h"
76 static void default_error_cb (guestfs_h *g, void *data, const char *msg);
77 static void close_handles (void);
79 gl_lock_define_initialized (static, handles_lock);
80 static guestfs_h *handles = NULL;
81 static int atexit_handler_set = 0;
89 g = malloc (sizeof (*g));
92 memset (g, 0, sizeof (*g));
101 g->error_cb = default_error_cb;
102 g->error_cb_data = NULL;
104 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 fprintf (stderr, "libguestfs: non-numeric or too small value for LIBGUESTFS_MEMSIZE\n");
142 /* Start with large serial numbers so they are easy to spot
143 * inside the protocol.
145 g->msg_next_serial = 0x00123400;
147 /* Link the handles onto a global list. */
148 gl_lock_lock (handles_lock);
151 if (!atexit_handler_set) {
152 atexit (close_handles);
153 atexit_handler_set = 1;
155 gl_lock_unlock (handles_lock);
158 fprintf (stderr, "new guestfs handle %p\n", g);
171 guestfs_close (guestfs_h *g)
177 if (g->state == NO_HANDLE) {
178 /* Not safe to call 'error' here, so ... */
179 fprintf (stderr, _("guestfs_close: called twice on the same handle\n"));
184 fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
186 /* Run user close callback before anything else. */
188 g->close_cb (g, g->close_cb_data);
190 guestfs___free_inspect_info (g);
192 /* Try to sync if autosync flag is set. */
193 if (g->autosync && g->state == READY) {
194 guestfs_umount_all (g);
198 /* Remove any handlers that might be called back before we kill the
201 g->log_message_cb = NULL;
203 if (g->state != CONFIG)
204 guestfs_kill_subprocess (g);
217 /* Wait for subprocess(es) to exit. */
218 waitpid (g->pid, NULL, 0);
219 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
221 /* Remove tmpfiles. */
223 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
232 for (i = 0; i < g->cmdline_size; ++i)
233 free (g->cmdline[i]);
237 /* Mark the handle as dead before freeing it. */
238 g->state = NO_HANDLE;
240 gl_lock_lock (handles_lock);
244 for (gg = handles; gg->next != g; gg = gg->next)
248 gl_lock_unlock (handles_lock);
252 free (g->last_error);
257 free (g->qemu_version);
261 /* Close all open handles (called from atexit(3)). */
265 while (handles) guestfs_close (handles);
269 guestfs_last_error (guestfs_h *g)
271 return g->last_error;
275 set_last_error (guestfs_h *g, const char *msg)
277 free (g->last_error);
278 g->last_error = strdup (msg);
282 default_error_cb (guestfs_h *g, void *data, const char *msg)
284 fprintf (stderr, _("libguestfs: error: %s\n"), msg);
288 guestfs_error (guestfs_h *g, const char *fs, ...)
294 int err = vasprintf (&msg, fs, args);
299 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
300 set_last_error (g, msg);
306 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
313 int err = vasprintf (&msg, fs, args);
318 #if !defined(_GNU_SOURCE) || defined(__APPLE__)
320 strerror_r (errnum, buf, sizeof buf);
324 buf = strerror_r (errnum, _buf, sizeof _buf);
327 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
331 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
332 set_last_error (g, msg);
338 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
340 void *ptr = malloc (nbytes);
341 if (nbytes > 0 && !ptr) g->abort_cb ();
345 /* Return 1 if an array of N objects, each of size S, cannot exist due
346 to size arithmetic overflow. S must be positive and N must be
347 nonnegative. This is a macro, not an inline function, so that it
348 works correctly even when SIZE_MAX < N.
350 By gnulib convention, SIZE_MAX represents overflow in size
351 calculations, so the conservative dividend to use here is
352 SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value.
353 However, malloc (SIZE_MAX) fails on all known hosts where
354 sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for
355 exactly-SIZE_MAX allocations on such hosts; this avoids a test and
356 branch when S is known to be 1. */
357 # define xalloc_oversized(n, s) \
358 ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
360 /* Technically we should add an autoconf test for this, testing for the desired
361 functionality, like what's done in gnulib, but for now, this is fine. */
362 #if defined(__GLIBC__)
363 #define HAVE_GNU_CALLOC (__GLIBC__ >= 2)
365 #define HAVE_GNU_CALLOC 0
368 /* Allocate zeroed memory for N elements of S bytes, with error
369 checking. S must be nonzero. */
371 guestfs_safe_calloc (guestfs_h *g, size_t n, size_t s)
373 /* From gnulib's calloc function in xmalloc.c. */
375 /* Test for overflow, since some calloc implementations don't have
376 proper overflow checks. But omit overflow and size-zero tests if
377 HAVE_GNU_CALLOC, since GNU calloc catches overflow and never
378 returns NULL if successful. */
379 if ((! HAVE_GNU_CALLOC && xalloc_oversized (n, s))
380 || (! (p = calloc (n, s)) && (HAVE_GNU_CALLOC || n != 0)))
386 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
388 void *p = realloc (ptr, nbytes);
389 if (nbytes > 0 && !p) g->abort_cb ();
394 guestfs_safe_strdup (guestfs_h *g, const char *str)
396 char *s = strdup (str);
397 if (!s) g->abort_cb ();
402 guestfs_safe_strndup (guestfs_h *g, const char *str, size_t n)
404 char *s = strndup (str, n);
405 if (!s) g->abort_cb ();
410 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
412 void *p = malloc (size);
413 if (!p) g->abort_cb ();
414 memcpy (p, ptr, size);
419 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
425 guestfs_get_out_of_memory_handler (guestfs_h *g)
431 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
434 g->error_cb_data = data;
437 guestfs_error_handler_cb
438 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
440 if (data_rtn) *data_rtn = g->error_cb_data;
445 guestfs__set_verbose (guestfs_h *g, int v)
452 guestfs__get_verbose (guestfs_h *g)
458 guestfs__set_autosync (guestfs_h *g, int a)
465 guestfs__get_autosync (guestfs_h *g)
471 guestfs__set_path (guestfs_h *g, const char *path)
478 safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
483 guestfs__get_path (guestfs_h *g)
489 guestfs__set_qemu (guestfs_h *g, const char *qemu)
494 g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
499 guestfs__get_qemu (guestfs_h *g)
505 guestfs__set_append (guestfs_h *g, const char *append)
510 g->append = append ? safe_strdup (g, append) : NULL;
515 guestfs__get_append (guestfs_h *g)
521 guestfs__set_memsize (guestfs_h *g, int memsize)
523 g->memsize = memsize;
528 guestfs__get_memsize (guestfs_h *g)
534 guestfs__set_selinux (guestfs_h *g, int selinux)
536 g->selinux = selinux;
541 guestfs__get_selinux (guestfs_h *g)
547 guestfs__get_pid (guestfs_h *g)
552 error (g, "get_pid: no qemu subprocess");
557 struct guestfs_version *
558 guestfs__version (guestfs_h *g)
560 struct guestfs_version *r;
562 r = safe_malloc (g, sizeof *r);
563 r->major = PACKAGE_VERSION_MAJOR;
564 r->minor = PACKAGE_VERSION_MINOR;
565 r->release = PACKAGE_VERSION_RELEASE;
566 r->extra = safe_strdup (g, PACKAGE_VERSION_EXTRA);
571 guestfs__set_trace (guestfs_h *g, int t)
578 guestfs__get_trace (guestfs_h *g)
584 guestfs__set_direct (guestfs_h *g, int d)
591 guestfs__get_direct (guestfs_h *g)
597 guestfs__set_recovery_proc (guestfs_h *g, int f)
599 g->recovery_proc = !!f;
604 guestfs__get_recovery_proc (guestfs_h *g)
606 return g->recovery_proc;
610 guestfs__set_network (guestfs_h *g, int v)
612 g->enable_network = !!v;
617 guestfs__get_network (guestfs_h *g)
619 return g->enable_network;
623 guestfs_set_log_message_callback (guestfs_h *g,
624 guestfs_log_message_cb cb, void *opaque)
626 g->log_message_cb = cb;
627 g->log_message_cb_data = opaque;
631 guestfs_set_subprocess_quit_callback (guestfs_h *g,
632 guestfs_subprocess_quit_cb cb, void *opaque)
634 g->subprocess_quit_cb = cb;
635 g->subprocess_quit_cb_data = opaque;
639 guestfs_set_launch_done_callback (guestfs_h *g,
640 guestfs_launch_done_cb cb, void *opaque)
642 g->launch_done_cb = cb;
643 g->launch_done_cb_data = opaque;
647 guestfs_set_close_callback (guestfs_h *g,
648 guestfs_close_cb cb, void *opaque)
651 g->close_cb_data = opaque;
655 guestfs_set_progress_callback (guestfs_h *g,
656 guestfs_progress_cb cb, void *opaque)
659 g->progress_cb_data = opaque;
662 /* Note the private data area is allocated lazily, since the vast
663 * majority of callers will never use it. This means g->pda is
668 void *data; /* opaque user data pointer */
672 hasher (void const *x, size_t table_size)
674 struct pda_entry const *p = x;
675 return hash_pjw (p->key, table_size);
679 comparator (void const *x, void const *y)
681 struct pda_entry const *a = x;
682 struct pda_entry const *b = y;
683 return STREQ (a->key, b->key);
690 struct pda_entry *p = x;
697 guestfs_set_private (guestfs_h *g, const char *key, void *data)
699 if (g->pda == NULL) {
700 g->pda = hash_initialize (16, NULL, hasher, comparator, freer);
705 struct pda_entry *new_entry = safe_malloc (g, sizeof *new_entry);
706 new_entry->key = safe_strdup (g, key);
707 new_entry->data = data;
709 struct pda_entry *old_entry = hash_delete (g->pda, new_entry);
712 struct pda_entry *entry = hash_insert (g->pda, new_entry);
715 assert (entry == new_entry);
719 bad_cast (char const *s)
725 guestfs_get_private (guestfs_h *g, const char *key)
728 return NULL; /* no keys have been set */
730 const struct pda_entry k = { .key = bad_cast (key) };
731 struct pda_entry *entry = hash_lookup (g->pda, &k);