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