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