a8b53e730f781e5990d4a272472272ae381a9dec
[libguestfs.git] / daemon / guestfsd.c
1 /* libguestfs - the guestfsd daemon
2  * Copyright (C) 2009-2010 Red Hat Inc.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program 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
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17  */
18
19 #include <config.h>
20
21 #define _BSD_SOURCE             /* for daemon(3) */
22
23 #ifdef HAVE_WINDOWS_H
24 # include <windows.h>
25 #endif
26
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <unistd.h>
31 #include <rpc/types.h>
32 #include <rpc/xdr.h>
33 #include <getopt.h>
34 #include <sys/param.h>
35 #include <sys/types.h>
36 #include <sys/stat.h>
37 #include <fcntl.h>
38 #include <signal.h>
39 #include <netdb.h>
40 #include <sys/select.h>
41 #include <sys/wait.h>
42 #include <arpa/inet.h>
43 #include <netinet/in.h>
44 #include <errno.h>
45
46 #ifdef HAVE_PRINTF_H
47 # include <printf.h>
48 #endif
49
50 #include "sockets.h"
51 #include "c-ctype.h"
52 #include "ignore-value.h"
53 #include "error.h"
54
55 #include "daemon.h"
56
57 static char *read_cmdline (void);
58
59 #ifndef MAX
60 # define MAX(a,b) ((a)>(b)?(a):(b))
61 #endif
62
63 /* Not the end of the world if this open flag is not defined. */
64 #ifndef O_CLOEXEC
65 # define O_CLOEXEC 0
66 #endif
67
68 /* If root device is an ext2 filesystem, this is the major and minor.
69  * This is so we can ignore this device from the point of view of the
70  * user, eg. in guestfs_list_devices and many other places.
71  */
72 static dev_t root_device = 0;
73
74 int verbose = 0;
75
76 static int print_shell_quote (FILE *stream, const struct printf_info *info, const void *const *args);
77 static int print_sysroot_shell_quote (FILE *stream, const struct printf_info *info, const void *const *args);
78 #ifdef HAVE_REGISTER_PRINTF_SPECIFIER
79 static int print_arginfo (const struct printf_info *info, size_t n, int *argtypes, int *size);
80 #else
81 #ifdef HAVE_REGISTER_PRINTF_FUNCTION
82 static int print_arginfo (const struct printf_info *info, size_t n, int *argtypes);
83 #else
84 #error "HAVE_REGISTER_PRINTF_{SPECIFIER|FUNCTION} not defined"
85 #endif
86 #endif
87
88 #ifdef WIN32
89 static int
90 daemon (int nochdir, int noclose)
91 {
92   fprintf (stderr,
93            "On Windows the daemon does not support forking into the "
94            "background.\nYou *must* run the daemon with the -f option.\n");
95   exit (EXIT_FAILURE);
96 }
97 #endif /* WIN32 */
98
99 #ifdef WIN32
100 static int
101 winsock_init (void)
102 {
103   int r;
104
105   /* http://msdn2.microsoft.com/en-us/library/ms742213.aspx */
106   r = gl_sockets_startup (SOCKETS_2_2);
107   return r == 0 ? 0 : -1;
108 }
109 #else /* !WIN32 */
110 static int
111 winsock_init (void)
112 {
113   return 0;
114 }
115 #endif /* !WIN32 */
116
117 /* Location to mount root device. */
118 const char *sysroot = "/sysroot"; /* No trailing slash. */
119 int sysroot_len = 8;
120
121 /* Not used explicitly, but required by the gnulib 'error' module. */
122 const char *program_name = "guestfsd";
123
124 static void
125 usage (void)
126 {
127   fprintf (stderr,
128     "guestfsd [-f|--foreground] [-v|--verbose]\n");
129 }
130
131 int
132 main (int argc, char *argv[])
133 {
134   static const char *options = "fv?";
135   static const struct option long_options[] = {
136     { "foreground", 0, 0, 'f' },
137     { "help", 0, 0, '?' },
138     { "verbose", 0, 0, 'v' },
139     { 0, 0, 0, 0 }
140   };
141   int c;
142   int dont_fork = 0;
143   char *cmdline;
144
145   chdir ("/");
146
147   if (winsock_init () == -1)
148     error (EXIT_FAILURE, 0, "winsock initialization failed");
149
150 #ifdef HAVE_REGISTER_PRINTF_SPECIFIER
151   /* http://udrepper.livejournal.com/20948.html */
152   register_printf_specifier ('Q', print_shell_quote, print_arginfo);
153   register_printf_specifier ('R', print_sysroot_shell_quote, print_arginfo);
154 #else
155 #ifdef HAVE_REGISTER_PRINTF_FUNCTION
156   register_printf_function ('Q', print_shell_quote, print_arginfo);
157   register_printf_function ('R', print_sysroot_shell_quote, print_arginfo);
158 #else
159 #error "HAVE_REGISTER_PRINTF_{SPECIFIER|FUNCTION} not defined"
160 #endif
161 #endif
162
163   struct stat statbuf;
164   if (stat ("/", &statbuf) == 0)
165     root_device = statbuf.st_dev;
166
167   for (;;) {
168     c = getopt_long (argc, argv, options, long_options, NULL);
169     if (c == -1) break;
170
171     switch (c) {
172     case 'f':
173       dont_fork = 1;
174       break;
175
176     case 'v':
177       verbose = 1;
178       break;
179
180     case '?':
181       usage ();
182       exit (EXIT_SUCCESS);
183
184     default:
185       fprintf (stderr, "guestfsd: unexpected command line option 0x%x\n", c);
186       exit (EXIT_FAILURE);
187     }
188   }
189
190   if (optind < argc) {
191     usage ();
192     exit (EXIT_FAILURE);
193   }
194
195   cmdline = read_cmdline ();
196
197   /* Set the verbose flag. */
198   verbose = verbose ||
199     (cmdline && strstr (cmdline, "guestfs_verbose=1") != NULL);
200   if (verbose)
201     printf ("verbose daemon enabled\n");
202
203   if (verbose) {
204     if (cmdline)
205       printf ("linux commmand line: %s\n", cmdline);
206     else
207       printf ("could not read linux command line\n");
208   }
209
210 #ifndef WIN32
211   /* Make sure SIGPIPE doesn't kill us. */
212   struct sigaction sa;
213   memset (&sa, 0, sizeof sa);
214   sa.sa_handler = SIG_IGN;
215   sa.sa_flags = 0;
216   if (sigaction (SIGPIPE, &sa, NULL) == -1)
217     perror ("sigaction SIGPIPE"); /* but try to continue anyway ... */
218 #endif
219
220 #ifdef WIN32
221 # define setenv(n,v,f) _putenv(n "=" v)
222 #endif
223   /* Set up a basic environment.  After we are called by /init the
224    * environment is essentially empty.
225    * https://bugzilla.redhat.com/show_bug.cgi?id=502074#c5
226    *
227    * NOTE: if you change $PATH, you must also change 'prog_exists'
228    * function below.
229    */
230   setenv ("PATH", "/sbin:/usr/sbin:/bin:/usr/bin", 1);
231   setenv ("SHELL", "/bin/sh", 1);
232   setenv ("LC_ALL", "C", 1);
233   setenv ("TERM", "dumb", 1);
234
235 #ifndef WIN32
236   /* We document that umask defaults to 022 (it should be this anyway). */
237   umask (022);
238 #else
239   /* This is the default for Windows anyway.  It's not even clear if
240    * Windows ever uses this -- the MSDN documentation for the function
241    * contains obvious errors.
242    */
243   _umask (0);
244 #endif
245
246   /* Connect to virtio-serial channel. */
247   int sock = open ("/dev/virtio-ports/org.libguestfs.channel.0",
248                    O_RDWR | O_CLOEXEC);
249   if (sock == -1) {
250     fprintf (stderr,
251              "\n"
252              "Failed to connect to virtio-serial channel.\n"
253              "\n"
254              "This is a fatal error and the appliance will now exit.\n"
255              "\n"
256              "Usually this error is caused by either QEMU or the appliance\n"
257              "kernel not supporting the vmchannel method that the\n"
258              "libguestfs library chose to use.  Please run\n"
259              "'libguestfs-test-tool' and provide the complete, unedited\n"
260              "output to the libguestfs developers, either in a bug report\n"
261              "or on the libguestfs redhat com mailing list.\n"
262              "\n");
263     perror ("/dev/virtio-ports/org.libguestfs.channel.0");
264     exit (EXIT_FAILURE);
265   }
266
267   /* Send the magic length message which indicates that
268    * userspace is up inside the guest.
269    */
270   char lenbuf[4];
271   XDR xdr;
272   uint32_t len = GUESTFS_LAUNCH_FLAG;
273   xdrmem_create (&xdr, lenbuf, sizeof lenbuf, XDR_ENCODE);
274   xdr_u_int (&xdr, &len);
275
276   if (xwrite (sock, lenbuf, sizeof lenbuf) == -1) {
277     perror ("xwrite");
278     exit (EXIT_FAILURE);
279   }
280
281   xdr_destroy (&xdr);
282
283   /* Fork into the background. */
284   if (!dont_fork) {
285     if (daemon (0, 1) == -1) {
286       perror ("daemon");
287       exit (EXIT_FAILURE);
288     }
289   }
290
291   /* Enter the main loop, reading and performing actions. */
292   main_loop (sock);
293
294   exit (EXIT_SUCCESS);
295 }
296
297 /* Read /proc/cmdline. */
298 static char *
299 read_cmdline (void)
300 {
301   int fd = open ("/proc/cmdline", O_RDONLY);
302   if (fd == -1) {
303     perror ("/proc/cmdline");
304     return NULL;
305   }
306
307   size_t len = 0;
308   ssize_t n;
309   char buf[256];
310   char *r = NULL;
311
312   for (;;) {
313     n = read (fd, buf, sizeof buf);
314     if (n == -1) {
315       perror ("read");
316       free (r);
317       close (fd);
318       return NULL;
319     }
320     if (n == 0)
321       break;
322     char *newr = realloc (r, len + n + 1); /* + 1 is for terminating NUL */
323     if (newr == NULL) {
324       perror ("realloc");
325       free (r);
326       close (fd);
327       return NULL;
328     }
329     r = newr;
330     memcpy (&r[len], buf, n);
331     len += n;
332   }
333
334   if (r)
335     r[len] = '\0';
336
337   if (close (fd) == -1) {
338     perror ("close");
339     free (r);
340     return NULL;
341   }
342
343   return r;
344 }
345
346 /* Return true iff device is the root device (and therefore should be
347  * ignored from the point of view of user calls).
348  */
349 int
350 is_root_device (const char *device)
351 {
352   struct stat statbuf;
353   if (stat (device, &statbuf) == -1) {
354     perror (device);
355     return 0;
356   }
357   if (statbuf.st_rdev == root_device)
358     return 1;
359   return 0;
360 }
361
362 /* Turn "/path" into "/sysroot/path".
363  *
364  * Caller must check for NULL and call reply_with_perror ("malloc")
365  * if it is.  Caller must also free the string.
366  *
367  * See also the custom %R printf formatter which does shell quoting too.
368  */
369 char *
370 sysroot_path (const char *path)
371 {
372   char *r;
373   int len = strlen (path) + sysroot_len + 1;
374
375   r = malloc (len);
376   if (r == NULL)
377     return NULL;
378
379   snprintf (r, len, "%s%s", sysroot, path);
380   return r;
381 }
382
383 int
384 xwrite (int sock, const void *v_buf, size_t len)
385 {
386   int r;
387   const char *buf = v_buf;
388
389   while (len > 0) {
390     r = write (sock, buf, len);
391     if (r == -1) {
392       perror ("write");
393       return -1;
394     }
395     buf += r;
396     len -= r;
397   }
398
399   return 0;
400 }
401
402 int
403 xread (int sock, void *v_buf, size_t len)
404 {
405   int r;
406   char *buf = v_buf;
407
408   while (len > 0) {
409     r = read (sock, buf, len);
410     if (r == -1) {
411       perror ("read");
412       return -1;
413     }
414     if (r == 0) {
415       fprintf (stderr, "read: unexpected end of file on fd %d\n", sock);
416       return -1;
417     }
418     buf += r;
419     len -= r;
420   }
421
422   return 0;
423 }
424
425 int
426 add_string (char ***argv, int *size, int *alloc, const char *str)
427 {
428   char **new_argv;
429   char *new_str;
430
431   if (*size >= *alloc) {
432     *alloc += 64;
433     new_argv = realloc (*argv, *alloc * sizeof (char *));
434     if (new_argv == NULL) {
435       reply_with_perror ("realloc");
436       free_strings (*argv);
437       return -1;
438     }
439     *argv = new_argv;
440   }
441
442   if (str) {
443     new_str = strdup (str);
444     if (new_str == NULL) {
445       reply_with_perror ("strdup");
446       free_strings (*argv);
447     }
448   } else
449     new_str = NULL;
450
451   (*argv)[*size] = new_str;
452
453   (*size)++;
454   return 0;
455 }
456
457 size_t
458 count_strings (char *const *argv)
459 {
460   size_t argc;
461
462   for (argc = 0; argv[argc] != NULL; ++argc)
463     ;
464   return argc;
465 }
466
467 /* http://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2 */
468 int
469 is_power_of_2 (unsigned long v)
470 {
471   return v && ((v & (v - 1)) == 0);
472 }
473
474 static int
475 compare (const void *vp1, const void *vp2)
476 {
477   char * const *p1 = (char * const *) vp1;
478   char * const *p2 = (char * const *) vp2;
479   return strcmp (*p1, *p2);
480 }
481
482 void
483 sort_strings (char **argv, int len)
484 {
485   qsort (argv, len, sizeof (char *), compare);
486 }
487
488 void
489 free_strings (char **argv)
490 {
491   int argc;
492
493   for (argc = 0; argv[argc] != NULL; ++argc)
494     free (argv[argc]);
495   free (argv);
496 }
497
498 void
499 free_stringslen (char **argv, int len)
500 {
501   int i;
502
503   for (i = 0; i < len; ++i)
504     free (argv[i]);
505   free (argv);
506 }
507
508 /* Easy ways to run external commands.  For full documentation, see
509  * 'commandrvf' below.
510  */
511 int
512 commandf (char **stdoutput, char **stderror, int flags, const char *name, ...)
513 {
514   va_list args;
515   const char **argv;
516   char *s;
517   int i, r;
518
519   /* Collect the command line arguments into an array. */
520   i = 2;
521   argv = malloc (sizeof (char *) * i);
522   if (argv == NULL) {
523     perror ("malloc");
524     return -1;
525   }
526   argv[0] = (char *) name;
527   argv[1] = NULL;
528
529   va_start (args, name);
530
531   while ((s = va_arg (args, char *)) != NULL) {
532     const char **p = realloc (argv, sizeof (char *) * (++i));
533     if (p == NULL) {
534       perror ("realloc");
535       free (argv);
536       va_end (args);
537       return -1;
538     }
539     argv = p;
540     argv[i-2] = s;
541     argv[i-1] = NULL;
542   }
543
544   va_end (args);
545
546   r = commandvf (stdoutput, stderror, flags, (const char * const*) argv);
547
548   /* NB: Mustn't free the strings which are on the stack. */
549   free (argv);
550
551   return r;
552 }
553
554 /* Same as 'command', but we allow the status code from the
555  * subcommand to be non-zero, and return that status code.
556  * We still return -1 if there was some other error.
557  */
558 int
559 commandrf (char **stdoutput, char **stderror, int flags, const char *name, ...)
560 {
561   va_list args;
562   const char **argv;
563   char *s;
564   int i, r;
565
566   /* Collect the command line arguments into an array. */
567   i = 2;
568   argv = malloc (sizeof (char *) * i);
569   if (argv == NULL) {
570     perror ("malloc");
571     return -1;
572   }
573   argv[0] = (char *) name;
574   argv[1] = NULL;
575
576   va_start (args, name);
577
578   while ((s = va_arg (args, char *)) != NULL) {
579     const char **p = realloc (argv, sizeof (char *) * (++i));
580     if (p == NULL) {
581       perror ("realloc");
582       free (argv);
583       va_end (args);
584       return -1;
585     }
586     argv = p;
587     argv[i-2] = s;
588     argv[i-1] = NULL;
589   }
590
591   va_end (args);
592
593   r = commandrvf (stdoutput, stderror, flags, argv);
594
595   /* NB: Mustn't free the strings which are on the stack. */
596   free (argv);
597
598   return r;
599 }
600
601 /* Same as 'command', but passing an argv. */
602 int
603 commandvf (char **stdoutput, char **stderror, int flags,
604            char const *const *argv)
605 {
606   int r;
607
608   r = commandrvf (stdoutput, stderror, flags, (void *) argv);
609   if (r == 0)
610     return 0;
611   else
612     return -1;
613 }
614
615 /* This is a more sane version of 'system(3)' for running external
616  * commands.  It uses fork/execvp, so we don't need to worry about
617  * quoting of parameters, and it allows us to capture any error
618  * messages in a buffer.
619  *
620  * If stdoutput is not NULL, then *stdoutput will return the stdout
621  * of the command.
622  *
623  * If stderror is not NULL, then *stderror will return the stderr
624  * of the command.  If there is a final \n character, it is removed
625  * so you can use the error string directly in a call to
626  * reply_with_error.
627  *
628  * Flags:
629  *
630  * COMMAND_FLAG_FOLD_STDOUT_ON_STDERR: For broken external commands
631  * that send error messages to stdout (hello, parted) but that don't
632  * have any useful stdout information, use this flag to capture the
633  * error messages in the *stderror buffer.  If using this flag,
634  * you should pass stdoutput as NULL because nothing could ever be
635  * captured in that buffer.
636  *
637  * COMMAND_FLAG_CHROOT_COPY_FILE_TO_STDIN: For running external
638  * commands on chrooted files correctly (see RHBZ#579608) specifying
639  * this flag causes another process to be forked which chroots into
640  * sysroot and just copies the input file to stdin of the specified
641  * command.  The file descriptor is ORed with the flags, and that file
642  * descriptor is always closed by this function.  See hexdump.c for an
643  * example of usage.
644  */
645 int
646 commandrvf (char **stdoutput, char **stderror, int flags,
647             char const* const *argv)
648 {
649   int so_size = 0, se_size = 0;
650   int so_fd[2], se_fd[2];
651   int flag_copy_stdin = flags & COMMAND_FLAG_CHROOT_COPY_FILE_TO_STDIN;
652   int stdin_fd[2] = { -1, -1 };
653   pid_t pid, stdin_pid = -1;
654   int r, quit, i;
655   fd_set rset, rset2;
656   char buf[256];
657   char *p;
658
659   if (stdoutput) *stdoutput = NULL;
660   if (stderror) *stderror = NULL;
661
662   if (verbose) {
663     printf ("%s", argv[0]);
664     for (i = 1; argv[i] != NULL; ++i)
665       printf (" %s", argv[i]);
666     printf ("\n");
667   }
668
669   /* Note: abort is used in a few places along the error paths early
670    * in this function.  This is because (a) cleaning up correctly is
671    * very complex at these places and (b) abort is used when a
672    * resource problems is indicated which would be due to much more
673    * serious issues - eg. memory or file descriptor leaks.  We
674    * wouldn't expect fork(2) or pipe(2) to fail in normal
675    * circumstances.
676    */
677
678   if (pipe (so_fd) == -1 || pipe (se_fd) == -1) {
679     error (0, errno, "pipe");
680     abort ();
681   }
682
683   if (flag_copy_stdin) {
684     if (pipe (stdin_fd) == -1) {
685       error (0, errno, "pipe");
686       abort ();
687     }
688   }
689
690   pid = fork ();
691   if (pid == -1) {
692     error (0, errno, "fork");
693     abort ();
694   }
695
696   if (pid == 0) {               /* Child process running the command. */
697     close (0);
698     if (flag_copy_stdin) {
699       dup2 (stdin_fd[0], 0);
700       close (stdin_fd[0]);
701       close (stdin_fd[1]);
702     } else {
703       /* Set stdin to /dev/null (ignore failure) */
704       open ("/dev/null", O_RDONLY);
705     }
706     close (so_fd[0]);
707     close (se_fd[0]);
708     if (!(flags & COMMAND_FLAG_FOLD_STDOUT_ON_STDERR))
709       dup2 (so_fd[1], 1);
710     else
711       dup2 (se_fd[1], 1);
712     dup2 (se_fd[1], 2);
713     close (so_fd[1]);
714     close (se_fd[1]);
715
716     execvp (argv[0], (void *) argv);
717     perror (argv[0]);
718     _exit (EXIT_FAILURE);
719   }
720
721   if (flag_copy_stdin) {
722     int fd = flags & COMMAND_FLAG_FD_MASK;
723
724     stdin_pid = fork ();
725     if (stdin_pid == -1) {
726       error (0, errno, "fork");
727       abort ();
728     }
729
730     if (stdin_pid == 0) {       /* Child process copying stdin. */
731       close (so_fd[0]);
732       close (so_fd[1]);
733       close (se_fd[0]);
734       close (se_fd[1]);
735
736       close (1);
737       dup2 (stdin_fd[1], 1);
738       close (stdin_fd[0]);
739       close (stdin_fd[1]);
740
741       if (chroot (sysroot) == -1) {
742         perror ("chroot");
743         _exit (EXIT_FAILURE);
744       }
745
746       ssize_t n;
747       char buffer[BUFSIZ];
748       while ((n = read (fd, buffer, sizeof buffer)) > 0) {
749         if (xwrite (1, buffer, n) == -1)
750           /* EPIPE error indicates the command process has exited
751            * early.  If the command process fails that will be caught
752            * by the daemon, and if not, then it's not an error.
753            */
754           _exit (errno == EPIPE ? EXIT_SUCCESS : EXIT_FAILURE);
755       }
756
757       if (n == -1) {
758         perror ("read");
759         _exit (EXIT_FAILURE);
760       }
761
762       if (close (fd) == -1) {
763         perror ("close");
764         _exit (EXIT_FAILURE);
765       }
766
767       _exit (EXIT_SUCCESS);
768     }
769
770     close (fd);
771     close (stdin_fd[0]);
772     close (stdin_fd[1]);
773   }
774
775   /* Parent process. */
776   close (so_fd[1]);
777   close (se_fd[1]);
778
779   FD_ZERO (&rset);
780   FD_SET (so_fd[0], &rset);
781   FD_SET (se_fd[0], &rset);
782
783   quit = 0;
784   while (quit < 2) {
785     rset2 = rset;
786     r = select (MAX (so_fd[0], se_fd[0]) + 1, &rset2, NULL, NULL, NULL);
787     if (r == -1) {
788       perror ("select");
789     quit:
790       if (stdoutput) free (*stdoutput);
791       if (stderror) free (*stderror);
792       close (so_fd[0]);
793       close (se_fd[0]);
794       waitpid (pid, NULL, 0);
795       if (stdin_pid >= 0) waitpid (stdin_pid, NULL, 0);
796       return -1;
797     }
798
799     if (FD_ISSET (so_fd[0], &rset2)) { /* something on stdout */
800       r = read (so_fd[0], buf, sizeof buf);
801       if (r == -1) {
802         perror ("read");
803         goto quit;
804       }
805       if (r == 0) { FD_CLR (so_fd[0], &rset); quit++; }
806
807       if (r > 0 && stdoutput) {
808         so_size += r;
809         p = realloc (*stdoutput, so_size);
810         if (p == NULL) {
811           perror ("realloc");
812           goto quit;
813         }
814         *stdoutput = p;
815         memcpy (*stdoutput + so_size - r, buf, r);
816       }
817     }
818
819     if (FD_ISSET (se_fd[0], &rset2)) { /* something on stderr */
820       r = read (se_fd[0], buf, sizeof buf);
821       if (r == -1) {
822         perror ("read");
823         goto quit;
824       }
825       if (r == 0) { FD_CLR (se_fd[0], &rset); quit++; }
826
827       if (r > 0) {
828         if (verbose)
829           ignore_value (write (2, buf, r));
830
831         if (stderror) {
832           se_size += r;
833           p = realloc (*stderror, se_size);
834           if (p == NULL) {
835             perror ("realloc");
836             goto quit;
837           }
838           *stderror = p;
839           memcpy (*stderror + se_size - r, buf, r);
840         }
841       }
842     }
843   }
844
845   close (so_fd[0]);
846   close (se_fd[0]);
847
848   /* Make sure the output buffers are \0-terminated.  Also remove any
849    * trailing \n characters from the error buffer (not from stdout).
850    */
851   if (stdoutput) {
852     void *q = realloc (*stdoutput, so_size+1);
853     if (q == NULL) {
854       perror ("realloc");
855       free (*stdoutput);
856     }
857     *stdoutput = q;
858     if (*stdoutput)
859       (*stdoutput)[so_size] = '\0';
860   }
861   if (stderror) {
862     void *q = realloc (*stderror, se_size+1);
863     if (q == NULL) {
864       perror ("realloc");
865       free (*stderror);
866     }
867     *stderror = q;
868     if (*stderror) {
869       (*stderror)[se_size] = '\0';
870       se_size--;
871       while (se_size >= 0 && (*stderror)[se_size] == '\n')
872         (*stderror)[se_size--] = '\0';
873     }
874   }
875
876   if (flag_copy_stdin) {
877     /* Check copy process didn't fail. */
878     if (waitpid (stdin_pid, &r, 0) != stdin_pid) {
879       perror ("waitpid");
880       kill (pid, 9);
881       waitpid (pid, NULL, 0);
882       return -1;
883     }
884
885     if (!WIFEXITED (r) || WEXITSTATUS (r) != 0) {
886       fprintf (stderr, "failed copying from input file, see earlier messages\n");
887       kill (pid, 9);
888       waitpid (pid, NULL, 0);
889       return -1;
890     }
891   }
892
893   /* Get the exit status of the command. */
894   if (waitpid (pid, &r, 0) != pid) {
895     perror ("waitpid");
896     return -1;
897   }
898
899   if (WIFEXITED (r)) {
900     return WEXITSTATUS (r);
901   } else
902     return -1;
903 }
904
905 /* Split an output string into a NULL-terminated list of lines.
906  * Typically this is used where we have run an external command
907  * which has printed out a list of things, and we want to return
908  * an actual list.
909  *
910  * The corner cases here are quite tricky.  Note in particular:
911  *
912  *   "" -> []
913  *   "\n" -> [""]
914  *   "a\nb" -> ["a"; "b"]
915  *   "a\nb\n" -> ["a"; "b"]
916  *   "a\nb\n\n" -> ["a"; "b"; ""]
917  *
918  * The original string is written over and destroyed by this
919  * function (which is usually OK because it's the 'out' string
920  * from command()).  You can free the original string, because
921  * add_string() strdups the strings.
922  */
923 char **
924 split_lines (char *str)
925 {
926   char **lines = NULL;
927   int size = 0, alloc = 0;
928   char *p, *pend;
929
930   if (STREQ (str, ""))
931     goto empty_list;
932
933   p = str;
934   while (p) {
935     /* Empty last line? */
936     if (p[0] == '\0')
937       break;
938
939     pend = strchr (p, '\n');
940     if (pend) {
941       *pend = '\0';
942       pend++;
943     }
944
945     if (add_string (&lines, &size, &alloc, p) == -1) {
946       return NULL;
947     }
948
949     p = pend;
950   }
951
952  empty_list:
953   if (add_string (&lines, &size, &alloc, NULL) == -1)
954     return NULL;
955
956   return lines;
957 }
958
959 /* Skip leading and trailing whitespace, updating the original string
960  * in-place.
961  */
962 void
963 trim (char *str)
964 {
965   size_t len = strlen (str);
966
967   while (len > 0 && c_isspace (str[len-1])) {
968     str[len-1] = '\0';
969     len--;
970   }
971
972   const char *p = str;
973   while (*p && c_isspace (*p)) {
974     p++;
975     len--;
976   }
977
978   memmove (str, p, len+1);
979 }
980
981 /* printf helper function so we can use %Q ("quoted") and %R to print
982  * shell-quoted strings.  See guestfs(3)/EXTENDING LIBGUESTFS for more
983  * details.
984  */
985 static int
986 print_shell_quote (FILE *stream,
987                    const struct printf_info *info ATTRIBUTE_UNUSED,
988                    const void *const *args)
989 {
990 #define SAFE(c) (c_isalnum((c)) ||                                      \
991                  (c) == '/' || (c) == '-' || (c) == '_' || (c) == '.')
992   int i, len;
993   const char *str = *((const char **) (args[0]));
994
995   for (i = len = 0; str[i]; ++i) {
996     if (!SAFE(str[i])) {
997       putc ('\\', stream);
998       len ++;
999     }
1000     putc (str[i], stream);
1001     len ++;
1002   }
1003
1004   return len;
1005 }
1006
1007 static int
1008 print_sysroot_shell_quote (FILE *stream,
1009                            const struct printf_info *info,
1010                            const void *const *args)
1011 {
1012   fputs (sysroot, stream);
1013   return sysroot_len + print_shell_quote (stream, info, args);
1014 }
1015
1016 #ifdef HAVE_REGISTER_PRINTF_SPECIFIER
1017 static int
1018 print_arginfo (const struct printf_info *info ATTRIBUTE_UNUSED,
1019                size_t n, int *argtypes, int *size)
1020 {
1021   if (n > 0) {
1022     argtypes[0] = PA_STRING;
1023     size[0] = sizeof (const char *);
1024   }
1025   return 1;
1026 }
1027 #else
1028 #ifdef HAVE_REGISTER_PRINTF_FUNCTION
1029 static int
1030 print_arginfo (const struct printf_info *info, size_t n, int *argtypes)
1031 {
1032   if (n > 0)
1033     argtypes[0] = PA_STRING;
1034   return 1;
1035 }
1036 #else
1037 #error "HAVE_REGISTER_PRINTF_{SPECIFIER|FUNCTION} not defined"
1038 #endif
1039 #endif
1040
1041 /* Perform device name translation.  Don't call this directly -
1042  * use the RESOLVE_DEVICE macro.
1043  *
1044  * See guestfs(3) for the algorithm.
1045  *
1046  * We have to open the device and test for ENXIO, because
1047  * the device nodes themselves will exist in the appliance.
1048  */
1049 int
1050 device_name_translation (char *device)
1051 {
1052   int fd;
1053
1054   fd = open (device, O_RDONLY);
1055   if (fd >= 0) {
1056   close_ok:
1057     close (fd);
1058     return 0;
1059   }
1060
1061   if (errno != ENXIO && errno != ENOENT)
1062     return -1;
1063
1064   /* If the name begins with "/dev/sd" then try the alternatives. */
1065   if (STRNEQLEN (device, "/dev/sd", 7))
1066     return -1;
1067
1068   device[5] = 'h';              /* /dev/hd (old IDE driver) */
1069   fd = open (device, O_RDONLY);
1070   if (fd >= 0)
1071     goto close_ok;
1072
1073   device[5] = 'v';              /* /dev/vd (for virtio devices) */
1074   fd = open (device, O_RDONLY);
1075   if (fd >= 0)
1076     goto close_ok;
1077
1078   device[5] = 's';              /* Restore original device name. */
1079   return -1;
1080 }
1081
1082 /* Check program exists and is executable on $PATH.  Actually, we
1083  * just assume PATH contains the default entries (see main() above).
1084  */
1085 int
1086 prog_exists (const char *prog)
1087 {
1088   static const char * const dirs[] =
1089     { "/sbin", "/usr/sbin", "/bin", "/usr/bin" };
1090   size_t i;
1091   char buf[1024];
1092
1093   for (i = 0; i < sizeof dirs / sizeof dirs[0]; ++i) {
1094     snprintf (buf, sizeof buf, "%s/%s", dirs[i], prog);
1095     if (access (buf, X_OK) == 0)
1096       return 1;
1097   }
1098   return 0;
1099 }
1100
1101 /* LVM and other commands aren't synchronous, especially when udev is
1102  * involved.  eg. You can create or remove some device, but the /dev
1103  * device node won't appear until some time later.  This means that
1104  * you get an error if you run one command followed by another.
1105  *
1106  * Use 'udevadm settle' after certain commands, but don't be too
1107  * fussed if it fails.
1108  *
1109  * 'udevsettle' was the old name for this command (RHEL 5).  This was
1110  * deprecated in favour of 'udevadm settle'.  The old 'udevsettle'
1111  * command was left as a symlink.  Then in Fedora 13 the old symlink
1112  * remained but it stopped working (RHBZ#548121), so we have to be
1113  * careful not to assume that we can use 'udevsettle' if it exists.
1114  */
1115 void
1116 udev_settle (void)
1117 {
1118   (void) command (NULL, NULL, "udevadm", "settle", NULL);
1119   (void) command (NULL, NULL, "udevsettle", NULL);
1120 }