6730c1d23b3fbeb400f4106a5cb587235ac68910
[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 void
276 free_strings (char **argv)
277 {
278   int argc;
279
280   for (argc = 0; argv[argc] != NULL; ++argc)
281     free (argv[argc]);
282   free (argv);
283 }
284
285 /* This is a more sane version of 'system(3)' for running external
286  * commands.  It uses fork/execvp, so we don't need to worry about
287  * quoting of parameters, and it allows us to capture any error
288  * messages in a buffer.
289  */
290 int
291 command (char **stdoutput, char **stderror, const char *name, ...)
292 {
293   int so_size = 0, se_size = 0;
294   int so_fd[2], se_fd[2];
295   int pid, r, quit;
296   fd_set rset, rset2;
297   char buf[256];
298
299   if (stdoutput) *stdoutput = NULL;
300   if (stderror) *stderror = NULL;
301
302   if (pipe (so_fd) == -1 || pipe (se_fd) == -1) {
303     perror ("pipe");
304     return -1;
305   }
306
307   pid = fork ();
308   if (pid == -1) {
309     perror ("fork");
310     return -1;
311   }
312
313   if (pid == 0) {               /* Child process. */
314     va_list args;
315     char **argv;
316     char *s;
317     int i;
318
319     /* Collect the command line arguments into an array. */
320     va_start (args, name);
321
322     i = 2;
323     argv = malloc (sizeof (char *) * i);
324     argv[0] = (char *) name;
325     argv[1] = NULL;
326
327     while ((s = va_arg (args, char *)) != NULL) {
328       argv = realloc (argv, sizeof (char *) * (++i));
329       argv[i-2] = s;
330       argv[i-1] = NULL;
331     }
332
333     close (0);
334     close (so_fd[0]);
335     close (se_fd[0]);
336     dup2 (so_fd[1], 1);
337     dup2 (se_fd[1], 2);
338     close (so_fd[1]);
339     close (se_fd[1]);
340
341     execvp (name, argv);
342     perror (name);
343     _exit (1);
344   }
345
346   /* Parent process. */
347   close (so_fd[1]);
348   close (se_fd[1]);
349
350   FD_ZERO (&rset);
351   FD_SET (so_fd[0], &rset);
352   FD_SET (se_fd[0], &rset);
353
354   quit = 0;
355   while (!quit) {
356     rset2 = rset;
357     r = select (MAX (so_fd[0], se_fd[0]) + 1, &rset2, NULL, NULL, NULL);
358     if (r == -1) {
359       perror ("select");
360       waitpid (pid, NULL, 0);
361       return -1;
362     }
363
364     if (FD_ISSET (so_fd[0], &rset2)) { /* something on stdout */
365       r = read (so_fd[0], buf, sizeof buf);
366       if (r == -1) {
367         perror ("read");
368         waitpid (pid, NULL, 0);
369         return -1;
370       }
371       if (r == 0) quit = 1;
372
373       if (r > 0 && stdoutput) {
374         so_size += r;
375         *stdoutput = realloc (*stdoutput, so_size);
376         if (*stdoutput == NULL) {
377           perror ("realloc");
378           *stdoutput = NULL;
379           continue;
380         }
381         memcpy (*stdoutput + so_size - r, buf, r);
382       }
383     }
384
385     if (FD_ISSET (se_fd[0], &rset2)) { /* something on stderr */
386       r = read (se_fd[0], buf, sizeof buf);
387       if (r == -1) {
388         perror ("read");
389         waitpid (pid, NULL, 0);
390         return -1;
391       }
392       if (r == 0) quit = 1;
393
394       if (r > 0 && stderror) {
395         se_size += r;
396         *stderror = realloc (*stderror, se_size);
397         if (*stderror == NULL) {
398           perror ("realloc");
399           *stderror = NULL;
400           continue;
401         }
402         memcpy (*stderror + se_size - r, buf, r);
403       }
404     }
405   }
406
407   /* Make sure the output buffers are \0-terminated.  Also remove any
408    * trailing \n characters from the error buffer (not from stdout).
409    */
410   if (stdoutput) {
411     *stdoutput = realloc (*stdoutput, so_size+1);
412     if (*stdoutput == NULL) {
413       perror ("realloc");
414       *stdoutput = NULL;
415     } else
416       (*stdoutput)[so_size] = '\0';
417   }
418   if (stderror) {
419     *stderror = realloc (*stderror, se_size+1);
420     if (*stderror == NULL) {
421       perror ("realloc");
422       *stderror = NULL;
423     } else {
424       (*stderror)[se_size] = '\0';
425       se_size--;
426       while (se_size >= 0 && (*stderror)[se_size] == '\n')
427         (*stderror)[se_size--] = '\0';
428     }
429   }
430
431   /* Get the exit status of the command. */
432   waitpid (pid, &r, 0);
433
434   if (WIFEXITED (r)) {
435     if (WEXITSTATUS (r) == 0)
436       return 0;
437     else
438       return -1;
439   } else
440     return -1;
441 }