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