87065b9de30e666555acb72cf06da5bb93e84025
[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   /* We document that umask defaults to 022 (it should be this anyway). */
164   umask (022);
165
166   /* Resolve the hostname. */
167   memset (&hints, 0, sizeof hints);
168   hints.ai_socktype = SOCK_STREAM;
169   hints.ai_flags = AI_ADDRCONFIG;
170   r = getaddrinfo (host, port, &hints, &res);
171   if (r != 0) {
172     fprintf (stderr, "%s:%s: %s\n", host, port, gai_strerror (r));
173     exit (1);
174   }
175
176   /* Connect to the given TCP socket. */
177   sock = -1;
178   for (rr = res; rr != NULL; rr = rr->ai_next) {
179     sock = socket (rr->ai_family, rr->ai_socktype, rr->ai_protocol);
180     if (sock != -1) {
181       if (connect (sock, rr->ai_addr, rr->ai_addrlen) == 0)
182         break;
183       perror ("connect");
184
185       close (sock);
186       sock = -1;
187     }
188   }
189   freeaddrinfo (res);
190
191   if (sock == -1) {
192     fprintf (stderr, "connection to %s:%s failed\n", host, port);
193     exit (1);
194   }
195
196   /* Send the magic length message which indicates that
197    * userspace is up inside the guest.
198    */
199   len = GUESTFS_LAUNCH_FLAG;
200   xdrmem_create (&xdr, buf, sizeof buf, XDR_ENCODE);
201   if (!xdr_uint32_t (&xdr, &len)) {
202     fprintf (stderr, "xdr_uint32_t failed\n");
203     exit (1);
204   }
205
206   (void) xwrite (sock, buf, xdr_getpos (&xdr));
207
208   xdr_destroy (&xdr);
209
210   /* Fork into the background. */
211   if (!dont_fork) {
212     if (daemon (0, 1) == -1) {
213       perror ("daemon");
214       exit (1);
215     }
216   }
217
218   /* Enter the main loop, reading and performing actions. */
219   main_loop (sock);
220
221   exit (0);
222 }
223
224 int
225 xwrite (int sock, const void *buf, size_t len)
226 {
227   int r;
228
229   while (len > 0) {
230     r = write (sock, buf, len);
231     if (r == -1) {
232       perror ("write");
233       return -1;
234     }
235     buf += r;
236     len -= r;
237   }
238
239   return 0;
240 }
241
242 int
243 xread (int sock, void *buf, size_t len)
244 {
245   int r;
246
247   while (len > 0) {
248     r = read (sock, buf, len);
249     if (r == -1) {
250       perror ("read");
251       return -1;
252     }
253     if (r == 0) {
254       fprintf (stderr, "read: unexpected end of file on fd %d\n", sock);
255       return -1;
256     }
257     buf += r;
258     len -= r;
259   }
260
261   return 0;
262 }
263
264 static void
265 usage (void)
266 {
267   fprintf (stderr, "guestfsd [-f] [-h host -p port]\n");
268 }
269
270 int
271 add_string (char ***argv, int *size, int *alloc, const char *str)
272 {
273   char **new_argv;
274   char *new_str;
275
276   if (*size >= *alloc) {
277     *alloc += 64;
278     new_argv = realloc (*argv, *alloc * sizeof (char *));
279     if (new_argv == NULL) {
280       reply_with_perror ("realloc");
281       free_strings (*argv);
282       return -1;
283     }
284     *argv = new_argv;
285   }
286
287   if (str) {
288     new_str = strdup (str);
289     if (new_str == NULL) {
290       reply_with_perror ("strdup");
291       free_strings (*argv);
292     }
293   } else
294     new_str = NULL;
295
296   (*argv)[*size] = new_str;
297
298   (*size)++;
299   return 0;
300 }
301
302 int
303 count_strings (char * const* const argv)
304 {
305   int argc;
306
307   for (argc = 0; argv[argc] != NULL; ++argc)
308     ;
309   return argc;
310 }
311
312 static int
313 compare (const void *vp1, const void *vp2)
314 {
315   char * const *p1 = (char * const *) vp1;
316   char * const *p2 = (char * const *) vp2;
317   return strcmp (*p1, *p2);
318 }
319
320 void
321 sort_strings (char **argv, int len)
322 {
323   qsort (argv, len, sizeof (char *), compare);
324 }
325
326 void
327 free_strings (char **argv)
328 {
329   int argc;
330
331   for (argc = 0; argv[argc] != NULL; ++argc)
332     free (argv[argc]);
333   free (argv);
334 }
335
336 void
337 free_stringslen (char **argv, int len)
338 {
339   int i;
340
341   for (i = 0; i < len; ++i)
342     free (argv[i]);
343   free (argv);
344 }
345
346 /* This is a more sane version of 'system(3)' for running external
347  * commands.  It uses fork/execvp, so we don't need to worry about
348  * quoting of parameters, and it allows us to capture any error
349  * messages in a buffer.
350  */
351 int
352 command (char **stdoutput, char **stderror, const char *name, ...)
353 {
354   va_list args;
355   char **argv, **p;
356   char *s;
357   int i, r;
358
359   /* Collect the command line arguments into an array. */
360   i = 2;
361   argv = malloc (sizeof (char *) * i);
362   if (argv == NULL) {
363     perror ("malloc");
364     return -1;
365   }
366   argv[0] = (char *) name;
367   argv[1] = NULL;
368
369   va_start (args, name);
370
371   while ((s = va_arg (args, char *)) != NULL) {
372     p = realloc (argv, sizeof (char *) * (++i));
373     if (p == NULL) {
374       perror ("realloc");
375       free (argv);
376       va_end (args);
377       return -1;
378     }
379     argv = p;
380     argv[i-2] = s;
381     argv[i-1] = NULL;
382   }
383
384   va_end (args);
385
386   r = commandv (stdoutput, stderror, argv);
387
388   /* NB: Mustn't free the strings which are on the stack. */
389   free (argv);
390
391   return r;
392 }
393
394 /* Same as 'command', but we allow the status code from the
395  * subcommand to be non-zero, and return that status code.
396  * We still return -1 if there was some other error.
397  */
398 int
399 commandr (char **stdoutput, char **stderror, const char *name, ...)
400 {
401   va_list args;
402   char **argv, **p;
403   char *s;
404   int i, r;
405
406   /* Collect the command line arguments into an array. */
407   i = 2;
408   argv = malloc (sizeof (char *) * i);
409   if (argv == NULL) {
410     perror ("malloc");
411     return -1;
412   }
413   argv[0] = (char *) name;
414   argv[1] = NULL;
415
416   va_start (args, name);
417
418   while ((s = va_arg (args, char *)) != NULL) {
419     p = realloc (argv, sizeof (char *) * (++i));
420     if (p == NULL) {
421       perror ("realloc");
422       free (argv);
423       va_end (args);
424       return -1;
425     }
426     argv = p;
427     argv[i-2] = s;
428     argv[i-1] = NULL;
429   }
430
431   va_end (args);
432
433   r = commandrv (stdoutput, stderror, argv);
434
435   /* NB: Mustn't free the strings which are on the stack. */
436   free (argv);
437
438   return r;
439 }
440
441 /* Same as 'command', but passing an argv. */
442 int
443 commandv (char **stdoutput, char **stderror, char * const* const argv)
444 {
445   int r;
446
447   r = commandrv (stdoutput, stderror, argv);
448   if (r == 0)
449     return 0;
450   else
451     return -1;
452 }
453
454 int
455 commandrv (char **stdoutput, char **stderror, char * const* const argv)
456 {
457   int so_size = 0, se_size = 0;
458   int so_fd[2], se_fd[2];
459   pid_t pid;
460   int r, quit, i;
461   fd_set rset, rset2;
462   char buf[256];
463   char *p;
464
465   if (stdoutput) *stdoutput = NULL;
466   if (stderror) *stderror = NULL;
467
468   if (verbose) {
469     printf ("%s", argv[0]);
470     for (i = 1; argv[i] != NULL; ++i)
471       printf (" %s", argv[i]);
472     printf ("\n");
473   }
474
475   if (pipe (so_fd) == -1 || pipe (se_fd) == -1) {
476     perror ("pipe");
477     return -1;
478   }
479
480   pid = fork ();
481   if (pid == -1) {
482     perror ("fork");
483     close (so_fd[0]);
484     close (so_fd[1]);
485     close (se_fd[0]);
486     close (se_fd[1]);
487     return -1;
488   }
489
490   if (pid == 0) {               /* Child process. */
491     close (0);
492     close (so_fd[0]);
493     close (se_fd[0]);
494     dup2 (so_fd[1], 1);
495     dup2 (se_fd[1], 2);
496     close (so_fd[1]);
497     close (se_fd[1]);
498
499     execvp (argv[0], argv);
500     perror (argv[0]);
501     _exit (1);
502   }
503
504   /* Parent process. */
505   close (so_fd[1]);
506   close (se_fd[1]);
507
508   FD_ZERO (&rset);
509   FD_SET (so_fd[0], &rset);
510   FD_SET (se_fd[0], &rset);
511
512   quit = 0;
513   while (quit < 2) {
514     rset2 = rset;
515     r = select (MAX (so_fd[0], se_fd[0]) + 1, &rset2, NULL, NULL, NULL);
516     if (r == -1) {
517       perror ("select");
518     quit:
519       if (stdoutput) free (*stdoutput);
520       if (stderror) free (*stderror);
521       close (so_fd[0]);
522       close (se_fd[0]);
523       waitpid (pid, NULL, 0);
524       return -1;
525     }
526
527     if (FD_ISSET (so_fd[0], &rset2)) { /* something on stdout */
528       r = read (so_fd[0], buf, sizeof buf);
529       if (r == -1) {
530         perror ("read");
531         goto quit;
532       }
533       if (r == 0) { FD_CLR (so_fd[0], &rset); quit++; }
534
535       if (r > 0 && stdoutput) {
536         so_size += r;
537         p = realloc (*stdoutput, so_size);
538         if (p == NULL) {
539           perror ("realloc");
540           goto quit;
541         }
542         *stdoutput = p;
543         memcpy (*stdoutput + so_size - r, buf, r);
544       }
545     }
546
547     if (FD_ISSET (se_fd[0], &rset2)) { /* something on stderr */
548       r = read (se_fd[0], buf, sizeof buf);
549       if (r == -1) {
550         perror ("read");
551         goto quit;
552       }
553       if (r == 0) { FD_CLR (se_fd[0], &rset); quit++; }
554
555       if (r > 0 && stderror) {
556         se_size += r;
557         p = realloc (*stderror, se_size);
558         if (p == NULL) {
559           perror ("realloc");
560           goto quit;
561         }
562         *stderror = p;
563         memcpy (*stderror + se_size - r, buf, r);
564       }
565     }
566   }
567
568   close (so_fd[0]);
569   close (se_fd[0]);
570
571   /* Make sure the output buffers are \0-terminated.  Also remove any
572    * trailing \n characters from the error buffer (not from stdout).
573    */
574   if (stdoutput) {
575     void *q = realloc (*stdoutput, so_size+1);
576     if (q == NULL) {
577       perror ("realloc");
578       free (*stdoutput);
579     }
580     *stdoutput = q;
581     if (*stdoutput)
582       (*stdoutput)[so_size] = '\0';
583   }
584   if (stderror) {
585     void *q = realloc (*stderror, se_size+1);
586     if (q == NULL) {
587       perror ("realloc");
588       free (*stderror);
589     }
590     *stderror = q;
591     if (*stderror) {
592       (*stderror)[se_size] = '\0';
593       se_size--;
594       while (se_size >= 0 && (*stderror)[se_size] == '\n')
595         (*stderror)[se_size--] = '\0';
596     }
597   }
598
599   /* Get the exit status of the command. */
600   if (waitpid (pid, &r, 0) != pid) {
601     perror ("waitpid");
602     return -1;
603   }
604
605   if (WIFEXITED (r)) {
606     return WEXITSTATUS (r);
607   } else
608     return -1;
609 }
610
611 /* Split an output string into a NULL-terminated list of lines.
612  * Typically this is used where we have run an external command
613  * which has printed out a list of things, and we want to return
614  * an actual list.
615  *
616  * The corner cases here are quite tricky.  Note in particular:
617  *
618  *   "" -> []
619  *   "\n" -> [""]
620  *   "a\nb" -> ["a"; "b"]
621  *   "a\nb\n" -> ["a"; "b"]
622  *   "a\nb\n\n" -> ["a"; "b"; ""]
623  *
624  * The original string is written over and destroyed by this
625  * function (which is usually OK because it's the 'out' string
626  * from command()).  You can free the original string, because
627  * add_string() strdups the strings.
628  */
629 char **
630 split_lines (char *str)
631 {
632   char **lines = NULL;
633   int size = 0, alloc = 0;
634   char *p, *pend;
635
636   if (strcmp (str, "") == 0)
637     goto empty_list;
638
639   p = str;
640   while (p) {
641     /* Empty last line? */
642     if (p[0] == '\0')
643       break;
644
645     pend = strchr (p, '\n');
646     if (pend) {
647       *pend = '\0';
648       pend++;
649     }
650
651     if (add_string (&lines, &size, &alloc, p) == -1) {
652       return NULL;
653     }
654
655     p = pend;
656   }
657
658  empty_list:
659   if (add_string (&lines, &size, &alloc, NULL) == -1)
660     return NULL;
661
662   return lines;
663 }
664
665 /* Quote 'in' for the shell, and write max len-1 bytes to out.  The
666  * result will be NUL-terminated, even if it is truncated.
667  *
668  * Returns number of bytes needed, so if result >= len then the buffer
669  * should have been longer.
670  *
671  * XXX This doesn't quote \n correctly (but is still safe).
672  */
673 int
674 shell_quote (char *out, int len, const char *in)
675 {
676 #define SAFE(c) (isalnum((c)) ||                                        \
677                  (c) == '/' || (c) == '-' || (c) == '_' || (c) == '.')
678   int i, j;
679   int outlen = strlen (in);
680
681   /* Calculate how much output space this really needs. */
682   for (i = 0; in[i]; ++i)
683     if (!SAFE (in[i])) outlen++;
684
685   /* Now copy the string, but only up to len-1 bytes. */
686   for (i = 0, j = 0; in[i]; ++i) {
687     int is_safe = SAFE (in[i]);
688
689     /* Enough space left to write this character? */
690     if (j >= len-1 || (!is_safe && j >= len-2))
691       break;
692
693     if (!is_safe) out[j++] = '\\';
694     out[j++] = in[i];
695   }
696
697   out[j] = '\0';
698
699   return outlen;
700 }
701
702 /* Perform device name translation.  Don't call this directly -
703  * use the IS_DEVICE macro.
704  *
705  * See guestfs(3) for the algorithm.
706  *
707  * We have to open the device and test for ENXIO, because
708  * the device nodes themselves will exist in the appliance.
709  */
710 int
711 device_name_translation (char *device, const char *func)
712 {
713   int fd;
714
715   fd = open (device, O_RDONLY);
716   if (fd >= 0) {
717     close (fd);
718     return 0;
719   }
720
721   if (errno != ENXIO && errno != ENOENT) {
722   error:
723     reply_with_perror ("%s: %s", func, device);
724     return -1;
725   }
726
727   /* If the name begins with "/dev/sd" then try the alternatives. */
728   if (strncmp (device, "/dev/sd", 7) != 0)
729     goto error;
730
731   device[5] = 'h';              /* /dev/hd (old IDE driver) */
732   fd = open (device, O_RDONLY);
733   if (fd >= 0) {
734     close (fd);
735     return 0;
736   }
737
738   device[5] = 'v';              /* /dev/vd (for virtio devices) */
739   fd = open (device, O_RDONLY);
740   if (fd >= 0) {
741     close (fd);
742     return 0;
743   }
744
745   device[5] = 's';              /* Restore original device name. */
746   goto error;
747 }
748
749 /* LVM and other commands aren't synchronous, especially when udev is
750  * involved.  eg. You can create or remove some device, but the /dev
751  * device node won't appear until some time later.  This means that
752  * you get an error if you run one command followed by another.
753  * Use 'udevadm settle' after certain commands, but don't be too
754  * fussed if it fails.
755  */
756 void
757 udev_settle (void)
758 {
759   command (NULL, NULL, "/sbin/udevadm", "settle", NULL);
760 }