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