'guestfish edit' commands and several bugfixes.
[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   (void) 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 int
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       return -1;
201     }
202     buf += r;
203     len -= r;
204   }
205
206   return 0;
207 }
208
209 int
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       return -1;
219     }
220     if (r == 0) {
221       fprintf (stderr, "read: unexpected end of file on fd %d\n", sock);
222       return -1;
223     }
224     buf += r;
225     len -= r;
226   }
227
228   return 0;
229 }
230
231 static void
232 usage (void)
233 {
234   fprintf (stderr, "guestfsd [-f] [-h host -p port]\n");
235 }
236
237 int
238 add_string (char ***argv, int *size, int *alloc, const char *str)
239 {
240   char **new_argv;
241   char *new_str;
242
243   if (*size >= *alloc) {
244     *alloc += 64;
245     new_argv = realloc (*argv, *alloc * sizeof (char *));
246     if (new_argv == NULL) {
247       reply_with_perror ("realloc");
248       free_strings (*argv);
249       return -1;
250     }
251     *argv = new_argv;
252   }
253
254   if (str) {
255     new_str = strdup (str);
256     if (new_str == NULL) {
257       reply_with_perror ("strdup");
258       free_strings (*argv);
259     }
260   } else
261     new_str = NULL;
262
263   (*argv)[*size] = new_str;
264
265   (*size)++;
266   return 0;
267 }
268
269 int
270 count_strings (char * const* const argv)
271 {
272   int argc;
273
274   for (argc = 0; argv[argc] != NULL; ++argc)
275     ;
276   return argc;
277 }
278
279 static int
280 compare (const void *vp1, const void *vp2)
281 {
282   char * const *p1 = (char * const *) vp1;
283   char * const *p2 = (char * const *) vp2;
284   return strcmp (*p1, *p2);
285 }
286
287 void
288 sort_strings (char **argv, int len)
289 {
290   qsort (argv, len, sizeof (char *), compare);
291 }
292
293 void
294 free_strings (char **argv)
295 {
296   int argc;
297
298   for (argc = 0; argv[argc] != NULL; ++argc)
299     free (argv[argc]);
300   free (argv);
301 }
302
303 void
304 free_stringslen (char **argv, int len)
305 {
306   int i;
307
308   for (i = 0; i < len; ++i)
309     free (argv[i]);
310   free (argv);
311 }
312
313 /* This is a more sane version of 'system(3)' for running external
314  * commands.  It uses fork/execvp, so we don't need to worry about
315  * quoting of parameters, and it allows us to capture any error
316  * messages in a buffer.
317  */
318 int
319 command (char **stdoutput, char **stderror, const char *name, ...)
320 {
321   va_list args;
322   char **argv;
323   char *s;
324   int i, r;
325
326   /* Collect the command line arguments into an array. */
327   va_start (args, name);
328
329   i = 2;
330   argv = malloc (sizeof (char *) * i);
331   argv[0] = (char *) name;
332   argv[1] = NULL;
333
334   while ((s = va_arg (args, char *)) != NULL) {
335     argv = realloc (argv, sizeof (char *) * (++i));
336     argv[i-2] = s;
337     argv[i-1] = NULL;
338   }
339
340   va_end (args);
341
342   r = commandv (stdoutput, stderror, argv);
343
344   /* NB: Mustn't free the strings which are on the stack. */
345   free (argv);
346
347   return r;
348 }
349
350 int
351 commandv (char **stdoutput, char **stderror, char * const* const argv)
352 {
353   int so_size = 0, se_size = 0;
354   int so_fd[2], se_fd[2];
355   int pid, r, quit, i;
356   fd_set rset, rset2;
357   char buf[256];
358
359   if (stdoutput) *stdoutput = NULL;
360   if (stderror) *stderror = NULL;
361
362   printf ("%s", argv[0]);
363   for (i = 1; argv[i] != NULL; ++i)
364     printf (" %s", argv[i]);
365   printf ("\n");
366
367   if (pipe (so_fd) == -1 || pipe (se_fd) == -1) {
368     perror ("pipe");
369     return -1;
370   }
371
372   pid = fork ();
373   if (pid == -1) {
374     perror ("fork");
375     return -1;
376   }
377
378   if (pid == 0) {               /* Child process. */
379     close (0);
380     close (so_fd[0]);
381     close (se_fd[0]);
382     dup2 (so_fd[1], 1);
383     dup2 (se_fd[1], 2);
384     close (so_fd[1]);
385     close (se_fd[1]);
386
387     execvp (argv[0], argv);
388     perror (argv[0]);
389     _exit (1);
390   }
391
392   /* Parent process. */
393   close (so_fd[1]);
394   close (se_fd[1]);
395
396   FD_ZERO (&rset);
397   FD_SET (so_fd[0], &rset);
398   FD_SET (se_fd[0], &rset);
399
400   quit = 0;
401   while (quit < 2) {
402     rset2 = rset;
403     r = select (MAX (so_fd[0], se_fd[0]) + 1, &rset2, NULL, NULL, NULL);
404     if (r == -1) {
405       perror ("select");
406       waitpid (pid, NULL, 0);
407       return -1;
408     }
409
410     if (FD_ISSET (so_fd[0], &rset2)) { /* something on stdout */
411       r = read (so_fd[0], buf, sizeof buf);
412       if (r == -1) {
413         perror ("read");
414         waitpid (pid, NULL, 0);
415         return -1;
416       }
417       if (r == 0) { FD_CLR (so_fd[0], &rset); quit++; }
418
419       if (r > 0 && stdoutput) {
420         so_size += r;
421         *stdoutput = realloc (*stdoutput, so_size);
422         if (*stdoutput == NULL) {
423           perror ("realloc");
424           *stdoutput = NULL;
425           continue;
426         }
427         memcpy (*stdoutput + so_size - r, buf, r);
428       }
429     }
430
431     if (FD_ISSET (se_fd[0], &rset2)) { /* something on stderr */
432       r = read (se_fd[0], buf, sizeof buf);
433       if (r == -1) {
434         perror ("read");
435         waitpid (pid, NULL, 0);
436         return -1;
437       }
438       if (r == 0) { FD_CLR (se_fd[0], &rset); quit++; }
439
440       if (r > 0 && stderror) {
441         se_size += r;
442         *stderror = realloc (*stderror, se_size);
443         if (*stderror == NULL) {
444           perror ("realloc");
445           *stderror = NULL;
446           continue;
447         }
448         memcpy (*stderror + se_size - r, buf, r);
449       }
450     }
451   }
452
453   /* Make sure the output buffers are \0-terminated.  Also remove any
454    * trailing \n characters from the error buffer (not from stdout).
455    */
456   if (stdoutput) {
457     *stdoutput = realloc (*stdoutput, so_size+1);
458     if (*stdoutput == NULL) {
459       perror ("realloc");
460       *stdoutput = NULL;
461     } else
462       (*stdoutput)[so_size] = '\0';
463   }
464   if (stderror) {
465     *stderror = realloc (*stderror, se_size+1);
466     if (*stderror == NULL) {
467       perror ("realloc");
468       *stderror = NULL;
469     } else {
470       (*stderror)[se_size] = '\0';
471       se_size--;
472       while (se_size >= 0 && (*stderror)[se_size] == '\n')
473         (*stderror)[se_size--] = '\0';
474     }
475   }
476
477   /* Get the exit status of the command. */
478   waitpid (pid, &r, 0);
479
480   if (WIFEXITED (r)) {
481     if (WEXITSTATUS (r) == 0)
482       return 0;
483     else
484       return -1;
485   } else
486     return -1;
487 }