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