810d9d0e8162c1f2cfee5aa0cf2e3d1ace92731f
[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 void xwrite (int sock, const void *buf, size_t len);
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
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   unsigned 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     p = strstr (buf, "guestfs=");
114
115     if (p) {
116       p += 8;
117       p2 = strchr (p, ':');
118       if (p2) {
119         *p2++ = '\0';
120         host = p;
121         r = strcspn (p2, " \n");
122         p2[r] = '\0';
123         port = p2;
124       }
125     }
126   }
127
128  next:
129   /* Can't parse /proc/cmdline, so use built-in defaults. */
130   if (!host || !port) {
131     host = VMCHANNEL_ADDR;
132     port = VMCHANNEL_PORT;
133   }
134
135   /* Resolve the hostname. */
136   memset (&hints, 0, sizeof hints);
137   hints.ai_socktype = SOCK_STREAM;
138   hints.ai_flags = AI_ADDRCONFIG;
139   r = getaddrinfo (host, port, &hints, &res);
140   if (r != 0) {
141     fprintf (stderr, "%s:%s: %s\n", host, port, gai_strerror (r));
142     exit (1);
143   }
144
145   /* Connect to the given TCP socket. */
146   sock = -1;
147   for (rr = res; rr != NULL; rr = rr->ai_next) {
148     sock = socket (rr->ai_family, rr->ai_socktype, rr->ai_protocol);
149     if (sock != -1) {
150       if (connect (sock, rr->ai_addr, rr->ai_addrlen) == 0)
151         break;
152       perror ("connect");
153
154       close (sock);
155       sock = -1;
156     }
157   }
158   freeaddrinfo (res);
159
160   if (sock == -1) {
161     fprintf (stderr, "connection to %s:%s failed\n", host, port);
162     exit (1);
163   }
164
165   /* Send the magic length message which indicates that
166    * userspace is up inside the guest.
167    */
168   len = 0xf5f55ff5;
169   xdrmem_create (&xdr, buf, sizeof buf, XDR_ENCODE);
170   if (!xdr_uint32_t (&xdr, &len)) {
171     fprintf (stderr, "xdr_uint32_t failed\n");
172     exit (1);
173   }
174
175   xwrite (sock, buf, xdr_getpos (&xdr));
176
177   xdr_destroy (&xdr);
178
179   /* Fork into the background. */
180   if (!dont_fork) {
181     if (daemon (0, 1) == -1) {
182       perror ("daemon");
183       exit (1);
184     }
185   }
186
187   /* Enter the main loop, reading and performing actions. */
188   main_loop (sock);
189
190   exit (0);
191 }
192
193 void
194 xwrite (int sock, const void *buf, size_t len)
195 {
196   int r;
197
198   while (len > 0) {
199     r = write (sock, buf, len);
200     if (r == -1) {
201       perror ("write");
202       exit (1);
203     }
204     buf += r;
205     len -= r;
206   }
207 }
208
209 void
210 xread (int sock, void *buf, size_t len)
211 {
212   int r;
213
214   while (len > 0) {
215     r = read (sock, buf, len);
216     if (r == -1) {
217       perror ("read");
218       exit (1);
219     }
220     if (r == 0) {
221       fprintf (stderr, "read: unexpected end of file on comms socket\n");
222       exit (1);
223     }
224     buf += r;
225     len -= r;
226   }
227 }
228
229 static void
230 usage (void)
231 {
232   fprintf (stderr, "guestfsd [-f] [-h host -p port]\n");
233 }
234
235 /* This is a more sane version of 'system(3)' for running external
236  * commands.  It uses fork/execvp, so we don't need to worry about
237  * quoting of parameters, and it allows us to capture any error
238  * messages in a buffer.
239  */
240 int
241 command (char **stdoutput, char **stderror, const char *name, ...)
242 {
243   int so_size = 0, se_size = 0;
244   int so_fd[2], se_fd[2];
245   int pid, r, quit;
246   fd_set rset, rset2;
247   char buf[256];
248
249   if (stdoutput) *stdoutput = NULL;
250   if (stderror) *stderror = NULL;
251
252   if (pipe (so_fd) == -1 || pipe (se_fd) == -1) {
253     perror ("pipe");
254     return -1;
255   }
256
257   pid = fork ();
258   if (pid == -1) {
259     perror ("fork");
260     return -1;
261   }
262
263   if (pid == 0) {               /* Child process. */
264     va_list args;
265     char **argv;
266     char *s;
267     int i;
268
269     /* Collect the command line arguments into an array. */
270     va_start (args, name);
271
272     i = 2;
273     argv = malloc (sizeof (char *) * i);
274     argv[0] = (char *) name;
275     argv[1] = NULL;
276
277     while ((s = va_arg (args, char *)) != NULL) {
278       argv = realloc (argv, sizeof (char *) * (++i));
279       argv[i-2] = s;
280       argv[i-1] = NULL;
281     }
282
283     close (0);
284     close (so_fd[0]);
285     close (se_fd[0]);
286     dup2 (so_fd[1], 1);
287     dup2 (se_fd[1], 2);
288     close (so_fd[1]);
289     close (se_fd[1]);
290
291     execvp (name, argv);
292     perror (name);
293     _exit (1);
294   }
295
296   /* Parent process. */
297   close (so_fd[1]);
298   close (se_fd[1]);
299
300   FD_ZERO (&rset);
301   FD_SET (so_fd[0], &rset);
302   FD_SET (se_fd[0], &rset);
303
304   quit = 0;
305   while (!quit) {
306     rset2 = rset;
307     r = select (MAX (so_fd[0], se_fd[0]) + 1, &rset2, NULL, NULL, NULL);
308     if (r == -1) {
309       perror ("select");
310       waitpid (pid, NULL, 0);
311       return -1;
312     }
313
314     if (FD_ISSET (so_fd[0], &rset2)) { /* something on stdout */
315       r = read (so_fd[0], buf, sizeof buf);
316       if (r == -1) {
317         perror ("read");
318         waitpid (pid, NULL, 0);
319         return -1;
320       }
321       if (r == 0) quit = 1;
322
323       if (r > 0 && stdoutput) {
324         so_size += r;
325         *stdoutput = realloc (*stdoutput, so_size);
326         if (*stdoutput == NULL) {
327           perror ("realloc");
328           *stdoutput = NULL;
329           continue;
330         }
331         memcpy (*stdoutput + so_size - r, buf, r);
332       }
333     }
334
335     if (FD_ISSET (se_fd[0], &rset2)) { /* something on stderr */
336       r = read (se_fd[0], buf, sizeof buf);
337       if (r == -1) {
338         perror ("read");
339         waitpid (pid, NULL, 0);
340         return -1;
341       }
342       if (r == 0) quit = 1;
343
344       if (r > 0 && stderror) {
345         se_size += r;
346         *stderror = realloc (*stderror, se_size);
347         if (*stderror == NULL) {
348           perror ("realloc");
349           *stderror = NULL;
350           continue;
351         }
352         memcpy (*stderror + se_size - r, buf, r);
353       }
354     }
355   }
356
357   /* Make sure the output buffers are \0-terminated.  Also remove any
358    * trailing \n characters.
359    */
360   if (stdoutput) {
361     *stdoutput = realloc (*stdoutput, so_size+1);
362     if (*stdoutput == NULL) {
363       perror ("realloc");
364       *stdoutput = NULL;
365     } else {
366       (*stdoutput)[so_size] = '\0';
367       so_size--;
368       while (so_size >= 0 && (*stdoutput)[so_size] == '\n')
369         (*stdoutput)[so_size--] = '\0';
370     }
371   }
372   if (stderror) {
373     *stderror = realloc (*stderror, se_size+1);
374     if (*stderror == NULL) {
375       perror ("realloc");
376       *stderror = NULL;
377     } else {
378       (*stderror)[se_size] = '\0';
379       se_size--;
380       while (se_size >= 0 && (*stderror)[se_size] == '\n')
381         (*stderror)[se_size--] = '\0';
382     }
383   }
384
385   /* Get the exit status of the command. */
386   waitpid (pid, &r, 0);
387
388   if (WIFEXITED (r)) {
389     if (WEXITSTATUS (r) == 0)
390       return 0;
391     else
392       return -1;
393   } else
394     return -1;
395 }