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