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