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