Add 'realpath' command.
[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 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 ("LANG", "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   (void) xwrite (sock, buf, xdr_getpos (&xdr));
237
238   xdr_destroy (&xdr);
239
240   /* Fork into the background. */
241   if (!dont_fork) {
242     if (daemon (0, 1) == -1) {
243       perror ("daemon");
244       exit (1);
245     }
246   }
247
248   /* Enter the main loop, reading and performing actions. */
249   main_loop (sock);
250
251   exit (0);
252 }
253
254 /* Turn "/path" into "/sysroot/path".
255  *
256  * Caller must check for NULL and call reply_with_perror ("malloc")
257  * if it is.  Caller must also free the string.
258  *
259  * See also the custom %R printf formatter which does shell quoting too.
260  */
261 char *
262 sysroot_path (const char *path)
263 {
264   char *r;
265   int len = strlen (path) + sysroot_len + 1;
266
267   r = malloc (len);
268   if (r == NULL)
269     return NULL;
270
271   snprintf (r, len, "%s%s", sysroot, path);
272   return r;
273 }
274
275 int
276 xwrite (int sock, const void *buf, size_t len)
277 {
278   int r;
279
280   while (len > 0) {
281     r = write (sock, buf, len);
282     if (r == -1) {
283       perror ("write");
284       return -1;
285     }
286     buf += r;
287     len -= r;
288   }
289
290   return 0;
291 }
292
293 int
294 xread (int sock, void *buf, size_t len)
295 {
296   int r;
297
298   while (len > 0) {
299     r = read (sock, buf, len);
300     if (r == -1) {
301       perror ("read");
302       return -1;
303     }
304     if (r == 0) {
305       fprintf (stderr, "read: unexpected end of file on fd %d\n", sock);
306       return -1;
307     }
308     buf += r;
309     len -= r;
310   }
311
312   return 0;
313 }
314
315 static void
316 usage (void)
317 {
318   fprintf (stderr, "guestfsd [-f] [-h host -p port]\n");
319 }
320
321 int
322 add_string (char ***argv, int *size, int *alloc, const char *str)
323 {
324   char **new_argv;
325   char *new_str;
326
327   if (*size >= *alloc) {
328     *alloc += 64;
329     new_argv = realloc (*argv, *alloc * sizeof (char *));
330     if (new_argv == NULL) {
331       reply_with_perror ("realloc");
332       free_strings (*argv);
333       return -1;
334     }
335     *argv = new_argv;
336   }
337
338   if (str) {
339     new_str = strdup (str);
340     if (new_str == NULL) {
341       reply_with_perror ("strdup");
342       free_strings (*argv);
343     }
344   } else
345     new_str = NULL;
346
347   (*argv)[*size] = new_str;
348
349   (*size)++;
350   return 0;
351 }
352
353 int
354 count_strings (char * const* const argv)
355 {
356   int argc;
357
358   for (argc = 0; argv[argc] != NULL; ++argc)
359     ;
360   return argc;
361 }
362
363 static int
364 compare (const void *vp1, const void *vp2)
365 {
366   char * const *p1 = (char * const *) vp1;
367   char * const *p2 = (char * const *) vp2;
368   return strcmp (*p1, *p2);
369 }
370
371 void
372 sort_strings (char **argv, int len)
373 {
374   qsort (argv, len, sizeof (char *), compare);
375 }
376
377 void
378 free_strings (char **argv)
379 {
380   int argc;
381
382   for (argc = 0; argv[argc] != NULL; ++argc)
383     free (argv[argc]);
384   free (argv);
385 }
386
387 void
388 free_stringslen (char **argv, int len)
389 {
390   int i;
391
392   for (i = 0; i < len; ++i)
393     free (argv[i]);
394   free (argv);
395 }
396
397 /* This is a more sane version of 'system(3)' for running external
398  * commands.  It uses fork/execvp, so we don't need to worry about
399  * quoting of parameters, and it allows us to capture any error
400  * messages in a buffer.
401  */
402 int
403 command (char **stdoutput, char **stderror, const char *name, ...)
404 {
405   va_list args;
406   char **argv, **p;
407   char *s;
408   int i, r;
409
410   /* Collect the command line arguments into an array. */
411   i = 2;
412   argv = malloc (sizeof (char *) * i);
413   if (argv == NULL) {
414     perror ("malloc");
415     return -1;
416   }
417   argv[0] = (char *) name;
418   argv[1] = NULL;
419
420   va_start (args, name);
421
422   while ((s = va_arg (args, char *)) != NULL) {
423     p = realloc (argv, sizeof (char *) * (++i));
424     if (p == NULL) {
425       perror ("realloc");
426       free (argv);
427       va_end (args);
428       return -1;
429     }
430     argv = p;
431     argv[i-2] = s;
432     argv[i-1] = NULL;
433   }
434
435   va_end (args);
436
437   r = commandv (stdoutput, stderror, argv);
438
439   /* NB: Mustn't free the strings which are on the stack. */
440   free (argv);
441
442   return r;
443 }
444
445 /* Same as 'command', but we allow the status code from the
446  * subcommand to be non-zero, and return that status code.
447  * We still return -1 if there was some other error.
448  */
449 int
450 commandr (char **stdoutput, char **stderror, const char *name, ...)
451 {
452   va_list args;
453   char **argv, **p;
454   char *s;
455   int i, r;
456
457   /* Collect the command line arguments into an array. */
458   i = 2;
459   argv = malloc (sizeof (char *) * i);
460   if (argv == NULL) {
461     perror ("malloc");
462     return -1;
463   }
464   argv[0] = (char *) name;
465   argv[1] = NULL;
466
467   va_start (args, name);
468
469   while ((s = va_arg (args, char *)) != NULL) {
470     p = realloc (argv, sizeof (char *) * (++i));
471     if (p == NULL) {
472       perror ("realloc");
473       free (argv);
474       va_end (args);
475       return -1;
476     }
477     argv = p;
478     argv[i-2] = s;
479     argv[i-1] = NULL;
480   }
481
482   va_end (args);
483
484   r = commandrv (stdoutput, stderror, argv);
485
486   /* NB: Mustn't free the strings which are on the stack. */
487   free (argv);
488
489   return r;
490 }
491
492 /* Same as 'command', but passing an argv. */
493 int
494 commandv (char **stdoutput, char **stderror, char * const* const argv)
495 {
496   int r;
497
498   r = commandrv (stdoutput, stderror, argv);
499   if (r == 0)
500     return 0;
501   else
502     return -1;
503 }
504
505 int
506 commandrv (char **stdoutput, char **stderror, char * const* const argv)
507 {
508   int so_size = 0, se_size = 0;
509   int so_fd[2], se_fd[2];
510   pid_t pid;
511   int r, quit, i;
512   fd_set rset, rset2;
513   char buf[256];
514   char *p;
515
516   if (stdoutput) *stdoutput = NULL;
517   if (stderror) *stderror = NULL;
518
519   if (verbose) {
520     printf ("%s", argv[0]);
521     for (i = 1; argv[i] != NULL; ++i)
522       printf (" %s", argv[i]);
523     printf ("\n");
524   }
525
526   if (pipe (so_fd) == -1 || pipe (se_fd) == -1) {
527     perror ("pipe");
528     return -1;
529   }
530
531   pid = fork ();
532   if (pid == -1) {
533     perror ("fork");
534     close (so_fd[0]);
535     close (so_fd[1]);
536     close (se_fd[0]);
537     close (se_fd[1]);
538     return -1;
539   }
540
541   if (pid == 0) {               /* Child process. */
542     close (0);
543     close (so_fd[0]);
544     close (se_fd[0]);
545     dup2 (so_fd[1], 1);
546     dup2 (se_fd[1], 2);
547     close (so_fd[1]);
548     close (se_fd[1]);
549
550     execvp (argv[0], argv);
551     perror (argv[0]);
552     _exit (1);
553   }
554
555   /* Parent process. */
556   close (so_fd[1]);
557   close (se_fd[1]);
558
559   FD_ZERO (&rset);
560   FD_SET (so_fd[0], &rset);
561   FD_SET (se_fd[0], &rset);
562
563   quit = 0;
564   while (quit < 2) {
565     rset2 = rset;
566     r = select (MAX (so_fd[0], se_fd[0]) + 1, &rset2, NULL, NULL, NULL);
567     if (r == -1) {
568       perror ("select");
569     quit:
570       if (stdoutput) free (*stdoutput);
571       if (stderror) free (*stderror);
572       close (so_fd[0]);
573       close (se_fd[0]);
574       waitpid (pid, NULL, 0);
575       return -1;
576     }
577
578     if (FD_ISSET (so_fd[0], &rset2)) { /* something on stdout */
579       r = read (so_fd[0], buf, sizeof buf);
580       if (r == -1) {
581         perror ("read");
582         goto quit;
583       }
584       if (r == 0) { FD_CLR (so_fd[0], &rset); quit++; }
585
586       if (r > 0 && stdoutput) {
587         so_size += r;
588         p = realloc (*stdoutput, so_size);
589         if (p == NULL) {
590           perror ("realloc");
591           goto quit;
592         }
593         *stdoutput = p;
594         memcpy (*stdoutput + so_size - r, buf, r);
595       }
596     }
597
598     if (FD_ISSET (se_fd[0], &rset2)) { /* something on stderr */
599       r = read (se_fd[0], buf, sizeof buf);
600       if (r == -1) {
601         perror ("read");
602         goto quit;
603       }
604       if (r == 0) { FD_CLR (se_fd[0], &rset); quit++; }
605
606       if (r > 0 && stderror) {
607         se_size += r;
608         p = realloc (*stderror, se_size);
609         if (p == NULL) {
610           perror ("realloc");
611           goto quit;
612         }
613         *stderror = p;
614         memcpy (*stderror + se_size - r, buf, r);
615       }
616     }
617   }
618
619   close (so_fd[0]);
620   close (se_fd[0]);
621
622   /* Make sure the output buffers are \0-terminated.  Also remove any
623    * trailing \n characters from the error buffer (not from stdout).
624    */
625   if (stdoutput) {
626     void *q = realloc (*stdoutput, so_size+1);
627     if (q == NULL) {
628       perror ("realloc");
629       free (*stdoutput);
630     }
631     *stdoutput = q;
632     if (*stdoutput)
633       (*stdoutput)[so_size] = '\0';
634   }
635   if (stderror) {
636     void *q = realloc (*stderror, se_size+1);
637     if (q == NULL) {
638       perror ("realloc");
639       free (*stderror);
640     }
641     *stderror = q;
642     if (*stderror) {
643       (*stderror)[se_size] = '\0';
644       se_size--;
645       while (se_size >= 0 && (*stderror)[se_size] == '\n')
646         (*stderror)[se_size--] = '\0';
647     }
648   }
649
650   /* Get the exit status of the command. */
651   if (waitpid (pid, &r, 0) != pid) {
652     perror ("waitpid");
653     return -1;
654   }
655
656   if (WIFEXITED (r)) {
657     return WEXITSTATUS (r);
658   } else
659     return -1;
660 }
661
662 /* Split an output string into a NULL-terminated list of lines.
663  * Typically this is used where we have run an external command
664  * which has printed out a list of things, and we want to return
665  * an actual list.
666  *
667  * The corner cases here are quite tricky.  Note in particular:
668  *
669  *   "" -> []
670  *   "\n" -> [""]
671  *   "a\nb" -> ["a"; "b"]
672  *   "a\nb\n" -> ["a"; "b"]
673  *   "a\nb\n\n" -> ["a"; "b"; ""]
674  *
675  * The original string is written over and destroyed by this
676  * function (which is usually OK because it's the 'out' string
677  * from command()).  You can free the original string, because
678  * add_string() strdups the strings.
679  */
680 char **
681 split_lines (char *str)
682 {
683   char **lines = NULL;
684   int size = 0, alloc = 0;
685   char *p, *pend;
686
687   if (strcmp (str, "") == 0)
688     goto empty_list;
689
690   p = str;
691   while (p) {
692     /* Empty last line? */
693     if (p[0] == '\0')
694       break;
695
696     pend = strchr (p, '\n');
697     if (pend) {
698       *pend = '\0';
699       pend++;
700     }
701
702     if (add_string (&lines, &size, &alloc, p) == -1) {
703       return NULL;
704     }
705
706     p = pend;
707   }
708
709  empty_list:
710   if (add_string (&lines, &size, &alloc, NULL) == -1)
711     return NULL;
712
713   return lines;
714 }
715
716 /* printf helper function so we can use %Q ("quoted") and %R to print
717  * shell-quoted strings.  See HACKING file for more details.
718  */
719 static int
720 print_shell_quote (FILE *stream,
721                    const struct printf_info *info,
722                    const void *const *args)
723 {
724 #define SAFE(c) (isalnum((c)) ||                                        \
725                  (c) == '/' || (c) == '-' || (c) == '_' || (c) == '.')
726   int i, len;
727   const char *str = *((const char **) (args[0]));
728
729   for (i = len = 0; str[i]; ++i) {
730     if (!SAFE(str[i])) {
731       putc ('\\', stream);
732       len ++;
733     }
734     putc (str[i], stream);
735     len ++;
736   }
737
738   return len;
739 }
740
741 static int
742 print_sysroot_shell_quote (FILE *stream,
743                            const struct printf_info *info,
744                            const void *const *args)
745 {
746 #define SAFE(c) (isalnum((c)) ||                                        \
747                  (c) == '/' || (c) == '-' || (c) == '_' || (c) == '.')
748   fputs (sysroot, stream);
749   return sysroot_len + print_shell_quote (stream, info, args);
750 }
751
752 #ifdef HAVE_REGISTER_PRINTF_SPECIFIER
753 static int
754 print_arginfo (const struct printf_info *info,
755                size_t n, int *argtypes, int *size)
756 {
757   if (n > 0) {
758     argtypes[0] = PA_STRING;
759     size[0] = sizeof (const char *);
760   }
761   return 1;
762 }
763 #else
764 #ifdef HAVE_REGISTER_PRINTF_FUNCTION
765 static int
766 print_arginfo (const struct printf_info *info, size_t n, int *argtypes)
767 {
768   if (n > 0)
769     argtypes[0] = PA_STRING;
770   return 1;
771 }
772 #else
773 #error "HAVE_REGISTER_PRINTF_{SPECIFIER|FUNCTION} not defined"
774 #endif
775 #endif
776
777 /* Perform device name translation.  Don't call this directly -
778  * use the IS_DEVICE macro.
779  *
780  * See guestfs(3) for the algorithm.
781  *
782  * We have to open the device and test for ENXIO, because
783  * the device nodes themselves will exist in the appliance.
784  */
785 int
786 device_name_translation (char *device, const char *func)
787 {
788   int fd;
789
790   fd = open (device, O_RDONLY);
791   if (fd >= 0) {
792     close (fd);
793     return 0;
794   }
795
796   if (errno != ENXIO && errno != ENOENT) {
797   error:
798     reply_with_perror ("%s: %s", func, device);
799     return -1;
800   }
801
802   /* If the name begins with "/dev/sd" then try the alternatives. */
803   if (strncmp (device, "/dev/sd", 7) != 0)
804     goto error;
805
806   device[5] = 'h';              /* /dev/hd (old IDE driver) */
807   fd = open (device, O_RDONLY);
808   if (fd >= 0) {
809     close (fd);
810     return 0;
811   }
812
813   device[5] = 'v';              /* /dev/vd (for virtio devices) */
814   fd = open (device, O_RDONLY);
815   if (fd >= 0) {
816     close (fd);
817     return 0;
818   }
819
820   device[5] = 's';              /* Restore original device name. */
821   goto error;
822 }
823
824 /* LVM and other commands aren't synchronous, especially when udev is
825  * involved.  eg. You can create or remove some device, but the /dev
826  * device node won't appear until some time later.  This means that
827  * you get an error if you run one command followed by another.
828  * Use 'udevadm settle' after certain commands, but don't be too
829  * fussed if it fails.
830  */
831 void
832 udev_settle (void)
833 {
834   command (NULL, NULL, "/sbin/udevadm", "settle", NULL);
835 }