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