7c4e72e44fa62b60acd3a55df37ca0e222c865cf
[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 <ctype.h>
38 #include <signal.h>
39 #include <printf.h>
40
41 #include "daemon.h"
42
43 static void usage (void);
44
45 /* Also in guestfs.c */
46 #define VMCHANNEL_PORT "6666"
47 #define VMCHANNEL_ADDR "10.0.2.4"
48
49 int verbose = 0;
50
51 static int print_shell_quote (FILE *stream, const struct printf_info *info, const void *const *args);
52 static int print_sysroot_shell_quote (FILE *stream, const struct printf_info *info, const void *const *args);
53 #ifdef HAVE_REGISTER_PRINTF_SPECIFIER
54 static int print_arginfo (const struct printf_info *info, size_t n, int *argtypes, int *size);
55 #else
56 #ifdef HAVE_REGISTER_PRINTF_FUNCTION
57 static int print_arginfo (const struct printf_info *info, size_t n, int *argtypes);
58 #else
59 #error "HAVE_REGISTER_PRINTF_{SPECIFIER|FUNCTION} not defined"
60 #endif
61 #endif
62
63 /* Location to mount root device. */
64 const char *sysroot = "/sysroot"; /* No trailing slash. */
65 int sysroot_len = 8;
66
67 int
68 main (int argc, char *argv[])
69 {
70   static const char *options = "fh:p:?";
71   static const struct option long_options[] = {
72     { "foreground", 0, 0, 'f' },
73     { "help", 0, 0, '?' },
74     { "host", 1, 0, 'h' },
75     { "port", 1, 0, 'p' },
76     { 0, 0, 0, 0 }
77   };
78   int c, n, r;
79   int dont_fork = 0;
80   const char *host = NULL;
81   const char *port = NULL;
82   FILE *fp;
83   char buf[4096];
84   char *p, *p2;
85   int sock;
86   struct addrinfo *res, *rr;
87   struct addrinfo hints;
88   XDR xdr;
89   uint32_t len;
90   struct sigaction sa;
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 'f':
111       dont_fork = 1;
112       break;
113
114     case 'h':
115       host = optarg;
116       break;
117
118     case 'p':
119       port = optarg;
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   /* If host and port aren't set yet, try /proc/cmdline. */
138   if (!host || !port) {
139     fp = fopen ("/proc/cmdline", "r");
140     if (fp == NULL) {
141       perror ("/proc/cmdline");
142       goto next;
143     }
144     n = fread (buf, 1, sizeof buf - 1, fp);
145     fclose (fp);
146     buf[n] = '\0';
147
148     /* Set the verbose flag.  Not quite right because this will only
149      * set the flag if host and port aren't set on the command line.
150      * Don't worry about this for now. (XXX)
151      */
152     verbose = strstr (buf, "guestfs_verbose=1") != NULL;
153     if (verbose)
154       printf ("verbose daemon enabled\n");
155
156     p = strstr (buf, "guestfs=");
157
158     if (p) {
159       p += 8;
160       p2 = strchr (p, ':');
161       if (p2) {
162         *p2++ = '\0';
163         host = p;
164         r = strcspn (p2, " \n");
165         p2[r] = '\0';
166         port = p2;
167       }
168     }
169   }
170
171  next:
172   /* Can't parse /proc/cmdline, so use built-in defaults. */
173   if (!host || !port) {
174     host = VMCHANNEL_ADDR;
175     port = VMCHANNEL_PORT;
176   }
177
178   /* Make sure SIGPIPE doesn't kill us. */
179   memset (&sa, 0, sizeof sa);
180   sa.sa_handler = SIG_IGN;
181   sa.sa_flags = 0;
182   if (sigaction (SIGPIPE, &sa, NULL) == -1)
183     perror ("sigaction SIGPIPE"); /* but try to continue anyway ... */
184
185   /* Set up a basic environment.  After we are called by /init the
186    * environment is essentially empty.
187    * https://bugzilla.redhat.com/show_bug.cgi?id=502074#c5
188    */
189   setenv ("PATH", "/usr/bin:/bin", 1);
190   setenv ("SHELL", "/bin/sh", 1);
191   setenv ("LC_ALL", "C", 1);
192
193   /* We document that umask defaults to 022 (it should be this anyway). */
194   umask (022);
195
196   /* Resolve the hostname. */
197   memset (&hints, 0, sizeof hints);
198   hints.ai_socktype = SOCK_STREAM;
199   hints.ai_flags = AI_ADDRCONFIG;
200   r = getaddrinfo (host, port, &hints, &res);
201   if (r != 0) {
202     fprintf (stderr, "%s:%s: %s\n", host, port, gai_strerror (r));
203     exit (1);
204   }
205
206   /* Connect to the given TCP socket. */
207   sock = -1;
208   for (rr = res; rr != NULL; rr = rr->ai_next) {
209     sock = socket (rr->ai_family, rr->ai_socktype, rr->ai_protocol);
210     if (sock != -1) {
211       if (connect (sock, rr->ai_addr, rr->ai_addrlen) == 0)
212         break;
213       perror ("connect");
214
215       close (sock);
216       sock = -1;
217     }
218   }
219   freeaddrinfo (res);
220
221   if (sock == -1) {
222     fprintf (stderr, "connection to %s:%s failed\n", host, port);
223     exit (1);
224   }
225
226   /* Send the magic length message which indicates that
227    * userspace is up inside the guest.
228    */
229   len = GUESTFS_LAUNCH_FLAG;
230   xdrmem_create (&xdr, buf, sizeof buf, XDR_ENCODE);
231   if (!xdr_uint32_t (&xdr, &len)) {
232     fprintf (stderr, "xdr_uint32_t failed\n");
233     exit (1);
234   }
235
236   if (xwrite (sock, buf, xdr_getpos (&xdr)) == -1)
237     exit (1);
238
239   xdr_destroy (&xdr);
240
241   /* Fork into the background. */
242   if (!dont_fork) {
243     if (daemon (0, 1) == -1) {
244       perror ("daemon");
245       exit (1);
246     }
247   }
248
249   /* Enter the main loop, reading and performing actions. */
250   main_loop (sock);
251
252   exit (0);
253 }
254
255 /* Turn "/path" into "/sysroot/path".
256  *
257  * Caller must check for NULL and call reply_with_perror ("malloc")
258  * if it is.  Caller must also free the string.
259  *
260  * See also the custom %R printf formatter which does shell quoting too.
261  */
262 char *
263 sysroot_path (const char *path)
264 {
265   char *r;
266   int len = strlen (path) + sysroot_len + 1;
267
268   r = malloc (len);
269   if (r == NULL)
270     return NULL;
271
272   snprintf (r, len, "%s%s", sysroot, path);
273   return r;
274 }
275
276 int
277 xwrite (int sock, const void *v_buf, size_t len)
278 {
279   int r;
280   const char *buf = v_buf;
281
282   while (len > 0) {
283     r = write (sock, buf, len);
284     if (r == -1) {
285       perror ("write");
286       return -1;
287     }
288     buf += r;
289     len -= r;
290   }
291
292   return 0;
293 }
294
295 int
296 xread (int sock, void *v_buf, size_t len)
297 {
298   int r;
299   char *buf = v_buf;
300
301   while (len > 0) {
302     r = read (sock, buf, len);
303     if (r == -1) {
304       perror ("read");
305       return -1;
306     }
307     if (r == 0) {
308       fprintf (stderr, "read: unexpected end of file on fd %d\n", sock);
309       return -1;
310     }
311     buf += r;
312     len -= r;
313   }
314
315   return 0;
316 }
317
318 static void
319 usage (void)
320 {
321   fprintf (stderr, "guestfsd [-f] [-h host -p port]\n");
322 }
323
324 int
325 add_string (char ***argv, int *size, int *alloc, const char *str)
326 {
327   char **new_argv;
328   char *new_str;
329
330   if (*size >= *alloc) {
331     *alloc += 64;
332     new_argv = realloc (*argv, *alloc * sizeof (char *));
333     if (new_argv == NULL) {
334       reply_with_perror ("realloc");
335       free_strings (*argv);
336       return -1;
337     }
338     *argv = new_argv;
339   }
340
341   if (str) {
342     new_str = strdup (str);
343     if (new_str == NULL) {
344       reply_with_perror ("strdup");
345       free_strings (*argv);
346     }
347   } else
348     new_str = NULL;
349
350   (*argv)[*size] = new_str;
351
352   (*size)++;
353   return 0;
354 }
355
356 int
357 count_strings (char *const *argv)
358 {
359   int argc;
360
361   for (argc = 0; argv[argc] != NULL; ++argc)
362     ;
363   return argc;
364 }
365
366 static int
367 compare (const void *vp1, const void *vp2)
368 {
369   char * const *p1 = (char * const *) vp1;
370   char * const *p2 = (char * const *) vp2;
371   return strcmp (*p1, *p2);
372 }
373
374 void
375 sort_strings (char **argv, int len)
376 {
377   qsort (argv, len, sizeof (char *), compare);
378 }
379
380 void
381 free_strings (char **argv)
382 {
383   int argc;
384
385   for (argc = 0; argv[argc] != NULL; ++argc)
386     free (argv[argc]);
387   free (argv);
388 }
389
390 void
391 free_stringslen (char **argv, int len)
392 {
393   int i;
394
395   for (i = 0; i < len; ++i)
396     free (argv[i]);
397   free (argv);
398 }
399
400 /* This is a more sane version of 'system(3)' for running external
401  * commands.  It uses fork/execvp, so we don't need to worry about
402  * quoting of parameters, and it allows us to capture any error
403  * messages in a buffer.
404  */
405 int
406 command (char **stdoutput, char **stderror, const char *name, ...)
407 {
408   va_list args;
409   const char **argv;
410   char *s;
411   int i, r;
412
413   /* Collect the command line arguments into an array. */
414   i = 2;
415   argv = malloc (sizeof (char *) * i);
416   if (argv == NULL) {
417     perror ("malloc");
418     return -1;
419   }
420   argv[0] = (char *) name;
421   argv[1] = NULL;
422
423   va_start (args, name);
424
425   while ((s = va_arg (args, char *)) != NULL) {
426     const char **p = realloc (argv, sizeof (char *) * (++i));
427     if (p == NULL) {
428       perror ("realloc");
429       free (argv);
430       va_end (args);
431       return -1;
432     }
433     argv = p;
434     argv[i-2] = s;
435     argv[i-1] = NULL;
436   }
437
438   va_end (args);
439
440   r = commandv (stdoutput, stderror, (char **) argv);
441
442   /* NB: Mustn't free the strings which are on the stack. */
443   free (argv);
444
445   return r;
446 }
447
448 /* Same as 'command', but we allow the status code from the
449  * subcommand to be non-zero, and return that status code.
450  * We still return -1 if there was some other error.
451  */
452 int
453 commandr (char **stdoutput, char **stderror, const char *name, ...)
454 {
455   va_list args;
456   const char **argv;
457   char *s;
458   int i, r;
459
460   /* Collect the command line arguments into an array. */
461   i = 2;
462   argv = malloc (sizeof (char *) * i);
463   if (argv == NULL) {
464     perror ("malloc");
465     return -1;
466   }
467   argv[0] = (char *) name;
468   argv[1] = NULL;
469
470   va_start (args, name);
471
472   while ((s = va_arg (args, char *)) != NULL) {
473     const char **p = realloc (argv, sizeof (char *) * (++i));
474     if (p == NULL) {
475       perror ("realloc");
476       free (argv);
477       va_end (args);
478       return -1;
479     }
480     argv = p;
481     argv[i-2] = s;
482     argv[i-1] = NULL;
483   }
484
485   va_end (args);
486
487   r = commandrv (stdoutput, stderror, argv);
488
489   /* NB: Mustn't free the strings which are on the stack. */
490   free (argv);
491
492   return r;
493 }
494
495 /* Same as 'command', but passing an argv. */
496 int
497 commandv (char **stdoutput, char **stderror, char *const *argv)
498 {
499   int r;
500
501   r = commandrv (stdoutput, stderror, (void *) argv);
502   if (r == 0)
503     return 0;
504   else
505     return -1;
506 }
507
508 int
509 commandrv (char **stdoutput, char **stderror, char const* const *argv)
510 {
511   int so_size = 0, se_size = 0;
512   int so_fd[2], se_fd[2];
513   pid_t pid;
514   int r, quit, i;
515   fd_set rset, rset2;
516   char buf[256];
517   char *p;
518
519   if (stdoutput) *stdoutput = NULL;
520   if (stderror) *stderror = NULL;
521
522   if (verbose) {
523     printf ("%s", argv[0]);
524     for (i = 1; argv[i] != NULL; ++i)
525       printf (" %s", argv[i]);
526     printf ("\n");
527   }
528
529   if (pipe (so_fd) == -1 || pipe (se_fd) == -1) {
530     perror ("pipe");
531     return -1;
532   }
533
534   pid = fork ();
535   if (pid == -1) {
536     perror ("fork");
537     close (so_fd[0]);
538     close (so_fd[1]);
539     close (se_fd[0]);
540     close (se_fd[1]);
541     return -1;
542   }
543
544   if (pid == 0) {               /* Child process. */
545     close (0);
546     close (so_fd[0]);
547     close (se_fd[0]);
548     dup2 (so_fd[1], 1);
549     dup2 (se_fd[1], 2);
550     close (so_fd[1]);
551     close (se_fd[1]);
552
553     execvp (argv[0], (void *) argv);
554     perror (argv[0]);
555     _exit (1);
556   }
557
558   /* Parent process. */
559   close (so_fd[1]);
560   close (se_fd[1]);
561
562   FD_ZERO (&rset);
563   FD_SET (so_fd[0], &rset);
564   FD_SET (se_fd[0], &rset);
565
566   quit = 0;
567   while (quit < 2) {
568     rset2 = rset;
569     r = select (MAX (so_fd[0], se_fd[0]) + 1, &rset2, NULL, NULL, NULL);
570     if (r == -1) {
571       perror ("select");
572     quit:
573       if (stdoutput) free (*stdoutput);
574       if (stderror) free (*stderror);
575       close (so_fd[0]);
576       close (se_fd[0]);
577       waitpid (pid, NULL, 0);
578       return -1;
579     }
580
581     if (FD_ISSET (so_fd[0], &rset2)) { /* something on stdout */
582       r = read (so_fd[0], buf, sizeof buf);
583       if (r == -1) {
584         perror ("read");
585         goto quit;
586       }
587       if (r == 0) { FD_CLR (so_fd[0], &rset); quit++; }
588
589       if (r > 0 && stdoutput) {
590         so_size += r;
591         p = realloc (*stdoutput, so_size);
592         if (p == NULL) {
593           perror ("realloc");
594           goto quit;
595         }
596         *stdoutput = p;
597         memcpy (*stdoutput + so_size - r, buf, r);
598       }
599     }
600
601     if (FD_ISSET (se_fd[0], &rset2)) { /* something on stderr */
602       r = read (se_fd[0], buf, sizeof buf);
603       if (r == -1) {
604         perror ("read");
605         goto quit;
606       }
607       if (r == 0) { FD_CLR (se_fd[0], &rset); quit++; }
608
609       if (r > 0 && stderror) {
610         se_size += r;
611         p = realloc (*stderror, se_size);
612         if (p == NULL) {
613           perror ("realloc");
614           goto quit;
615         }
616         *stderror = p;
617         memcpy (*stderror + se_size - r, buf, r);
618       }
619     }
620   }
621
622   close (so_fd[0]);
623   close (se_fd[0]);
624
625   /* Make sure the output buffers are \0-terminated.  Also remove any
626    * trailing \n characters from the error buffer (not from stdout).
627    */
628   if (stdoutput) {
629     void *q = realloc (*stdoutput, so_size+1);
630     if (q == NULL) {
631       perror ("realloc");
632       free (*stdoutput);
633     }
634     *stdoutput = q;
635     if (*stdoutput)
636       (*stdoutput)[so_size] = '\0';
637   }
638   if (stderror) {
639     void *q = realloc (*stderror, se_size+1);
640     if (q == NULL) {
641       perror ("realloc");
642       free (*stderror);
643     }
644     *stderror = q;
645     if (*stderror) {
646       (*stderror)[se_size] = '\0';
647       se_size--;
648       while (se_size >= 0 && (*stderror)[se_size] == '\n')
649         (*stderror)[se_size--] = '\0';
650     }
651   }
652
653   /* Get the exit status of the command. */
654   if (waitpid (pid, &r, 0) != pid) {
655     perror ("waitpid");
656     return -1;
657   }
658
659   if (WIFEXITED (r)) {
660     return WEXITSTATUS (r);
661   } else
662     return -1;
663 }
664
665 /* Split an output string into a NULL-terminated list of lines.
666  * Typically this is used where we have run an external command
667  * which has printed out a list of things, and we want to return
668  * an actual list.
669  *
670  * The corner cases here are quite tricky.  Note in particular:
671  *
672  *   "" -> []
673  *   "\n" -> [""]
674  *   "a\nb" -> ["a"; "b"]
675  *   "a\nb\n" -> ["a"; "b"]
676  *   "a\nb\n\n" -> ["a"; "b"; ""]
677  *
678  * The original string is written over and destroyed by this
679  * function (which is usually OK because it's the 'out' string
680  * from command()).  You can free the original string, because
681  * add_string() strdups the strings.
682  */
683 char **
684 split_lines (char *str)
685 {
686   char **lines = NULL;
687   int size = 0, alloc = 0;
688   char *p, *pend;
689
690   if (strcmp (str, "") == 0)
691     goto empty_list;
692
693   p = str;
694   while (p) {
695     /* Empty last line? */
696     if (p[0] == '\0')
697       break;
698
699     pend = strchr (p, '\n');
700     if (pend) {
701       *pend = '\0';
702       pend++;
703     }
704
705     if (add_string (&lines, &size, &alloc, p) == -1) {
706       return NULL;
707     }
708
709     p = pend;
710   }
711
712  empty_list:
713   if (add_string (&lines, &size, &alloc, NULL) == -1)
714     return NULL;
715
716   return lines;
717 }
718
719 /* printf helper function so we can use %Q ("quoted") and %R to print
720  * shell-quoted strings.  See HACKING file for more details.
721  */
722 static int
723 print_shell_quote (FILE *stream,
724                    const struct printf_info *info ATTRIBUTE_UNUSED,
725                    const void *const *args)
726 {
727 #define SAFE(c) (isalnum((c)) ||                                        \
728                  (c) == '/' || (c) == '-' || (c) == '_' || (c) == '.')
729   int i, len;
730   const char *str = *((const char **) (args[0]));
731
732   for (i = len = 0; str[i]; ++i) {
733     if (!SAFE(str[i])) {
734       putc ('\\', stream);
735       len ++;
736     }
737     putc (str[i], stream);
738     len ++;
739   }
740
741   return len;
742 }
743
744 static int
745 print_sysroot_shell_quote (FILE *stream,
746                            const struct printf_info *info,
747                            const void *const *args)
748 {
749   fputs (sysroot, stream);
750   return sysroot_len + print_shell_quote (stream, info, args);
751 }
752
753 #ifdef HAVE_REGISTER_PRINTF_SPECIFIER
754 static int
755 print_arginfo (const struct printf_info *info ATTRIBUTE_UNUSED,
756                size_t n, int *argtypes, int *size)
757 {
758   if (n > 0) {
759     argtypes[0] = PA_STRING;
760     size[0] = sizeof (const char *);
761   }
762   return 1;
763 }
764 #else
765 #ifdef HAVE_REGISTER_PRINTF_FUNCTION
766 static int
767 print_arginfo (const struct printf_info *info, size_t n, int *argtypes)
768 {
769   if (n > 0)
770     argtypes[0] = PA_STRING;
771   return 1;
772 }
773 #else
774 #error "HAVE_REGISTER_PRINTF_{SPECIFIER|FUNCTION} not defined"
775 #endif
776 #endif
777
778 /* Perform device name translation.  Don't call this directly -
779  * use the RESOLVE_DEVICE macro.
780  *
781  * See guestfs(3) for the algorithm.
782  *
783  * We have to open the device and test for ENXIO, because
784  * the device nodes themselves will exist in the appliance.
785  */
786 int
787 device_name_translation (char *device, const char *func)
788 {
789   int fd;
790
791   fd = open (device, O_RDONLY);
792   if (fd >= 0) {
793     close (fd);
794     return 0;
795   }
796
797   if (errno != ENXIO && errno != ENOENT) {
798   error:
799     reply_with_perror ("%s: %s", func, device);
800     return -1;
801   }
802
803   /* If the name begins with "/dev/sd" then try the alternatives. */
804   if (strncmp (device, "/dev/sd", 7) != 0)
805     goto error;
806
807   device[5] = 'h';              /* /dev/hd (old IDE driver) */
808   fd = open (device, O_RDONLY);
809   if (fd >= 0) {
810     close (fd);
811     return 0;
812   }
813
814   device[5] = 'v';              /* /dev/vd (for virtio devices) */
815   fd = open (device, O_RDONLY);
816   if (fd >= 0) {
817     close (fd);
818     return 0;
819   }
820
821   device[5] = 's';              /* Restore original device name. */
822   goto error;
823 }
824
825 /* LVM and other commands aren't synchronous, especially when udev is
826  * involved.  eg. You can create or remove some device, but the /dev
827  * device node won't appear until some time later.  This means that
828  * you get an error if you run one command followed by another.
829  * Use 'udevadm settle' after certain commands, but don't be too
830  * fussed if it fails.
831  */
832 void
833 udev_settle (void)
834 {
835   command (NULL, NULL, "/sbin/udevadm", "settle", NULL);
836 }