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