daemon: Always reflect command stderr to stderr when debugging.
[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, (char **) 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, char *const *argv)
609 {
610   int r;
611
612   r = commandrvf (stdoutput, stderror, flags, (void *) argv);
613   if (r == 0)
614     return 0;
615   else
616     return -1;
617 }
618
619 /* This is a more sane version of 'system(3)' for running external
620  * commands.  It uses fork/execvp, so we don't need to worry about
621  * quoting of parameters, and it allows us to capture any error
622  * messages in a buffer.
623  *
624  * If stdoutput is not NULL, then *stdoutput will return the stdout
625  * of the command.
626  *
627  * If stderror is not NULL, then *stderror will return the stderr
628  * of the command.  If there is a final \n character, it is removed
629  * so you can use the error string directly in a call to
630  * reply_with_error.
631  *
632  * Flags:
633  *
634  * COMMAND_FLAG_FOLD_STDOUT_ON_STDERR: For broken external commands
635  * that send error messages to stdout (hello, parted) but that don't
636  * have any useful stdout information, use this flag to capture the
637  * error messages in the *stderror buffer.  If using this flag,
638  * you should pass stdoutput as NULL because nothing could ever be
639  * captured in that buffer.
640  */
641 int
642 commandrvf (char **stdoutput, char **stderror, int flags,
643             char const* const *argv)
644 {
645   int so_size = 0, se_size = 0;
646   int so_fd[2], se_fd[2];
647   pid_t pid;
648   int r, quit, i;
649   fd_set rset, rset2;
650   char buf[256];
651   char *p;
652
653   if (stdoutput) *stdoutput = NULL;
654   if (stderror) *stderror = NULL;
655
656   if (verbose) {
657     printf ("%s", argv[0]);
658     for (i = 1; argv[i] != NULL; ++i)
659       printf (" %s", argv[i]);
660     printf ("\n");
661   }
662
663   if (pipe (so_fd) == -1 || pipe (se_fd) == -1) {
664     perror ("pipe");
665     return -1;
666   }
667
668   pid = fork ();
669   if (pid == -1) {
670     perror ("fork");
671     close (so_fd[0]);
672     close (so_fd[1]);
673     close (se_fd[0]);
674     close (se_fd[1]);
675     return -1;
676   }
677
678   if (pid == 0) {               /* Child process. */
679     close (0);
680     open ("/dev/null", O_RDONLY); /* Set stdin to /dev/null (ignore failure) */
681     close (so_fd[0]);
682     close (se_fd[0]);
683     if (!(flags & COMMAND_FLAG_FOLD_STDOUT_ON_STDERR))
684       dup2 (so_fd[1], 1);
685     else
686       dup2 (se_fd[1], 1);
687     dup2 (se_fd[1], 2);
688     close (so_fd[1]);
689     close (se_fd[1]);
690
691     execvp (argv[0], (void *) argv);
692     perror (argv[0]);
693     _exit (1);
694   }
695
696   /* Parent process. */
697   close (so_fd[1]);
698   close (se_fd[1]);
699
700   FD_ZERO (&rset);
701   FD_SET (so_fd[0], &rset);
702   FD_SET (se_fd[0], &rset);
703
704   quit = 0;
705   while (quit < 2) {
706     rset2 = rset;
707     r = select (MAX (so_fd[0], se_fd[0]) + 1, &rset2, NULL, NULL, NULL);
708     if (r == -1) {
709       perror ("select");
710     quit:
711       if (stdoutput) free (*stdoutput);
712       if (stderror) free (*stderror);
713       close (so_fd[0]);
714       close (se_fd[0]);
715       waitpid (pid, NULL, 0);
716       return -1;
717     }
718
719     if (FD_ISSET (so_fd[0], &rset2)) { /* something on stdout */
720       r = read (so_fd[0], buf, sizeof buf);
721       if (r == -1) {
722         perror ("read");
723         goto quit;
724       }
725       if (r == 0) { FD_CLR (so_fd[0], &rset); quit++; }
726
727       if (r > 0 && stdoutput) {
728         so_size += r;
729         p = realloc (*stdoutput, so_size);
730         if (p == NULL) {
731           perror ("realloc");
732           goto quit;
733         }
734         *stdoutput = p;
735         memcpy (*stdoutput + so_size - r, buf, r);
736       }
737     }
738
739     if (FD_ISSET (se_fd[0], &rset2)) { /* something on stderr */
740       r = read (se_fd[0], buf, sizeof buf);
741       if (r == -1) {
742         perror ("read");
743         goto quit;
744       }
745       if (r == 0) { FD_CLR (se_fd[0], &rset); quit++; }
746
747       if (r > 0) {
748         if (verbose)
749           ignore_value (write (2, buf, r));
750
751         if (stderror) {
752           se_size += r;
753           p = realloc (*stderror, se_size);
754           if (p == NULL) {
755             perror ("realloc");
756             goto quit;
757           }
758           *stderror = p;
759           memcpy (*stderror + se_size - r, buf, r);
760         }
761       }
762     }
763   }
764
765   close (so_fd[0]);
766   close (se_fd[0]);
767
768   /* Make sure the output buffers are \0-terminated.  Also remove any
769    * trailing \n characters from the error buffer (not from stdout).
770    */
771   if (stdoutput) {
772     void *q = realloc (*stdoutput, so_size+1);
773     if (q == NULL) {
774       perror ("realloc");
775       free (*stdoutput);
776     }
777     *stdoutput = q;
778     if (*stdoutput)
779       (*stdoutput)[so_size] = '\0';
780   }
781   if (stderror) {
782     void *q = realloc (*stderror, se_size+1);
783     if (q == NULL) {
784       perror ("realloc");
785       free (*stderror);
786     }
787     *stderror = q;
788     if (*stderror) {
789       (*stderror)[se_size] = '\0';
790       se_size--;
791       while (se_size >= 0 && (*stderror)[se_size] == '\n')
792         (*stderror)[se_size--] = '\0';
793     }
794   }
795
796   /* Get the exit status of the command. */
797   if (waitpid (pid, &r, 0) != pid) {
798     perror ("waitpid");
799     return -1;
800   }
801
802   if (WIFEXITED (r)) {
803     return WEXITSTATUS (r);
804   } else
805     return -1;
806 }
807
808 /* Split an output string into a NULL-terminated list of lines.
809  * Typically this is used where we have run an external command
810  * which has printed out a list of things, and we want to return
811  * an actual list.
812  *
813  * The corner cases here are quite tricky.  Note in particular:
814  *
815  *   "" -> []
816  *   "\n" -> [""]
817  *   "a\nb" -> ["a"; "b"]
818  *   "a\nb\n" -> ["a"; "b"]
819  *   "a\nb\n\n" -> ["a"; "b"; ""]
820  *
821  * The original string is written over and destroyed by this
822  * function (which is usually OK because it's the 'out' string
823  * from command()).  You can free the original string, because
824  * add_string() strdups the strings.
825  */
826 char **
827 split_lines (char *str)
828 {
829   char **lines = NULL;
830   int size = 0, alloc = 0;
831   char *p, *pend;
832
833   if (strcmp (str, "") == 0)
834     goto empty_list;
835
836   p = str;
837   while (p) {
838     /* Empty last line? */
839     if (p[0] == '\0')
840       break;
841
842     pend = strchr (p, '\n');
843     if (pend) {
844       *pend = '\0';
845       pend++;
846     }
847
848     if (add_string (&lines, &size, &alloc, p) == -1) {
849       return NULL;
850     }
851
852     p = pend;
853   }
854
855  empty_list:
856   if (add_string (&lines, &size, &alloc, NULL) == -1)
857     return NULL;
858
859   return lines;
860 }
861
862 /* printf helper function so we can use %Q ("quoted") and %R to print
863  * shell-quoted strings.  See HACKING file for more details.
864  */
865 static int
866 print_shell_quote (FILE *stream,
867                    const struct printf_info *info ATTRIBUTE_UNUSED,
868                    const void *const *args)
869 {
870 #define SAFE(c) (c_isalnum((c)) ||                                      \
871                  (c) == '/' || (c) == '-' || (c) == '_' || (c) == '.')
872   int i, len;
873   const char *str = *((const char **) (args[0]));
874
875   for (i = len = 0; str[i]; ++i) {
876     if (!SAFE(str[i])) {
877       putc ('\\', stream);
878       len ++;
879     }
880     putc (str[i], stream);
881     len ++;
882   }
883
884   return len;
885 }
886
887 static int
888 print_sysroot_shell_quote (FILE *stream,
889                            const struct printf_info *info,
890                            const void *const *args)
891 {
892   fputs (sysroot, stream);
893   return sysroot_len + print_shell_quote (stream, info, args);
894 }
895
896 #ifdef HAVE_REGISTER_PRINTF_SPECIFIER
897 static int
898 print_arginfo (const struct printf_info *info ATTRIBUTE_UNUSED,
899                size_t n, int *argtypes, int *size)
900 {
901   if (n > 0) {
902     argtypes[0] = PA_STRING;
903     size[0] = sizeof (const char *);
904   }
905   return 1;
906 }
907 #else
908 #ifdef HAVE_REGISTER_PRINTF_FUNCTION
909 static int
910 print_arginfo (const struct printf_info *info, size_t n, int *argtypes)
911 {
912   if (n > 0)
913     argtypes[0] = PA_STRING;
914   return 1;
915 }
916 #else
917 #error "HAVE_REGISTER_PRINTF_{SPECIFIER|FUNCTION} not defined"
918 #endif
919 #endif
920
921 /* Perform device name translation.  Don't call this directly -
922  * use the RESOLVE_DEVICE macro.
923  *
924  * See guestfs(3) for the algorithm.
925  *
926  * We have to open the device and test for ENXIO, because
927  * the device nodes themselves will exist in the appliance.
928  */
929 int
930 device_name_translation (char *device, const char *func)
931 {
932   int fd;
933
934   fd = open (device, O_RDONLY);
935   if (fd >= 0) {
936     close (fd);
937     return 0;
938   }
939
940   if (errno != ENXIO && errno != ENOENT) {
941   error:
942     reply_with_perror ("%s: %s", func, device);
943     return -1;
944   }
945
946   /* If the name begins with "/dev/sd" then try the alternatives. */
947   if (strncmp (device, "/dev/sd", 7) != 0)
948     goto error;
949
950   device[5] = 'h';              /* /dev/hd (old IDE driver) */
951   fd = open (device, O_RDONLY);
952   if (fd >= 0) {
953     close (fd);
954     return 0;
955   }
956
957   device[5] = 'v';              /* /dev/vd (for virtio devices) */
958   fd = open (device, O_RDONLY);
959   if (fd >= 0) {
960     close (fd);
961     return 0;
962   }
963
964   device[5] = 's';              /* Restore original device name. */
965   goto error;
966 }
967
968 /* LVM and other commands aren't synchronous, especially when udev is
969  * involved.  eg. You can create or remove some device, but the /dev
970  * device node won't appear until some time later.  This means that
971  * you get an error if you run one command followed by another.
972  * Use 'udevadm settle' after certain commands, but don't be too
973  * fussed if it fails.
974  */
975 void
976 udev_settle (void)
977 {
978   command (NULL, NULL, "/sbin/udevadm", "settle", NULL);
979 }