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