a9576836b0d7ea35339933f68cb9a8cef29888ef
[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
36 #include "daemon.h"
37
38 static void usage (void);
39
40 /* Also in guestfs.c */
41 #define VMCHANNEL_PORT "6666"
42 #define VMCHANNEL_ADDR "10.0.2.4"
43
44 int verbose = 0;
45
46 int
47 main (int argc, char *argv[])
48 {
49   static const char *options = "fh:p:?";
50   static struct option long_options[] = {
51     { "foreground", 0, 0, 'f' },
52     { "help", 0, 0, '?' },
53     { "host", 1, 0, 'h' },
54     { "port", 1, 0, 'p' },
55     { 0, 0, 0, 0 }
56   };
57   int c, n, r;
58   int dont_fork = 0;
59   const char *host = NULL;
60   const char *port = NULL;
61   FILE *fp;
62   char buf[4096];
63   char *p, *p2;
64   int sock;
65   struct addrinfo *res, *rr;
66   struct addrinfo hints;
67   XDR xdr;
68   uint32_t len;
69
70   for (;;) {
71     c = getopt_long (argc, argv, options, long_options, NULL);
72     if (c == -1) break;
73
74     switch (c) {
75     case 'f':
76       dont_fork = 1;
77       break;
78
79     case 'h':
80       host = optarg;
81       break;
82
83     case 'p':
84       port = optarg;
85       break;
86
87     case '?':
88       usage ();
89       exit (0);
90
91     default:
92       fprintf (stderr, "guestfsd: unexpected command line option 0x%x\n", c);
93       exit (1);
94     }
95   }
96
97   if (optind < argc) {
98     usage ();
99     exit (1);
100   }
101
102   /* If host and port aren't set yet, try /proc/cmdline. */
103   if (!host || !port) {
104     fp = fopen ("/proc/cmdline", "r");
105     if (fp == NULL) {
106       perror ("/proc/cmdline");
107       goto next;
108     }
109     n = fread (buf, 1, sizeof buf - 1, fp);
110     fclose (fp);
111     buf[n] = '\0';
112
113     /* Set the verbose flag.  Not quite right because this will only
114      * set the flag if host and port aren't set on the command line.
115      * Don't worry about this for now. (XXX)
116      */
117     verbose = strstr (buf, "guestfs_verbose=1") != NULL;
118     if (verbose)
119       printf ("verbose daemon enabled\n");
120
121     p = strstr (buf, "guestfs=");
122
123     if (p) {
124       p += 8;
125       p2 = strchr (p, ':');
126       if (p2) {
127         *p2++ = '\0';
128         host = p;
129         r = strcspn (p2, " \n");
130         p2[r] = '\0';
131         port = p2;
132       }
133     }
134   }
135
136  next:
137   /* Can't parse /proc/cmdline, so use built-in defaults. */
138   if (!host || !port) {
139     host = VMCHANNEL_ADDR;
140     port = VMCHANNEL_PORT;
141   }
142
143   /* Resolve the hostname. */
144   memset (&hints, 0, sizeof hints);
145   hints.ai_socktype = SOCK_STREAM;
146   hints.ai_flags = AI_ADDRCONFIG;
147   r = getaddrinfo (host, port, &hints, &res);
148   if (r != 0) {
149     fprintf (stderr, "%s:%s: %s\n", host, port, gai_strerror (r));
150     exit (1);
151   }
152
153   /* Connect to the given TCP socket. */
154   sock = -1;
155   for (rr = res; rr != NULL; rr = rr->ai_next) {
156     sock = socket (rr->ai_family, rr->ai_socktype, rr->ai_protocol);
157     if (sock != -1) {
158       if (connect (sock, rr->ai_addr, rr->ai_addrlen) == 0)
159         break;
160       perror ("connect");
161
162       close (sock);
163       sock = -1;
164     }
165   }
166   freeaddrinfo (res);
167
168   if (sock == -1) {
169     fprintf (stderr, "connection to %s:%s failed\n", host, port);
170     exit (1);
171   }
172
173   /* Send the magic length message which indicates that
174    * userspace is up inside the guest.
175    */
176   len = GUESTFS_LAUNCH_FLAG;
177   xdrmem_create (&xdr, buf, sizeof buf, XDR_ENCODE);
178   if (!xdr_uint32_t (&xdr, &len)) {
179     fprintf (stderr, "xdr_uint32_t failed\n");
180     exit (1);
181   }
182
183   (void) xwrite (sock, buf, xdr_getpos (&xdr));
184
185   xdr_destroy (&xdr);
186
187   /* Fork into the background. */
188   if (!dont_fork) {
189     if (daemon (0, 1) == -1) {
190       perror ("daemon");
191       exit (1);
192     }
193   }
194
195   /* Enter the main loop, reading and performing actions. */
196   main_loop (sock);
197
198   exit (0);
199 }
200
201 int
202 xwrite (int sock, const void *buf, size_t len)
203 {
204   int r;
205
206   while (len > 0) {
207     r = write (sock, buf, len);
208     if (r == -1) {
209       perror ("write");
210       return -1;
211     }
212     buf += r;
213     len -= r;
214   }
215
216   return 0;
217 }
218
219 int
220 xread (int sock, void *buf, size_t len)
221 {
222   int r;
223
224   while (len > 0) {
225     r = read (sock, buf, len);
226     if (r == -1) {
227       perror ("read");
228       return -1;
229     }
230     if (r == 0) {
231       fprintf (stderr, "read: unexpected end of file on fd %d\n", sock);
232       return -1;
233     }
234     buf += r;
235     len -= r;
236   }
237
238   return 0;
239 }
240
241 static void
242 usage (void)
243 {
244   fprintf (stderr, "guestfsd [-f] [-h host -p port]\n");
245 }
246
247 int
248 add_string (char ***argv, int *size, int *alloc, const char *str)
249 {
250   char **new_argv;
251   char *new_str;
252
253   if (*size >= *alloc) {
254     *alloc += 64;
255     new_argv = realloc (*argv, *alloc * sizeof (char *));
256     if (new_argv == NULL) {
257       reply_with_perror ("realloc");
258       free_strings (*argv);
259       return -1;
260     }
261     *argv = new_argv;
262   }
263
264   if (str) {
265     new_str = strdup (str);
266     if (new_str == NULL) {
267       reply_with_perror ("strdup");
268       free_strings (*argv);
269     }
270   } else
271     new_str = NULL;
272
273   (*argv)[*size] = new_str;
274
275   (*size)++;
276   return 0;
277 }
278
279 int
280 count_strings (char * const* const argv)
281 {
282   int argc;
283
284   for (argc = 0; argv[argc] != NULL; ++argc)
285     ;
286   return argc;
287 }
288
289 static int
290 compare (const void *vp1, const void *vp2)
291 {
292   char * const *p1 = (char * const *) vp1;
293   char * const *p2 = (char * const *) vp2;
294   return strcmp (*p1, *p2);
295 }
296
297 void
298 sort_strings (char **argv, int len)
299 {
300   qsort (argv, len, sizeof (char *), compare);
301 }
302
303 void
304 free_strings (char **argv)
305 {
306   int argc;
307
308   for (argc = 0; argv[argc] != NULL; ++argc)
309     free (argv[argc]);
310   free (argv);
311 }
312
313 void
314 free_stringslen (char **argv, int len)
315 {
316   int i;
317
318   for (i = 0; i < len; ++i)
319     free (argv[i]);
320   free (argv);
321 }
322
323 /* This is a more sane version of 'system(3)' for running external
324  * commands.  It uses fork/execvp, so we don't need to worry about
325  * quoting of parameters, and it allows us to capture any error
326  * messages in a buffer.
327  */
328 int
329 command (char **stdoutput, char **stderror, const char *name, ...)
330 {
331   va_list args;
332   char **argv;
333   char *s;
334   int i, r;
335
336   /* Collect the command line arguments into an array. */
337   va_start (args, name);
338
339   i = 2;
340   argv = malloc (sizeof (char *) * i);
341   argv[0] = (char *) name;
342   argv[1] = NULL;
343
344   while ((s = va_arg (args, char *)) != NULL) {
345     argv = realloc (argv, sizeof (char *) * (++i));
346     argv[i-2] = s;
347     argv[i-1] = NULL;
348   }
349
350   va_end (args);
351
352   r = commandv (stdoutput, stderror, argv);
353
354   /* NB: Mustn't free the strings which are on the stack. */
355   free (argv);
356
357   return r;
358 }
359
360 int
361 commandv (char **stdoutput, char **stderror, char * const* const argv)
362 {
363   int so_size = 0, se_size = 0;
364   int so_fd[2], se_fd[2];
365   int pid, r, quit, i;
366   fd_set rset, rset2;
367   char buf[256];
368
369   if (stdoutput) *stdoutput = NULL;
370   if (stderror) *stderror = NULL;
371
372   if (verbose) {
373     printf ("%s", argv[0]);
374     for (i = 1; argv[i] != NULL; ++i)
375       printf (" %s", argv[i]);
376     printf ("\n");
377   }
378
379   if (pipe (so_fd) == -1 || pipe (se_fd) == -1) {
380     perror ("pipe");
381     return -1;
382   }
383
384   pid = fork ();
385   if (pid == -1) {
386     perror ("fork");
387     close (so_fd[0]);
388     close (so_fd[1]);
389     close (se_fd[0]);
390     close (se_fd[1]);
391     return -1;
392   }
393
394   if (pid == 0) {               /* Child process. */
395     close (0);
396     close (so_fd[0]);
397     close (se_fd[0]);
398     dup2 (so_fd[1], 1);
399     dup2 (se_fd[1], 2);
400     close (so_fd[1]);
401     close (se_fd[1]);
402
403     execvp (argv[0], argv);
404     perror (argv[0]);
405     _exit (1);
406   }
407
408   /* Parent process. */
409   close (so_fd[1]);
410   close (se_fd[1]);
411
412   FD_ZERO (&rset);
413   FD_SET (so_fd[0], &rset);
414   FD_SET (se_fd[0], &rset);
415
416   quit = 0;
417   while (quit < 2) {
418     rset2 = rset;
419     r = select (MAX (so_fd[0], se_fd[0]) + 1, &rset2, NULL, NULL, NULL);
420     if (r == -1) {
421       perror ("select");
422       close (so_fd[0]);
423       close (se_fd[0]);
424       waitpid (pid, NULL, 0);
425       return -1;
426     }
427
428     if (FD_ISSET (so_fd[0], &rset2)) { /* something on stdout */
429       r = read (so_fd[0], buf, sizeof buf);
430       if (r == -1) {
431         perror ("read");
432         close (so_fd[0]);
433         close (se_fd[0]);
434         waitpid (pid, NULL, 0);
435         return -1;
436       }
437       if (r == 0) { FD_CLR (so_fd[0], &rset); quit++; }
438
439       if (r > 0 && stdoutput) {
440         so_size += r;
441         *stdoutput = realloc (*stdoutput, so_size);
442         if (*stdoutput == NULL) {
443           perror ("realloc");
444           *stdoutput = NULL;
445           continue;
446         }
447         memcpy (*stdoutput + so_size - r, buf, r);
448       }
449     }
450
451     if (FD_ISSET (se_fd[0], &rset2)) { /* something on stderr */
452       r = read (se_fd[0], buf, sizeof buf);
453       if (r == -1) {
454         perror ("read");
455         close (so_fd[0]);
456         close (se_fd[0]);
457         waitpid (pid, NULL, 0);
458         return -1;
459       }
460       if (r == 0) { FD_CLR (se_fd[0], &rset); quit++; }
461
462       if (r > 0 && stderror) {
463         se_size += r;
464         *stderror = realloc (*stderror, se_size);
465         if (*stderror == NULL) {
466           perror ("realloc");
467           *stderror = NULL;
468           continue;
469         }
470         memcpy (*stderror + se_size - r, buf, r);
471       }
472     }
473   }
474
475   close (so_fd[0]);
476   close (se_fd[0]);
477
478   /* Make sure the output buffers are \0-terminated.  Also remove any
479    * trailing \n characters from the error buffer (not from stdout).
480    */
481   if (stdoutput) {
482     *stdoutput = realloc (*stdoutput, so_size+1);
483     if (*stdoutput == NULL) {
484       perror ("realloc");
485       *stdoutput = NULL;
486     } else
487       (*stdoutput)[so_size] = '\0';
488   }
489   if (stderror) {
490     *stderror = realloc (*stderror, se_size+1);
491     if (*stderror == NULL) {
492       perror ("realloc");
493       *stderror = NULL;
494     } else {
495       (*stderror)[se_size] = '\0';
496       se_size--;
497       while (se_size >= 0 && (*stderror)[se_size] == '\n')
498         (*stderror)[se_size--] = '\0';
499     }
500   }
501
502   /* Get the exit status of the command. */
503   waitpid (pid, &r, 0);
504
505   if (WIFEXITED (r)) {
506     if (WEXITSTATUS (r) == 0)
507       return 0;
508     else
509       return -1;
510   } else
511     return -1;
512 }