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