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