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