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