Add generated code for 'fsck' command.
[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 #include <ctype.h>
36 #include <signal.h>
37
38 #include "daemon.h"
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 verbose = 0;
47
48 int
49 main (int argc, char *argv[])
50 {
51   static const char *options = "fh:p:?";
52   static struct option long_options[] = {
53     { "foreground", 0, 0, 'f' },
54     { "help", 0, 0, '?' },
55     { "host", 1, 0, 'h' },
56     { "port", 1, 0, 'p' },
57     { 0, 0, 0, 0 }
58   };
59   int c, n, r;
60   int dont_fork = 0;
61   const char *host = NULL;
62   const char *port = NULL;
63   FILE *fp;
64   char buf[4096];
65   char *p, *p2;
66   int sock;
67   struct addrinfo *res, *rr;
68   struct addrinfo hints;
69   XDR xdr;
70   uint32_t len;
71   struct sigaction sa;
72
73   for (;;) {
74     c = getopt_long (argc, argv, options, long_options, NULL);
75     if (c == -1) break;
76
77     switch (c) {
78     case 'f':
79       dont_fork = 1;
80       break;
81
82     case 'h':
83       host = optarg;
84       break;
85
86     case 'p':
87       port = optarg;
88       break;
89
90     case '?':
91       usage ();
92       exit (0);
93
94     default:
95       fprintf (stderr, "guestfsd: unexpected command line option 0x%x\n", c);
96       exit (1);
97     }
98   }
99
100   if (optind < argc) {
101     usage ();
102     exit (1);
103   }
104
105   /* If host and port aren't set yet, try /proc/cmdline. */
106   if (!host || !port) {
107     fp = fopen ("/proc/cmdline", "r");
108     if (fp == NULL) {
109       perror ("/proc/cmdline");
110       goto next;
111     }
112     n = fread (buf, 1, sizeof buf - 1, fp);
113     fclose (fp);
114     buf[n] = '\0';
115
116     /* Set the verbose flag.  Not quite right because this will only
117      * set the flag if host and port aren't set on the command line.
118      * Don't worry about this for now. (XXX)
119      */
120     verbose = strstr (buf, "guestfs_verbose=1") != NULL;
121     if (verbose)
122       printf ("verbose daemon enabled\n");
123
124     p = strstr (buf, "guestfs=");
125
126     if (p) {
127       p += 8;
128       p2 = strchr (p, ':');
129       if (p2) {
130         *p2++ = '\0';
131         host = p;
132         r = strcspn (p2, " \n");
133         p2[r] = '\0';
134         port = p2;
135       }
136     }
137   }
138
139  next:
140   /* Can't parse /proc/cmdline, so use built-in defaults. */
141   if (!host || !port) {
142     host = VMCHANNEL_ADDR;
143     port = VMCHANNEL_PORT;
144   }
145
146   /* Make sure SIGPIPE doesn't kill us. */
147   memset (&sa, 0, sizeof sa);
148   sa.sa_handler = SIG_IGN;
149   sa.sa_flags = 0;
150   if (sigaction (SIGPIPE, &sa, NULL) == -1)
151     perror ("sigaction SIGPIPE"); /* but try to continue anyway ... */
152
153   /* Resolve the hostname. */
154   memset (&hints, 0, sizeof hints);
155   hints.ai_socktype = SOCK_STREAM;
156   hints.ai_flags = AI_ADDRCONFIG;
157   r = getaddrinfo (host, port, &hints, &res);
158   if (r != 0) {
159     fprintf (stderr, "%s:%s: %s\n", host, port, gai_strerror (r));
160     exit (1);
161   }
162
163   /* Connect to the given TCP socket. */
164   sock = -1;
165   for (rr = res; rr != NULL; rr = rr->ai_next) {
166     sock = socket (rr->ai_family, rr->ai_socktype, rr->ai_protocol);
167     if (sock != -1) {
168       if (connect (sock, rr->ai_addr, rr->ai_addrlen) == 0)
169         break;
170       perror ("connect");
171
172       close (sock);
173       sock = -1;
174     }
175   }
176   freeaddrinfo (res);
177
178   if (sock == -1) {
179     fprintf (stderr, "connection to %s:%s failed\n", host, port);
180     exit (1);
181   }
182
183   /* Send the magic length message which indicates that
184    * userspace is up inside the guest.
185    */
186   len = GUESTFS_LAUNCH_FLAG;
187   xdrmem_create (&xdr, buf, sizeof buf, XDR_ENCODE);
188   if (!xdr_uint32_t (&xdr, &len)) {
189     fprintf (stderr, "xdr_uint32_t failed\n");
190     exit (1);
191   }
192
193   (void) xwrite (sock, buf, xdr_getpos (&xdr));
194
195   xdr_destroy (&xdr);
196
197   /* Fork into the background. */
198   if (!dont_fork) {
199     if (daemon (0, 1) == -1) {
200       perror ("daemon");
201       exit (1);
202     }
203   }
204
205   /* Enter the main loop, reading and performing actions. */
206   main_loop (sock);
207
208   exit (0);
209 }
210
211 int
212 xwrite (int sock, const void *buf, size_t len)
213 {
214   int r;
215
216   while (len > 0) {
217     r = write (sock, buf, len);
218     if (r == -1) {
219       perror ("write");
220       return -1;
221     }
222     buf += r;
223     len -= r;
224   }
225
226   return 0;
227 }
228
229 int
230 xread (int sock, void *buf, size_t len)
231 {
232   int r;
233
234   while (len > 0) {
235     r = read (sock, buf, len);
236     if (r == -1) {
237       perror ("read");
238       return -1;
239     }
240     if (r == 0) {
241       fprintf (stderr, "read: unexpected end of file on fd %d\n", sock);
242       return -1;
243     }
244     buf += r;
245     len -= r;
246   }
247
248   return 0;
249 }
250
251 static void
252 usage (void)
253 {
254   fprintf (stderr, "guestfsd [-f] [-h host -p port]\n");
255 }
256
257 int
258 add_string (char ***argv, int *size, int *alloc, const char *str)
259 {
260   char **new_argv;
261   char *new_str;
262
263   if (*size >= *alloc) {
264     *alloc += 64;
265     new_argv = realloc (*argv, *alloc * sizeof (char *));
266     if (new_argv == NULL) {
267       reply_with_perror ("realloc");
268       free_strings (*argv);
269       return -1;
270     }
271     *argv = new_argv;
272   }
273
274   if (str) {
275     new_str = strdup (str);
276     if (new_str == NULL) {
277       reply_with_perror ("strdup");
278       free_strings (*argv);
279     }
280   } else
281     new_str = NULL;
282
283   (*argv)[*size] = new_str;
284
285   (*size)++;
286   return 0;
287 }
288
289 int
290 count_strings (char * const* const argv)
291 {
292   int argc;
293
294   for (argc = 0; argv[argc] != NULL; ++argc)
295     ;
296   return argc;
297 }
298
299 static int
300 compare (const void *vp1, const void *vp2)
301 {
302   char * const *p1 = (char * const *) vp1;
303   char * const *p2 = (char * const *) vp2;
304   return strcmp (*p1, *p2);
305 }
306
307 void
308 sort_strings (char **argv, int len)
309 {
310   qsort (argv, len, sizeof (char *), compare);
311 }
312
313 void
314 free_strings (char **argv)
315 {
316   int argc;
317
318   for (argc = 0; argv[argc] != NULL; ++argc)
319     free (argv[argc]);
320   free (argv);
321 }
322
323 void
324 free_stringslen (char **argv, int len)
325 {
326   int i;
327
328   for (i = 0; i < len; ++i)
329     free (argv[i]);
330   free (argv);
331 }
332
333 /* This is a more sane version of 'system(3)' for running external
334  * commands.  It uses fork/execvp, so we don't need to worry about
335  * quoting of parameters, and it allows us to capture any error
336  * messages in a buffer.
337  */
338 int
339 command (char **stdoutput, char **stderror, const char *name, ...)
340 {
341   va_list args;
342   char **argv, **p;
343   char *s;
344   int i, r;
345
346   /* Collect the command line arguments into an array. */
347   i = 2;
348   argv = malloc (sizeof (char *) * i);
349   if (argv == NULL) {
350     perror ("malloc");
351     return -1;
352   }
353   argv[0] = (char *) name;
354   argv[1] = NULL;
355
356   va_start (args, name);
357
358   while ((s = va_arg (args, char *)) != NULL) {
359     p = realloc (argv, sizeof (char *) * (++i));
360     if (p == NULL) {
361       perror ("realloc");
362       free (argv);
363       va_end (args);
364       return -1;
365     }
366     argv = p;
367     argv[i-2] = s;
368     argv[i-1] = NULL;
369   }
370
371   va_end (args);
372
373   r = commandv (stdoutput, stderror, argv);
374
375   /* NB: Mustn't free the strings which are on the stack. */
376   free (argv);
377
378   return r;
379 }
380
381 /* Same as 'command', but we allow the status code from the
382  * subcommand to be non-zero, and return that status code.
383  * We still return -1 if there was some other error.
384  */
385 int
386 commandr (char **stdoutput, char **stderror, const char *name, ...)
387 {
388   va_list args;
389   char **argv, **p;
390   char *s;
391   int i, r;
392
393   /* Collect the command line arguments into an array. */
394   i = 2;
395   argv = malloc (sizeof (char *) * i);
396   if (argv == NULL) {
397     perror ("malloc");
398     return -1;
399   }
400   argv[0] = (char *) name;
401   argv[1] = NULL;
402
403   va_start (args, name);
404
405   while ((s = va_arg (args, char *)) != NULL) {
406     p = realloc (argv, sizeof (char *) * (++i));
407     if (p == NULL) {
408       perror ("realloc");
409       free (argv);
410       va_end (args);
411       return -1;
412     }
413     argv = p;
414     argv[i-2] = s;
415     argv[i-1] = NULL;
416   }
417
418   va_end (args);
419
420   r = commandrv (stdoutput, stderror, argv);
421
422   /* NB: Mustn't free the strings which are on the stack. */
423   free (argv);
424
425   return r;
426 }
427
428 /* Same as 'command', but passing an argv. */
429 int
430 commandv (char **stdoutput, char **stderror, char * const* const argv)
431 {
432   int r;
433
434   r = commandrv (stdoutput, stderror, argv);
435   if (r == 0)
436     return 0;
437   else
438     return -1;
439 }
440
441 int
442 commandrv (char **stdoutput, char **stderror, char * const* const argv)
443 {
444   int so_size = 0, se_size = 0;
445   int so_fd[2], se_fd[2];
446   int pid, r, quit, i;
447   fd_set rset, rset2;
448   char buf[256];
449
450   if (stdoutput) *stdoutput = NULL;
451   if (stderror) *stderror = NULL;
452
453   if (verbose) {
454     printf ("%s", argv[0]);
455     for (i = 1; argv[i] != NULL; ++i)
456       printf (" %s", argv[i]);
457     printf ("\n");
458   }
459
460   if (pipe (so_fd) == -1 || pipe (se_fd) == -1) {
461     perror ("pipe");
462     return -1;
463   }
464
465   pid = fork ();
466   if (pid == -1) {
467     perror ("fork");
468     close (so_fd[0]);
469     close (so_fd[1]);
470     close (se_fd[0]);
471     close (se_fd[1]);
472     return -1;
473   }
474
475   if (pid == 0) {               /* Child process. */
476     close (0);
477     close (so_fd[0]);
478     close (se_fd[0]);
479     dup2 (so_fd[1], 1);
480     dup2 (se_fd[1], 2);
481     close (so_fd[1]);
482     close (se_fd[1]);
483
484     execvp (argv[0], argv);
485     perror (argv[0]);
486     _exit (1);
487   }
488
489   /* Parent process. */
490   close (so_fd[1]);
491   close (se_fd[1]);
492
493   FD_ZERO (&rset);
494   FD_SET (so_fd[0], &rset);
495   FD_SET (se_fd[0], &rset);
496
497   quit = 0;
498   while (quit < 2) {
499     rset2 = rset;
500     r = select (MAX (so_fd[0], se_fd[0]) + 1, &rset2, NULL, NULL, NULL);
501     if (r == -1) {
502       perror ("select");
503       close (so_fd[0]);
504       close (se_fd[0]);
505       waitpid (pid, NULL, 0);
506       return -1;
507     }
508
509     if (FD_ISSET (so_fd[0], &rset2)) { /* something on stdout */
510       r = read (so_fd[0], buf, sizeof buf);
511       if (r == -1) {
512         perror ("read");
513         close (so_fd[0]);
514         close (se_fd[0]);
515         waitpid (pid, NULL, 0);
516         return -1;
517       }
518       if (r == 0) { FD_CLR (so_fd[0], &rset); quit++; }
519
520       if (r > 0 && stdoutput) {
521         so_size += r;
522         *stdoutput = realloc (*stdoutput, so_size);
523         if (*stdoutput == NULL) {
524           perror ("realloc");
525           *stdoutput = NULL;
526           continue;
527         }
528         memcpy (*stdoutput + so_size - r, buf, r);
529       }
530     }
531
532     if (FD_ISSET (se_fd[0], &rset2)) { /* something on stderr */
533       r = read (se_fd[0], buf, sizeof buf);
534       if (r == -1) {
535         perror ("read");
536         close (so_fd[0]);
537         close (se_fd[0]);
538         waitpid (pid, NULL, 0);
539         return -1;
540       }
541       if (r == 0) { FD_CLR (se_fd[0], &rset); quit++; }
542
543       if (r > 0 && stderror) {
544         se_size += r;
545         *stderror = realloc (*stderror, se_size);
546         if (*stderror == NULL) {
547           perror ("realloc");
548           *stderror = NULL;
549           continue;
550         }
551         memcpy (*stderror + se_size - r, buf, r);
552       }
553     }
554   }
555
556   close (so_fd[0]);
557   close (se_fd[0]);
558
559   /* Make sure the output buffers are \0-terminated.  Also remove any
560    * trailing \n characters from the error buffer (not from stdout).
561    */
562   if (stdoutput) {
563     *stdoutput = realloc (*stdoutput, so_size+1);
564     if (*stdoutput == NULL) {
565       perror ("realloc");
566       *stdoutput = NULL;
567     } else
568       (*stdoutput)[so_size] = '\0';
569   }
570   if (stderror) {
571     *stderror = realloc (*stderror, se_size+1);
572     if (*stderror == NULL) {
573       perror ("realloc");
574       *stderror = NULL;
575     } else {
576       (*stderror)[se_size] = '\0';
577       se_size--;
578       while (se_size >= 0 && (*stderror)[se_size] == '\n')
579         (*stderror)[se_size--] = '\0';
580     }
581   }
582
583   /* Get the exit status of the command. */
584   waitpid (pid, &r, 0);
585
586   if (WIFEXITED (r)) {
587     return WEXITSTATUS (r);
588   } else
589     return -1;
590 }
591
592 /* Quote 'in' for the shell, and write max len-1 bytes to out.  The
593  * result will be NUL-terminated, even if it is truncated.
594  *
595  * Returns number of bytes needed, so if result >= len then the buffer
596  * should have been longer.
597  *
598  * XXX This doesn't quote \n correctly (but is still safe).
599  */
600 int
601 shell_quote (char *out, int len, const char *in)
602 {
603 #define SAFE(c) (isalnum((c)) ||                                        \
604                  (c) == '/' || (c) == '-' || (c) == '_' || (c) == '.')
605   int i, j;
606   int outlen = strlen (in);
607
608   /* Calculate how much output space this really needs. */
609   for (i = 0; in[i]; ++i)
610     if (!SAFE (in[i])) outlen++;
611
612   /* Now copy the string, but only up to len-1 bytes. */
613   for (i = 0, j = 0; in[i]; ++i) {
614     int is_safe = SAFE (in[i]);
615
616     /* Enough space left to write this character? */
617     if (j >= len-1 || (!is_safe && j >= len-2))
618       break;
619
620     if (!is_safe) out[j++] = '\\';
621     out[j++] = in[i];
622   }
623
624   out[j] = '\0';
625
626   return outlen;
627 }