docs: Error strings are in fact localized, documentation was wrong.
[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 "c-ctype.h"
65 #include "glthread/lock.h"
66 #include "hash.h"
67 #include "hash-pjw.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   g->autosync = 1;
104
105   str = getenv ("LIBGUESTFS_DEBUG");
106   g->verbose = str != NULL && STREQ (str, "1");
107
108   str = getenv ("LIBGUESTFS_TRACE");
109   g->trace = str != NULL && STREQ (str, "1");
110
111   str = getenv ("LIBGUESTFS_PATH");
112   g->path = str != NULL ? strdup (str) : strdup (GUESTFS_DEFAULT_PATH);
113   if (!g->path) goto error;
114
115   str = getenv ("LIBGUESTFS_QEMU");
116   g->qemu = str != NULL ? strdup (str) : strdup (QEMU);
117   if (!g->qemu) goto error;
118
119   str = getenv ("LIBGUESTFS_APPEND");
120   if (str) {
121     g->append = strdup (str);
122     if (!g->append) goto error;
123   }
124
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.
131    */
132   str = getenv ("LIBGUESTFS_MEMSIZE");
133   if (str) {
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");
136       goto error;
137     }
138   } else
139     g->memsize = 500;
140
141   /* Start with large serial numbers so they are easy to spot
142    * inside the protocol.
143    */
144   g->msg_next_serial = 0x00123400;
145
146   /* Link the handles onto a global list. */
147   gl_lock_lock (handles_lock);
148   g->next = handles;
149   handles = g;
150   if (!atexit_handler_set) {
151     atexit (close_handles);
152     atexit_handler_set = 1;
153   }
154   gl_lock_unlock (handles_lock);
155
156   if (g->verbose)
157     fprintf (stderr, "new guestfs handle %p\n", g);
158
159   return g;
160
161  error:
162   free (g->path);
163   free (g->qemu);
164   free (g->append);
165   free (g);
166   return NULL;
167 }
168
169 void
170 guestfs_close (guestfs_h *g)
171 {
172   int i;
173   char filename[256];
174   guestfs_h *gg;
175
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"));
179     return;
180   }
181
182   if (g->verbose)
183     fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
184
185   /* Run user close callback before anything else. */
186   if (g->close_cb)
187     g->close_cb (g, g->close_cb_data);
188
189   guestfs___free_inspect_info (g);
190
191   /* Try to sync if autosync flag is set. */
192   if (g->autosync && g->state == READY) {
193     guestfs_umount_all (g);
194     guestfs_sync (g);
195   }
196
197   /* Remove any handlers that might be called back before we kill the
198    * subprocess.
199    */
200   g->log_message_cb = NULL;
201
202   if (g->state != CONFIG)
203     guestfs_kill_subprocess (g);
204
205   /* Close sockets. */
206   if (g->fd[0] >= 0)
207     close (g->fd[0]);
208   if (g->fd[1] >= 0)
209     close (g->fd[1]);
210   if (g->sock >= 0)
211     close (g->sock);
212   g->fd[0] = -1;
213   g->fd[1] = -1;
214   g->sock = -1;
215
216   /* Wait for subprocess(es) to exit. */
217   waitpid (g->pid, NULL, 0);
218   if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
219
220   /* Remove tmpfiles. */
221   if (g->tmpdir) {
222     snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
223     unlink (filename);
224
225     rmdir (g->tmpdir);
226
227     free (g->tmpdir);
228   }
229
230   if (g->cmdline) {
231     for (i = 0; i < g->cmdline_size; ++i)
232       free (g->cmdline[i]);
233     free (g->cmdline);
234   }
235
236   /* Mark the handle as dead before freeing it. */
237   g->state = NO_HANDLE;
238
239   gl_lock_lock (handles_lock);
240   if (handles == g)
241     handles = g->next;
242   else {
243     for (gg = handles; gg->next != g; gg = gg->next)
244       ;
245     gg->next = g->next;
246   }
247   gl_lock_unlock (handles_lock);
248
249   if (g->pda)
250     hash_free (g->pda);
251   free (g->last_error);
252   free (g->path);
253   free (g->qemu);
254   free (g->append);
255   free (g->qemu_help);
256   free (g->qemu_version);
257   free (g);
258 }
259
260 /* Close all open handles (called from atexit(3)). */
261 static void
262 close_handles (void)
263 {
264   while (handles) guestfs_close (handles);
265 }
266
267 const char *
268 guestfs_last_error (guestfs_h *g)
269 {
270   return g->last_error;
271 }
272
273 int
274 guestfs_last_errno (guestfs_h *g)
275 {
276   return g->last_errnum;
277 }
278
279 static void
280 set_last_error (guestfs_h *g, int errnum, const char *msg)
281 {
282   free (g->last_error);
283   g->last_error = strdup (msg);
284   g->last_errnum = errnum;
285 }
286
287 static void
288 default_error_cb (guestfs_h *g, void *data, const char *msg)
289 {
290   fprintf (stderr, _("libguestfs: error: %s\n"), msg);
291 }
292
293 void
294 guestfs_error_errno (guestfs_h *g, int errnum, const char *fs, ...)
295 {
296   va_list args;
297   char *msg;
298
299   va_start (args, fs);
300   int err = vasprintf (&msg, fs, args);
301   va_end (args);
302
303   if (err < 0) return;
304
305   /* set_last_error first so that the callback can access the error
306    * message and errno through the handle if it wishes.
307    */
308   set_last_error (g, errnum, msg);
309   if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
310
311   free (msg);
312 }
313
314 void
315 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
316 {
317   va_list args;
318   char *msg;
319   int errnum = errno;
320
321   va_start (args, fs);
322   int err = vasprintf (&msg, fs, args);
323   va_end (args);
324
325   if (err < 0) return;
326
327 #if !defined(_GNU_SOURCE) || defined(__APPLE__)
328   char buf[256];
329   strerror_r (errnum, buf, sizeof buf);
330 #else
331   char _buf[256];
332   char *buf;
333   buf = strerror_r (errnum, _buf, sizeof _buf);
334 #endif
335
336   msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
337   strcat (msg, ": ");
338   strcat (msg, buf);
339
340   /* set_last_error first so that the callback can access the error
341    * message and errno through the handle if it wishes.
342    */
343   set_last_error (g, errnum, msg);
344   if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
345
346   free (msg);
347 }
348
349 void *
350 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
351 {
352   void *ptr = malloc (nbytes);
353   if (nbytes > 0 && !ptr) g->abort_cb ();
354   return ptr;
355 }
356
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.
361
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))
371
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)
376 #else
377 #define HAVE_GNU_CALLOC 0
378 #endif
379
380 /* Allocate zeroed memory for N elements of S bytes, with error
381    checking.  S must be nonzero.  */
382 void *
383 guestfs_safe_calloc (guestfs_h *g, size_t n, size_t s)
384 {
385   /* From gnulib's calloc function in xmalloc.c.  */
386   void *p;
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)))
393     g->abort_cb ();
394   return p;
395 }
396
397 void *
398 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
399 {
400   void *p = realloc (ptr, nbytes);
401   if (nbytes > 0 && !p) g->abort_cb ();
402   return p;
403 }
404
405 char *
406 guestfs_safe_strdup (guestfs_h *g, const char *str)
407 {
408   char *s = strdup (str);
409   if (!s) g->abort_cb ();
410   return s;
411 }
412
413 char *
414 guestfs_safe_strndup (guestfs_h *g, const char *str, size_t n)
415 {
416   char *s = strndup (str, n);
417   if (!s) g->abort_cb ();
418   return s;
419 }
420
421 void *
422 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
423 {
424   void *p = malloc (size);
425   if (!p) g->abort_cb ();
426   memcpy (p, ptr, size);
427   return p;
428 }
429
430 void
431 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
432 {
433   g->abort_cb = cb;
434 }
435
436 guestfs_abort_cb
437 guestfs_get_out_of_memory_handler (guestfs_h *g)
438 {
439   return g->abort_cb;
440 }
441
442 void
443 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
444 {
445   g->error_cb = cb;
446   g->error_cb_data = data;
447 }
448
449 guestfs_error_handler_cb
450 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
451 {
452   if (data_rtn) *data_rtn = g->error_cb_data;
453   return g->error_cb;
454 }
455
456 int
457 guestfs__set_verbose (guestfs_h *g, int v)
458 {
459   g->verbose = !!v;
460   return 0;
461 }
462
463 int
464 guestfs__get_verbose (guestfs_h *g)
465 {
466   return g->verbose;
467 }
468
469 int
470 guestfs__set_autosync (guestfs_h *g, int a)
471 {
472   g->autosync = !!a;
473   return 0;
474 }
475
476 int
477 guestfs__get_autosync (guestfs_h *g)
478 {
479   return g->autosync;
480 }
481
482 int
483 guestfs__set_path (guestfs_h *g, const char *path)
484 {
485   free (g->path);
486   g->path = NULL;
487
488   g->path =
489     path == NULL ?
490     safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
491   return 0;
492 }
493
494 const char *
495 guestfs__get_path (guestfs_h *g)
496 {
497   return g->path;
498 }
499
500 int
501 guestfs__set_qemu (guestfs_h *g, const char *qemu)
502 {
503   free (g->qemu);
504   g->qemu = NULL;
505
506   g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
507   return 0;
508 }
509
510 const char *
511 guestfs__get_qemu (guestfs_h *g)
512 {
513   return g->qemu;
514 }
515
516 int
517 guestfs__set_append (guestfs_h *g, const char *append)
518 {
519   free (g->append);
520   g->append = NULL;
521
522   g->append = append ? safe_strdup (g, append) : NULL;
523   return 0;
524 }
525
526 const char *
527 guestfs__get_append (guestfs_h *g)
528 {
529   return g->append;
530 }
531
532 int
533 guestfs__set_memsize (guestfs_h *g, int memsize)
534 {
535   g->memsize = memsize;
536   return 0;
537 }
538
539 int
540 guestfs__get_memsize (guestfs_h *g)
541 {
542   return g->memsize;
543 }
544
545 int
546 guestfs__set_selinux (guestfs_h *g, int selinux)
547 {
548   g->selinux = selinux;
549   return 0;
550 }
551
552 int
553 guestfs__get_selinux (guestfs_h *g)
554 {
555   return g->selinux;
556 }
557
558 int
559 guestfs__get_pid (guestfs_h *g)
560 {
561   if (g->pid > 0)
562     return g->pid;
563   else {
564     error (g, "get_pid: no qemu subprocess");
565     return -1;
566   }
567 }
568
569 struct guestfs_version *
570 guestfs__version (guestfs_h *g)
571 {
572   struct guestfs_version *r;
573
574   r = safe_malloc (g, sizeof *r);
575   r->major = PACKAGE_VERSION_MAJOR;
576   r->minor = PACKAGE_VERSION_MINOR;
577   r->release = PACKAGE_VERSION_RELEASE;
578   r->extra = safe_strdup (g, PACKAGE_VERSION_EXTRA);
579   return r;
580 }
581
582 int
583 guestfs__set_trace (guestfs_h *g, int t)
584 {
585   g->trace = !!t;
586   return 0;
587 }
588
589 int
590 guestfs__get_trace (guestfs_h *g)
591 {
592   return g->trace;
593 }
594
595 int
596 guestfs__set_direct (guestfs_h *g, int d)
597 {
598   g->direct = !!d;
599   return 0;
600 }
601
602 int
603 guestfs__get_direct (guestfs_h *g)
604 {
605   return g->direct;
606 }
607
608 int
609 guestfs__set_recovery_proc (guestfs_h *g, int f)
610 {
611   g->recovery_proc = !!f;
612   return 0;
613 }
614
615 int
616 guestfs__get_recovery_proc (guestfs_h *g)
617 {
618   return g->recovery_proc;
619 }
620
621 int
622 guestfs__set_network (guestfs_h *g, int v)
623 {
624   g->enable_network = !!v;
625   return 0;
626 }
627
628 int
629 guestfs__get_network (guestfs_h *g)
630 {
631   return g->enable_network;
632 }
633
634 void
635 guestfs_set_log_message_callback (guestfs_h *g,
636                                   guestfs_log_message_cb cb, void *opaque)
637 {
638   g->log_message_cb = cb;
639   g->log_message_cb_data = opaque;
640 }
641
642 void
643 guestfs_set_subprocess_quit_callback (guestfs_h *g,
644                                       guestfs_subprocess_quit_cb cb, void *opaque)
645 {
646   g->subprocess_quit_cb = cb;
647   g->subprocess_quit_cb_data = opaque;
648 }
649
650 void
651 guestfs_set_launch_done_callback (guestfs_h *g,
652                                   guestfs_launch_done_cb cb, void *opaque)
653 {
654   g->launch_done_cb = cb;
655   g->launch_done_cb_data = opaque;
656 }
657
658 void
659 guestfs_set_close_callback (guestfs_h *g,
660                             guestfs_close_cb cb, void *opaque)
661 {
662   g->close_cb = cb;
663   g->close_cb_data = opaque;
664 }
665
666 void
667 guestfs_set_progress_callback (guestfs_h *g,
668                                guestfs_progress_cb cb, void *opaque)
669 {
670   g->progress_cb = cb;
671   g->progress_cb_data = opaque;
672 }
673
674 /* Note the private data area is allocated lazily, since the vast
675  * majority of callers will never use it.  This means g->pda is
676  * likely to be NULL.
677  */
678 struct pda_entry {
679   char *key;                    /* key */
680   void *data;                   /* opaque user data pointer */
681 };
682
683 static size_t
684 hasher (void const *x, size_t table_size)
685 {
686   struct pda_entry const *p = x;
687   return hash_pjw (p->key, table_size);
688 }
689
690 static bool
691 comparator (void const *x, void const *y)
692 {
693   struct pda_entry const *a = x;
694   struct pda_entry const *b = y;
695   return STREQ (a->key, b->key);
696 }
697
698 static void
699 freer (void *x)
700 {
701   if (x) {
702     struct pda_entry *p = x;
703     free (p->key);
704     free (p);
705   }
706 }
707
708 void
709 guestfs_set_private (guestfs_h *g, const char *key, void *data)
710 {
711   if (g->pda == NULL) {
712     g->pda = hash_initialize (16, NULL, hasher, comparator, freer);
713     if (g->pda == NULL)
714       g->abort_cb ();
715   }
716
717   struct pda_entry *new_entry = safe_malloc (g, sizeof *new_entry);
718   new_entry->key = safe_strdup (g, key);
719   new_entry->data = data;
720
721   struct pda_entry *old_entry = hash_delete (g->pda, new_entry);
722   freer (old_entry);
723
724   struct pda_entry *entry = hash_insert (g->pda, new_entry);
725   if (entry == NULL)
726     g->abort_cb ();
727   assert (entry == new_entry);
728 }
729
730 static inline char *
731 bad_cast (char const *s)
732 {
733   return (char *) s;
734 }
735
736 void *
737 guestfs_get_private (guestfs_h *g, const char *key)
738 {
739   if (g->pda == NULL)
740     return NULL;                /* no keys have been set */
741
742   const struct pda_entry k = { .key = bad_cast (key) };
743   struct pda_entry *entry = hash_lookup (g->pda, &k);
744   if (entry)
745     return entry->data;
746   else
747     return NULL;
748 }
749
750 /* When tracing, be careful how we print BufferIn parameters which
751  * usually contain large amounts of binary data (RHBZ#646822).
752  */
753 void
754 guestfs___print_BufferIn (FILE *out, const char *buf, size_t buf_size)
755 {
756   size_t i;
757   size_t orig_size = buf_size;
758
759   if (buf_size > 256)
760     buf_size = 256;
761
762   fputc ('"', out);
763
764   for (i = 0; i < buf_size; ++i) {
765     if (c_isprint (buf[i]))
766       fputc (buf[i], out);
767     else
768       fprintf (out, "\\x%02x", (unsigned char) buf[i]);
769   }
770
771   fputc ('"', out);
772
773   if (orig_size > buf_size)
774     fprintf (out,
775              _("<truncated, original size %zu bytes>"), orig_size);
776 }