170d0d321c07df328df69ec52dee8eaa15457994
[libguestfs.git] / src / guestfs.c
1 /* libguestfs
2  * Copyright (C) 2009-2011 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 remove_tmpdir (guestfs_h *g);
76 static void close_handles (void);
77
78 gl_lock_define_initialized (static, handles_lock);
79 static guestfs_h *handles = NULL;
80 static int atexit_handler_set = 0;
81
82 guestfs_h *
83 guestfs_create (void)
84 {
85   guestfs_h *g;
86   const char *str;
87
88   g = malloc (sizeof (*g));
89   if (!g) return NULL;
90
91   memset (g, 0, sizeof (*g));
92
93   g->state = CONFIG;
94
95   g->fd[0] = -1;
96   g->fd[1] = -1;
97   g->sock = -1;
98
99   g->abort_cb = abort;
100   g->error_cb = default_error_cb;
101   g->error_cb_data = NULL;
102
103   g->recovery_proc = 1;
104   g->autosync = 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       warning (g, "non-numeric or too small value for LIBGUESTFS_MEMSIZE");
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   /* Default is uniprocessor appliance. */
148   g->smp = 1;
149
150   /* Link the handles onto a global list. */
151   gl_lock_lock (handles_lock);
152   g->next = handles;
153   handles = g;
154   if (!atexit_handler_set) {
155     atexit (close_handles);
156     atexit_handler_set = 1;
157   }
158   gl_lock_unlock (handles_lock);
159
160   debug (g, "new guestfs handle %p", g);
161
162   return g;
163
164  error:
165   free (g->path);
166   free (g->qemu);
167   free (g->append);
168   free (g);
169   return NULL;
170 }
171
172 void
173 guestfs_close (guestfs_h *g)
174 {
175   if (g->state == NO_HANDLE) {
176     /* Not safe to call ANY callbacks here, so ... */
177     fprintf (stderr, _("guestfs_close: called twice on the same handle\n"));
178     return;
179   }
180
181   if (g->trace) {
182     const char trace_msg[] = "close";
183
184     guestfs___call_callbacks_message (g, GUESTFS_EVENT_TRACE,
185                                       trace_msg, strlen (trace_msg));
186   }
187
188   debug (g, "closing guestfs handle %p (state %d)", g, g->state);
189
190   /* Try to sync if autosync flag is set. */
191   if (g->autosync && g->state == READY)
192     guestfs_internal_autosync (g);
193
194   /* Kill the qemu subprocess. */
195   if (g->state != CONFIG)
196     guestfs_kill_subprocess (g);
197
198   /* Run user close callbacks. */
199   guestfs___call_callbacks_void (g, GUESTFS_EVENT_CLOSE);
200
201   /* Remove all other registered callbacks.  Since we've already
202    * called the close callbacks, we shouldn't call any others.
203    */
204   free (g->events);
205   g->nr_events = 0;
206   g->events = NULL;
207
208   guestfs___free_inspect_info (g);
209   guestfs___free_drives (&g->drives);
210
211   /* Close sockets. */
212   if (g->fd[0] >= 0)
213     close (g->fd[0]);
214   if (g->fd[1] >= 0)
215     close (g->fd[1]);
216   if (g->sock >= 0)
217     close (g->sock);
218   g->fd[0] = -1;
219   g->fd[1] = -1;
220   g->sock = -1;
221
222   /* Wait for subprocess(es) to exit. */
223   if (g->pid > 0) waitpid (g->pid, NULL, 0);
224   if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
225
226   /* Remove whole temporary directory. */
227   remove_tmpdir (g);
228
229   if (g->cmdline) {
230     size_t i;
231
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     guestfs_h *gg;
245
246     for (gg = handles; gg->next != g; gg = gg->next)
247       ;
248     gg->next = g->next;
249   }
250   gl_lock_unlock (handles_lock);
251
252   if (g->pda)
253     hash_free (g->pda);
254   free (g->last_error);
255   free (g->path);
256   free (g->qemu);
257   free (g->append);
258   free (g->qemu_help);
259   free (g->qemu_version);
260   free (g);
261 }
262
263 /* g->tmpdir can contain any files (but not subdirectories).  Remove
264  * those and the directory itself.  Note that errors in this function
265  * aren't really that important: if we end up not deleting temporary
266  * files it's only annoying.
267  */
268 static void
269 remove_tmpdir (guestfs_h *g)
270 {
271   DIR *dir;
272   struct dirent *d;
273
274   if (!g->tmpdir)
275     return;
276
277   dir = opendir (g->tmpdir);
278   if (dir == NULL) {
279     perror (g->tmpdir);
280     return;
281   }
282
283   while ((d = readdir (dir)) != NULL) {
284     if (STRNEQ (d->d_name, ".") && STRNEQ (d->d_name, "..")) {
285       if (unlinkat (dirfd (dir), d->d_name, 0) == -1)
286         perror (d->d_name);
287     }
288   }
289
290   if (closedir (dir) == -1)
291     perror (g->tmpdir);
292
293   if (rmdir (g->tmpdir) == -1)
294     perror (g->tmpdir);
295
296   free (g->tmpdir);
297   g->tmpdir = NULL;
298 }
299
300 /* Close all open handles (called from atexit(3)). */
301 static void
302 close_handles (void)
303 {
304   while (handles) guestfs_close (handles);
305 }
306
307 const char *
308 guestfs_last_error (guestfs_h *g)
309 {
310   return g->last_error;
311 }
312
313 int
314 guestfs_last_errno (guestfs_h *g)
315 {
316   return g->last_errnum;
317 }
318
319 static void
320 set_last_error (guestfs_h *g, int errnum, const char *msg)
321 {
322   free (g->last_error);
323   g->last_error = strdup (msg);
324   g->last_errnum = errnum;
325 }
326
327 /* Warning are printed unconditionally.  We try to make these rare.
328  * Generally speaking, a warning should either be an error, or if it's
329  * not important for end users then it should be a debug message.
330  */
331 void
332 guestfs___warning (guestfs_h *g, const char *fs, ...)
333 {
334   va_list args;
335   char *msg, *msg2;
336   int len;
337
338   va_start (args, fs);
339   len = vasprintf (&msg, fs, args);
340   va_end (args);
341
342   if (len < 0) return;
343
344   len = asprintf (&msg2, _("warning: %s"), msg);
345   free (msg);
346
347   if (len < 0) return;
348
349   guestfs___call_callbacks_message (g, GUESTFS_EVENT_LIBRARY, msg2, len);
350
351   free (msg2);
352 }
353
354 /* Debug messages. */
355 void
356 guestfs___debug (guestfs_h *g, const char *fs, ...)
357 {
358   va_list args;
359   char *msg;
360   int len;
361
362   /* The cpp macro "debug" has already checked that g->verbose is true
363    * before calling this function, but we check it again just in case
364    * anyone calls this function directly.
365    */
366   if (!g->verbose)
367     return;
368
369   va_start (args, fs);
370   len = vasprintf (&msg, fs, args);
371   va_end (args);
372
373   if (len < 0) return;
374
375   guestfs___call_callbacks_message (g, GUESTFS_EVENT_LIBRARY, msg, len);
376 }
377
378 /* Call trace messages.  These are enabled by setting g->trace, and
379  * calls to this function should only happen from the generated code
380  * in src/actions.c
381  */
382 void
383 guestfs___trace (guestfs_h *g, const char *fs, ...)
384 {
385   va_list args;
386   char *msg;
387   int len;
388
389   va_start (args, fs);
390   len = vasprintf (&msg, fs, args);
391   va_end (args);
392
393   if (len < 0) return;
394
395   guestfs___call_callbacks_message (g, GUESTFS_EVENT_TRACE, msg, len);
396
397   free (msg);
398 }
399
400 static void
401 default_error_cb (guestfs_h *g, void *data, const char *msg)
402 {
403   fprintf (stderr, _("libguestfs: error: %s\n"), msg);
404 }
405
406 void
407 guestfs_error_errno (guestfs_h *g, int errnum, const char *fs, ...)
408 {
409   va_list args;
410   char *msg;
411
412   va_start (args, fs);
413   int err = vasprintf (&msg, fs, args);
414   va_end (args);
415
416   if (err < 0) return;
417
418   /* set_last_error first so that the callback can access the error
419    * message and errno through the handle if it wishes.
420    */
421   set_last_error (g, errnum, msg);
422   if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
423
424   free (msg);
425 }
426
427 void
428 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
429 {
430   va_list args;
431   char *msg;
432   int errnum = errno;
433
434   va_start (args, fs);
435   int err = vasprintf (&msg, fs, args);
436   va_end (args);
437
438   if (err < 0) return;
439
440   char buf[256];
441   strerror_r (errnum, buf, sizeof buf);
442
443   msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
444   strcat (msg, ": ");
445   strcat (msg, buf);
446
447   /* set_last_error first so that the callback can access the error
448    * message and errno through the handle if it wishes.
449    */
450   set_last_error (g, errnum, msg);
451   if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
452
453   free (msg);
454 }
455
456 void *
457 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
458 {
459   void *ptr = malloc (nbytes);
460   if (nbytes > 0 && !ptr) g->abort_cb ();
461   return ptr;
462 }
463
464 /* Return 1 if an array of N objects, each of size S, cannot exist due
465    to size arithmetic overflow.  S must be positive and N must be
466    nonnegative.  This is a macro, not an inline function, so that it
467    works correctly even when SIZE_MAX < N.
468
469    By gnulib convention, SIZE_MAX represents overflow in size
470    calculations, so the conservative dividend to use here is
471    SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value.
472    However, malloc (SIZE_MAX) fails on all known hosts where
473    sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for
474    exactly-SIZE_MAX allocations on such hosts; this avoids a test and
475    branch when S is known to be 1.  */
476 # define xalloc_oversized(n, s) \
477     ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
478
479 /* Technically we should add an autoconf test for this, testing for the desired
480    functionality, like what's done in gnulib, but for now, this is fine.  */
481 #if defined(__GLIBC__)
482 #define HAVE_GNU_CALLOC (__GLIBC__ >= 2)
483 #else
484 #define HAVE_GNU_CALLOC 0
485 #endif
486
487 /* Allocate zeroed memory for N elements of S bytes, with error
488    checking.  S must be nonzero.  */
489 void *
490 guestfs_safe_calloc (guestfs_h *g, size_t n, size_t s)
491 {
492   /* From gnulib's calloc function in xmalloc.c.  */
493   void *p;
494   /* Test for overflow, since some calloc implementations don't have
495      proper overflow checks.  But omit overflow and size-zero tests if
496      HAVE_GNU_CALLOC, since GNU calloc catches overflow and never
497      returns NULL if successful.  */
498   if ((! HAVE_GNU_CALLOC && xalloc_oversized (n, s))
499       || (! (p = calloc (n, s)) && (HAVE_GNU_CALLOC || n != 0)))
500     g->abort_cb ();
501   return p;
502 }
503
504 void *
505 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
506 {
507   void *p = realloc (ptr, nbytes);
508   if (nbytes > 0 && !p) g->abort_cb ();
509   return p;
510 }
511
512 char *
513 guestfs_safe_strdup (guestfs_h *g, const char *str)
514 {
515   char *s = strdup (str);
516   if (!s) g->abort_cb ();
517   return s;
518 }
519
520 char *
521 guestfs_safe_strndup (guestfs_h *g, const char *str, size_t n)
522 {
523   char *s = strndup (str, n);
524   if (!s) g->abort_cb ();
525   return s;
526 }
527
528 void *
529 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
530 {
531   void *p = malloc (size);
532   if (!p) g->abort_cb ();
533   memcpy (p, ptr, size);
534   return p;
535 }
536
537 char *
538 guestfs_safe_asprintf (guestfs_h *g, const char *fs, ...)
539 {
540   va_list args;
541   char *msg;
542
543   va_start (args, fs);
544   int err = vasprintf (&msg, fs, args);
545   va_end (args);
546
547   if (err == -1)
548     g->abort_cb ();
549
550   return msg;
551 }
552
553 void
554 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
555 {
556   g->abort_cb = cb;
557 }
558
559 guestfs_abort_cb
560 guestfs_get_out_of_memory_handler (guestfs_h *g)
561 {
562   return g->abort_cb;
563 }
564
565 void
566 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
567 {
568   g->error_cb = cb;
569   g->error_cb_data = data;
570 }
571
572 guestfs_error_handler_cb
573 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
574 {
575   if (data_rtn) *data_rtn = g->error_cb_data;
576   return g->error_cb;
577 }
578
579 void
580 guestfs_user_cancel (guestfs_h *g)
581 {
582   g->user_cancel = 1;
583 }
584
585 int
586 guestfs__set_verbose (guestfs_h *g, int v)
587 {
588   g->verbose = !!v;
589   return 0;
590 }
591
592 int
593 guestfs__get_verbose (guestfs_h *g)
594 {
595   return g->verbose;
596 }
597
598 int
599 guestfs__set_autosync (guestfs_h *g, int a)
600 {
601   g->autosync = !!a;
602   return 0;
603 }
604
605 int
606 guestfs__get_autosync (guestfs_h *g)
607 {
608   return g->autosync;
609 }
610
611 int
612 guestfs__set_path (guestfs_h *g, const char *path)
613 {
614   free (g->path);
615   g->path = NULL;
616
617   g->path =
618     path == NULL ?
619     safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
620   return 0;
621 }
622
623 const char *
624 guestfs__get_path (guestfs_h *g)
625 {
626   return g->path;
627 }
628
629 int
630 guestfs__set_qemu (guestfs_h *g, const char *qemu)
631 {
632   free (g->qemu);
633   g->qemu = NULL;
634
635   g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
636   return 0;
637 }
638
639 const char *
640 guestfs__get_qemu (guestfs_h *g)
641 {
642   return g->qemu;
643 }
644
645 int
646 guestfs__set_append (guestfs_h *g, const char *append)
647 {
648   free (g->append);
649   g->append = NULL;
650
651   g->append = append ? safe_strdup (g, append) : NULL;
652   return 0;
653 }
654
655 const char *
656 guestfs__get_append (guestfs_h *g)
657 {
658   return g->append;
659 }
660
661 int
662 guestfs__set_memsize (guestfs_h *g, int memsize)
663 {
664   g->memsize = memsize;
665   return 0;
666 }
667
668 int
669 guestfs__get_memsize (guestfs_h *g)
670 {
671   return g->memsize;
672 }
673
674 int
675 guestfs__set_selinux (guestfs_h *g, int selinux)
676 {
677   g->selinux = selinux;
678   return 0;
679 }
680
681 int
682 guestfs__get_selinux (guestfs_h *g)
683 {
684   return g->selinux;
685 }
686
687 int
688 guestfs__get_pid (guestfs_h *g)
689 {
690   if (g->pid > 0)
691     return g->pid;
692   else {
693     error (g, "get_pid: no qemu subprocess");
694     return -1;
695   }
696 }
697
698 struct guestfs_version *
699 guestfs__version (guestfs_h *g)
700 {
701   struct guestfs_version *r;
702
703   r = safe_malloc (g, sizeof *r);
704   r->major = PACKAGE_VERSION_MAJOR;
705   r->minor = PACKAGE_VERSION_MINOR;
706   r->release = PACKAGE_VERSION_RELEASE;
707   r->extra = safe_strdup (g, PACKAGE_VERSION_EXTRA);
708   return r;
709 }
710
711 int
712 guestfs__set_trace (guestfs_h *g, int t)
713 {
714   g->trace = !!t;
715   return 0;
716 }
717
718 int
719 guestfs__get_trace (guestfs_h *g)
720 {
721   return g->trace;
722 }
723
724 int
725 guestfs__set_direct (guestfs_h *g, int d)
726 {
727   g->direct = !!d;
728   return 0;
729 }
730
731 int
732 guestfs__get_direct (guestfs_h *g)
733 {
734   return g->direct;
735 }
736
737 int
738 guestfs__set_recovery_proc (guestfs_h *g, int f)
739 {
740   g->recovery_proc = !!f;
741   return 0;
742 }
743
744 int
745 guestfs__get_recovery_proc (guestfs_h *g)
746 {
747   return g->recovery_proc;
748 }
749
750 int
751 guestfs__set_network (guestfs_h *g, int v)
752 {
753   g->enable_network = !!v;
754   return 0;
755 }
756
757 int
758 guestfs__get_network (guestfs_h *g)
759 {
760   return g->enable_network;
761 }
762
763 int
764 guestfs__set_attach_method (guestfs_h *g, const char *method)
765 {
766   if (STREQ (method, "appliance")) {
767     g->attach_method = ATTACH_METHOD_APPLIANCE;
768     free (g->attach_method_arg);
769     g->attach_method_arg = NULL;
770   }
771   else if (STRPREFIX (method, "unix:") && strlen (method) > 5) {
772     g->attach_method = ATTACH_METHOD_UNIX;
773     free (g->attach_method_arg);
774     g->attach_method_arg = safe_strdup (g, method + 5);
775     /* Note that we don't check the path exists until launch is called. */
776   }
777   else {
778     error (g, "invalid attach method: %s", method);
779     return -1;
780   }
781
782   return 0;
783 }
784
785 char *
786 guestfs__get_attach_method (guestfs_h *g)
787 {
788   char *ret;
789
790   switch (g->attach_method) {
791   case ATTACH_METHOD_APPLIANCE:
792     ret = safe_strdup (g, "appliance");
793     break;
794
795   case ATTACH_METHOD_UNIX:
796     ret = safe_malloc (g, strlen (g->attach_method_arg) + 5 + 1);
797     strcpy (ret, "unix:");
798     strcat (ret, g->attach_method_arg);
799     break;
800
801   default: /* keep GCC happy - this is not reached */
802     abort ();
803   }
804
805   return ret;
806 }
807
808 int
809 guestfs__set_pgroup (guestfs_h *g, int v)
810 {
811   g->pgroup = !!v;
812   return 0;
813 }
814
815 int
816 guestfs__get_pgroup (guestfs_h *g)
817 {
818   return g->pgroup;
819 }
820
821 int
822 guestfs__set_smp (guestfs_h *g, int v)
823 {
824   if (v >= 1) {
825     g->smp = v;
826     return 0;
827   } else {
828     error (g, "invalid smp parameter: %d", v);
829     return -1;
830   }
831 }
832
833 int
834 guestfs__get_smp (guestfs_h *g)
835 {
836   return g->smp;
837 }
838
839 /* Note the private data area is allocated lazily, since the vast
840  * majority of callers will never use it.  This means g->pda is
841  * likely to be NULL.
842  */
843 struct pda_entry {
844   char *key;                    /* key */
845   void *data;                   /* opaque user data pointer */
846 };
847
848 static size_t
849 hasher (void const *x, size_t table_size)
850 {
851   struct pda_entry const *p = x;
852   return hash_pjw (p->key, table_size);
853 }
854
855 static bool
856 comparator (void const *x, void const *y)
857 {
858   struct pda_entry const *a = x;
859   struct pda_entry const *b = y;
860   return STREQ (a->key, b->key);
861 }
862
863 static void
864 freer (void *x)
865 {
866   if (x) {
867     struct pda_entry *p = x;
868     free (p->key);
869     free (p);
870   }
871 }
872
873 void
874 guestfs_set_private (guestfs_h *g, const char *key, void *data)
875 {
876   if (g->pda == NULL) {
877     g->pda = hash_initialize (16, NULL, hasher, comparator, freer);
878     if (g->pda == NULL)
879       g->abort_cb ();
880   }
881
882   struct pda_entry *new_entry = safe_malloc (g, sizeof *new_entry);
883   new_entry->key = safe_strdup (g, key);
884   new_entry->data = data;
885
886   struct pda_entry *old_entry = hash_delete (g->pda, new_entry);
887   freer (old_entry);
888
889   struct pda_entry *entry = hash_insert (g->pda, new_entry);
890   if (entry == NULL)
891     g->abort_cb ();
892   assert (entry == new_entry);
893 }
894
895 static inline char *
896 bad_cast (char const *s)
897 {
898   return (char *) s;
899 }
900
901 void *
902 guestfs_get_private (guestfs_h *g, const char *key)
903 {
904   if (g->pda == NULL)
905     return NULL;                /* no keys have been set */
906
907   const struct pda_entry k = { .key = bad_cast (key) };
908   struct pda_entry *entry = hash_lookup (g->pda, &k);
909   if (entry)
910     return entry->data;
911   else
912     return NULL;
913 }
914
915 /* Iterator. */
916 void *
917 guestfs_first_private (guestfs_h *g, const char **key_rtn)
918 {
919   if (g->pda == NULL)
920     return NULL;
921
922   g->pda_next = hash_get_first (g->pda);
923
924   /* Ignore any keys with NULL data pointers. */
925   while (g->pda_next && g->pda_next->data == NULL)
926     g->pda_next = hash_get_next (g->pda, g->pda_next);
927
928   if (g->pda_next == NULL)
929     return NULL;
930
931   *key_rtn = g->pda_next->key;
932   return g->pda_next->data;
933 }
934
935 void *
936 guestfs_next_private (guestfs_h *g, const char **key_rtn)
937 {
938   if (g->pda == NULL)
939     return NULL;
940
941   if (g->pda_next == NULL)
942     return NULL;
943
944   /* Walk to the next key with a non-NULL data pointer. */
945   do {
946     g->pda_next = hash_get_next (g->pda, g->pda_next);
947   } while (g->pda_next && g->pda_next->data == NULL);
948
949   if (g->pda_next == NULL)
950     return NULL;
951
952   *key_rtn = g->pda_next->key;
953   return g->pda_next->data;
954 }
955
956 /* When tracing, be careful how we print BufferIn parameters which
957  * usually contain large amounts of binary data (RHBZ#646822).
958  */
959 void
960 guestfs___print_BufferIn (FILE *out, const char *buf, size_t buf_size)
961 {
962   size_t i;
963   size_t orig_size = buf_size;
964
965   if (buf_size > 256)
966     buf_size = 256;
967
968   fputc ('"', out);
969
970   for (i = 0; i < buf_size; ++i) {
971     if (c_isprint (buf[i]))
972       fputc (buf[i], out);
973     else
974       fprintf (out, "\\x%02x", (unsigned char) buf[i]);
975   }
976
977   fputc ('"', out);
978
979   if (orig_size > buf_size)
980     fprintf (out,
981              _("<truncated, original size %zu bytes>"), orig_size);
982 }
983
984 void
985 guestfs___print_BufferOut (FILE *out, const char *buf, size_t buf_size)
986 {
987   guestfs___print_BufferIn (out, buf, buf_size);
988 }
989
990 void
991 guestfs___free_string_list (char **argv)
992 {
993   size_t i;
994   for (i = 0; argv[i] != NULL; ++i)
995     free (argv[i]);
996   free (argv);
997 }
998
999 void
1000 guestfs___free_drives (struct drive **drives)
1001 {
1002   struct drive *i = *drives;
1003   *drives = NULL;
1004
1005   while (i != NULL) {
1006     struct drive *next = i->next;
1007
1008     free (i->path);
1009     free (i->format);
1010     free (i->iface);
1011     free (i);
1012
1013     i = next;
1014   }
1015 }