pclose: Fix other places where we only tested pclose == -1.
[libguestfs.git] / src / appliance.c
1 /* libguestfs
2  * Copyright (C) 2010-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 #include <errno.h>
22 #include <dirent.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <stdarg.h>
26 #include <unistd.h>
27 #include <string.h>
28 #include <fcntl.h>
29 #include <time.h>
30 #include <sys/stat.h>
31 #include <sys/select.h>
32 #include <sys/wait.h>
33 #include <utime.h>
34
35 #ifdef HAVE_SYS_TYPES_H
36 #include <sys/types.h>
37 #endif
38
39 #include "guestfs.h"
40 #include "guestfs-internal.h"
41 #include "guestfs-internal-actions.h"
42 #include "guestfs_protocol.h"
43
44 /* Old-style appliance is going to be obsoleted. */
45 static const char *kernel_name = "vmlinuz." host_cpu;
46 static const char *initrd_name = "initramfs." host_cpu ".img";
47
48 static int find_path (guestfs_h *g, int (*pred) (guestfs_h *g, const char *pelem, void *data), void *data, char **pelem);
49 static int dir_contains_file (const char *dir, const char *file);
50 static int dir_contains_files (const char *dir, ...);
51 static int contains_ordinary_appliance (guestfs_h *g, const char *path, void *data);
52 static int contains_supermin_appliance (guestfs_h *g, const char *path, void *data);
53 static char *calculate_supermin_checksum (guestfs_h *g, const char *supermin_path);
54 static int check_for_cached_appliance (guestfs_h *g, const char *supermin_path, const char *checksum, uid_t uid, char **kernel, char **initrd, char **appliance);
55 static int build_supermin_appliance (guestfs_h *g, const char *supermin_path, const char *checksum, uid_t uid, char **kernel, char **initrd, char **appliance);
56 static int hard_link_to_cached_appliance (guestfs_h *g, const char *cachedir, char **kernel, char **initrd, char **appliance);
57 static int run_supermin_helper (guestfs_h *g, const char *supermin_path, const char *cachedir, size_t cdlen);
58 static void print_febootstrap_command_line (guestfs_h *g, const char *argv[]);
59
60 /* Locate or build the appliance.
61  *
62  * This function locates or builds the appliance as necessary,
63  * handling the supermin appliance, caching of supermin-built
64  * appliances, or using an ordinary appliance.
65  *
66  * The return value is 0 = good, -1 = error.  Returned in '*kernel'
67  * will be the name of the kernel to use, '*initrd' the name of the
68  * initrd, '*appliance' the name of the ext2 root filesystem.
69  * '*appliance' can be NULL, meaning that we are using an ordinary
70  * (non-ext2) appliance.  All three strings must be freed by the
71  * caller.  However the referenced files themselves must not be
72  * deleted.
73  *
74  * The process is as follows:
75  *
76  * (1) Look for the first element of g->path which contains a
77  * supermin appliance skeleton.  If no element has this, skip
78  * straight to step (5).
79  *
80  * (2) Calculate the checksum of this supermin appliance.
81  *
82  * (3) Check whether a cached appliance with the checksum calculated
83  * in (2) exists and passes basic security checks.  If so, return
84  * this appliance.
85  *
86  * (4) Try to build the supermin appliance.  If this is successful,
87  * return it.
88  *
89  * (5) Check each element of g->path, looking for an ordinary appliance.
90  * If one is found, return it.
91  *
92  * The supermin appliance cache directory lives in
93  * $TMPDIR/.guestfs-$UID/ and consists of four files:
94  *
95  *   $TMPDIR/.guestfs-$UID/checksum       - the checksum
96  *   $TMPDIR/.guestfs-$UID/kernel         - symlink to the kernel
97  *   $TMPDIR/.guestfs-$UID/initrd         - the febootstrap initrd
98  *   $TMPDIR/.guestfs-$UID/root           - the appliance
99  *
100  * Since multiple instances of libguestfs with the same UID may be
101  * racing to create an appliance, we need to be careful when building
102  * and using the appliance.
103  *
104  * If a cached appliance with checksum exists (step (2) above) then we
105  * make a hard link to it with our current PID, so that we have a copy
106  * even if the appliance is replaced by another process building an
107  * appliance afterwards:
108  *
109  *   $TMPDIR/.guestfs-$UID/kernel.$PID
110  *   $TMPDIR/.guestfs-$UID/initrd.$PID
111  *   $TMPDIR/.guestfs-$UID/root.$PID
112  *
113  * A lock is taken on "checksum" while we perform the link.
114  *
115  * Linked files are deleted by a garbage collection sweep which can be
116  * initiated by any libguestfs process with the same UID when the
117  * corresponding PID no longer exists.  (This is safe: the parent is
118  * always around in guestfs_launch() while qemu is starting up, and
119  * after that qemu will either have finished with the files or be
120  * holding them open, so we can unlink them).
121  *
122  * When building a new appliance (step (3)), it is built into randomly
123  * named temporary files in the $TMPDIR.  Then a lock is acquired on
124  * $TMPDIR/.guestfs-$UID/checksum (this file being created if
125  * necessary), the files are renamed into their final location, and
126  * the lock is released.
127  */
128 int
129 guestfs___build_appliance (guestfs_h *g,
130                            char **kernel, char **initrd, char **appliance)
131 {
132   int r;
133   uid_t uid = geteuid ();
134
135   /* Step (1). */
136   char *supermin_path;
137   r = find_path (g, contains_supermin_appliance, NULL, &supermin_path);
138   if (r == -1)
139     return -1;
140
141   if (r == 1) {
142     /* Step (2): calculate checksum. */
143     char *checksum = calculate_supermin_checksum (g, supermin_path);
144     if (checksum) {
145       /* Step (3): cached appliance exists? */
146       r = check_for_cached_appliance (g, supermin_path, checksum, uid,
147                                       kernel, initrd, appliance);
148       if (r != 0) {
149         free (supermin_path);
150         free (checksum);
151         return r == 1 ? 0 : -1;
152       }
153
154       /* Step (4): build supermin appliance. */
155       r = build_supermin_appliance (g, supermin_path, checksum, uid,
156                                     kernel, initrd, appliance);
157       free (supermin_path);
158       free (checksum);
159       return r;
160     }
161     free (supermin_path);
162   }
163
164   /* Step (5). */
165   char *path;
166   r = find_path (g, contains_ordinary_appliance, NULL, &path);
167   if (r == -1)
168     return -1;
169
170   if (r == 1) {
171     size_t len = strlen (path);
172     *kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
173     *initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
174     sprintf (*kernel, "%s/%s", path, kernel_name);
175     sprintf (*initrd, "%s/%s", path, initrd_name);
176     *appliance = NULL;
177
178     free (path);
179     return 0;
180   }
181
182   error (g, _("cannot find any suitable libguestfs supermin or ordinary appliance on LIBGUESTFS_PATH (search path: %s)"),
183          g->path);
184   return -1;
185 }
186
187 static int
188 contains_ordinary_appliance (guestfs_h *g, const char *path, void *data)
189 {
190   return dir_contains_files (path, kernel_name, initrd_name, NULL);
191 }
192
193 static int
194 contains_supermin_appliance (guestfs_h *g, const char *path, void *data)
195 {
196   return dir_contains_files (path, "supermin.d", NULL);
197 }
198
199 /* supermin_path is a path which is known to contain a supermin
200  * appliance.  Using febootstrap-supermin-helper -f checksum calculate
201  * the checksum so we can see if it is cached.
202  */
203 static char *
204 calculate_supermin_checksum (guestfs_h *g, const char *supermin_path)
205 {
206   size_t len = 2 * strlen (supermin_path) + 256;
207   char cmd[len];
208   int pass_u_g_args = getuid () != geteuid () || getgid () != getegid ();
209
210   if (!pass_u_g_args)
211     snprintf (cmd, len,
212               "febootstrap-supermin-helper%s "
213               "-f checksum "
214               "'%s/supermin.d' "
215               host_cpu,
216               g->verbose ? " --verbose" : "",
217               supermin_path);
218   else
219     snprintf (cmd, len,
220               "febootstrap-supermin-helper%s "
221               "-u %i "
222               "-g %i "
223               "-f checksum "
224               "'%s/supermin.d' "
225               host_cpu,
226               g->verbose ? " --verbose" : "",
227               geteuid (), getegid (),
228               supermin_path);
229
230   if (g->verbose)
231     guestfs___print_timestamped_message (g, "%s", cmd);
232
233   /* Errors here are non-fatal, so we don't need to call error(). */
234   FILE *pp = popen (cmd, "r");
235   if (pp == NULL)
236     return NULL;
237
238   char checksum[256];
239   if (fgets (checksum, sizeof checksum, pp) == NULL) {
240     pclose (pp);
241     return NULL;
242   }
243
244   if (pclose (pp) != 0) {
245     warning (g, "pclose: %m");
246     return NULL;
247   }
248
249   len = strlen (checksum);
250
251   if (len < 16) {               /* sanity check */
252     warning (g, "febootstrap-supermin-helper -f checksum returned a short string");
253     return NULL;
254   }
255
256   if (len > 0 && checksum[len-1] == '\n')
257     checksum[--len] = '\0';
258
259   return safe_strndup (g, checksum, len);
260 }
261
262 static int
263 process_exists (int pid)
264 {
265   if (kill (pid, 0) == 0)
266     return 1;
267
268   if (errno == ESRCH)
269     return 0;
270
271   return -1;
272 }
273
274 /* Garbage collect appliance hard links.  Files that match
275  * (kernel|initrd|root).$PID where the corresponding PID doesn't exist
276  * are deleted.  Note that errors in this function don't matter.
277  * There may also be other libguestfs processes racing to do the same
278  * thing here.
279  */
280 static void
281 garbage_collect_appliances (const char *cachedir)
282 {
283   DIR *dir;
284   struct dirent *d;
285   int pid;
286
287   dir = opendir (cachedir);
288   if (dir == NULL)
289     return;
290
291   while ((d = readdir (dir)) != NULL) {
292     if (sscanf (d->d_name, "kernel.%d", &pid) == 1 &&
293         process_exists (pid) == 0)
294       unlinkat (dirfd (dir), d->d_name, 0);
295     else if (sscanf (d->d_name, "initrd.%d", &pid) == 1 &&
296              process_exists (pid) == 0)
297       unlinkat (dirfd (dir), d->d_name, 0);
298     else if (sscanf (d->d_name, "root.%d", &pid) == 1 &&
299              process_exists (pid) == 0)
300       unlinkat (dirfd (dir), d->d_name, 0);
301   }
302
303   closedir (dir);
304 }
305
306 static int
307 check_for_cached_appliance (guestfs_h *g,
308                             const char *supermin_path, const char *checksum,
309                             uid_t uid,
310                             char **kernel, char **initrd, char **appliance)
311 {
312   const char *tmpdir = guestfs___persistent_tmpdir ();
313
314   /* len must be longer than the length of any pathname we can
315    * generate in this function.
316    */
317   size_t len = strlen (tmpdir) + 128;
318   char cachedir[len];
319   snprintf (cachedir, len, "%s/.guestfs-%d", tmpdir, uid);
320   char filename[len];
321   snprintf (filename, len, "%s/checksum", cachedir);
322
323   (void) mkdir (cachedir, 0755);
324
325   /* See if the cache directory exists and passes some simple checks
326    * to make sure it has not been tampered with.
327    */
328   struct stat statbuf;
329   if (lstat (cachedir, &statbuf) == -1)
330     return 0;
331   if (statbuf.st_uid != uid) {
332     error (g, _("security: cached appliance %s is not owned by UID %d"),
333            filename, uid);
334     return -1;
335   }
336   if (!S_ISDIR (statbuf.st_mode)) {
337     error (g, _("security: cached appliance %s is not a directory (mode %o)"),
338            filename, statbuf.st_mode);
339     return -1;
340   }
341   if ((statbuf.st_mode & 0022) != 0) {
342     error (g, _("security: cached appliance %s is writable by group or other (mode %o)"),
343            cachedir, statbuf.st_mode);
344     return -1;
345   }
346
347   (void) utime (cachedir, NULL);
348
349   garbage_collect_appliances (cachedir);
350
351   /* Try to open and acquire a lock on the checksum file. */
352   int fd = open (filename, O_RDONLY);
353   if (fd == -1)
354     return 0;
355 #ifdef HAVE_FUTIMENS
356   (void) futimens (fd, NULL);
357 #else
358   (void) futimes (fd, NULL);
359 #endif
360   struct flock fl;
361   fl.l_type = F_RDLCK;
362   fl.l_whence = SEEK_SET;
363   fl.l_start = 0;
364   fl.l_len = 1;
365  again:
366   if (fcntl (fd, F_SETLKW, &fl) == -1) {
367     if (errno == EINTR)
368       goto again;
369     perrorf (g, "fcntl: F_SETLKW: %s", filename);
370     close (fd);
371     return -1;
372   }
373
374   /* Read the checksum file. */
375   size_t clen = strlen (checksum);
376   char checksum_on_disk[clen];
377   ssize_t rr = read (fd, checksum_on_disk, clen);
378   if (rr == -1) {
379     perrorf (g, "read: %s", filename);
380     close (fd);
381     return -1;
382   }
383   if ((size_t) rr != clen) {
384     close (fd);
385     return 0;
386   }
387
388   if (memcmp (checksum, checksum_on_disk, clen) != 0) {
389     close (fd);
390     return 0;
391   }
392
393   /* At this point, cachedir exists, and checksum matches, and we have
394    * a read lock on the checksum file.  Make hard links to the files.
395    */
396   if (hard_link_to_cached_appliance (g, cachedir,
397                                      kernel, initrd, appliance) == -1) {
398     close (fd);
399     return -1;
400   }
401
402   /* Releases the lock on checksum. */
403   if (close (fd) == -1) {
404     perrorf (g, "close");
405     return -1;
406   }
407
408   /* Exists! */
409   return 1;
410 }
411
412 /* Build supermin appliance from supermin_path to $TMPDIR/.guestfs-$UID.
413  *
414  * Returns:
415  * 0 = built
416  * -1 = error (aborts launch)
417  */
418 static int
419 build_supermin_appliance (guestfs_h *g,
420                           const char *supermin_path, const char *checksum,
421                           uid_t uid,
422                           char **kernel, char **initrd, char **appliance)
423 {
424   if (g->verbose)
425     guestfs___print_timestamped_message (g, "begin building supermin appliance");
426
427   const char *tmpdir = guestfs___persistent_tmpdir ();
428
429   /* len must be longer than the length of any pathname we can
430    * generate in this function.
431    */
432   size_t len = strlen (tmpdir) + 128;
433
434   /* Build the appliance into a temporary directory. */
435   char tmpcd[len];
436   snprintf (tmpcd, len, "%s/guestfs.XXXXXX", tmpdir);
437
438   if (mkdtemp (tmpcd) == NULL) {
439     perrorf (g, "mkdtemp");
440     return -1;
441   }
442
443   if (g->verbose)
444     guestfs___print_timestamped_message (g, "run febootstrap-supermin-helper");
445
446   int r = run_supermin_helper (g, supermin_path, tmpcd, len);
447   if (r == -1)
448     return -1;
449
450   if (g->verbose)
451     guestfs___print_timestamped_message (g, "finished building supermin appliance");
452
453   char cachedir[len];
454   snprintf (cachedir, len, "%s/.guestfs-%d", tmpdir, uid);
455   char filename[len];
456   char filename2[len];
457   snprintf (filename, len, "%s/checksum", cachedir);
458
459   /* Open and acquire write lock on checksum file.  The file might
460    * not exist, in which case we want to create it.
461    */
462   int fd = open (filename, O_WRONLY|O_CREAT, 0755);
463   if (fd == -1) {
464     perrorf (g, "open: %s", filename);
465     return -1;
466   }
467   struct flock fl;
468   fl.l_type = F_WRLCK;
469   fl.l_whence = SEEK_SET;
470   fl.l_start = 0;
471   fl.l_len = 1;
472  again:
473   if (fcntl (fd, F_SETLKW, &fl) == -1) {
474     if (errno == EINTR)
475       goto again;
476     perrorf (g, "fcntl: F_SETLKW: %s", filename);
477     close (fd);
478     return -1;
479   }
480
481   /* At this point we have acquired a write lock on the checksum
482    * file so we go ahead and replace it with the new checksum, and
483    * rename in appliance files into this directory.
484    */
485   size_t clen = strlen (checksum);
486   if (ftruncate (fd, clen) == -1) {
487     perrorf (g, "ftruncate: %s", filename);
488     close (fd);
489     return -1;
490   }
491
492   ssize_t rr = write (fd, checksum, clen);
493   if (rr == -1) {
494     perrorf (g, "write: %s", filename);
495     close (fd);
496     return -1;
497   }
498   if ((size_t) rr != clen) {
499     error (g, "partial write: %s", filename);
500     close (fd);
501     return -1;
502   }
503
504   snprintf (filename, len, "%s/kernel", tmpcd);
505   snprintf (filename2, len, "%s/kernel", cachedir);
506   unlink (filename2);
507   if (rename (filename, filename2) == -1) {
508     perrorf (g, "rename: %s %s", filename, filename2);
509     close (fd);
510     return -1;
511   }
512
513   snprintf (filename, len, "%s/initrd", tmpcd);
514   snprintf (filename2, len, "%s/initrd", cachedir);
515   unlink (filename2);
516   if (rename (filename, filename2) == -1) {
517     perrorf (g, "rename: %s %s", filename, filename2);
518     close (fd);
519     return -1;
520   }
521
522   snprintf (filename, len, "%s/root", tmpcd);
523   snprintf (filename2, len, "%s/root", cachedir);
524   unlink (filename2);
525   if (rename (filename, filename2) == -1) {
526     perrorf (g, "rename: %s %s", filename, filename2);
527     close (fd);
528     return -1;
529   }
530
531   rmdir (tmpcd);
532
533   /* Now finish off by linking to the cached appliance and returning it. */
534   if (hard_link_to_cached_appliance (g, cachedir,
535                                      kernel, initrd, appliance) == -1) {
536     close (fd);
537     return -1;
538   }
539
540   /* Releases the lock on checksum. */
541   if (close (fd) == -1) {
542     perrorf (g, "close");
543     return -1;
544   }
545
546   return 0;
547 }
548
549 /* NB: lock on checksum file must be held when this is called. */
550 static int
551 hard_link_to_cached_appliance (guestfs_h *g,
552                                const char *cachedir,
553                                char **kernel, char **initrd, char **appliance)
554 {
555   pid_t pid = getpid ();
556   size_t len = strlen (cachedir) + 32;
557
558   *kernel = safe_malloc (g, len);
559   *initrd = safe_malloc (g, len);
560   *appliance = safe_malloc (g, len);
561   snprintf (*kernel, len, "%s/kernel.%d", cachedir, pid);
562   snprintf (*initrd, len, "%s/initrd.%d", cachedir, pid);
563   snprintf (*appliance, len, "%s/root.%d", cachedir, pid);
564
565   char filename[len];
566   snprintf (filename, len, "%s/kernel", cachedir);
567   (void) unlink (*kernel);
568   if (link (filename, *kernel) == -1) {
569     perrorf (g, "link: %s %s", filename, *kernel);
570     goto error;
571   }
572   (void) lutimes (filename, NULL); /* lutimes because it's a symlink */
573
574   snprintf (filename, len, "%s/initrd", cachedir);
575   (void) unlink (*initrd);
576   if (link (filename, *initrd) == -1) {
577     perrorf (g, "link: %s %s", filename, *initrd);
578     goto error;
579   }
580   (void) utime (filename, NULL);
581
582   snprintf (filename, len, "%s/root", cachedir);
583   (void) unlink (*appliance);
584   if (link (filename, *appliance) == -1) {
585     perrorf (g, "link: %s %s", filename, *appliance);
586     goto error;
587   }
588   (void) utime (filename, NULL);
589
590   return 0;
591
592  error:
593   free (*kernel);
594   free (*initrd);
595   free (*appliance);
596   return -1;
597 }
598
599 /* Run febootstrap-supermin-helper and tell it to generate the
600  * appliance.
601  */
602 static int
603 run_supermin_helper (guestfs_h *g, const char *supermin_path,
604                      const char *cachedir, size_t cdlen)
605 {
606   size_t pathlen = strlen (supermin_path);
607
608   const char *argv[30];
609   size_t i = 0;
610
611   char uid[32];
612   snprintf (uid, sizeof uid, "%i", geteuid ());
613   char gid[32];
614   snprintf (gid, sizeof gid, "%i", getegid ());
615   char supermin_d[pathlen + 32];
616   snprintf (supermin_d, pathlen + 32, "%s/supermin.d", supermin_path);
617   char kernel[cdlen + 32];
618   snprintf (kernel, cdlen + 32, "%s/kernel", cachedir);
619   char initrd[cdlen + 32];
620   snprintf (initrd, cdlen + 32, "%s/initrd", cachedir);
621   char root[cdlen + 32];
622   snprintf (root, cdlen + 32, "%s/root", cachedir);
623
624   int pass_u_g_args = getuid () != geteuid () || getgid () != getegid ();
625
626   argv[i++] = "febootstrap-supermin-helper";
627   if (g->verbose)
628     argv[i++] = "--verbose";
629   if (pass_u_g_args) {
630     argv[i++] = "-u";
631     argv[i++] = uid;
632     argv[i++] = "-g";
633     argv[i++] = gid;
634   }
635   argv[i++] = "-f";
636   argv[i++] = "ext2";
637   argv[i++] = supermin_d;
638   argv[i++] = host_cpu;
639   argv[i++] = kernel;
640   argv[i++] = initrd;
641   argv[i++] = root;
642   argv[i++] = NULL;
643
644   if (g->verbose)
645     print_febootstrap_command_line (g, argv);
646
647   pid_t pid = fork ();
648   if (pid == -1) {
649     perrorf (g, "fork");
650     return -1;
651   }
652
653   if (pid > 0) {                /* Parent. */
654     int status;
655     if (waitpid (pid, &status, 0) == -1) {
656       perrorf (g, "waitpid");
657       return -1;
658     }
659     if (!WIFEXITED (status) || WEXITSTATUS (status) != 0) {
660       error (g, _("external command failed, see earlier error messages"));
661       return -1;
662     }
663     return 0;
664   }
665
666   /* Child. */
667
668   /* Set a sensible umask in the subprocess, so kernel and initrd
669    * output files are world-readable (RHBZ#610880).
670    */
671   umask (0022);
672
673   execvp ("febootstrap-supermin-helper", (char * const *) argv);
674   perror ("execvp");
675   _exit (EXIT_FAILURE);
676 }
677
678 static void
679 print_febootstrap_command_line (guestfs_h *g, const char *argv[])
680 {
681   int i;
682   int needs_quote;
683   char *buf;
684   size_t len;
685
686   /* Calculate length of the buffer needed.  This is an overestimate. */
687   len = 0;
688   for (i = 0; argv[i] != NULL; ++i)
689     len += strlen (argv[i]) + 32;
690
691   buf = malloc (len);
692   if (buf == NULL) {
693     warning (g, "malloc: %m");
694     return;
695   }
696
697   len = 0;
698   for (i = 0; argv[i] != NULL; ++i) {
699     if (i > 0) {
700       strcpy (&buf[len], " ");
701       len++;
702     }
703
704     /* Does it need shell quoting?  This only deals with simple cases. */
705     needs_quote = strcspn (argv[i], " ") != strlen (argv[i]);
706
707     if (needs_quote) {
708       strcpy (&buf[len], "'");
709       len++;
710     }
711
712     strcpy (&buf[len], argv[i]);
713     len += strlen (argv[i]);
714
715     if (needs_quote) {
716       strcpy (&buf[len], "'");
717       len++;
718     }
719   }
720
721   guestfs___print_timestamped_message (g, "%s", buf);
722
723   free (buf);
724 }
725
726 /* Search elements of g->path, returning the first path element which
727  * matches the predicate function 'pred'.
728  *
729  * Function 'pred' must return a true or false value.  If it returns
730  * -1 then the entire search is aborted.
731  *
732  * Return values:
733  * 1 = a path element matched, it is returned in *pelem_ret and must be
734  *     freed by the caller,
735  * 0 = no path element matched, *pelem_ret is set to NULL, or
736  * -1 = error which aborts the launch process
737  */
738 static int
739 find_path (guestfs_h *g,
740            int (*pred) (guestfs_h *g, const char *pelem, void *data),
741            void *data,
742            char **pelem_ret)
743 {
744   size_t len;
745   int r;
746   const char *pelem = g->path;
747
748   /* Note that if g->path is an empty string, we want to check the
749    * current directory (for backwards compatibility with
750    * libguestfs < 1.5.4).
751    */
752   do {
753     len = strcspn (pelem, ":");
754
755     /* Empty element or "." means current directory. */
756     if (len == 0)
757       *pelem_ret = safe_strdup (g, ".");
758     else
759       *pelem_ret = safe_strndup (g, pelem, len);
760
761     r = pred (g, *pelem_ret, data);
762     if (r == -1) {
763       free (*pelem_ret);
764       return -1;
765     }
766
767     if (r != 0)                 /* predicate matched */
768       return 1;
769
770     free (*pelem_ret);
771
772     if (pelem[len] == ':')
773       pelem += len + 1;
774     else
775       pelem += len;
776   } while (*pelem);
777
778   /* Predicate didn't match on any path element. */
779   *pelem_ret = NULL;
780   return 0;
781 }
782
783 /* Returns true iff file is contained in dir. */
784 static int
785 dir_contains_file (const char *dir, const char *file)
786 {
787   size_t dirlen = strlen (dir);
788   size_t filelen = strlen (file);
789   size_t len = dirlen + filelen + 2;
790   char path[len];
791
792   snprintf (path, len, "%s/%s", dir, file);
793   return access (path, F_OK) == 0;
794 }
795
796 /* Returns true iff every listed file is contained in 'dir'. */
797 static int
798 dir_contains_files (const char *dir, ...)
799 {
800   va_list args;
801   const char *file;
802
803   va_start (args, dir);
804   while ((file = va_arg (args, const char *)) != NULL) {
805     if (!dir_contains_file (dir, file)) {
806       va_end (args);
807       return 0;
808     }
809   }
810   va_end (args);
811   return 1;
812 }