syntax: Remove unused signal.h header.
[libguestfs.git] / src / guestfs.c
1 /* libguestfs
2  * Copyright (C) 2009-2010 Red Hat Inc.
3  *
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.
8  *
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.
13  *
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
17  */
18
19 #include <config.h>
20
21 #define _BSD_SOURCE /* for mkdtemp, usleep */
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <stdarg.h>
26 #include <stddef.h>
27 #include <stdint.h>
28 #include <inttypes.h>
29 #include <unistd.h>
30 #include <string.h>
31 #include <fcntl.h>
32 #include <time.h>
33 #include <sys/stat.h>
34 #include <sys/select.h>
35 #include <dirent.h>
36 #include <assert.h>
37
38 #include <rpc/types.h>
39 #include <rpc/xdr.h>
40
41 #ifdef HAVE_ERRNO_H
42 #include <errno.h>
43 #endif
44
45 #ifdef HAVE_SYS_TYPES_H
46 #include <sys/types.h>
47 #endif
48
49 #ifdef HAVE_SYS_WAIT_H
50 #include <sys/wait.h>
51 #endif
52
53 #ifdef HAVE_SYS_SOCKET_H
54 #include <sys/socket.h>
55 #endif
56
57 #ifdef HAVE_SYS_UN_H
58 #include <sys/un.h>
59 #endif
60
61 #include <arpa/inet.h>
62 #include <netinet/in.h>
63
64 #include "glthread/lock.h"
65 #include "hash.h"
66 #include "hash-pjw.h"
67 #include "ignore-value.h"
68
69 #include "guestfs.h"
70 #include "guestfs-internal.h"
71 #include "guestfs-internal-actions.h"
72 #include "guestfs_protocol.h"
73
74 static void default_error_cb (guestfs_h *g, void *data, const char *msg);
75 static void close_handles (void);
76
77 gl_lock_define_initialized (static, handles_lock);
78 static guestfs_h *handles = NULL;
79 static int atexit_handler_set = 0;
80
81 guestfs_h *
82 guestfs_create (void)
83 {
84   guestfs_h *g;
85   const char *str;
86
87   g = malloc (sizeof (*g));
88   if (!g) return NULL;
89
90   memset (g, 0, sizeof (*g));
91
92   g->state = CONFIG;
93
94   g->fd[0] = -1;
95   g->fd[1] = -1;
96   g->sock = -1;
97
98   g->abort_cb = abort;
99   g->error_cb = default_error_cb;
100   g->error_cb_data = NULL;
101
102   g->recovery_proc = 1;
103
104   str = getenv ("LIBGUESTFS_DEBUG");
105   g->verbose = str != NULL && STREQ (str, "1");
106
107   str = getenv ("LIBGUESTFS_TRACE");
108   g->trace = str != NULL && STREQ (str, "1");
109
110   str = getenv ("LIBGUESTFS_PATH");
111   g->path = str != NULL ? strdup (str) : strdup (GUESTFS_DEFAULT_PATH);
112   if (!g->path) goto error;
113
114   str = getenv ("LIBGUESTFS_QEMU");
115   g->qemu = str != NULL ? strdup (str) : strdup (QEMU);
116   if (!g->qemu) goto error;
117
118   str = getenv ("LIBGUESTFS_APPEND");
119   if (str) {
120     g->append = strdup (str);
121     if (!g->append) goto error;
122   }
123
124   /* Choose a suitable memory size.  Previously we tried to choose
125    * a minimal memory size, but this isn't really necessary since
126    * recent QEMU and KVM don't do anything nasty like locking
127    * memory into core any more.  Thus we can safely choose a
128    * large, generous amount of memory, and it'll just get swapped
129    * on smaller systems.
130    */
131   str = getenv ("LIBGUESTFS_MEMSIZE");
132   if (str) {
133     if (sscanf (str, "%d", &g->memsize) != 1 || g->memsize <= 256) {
134       fprintf (stderr, "libguestfs: non-numeric or too small value for LIBGUESTFS_MEMSIZE\n");
135       goto error;
136     }
137   } else
138     g->memsize = 500;
139
140   /* Start with large serial numbers so they are easy to spot
141    * inside the protocol.
142    */
143   g->msg_next_serial = 0x00123400;
144
145   /* Link the handles onto a global list. */
146   gl_lock_lock (handles_lock);
147   g->next = handles;
148   handles = g;
149   if (!atexit_handler_set) {
150     atexit (close_handles);
151     atexit_handler_set = 1;
152   }
153   gl_lock_unlock (handles_lock);
154
155   if (g->verbose)
156     fprintf (stderr, "new guestfs handle %p\n", g);
157
158   return g;
159
160  error:
161   free (g->path);
162   free (g->qemu);
163   free (g->append);
164   free (g);
165   return NULL;
166 }
167
168 void
169 guestfs_close (guestfs_h *g)
170 {
171   int i;
172   char filename[256];
173   guestfs_h *gg;
174
175   if (g->state == NO_HANDLE) {
176     /* Not safe to call 'error' here, so ... */
177     fprintf (stderr, _("guestfs_close: called twice on the same handle\n"));
178     return;
179   }
180
181   if (g->verbose)
182     fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
183
184   /* Run user close callback before anything else. */
185   if (g->close_cb)
186     g->close_cb (g, g->close_cb_data);
187
188   guestfs___free_inspect_info (g);
189
190   /* Try to sync if autosync flag is set. */
191   if (g->autosync && g->state == READY) {
192     guestfs_umount_all (g);
193     guestfs_sync (g);
194   }
195
196   /* Remove any handlers that might be called back before we kill the
197    * subprocess.
198    */
199   g->log_message_cb = NULL;
200
201   if (g->state != CONFIG)
202     guestfs_kill_subprocess (g);
203
204   /* Close sockets. */
205   if (g->fd[0] >= 0)
206     close (g->fd[0]);
207   if (g->fd[1] >= 0)
208     close (g->fd[1]);
209   if (g->sock >= 0)
210     close (g->sock);
211   g->fd[0] = -1;
212   g->fd[1] = -1;
213   g->sock = -1;
214
215   /* Wait for subprocess(es) to exit. */
216   waitpid (g->pid, NULL, 0);
217   if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
218
219   /* Remove tmpfiles. */
220   if (g->tmpdir) {
221     snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
222     unlink (filename);
223
224     rmdir (g->tmpdir);
225
226     free (g->tmpdir);
227   }
228
229   if (g->cmdline) {
230     for (i = 0; i < g->cmdline_size; ++i)
231       free (g->cmdline[i]);
232     free (g->cmdline);
233   }
234
235   /* Mark the handle as dead before freeing it. */
236   g->state = NO_HANDLE;
237
238   gl_lock_lock (handles_lock);
239   if (handles == g)
240     handles = g->next;
241   else {
242     for (gg = handles; gg->next != g; gg = gg->next)
243       ;
244     gg->next = g->next;
245   }
246   gl_lock_unlock (handles_lock);
247
248   if (g->pda)
249     hash_free (g->pda);
250   free (g->last_error);
251   free (g->path);
252   free (g->qemu);
253   free (g->append);
254   free (g->qemu_help);
255   free (g->qemu_version);
256   free (g);
257 }
258
259 /* Close all open handles (called from atexit(3)). */
260 static void
261 close_handles (void)
262 {
263   while (handles) guestfs_close (handles);
264 }
265
266 const char *
267 guestfs_last_error (guestfs_h *g)
268 {
269   return g->last_error;
270 }
271
272 static void
273 set_last_error (guestfs_h *g, const char *msg)
274 {
275   free (g->last_error);
276   g->last_error = strdup (msg);
277 }
278
279 static void
280 default_error_cb (guestfs_h *g, void *data, const char *msg)
281 {
282   fprintf (stderr, _("libguestfs: error: %s\n"), msg);
283 }
284
285 void
286 guestfs_error (guestfs_h *g, const char *fs, ...)
287 {
288   va_list args;
289   char *msg;
290
291   va_start (args, fs);
292   int err = vasprintf (&msg, fs, args);
293   va_end (args);
294
295   if (err < 0) return;
296
297   if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
298   set_last_error (g, msg);
299
300   free (msg);
301 }
302
303 void
304 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
305 {
306   va_list args;
307   char *msg;
308   int errnum = errno;
309
310   va_start (args, fs);
311   int err = vasprintf (&msg, fs, args);
312   va_end (args);
313
314   if (err < 0) return;
315
316 #if !defined(_GNU_SOURCE) || defined(__APPLE__)
317   char buf[256];
318   strerror_r (errnum, buf, sizeof buf);
319 #else
320   char _buf[256];
321   char *buf;
322   buf = strerror_r (errnum, _buf, sizeof _buf);
323 #endif
324
325   msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
326   strcat (msg, ": ");
327   strcat (msg, buf);
328
329   if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
330   set_last_error (g, msg);
331
332   free (msg);
333 }
334
335 void *
336 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
337 {
338   void *ptr = malloc (nbytes);
339   if (nbytes > 0 && !ptr) g->abort_cb ();
340   return ptr;
341 }
342
343 /* Return 1 if an array of N objects, each of size S, cannot exist due
344    to size arithmetic overflow.  S must be positive and N must be
345    nonnegative.  This is a macro, not an inline function, so that it
346    works correctly even when SIZE_MAX < N.
347
348    By gnulib convention, SIZE_MAX represents overflow in size
349    calculations, so the conservative dividend to use here is
350    SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value.
351    However, malloc (SIZE_MAX) fails on all known hosts where
352    sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for
353    exactly-SIZE_MAX allocations on such hosts; this avoids a test and
354    branch when S is known to be 1.  */
355 # define xalloc_oversized(n, s) \
356     ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
357
358 /* Technically we should add an autoconf test for this, testing for the desired
359    functionality, like what's done in gnulib, but for now, this is fine.  */
360 #if defined(__GLIBC__)
361 #define HAVE_GNU_CALLOC (__GLIBC__ >= 2)
362 #else
363 #define HAVE_GNU_CALLOC 0
364 #endif
365
366 /* Allocate zeroed memory for N elements of S bytes, with error
367    checking.  S must be nonzero.  */
368 void *
369 guestfs_safe_calloc (guestfs_h *g, size_t n, size_t s)
370 {
371   /* From gnulib's calloc function in xmalloc.c.  */
372   void *p;
373   /* Test for overflow, since some calloc implementations don't have
374      proper overflow checks.  But omit overflow and size-zero tests if
375      HAVE_GNU_CALLOC, since GNU calloc catches overflow and never
376      returns NULL if successful.  */
377   if ((! HAVE_GNU_CALLOC && xalloc_oversized (n, s))
378       || (! (p = calloc (n, s)) && (HAVE_GNU_CALLOC || n != 0)))
379     g->abort_cb ();
380   return p;
381 }
382
383 void *
384 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
385 {
386   void *p = realloc (ptr, nbytes);
387   if (nbytes > 0 && !p) g->abort_cb ();
388   return p;
389 }
390
391 char *
392 guestfs_safe_strdup (guestfs_h *g, const char *str)
393 {
394   char *s = strdup (str);
395   if (!s) g->abort_cb ();
396   return s;
397 }
398
399 char *
400 guestfs_safe_strndup (guestfs_h *g, const char *str, size_t n)
401 {
402   char *s = strndup (str, n);
403   if (!s) g->abort_cb ();
404   return s;
405 }
406
407 void *
408 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
409 {
410   void *p = malloc (size);
411   if (!p) g->abort_cb ();
412   memcpy (p, ptr, size);
413   return p;
414 }
415
416 void
417 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
418 {
419   g->abort_cb = cb;
420 }
421
422 guestfs_abort_cb
423 guestfs_get_out_of_memory_handler (guestfs_h *g)
424 {
425   return g->abort_cb;
426 }
427
428 void
429 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
430 {
431   g->error_cb = cb;
432   g->error_cb_data = data;
433 }
434
435 guestfs_error_handler_cb
436 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
437 {
438   if (data_rtn) *data_rtn = g->error_cb_data;
439   return g->error_cb;
440 }
441
442 int
443 guestfs__set_verbose (guestfs_h *g, int v)
444 {
445   g->verbose = !!v;
446   return 0;
447 }
448
449 int
450 guestfs__get_verbose (guestfs_h *g)
451 {
452   return g->verbose;
453 }
454
455 int
456 guestfs__set_autosync (guestfs_h *g, int a)
457 {
458   g->autosync = !!a;
459   return 0;
460 }
461
462 int
463 guestfs__get_autosync (guestfs_h *g)
464 {
465   return g->autosync;
466 }
467
468 int
469 guestfs__set_path (guestfs_h *g, const char *path)
470 {
471   free (g->path);
472   g->path = NULL;
473
474   g->path =
475     path == NULL ?
476     safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
477   return 0;
478 }
479
480 const char *
481 guestfs__get_path (guestfs_h *g)
482 {
483   return g->path;
484 }
485
486 int
487 guestfs__set_qemu (guestfs_h *g, const char *qemu)
488 {
489   free (g->qemu);
490   g->qemu = NULL;
491
492   g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
493   return 0;
494 }
495
496 const char *
497 guestfs__get_qemu (guestfs_h *g)
498 {
499   return g->qemu;
500 }
501
502 int
503 guestfs__set_append (guestfs_h *g, const char *append)
504 {
505   free (g->append);
506   g->append = NULL;
507
508   g->append = append ? safe_strdup (g, append) : NULL;
509   return 0;
510 }
511
512 const char *
513 guestfs__get_append (guestfs_h *g)
514 {
515   return g->append;
516 }
517
518 int
519 guestfs__set_memsize (guestfs_h *g, int memsize)
520 {
521   g->memsize = memsize;
522   return 0;
523 }
524
525 int
526 guestfs__get_memsize (guestfs_h *g)
527 {
528   return g->memsize;
529 }
530
531 int
532 guestfs__set_selinux (guestfs_h *g, int selinux)
533 {
534   g->selinux = selinux;
535   return 0;
536 }
537
538 int
539 guestfs__get_selinux (guestfs_h *g)
540 {
541   return g->selinux;
542 }
543
544 int
545 guestfs__get_pid (guestfs_h *g)
546 {
547   if (g->pid > 0)
548     return g->pid;
549   else {
550     error (g, "get_pid: no qemu subprocess");
551     return -1;
552   }
553 }
554
555 struct guestfs_version *
556 guestfs__version (guestfs_h *g)
557 {
558   struct guestfs_version *r;
559
560   r = safe_malloc (g, sizeof *r);
561   r->major = PACKAGE_VERSION_MAJOR;
562   r->minor = PACKAGE_VERSION_MINOR;
563   r->release = PACKAGE_VERSION_RELEASE;
564   r->extra = safe_strdup (g, PACKAGE_VERSION_EXTRA);
565   return r;
566 }
567
568 int
569 guestfs__set_trace (guestfs_h *g, int t)
570 {
571   g->trace = !!t;
572   return 0;
573 }
574
575 int
576 guestfs__get_trace (guestfs_h *g)
577 {
578   return g->trace;
579 }
580
581 int
582 guestfs__set_direct (guestfs_h *g, int d)
583 {
584   g->direct = !!d;
585   return 0;
586 }
587
588 int
589 guestfs__get_direct (guestfs_h *g)
590 {
591   return g->direct;
592 }
593
594 int
595 guestfs__set_recovery_proc (guestfs_h *g, int f)
596 {
597   g->recovery_proc = !!f;
598   return 0;
599 }
600
601 int
602 guestfs__get_recovery_proc (guestfs_h *g)
603 {
604   return g->recovery_proc;
605 }
606
607 int
608 guestfs__set_network (guestfs_h *g, int v)
609 {
610   g->enable_network = !!v;
611   return 0;
612 }
613
614 int
615 guestfs__get_network (guestfs_h *g)
616 {
617   return g->enable_network;
618 }
619
620 void
621 guestfs_set_log_message_callback (guestfs_h *g,
622                                   guestfs_log_message_cb cb, void *opaque)
623 {
624   g->log_message_cb = cb;
625   g->log_message_cb_data = opaque;
626 }
627
628 void
629 guestfs_set_subprocess_quit_callback (guestfs_h *g,
630                                       guestfs_subprocess_quit_cb cb, void *opaque)
631 {
632   g->subprocess_quit_cb = cb;
633   g->subprocess_quit_cb_data = opaque;
634 }
635
636 void
637 guestfs_set_launch_done_callback (guestfs_h *g,
638                                   guestfs_launch_done_cb cb, void *opaque)
639 {
640   g->launch_done_cb = cb;
641   g->launch_done_cb_data = opaque;
642 }
643
644 void
645 guestfs_set_close_callback (guestfs_h *g,
646                             guestfs_close_cb cb, void *opaque)
647 {
648   g->close_cb = cb;
649   g->close_cb_data = opaque;
650 }
651
652 void
653 guestfs_set_progress_callback (guestfs_h *g,
654                                guestfs_progress_cb cb, void *opaque)
655 {
656   g->progress_cb = cb;
657   g->progress_cb_data = opaque;
658 }
659
660 /* Note the private data area is allocated lazily, since the vast
661  * majority of callers will never use it.  This means g->pda is
662  * likely to be NULL.
663  */
664 struct pda_entry {
665   char *key;                    /* key */
666   void *data;                   /* opaque user data pointer */
667 };
668
669 static size_t
670 hasher (void const *x, size_t table_size)
671 {
672   struct pda_entry const *p = x;
673   return hash_pjw (p->key, table_size);
674 }
675
676 static bool
677 comparator (void const *x, void const *y)
678 {
679   struct pda_entry const *a = x;
680   struct pda_entry const *b = y;
681   return STREQ (a->key, b->key);
682 }
683
684 static void
685 freer (void *x)
686 {
687   if (x) {
688     struct pda_entry *p = x;
689     free (p->key);
690     free (p);
691   }
692 }
693
694 void
695 guestfs_set_private (guestfs_h *g, const char *key, void *data)
696 {
697   if (g->pda == NULL) {
698     g->pda = hash_initialize (16, NULL, hasher, comparator, freer);
699     if (g->pda == NULL)
700       g->abort_cb ();
701   }
702
703   struct pda_entry *new_entry = safe_malloc (g, sizeof *new_entry);
704   new_entry->key = safe_strdup (g, key);
705   new_entry->data = data;
706
707   struct pda_entry *old_entry = hash_delete (g->pda, new_entry);
708   freer (old_entry);
709
710   struct pda_entry *entry = hash_insert (g->pda, new_entry);
711   if (entry == NULL)
712     g->abort_cb ();
713   assert (entry == new_entry);
714 }
715
716 static inline char *
717 bad_cast (char const *s)
718 {
719   return (char *) s;
720 }
721
722 void *
723 guestfs_get_private (guestfs_h *g, const char *key)
724 {
725   if (g->pda == NULL)
726     return NULL;                /* no keys have been set */
727
728   const struct pda_entry k = { .key = bad_cast (key) };
729   struct pda_entry *entry = hash_lookup (g->pda, &k);
730   if (entry)
731     return entry->data;
732   else
733     return NULL;
734 }