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