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