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