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