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