Fix unchecked malloc & realloc in 'commandv' func (Jim Meyering).
[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 int
382 commandv (char **stdoutput, char **stderror, char * const* const argv)
383 {
384   int so_size = 0, se_size = 0;
385   int so_fd[2], se_fd[2];
386   int pid, r, quit, i;
387   fd_set rset, rset2;
388   char buf[256];
389
390   if (stdoutput) *stdoutput = NULL;
391   if (stderror) *stderror = NULL;
392
393   if (verbose) {
394     printf ("%s", argv[0]);
395     for (i = 1; argv[i] != NULL; ++i)
396       printf (" %s", argv[i]);
397     printf ("\n");
398   }
399
400   if (pipe (so_fd) == -1 || pipe (se_fd) == -1) {
401     perror ("pipe");
402     return -1;
403   }
404
405   pid = fork ();
406   if (pid == -1) {
407     perror ("fork");
408     close (so_fd[0]);
409     close (so_fd[1]);
410     close (se_fd[0]);
411     close (se_fd[1]);
412     return -1;
413   }
414
415   if (pid == 0) {               /* Child process. */
416     close (0);
417     close (so_fd[0]);
418     close (se_fd[0]);
419     dup2 (so_fd[1], 1);
420     dup2 (se_fd[1], 2);
421     close (so_fd[1]);
422     close (se_fd[1]);
423
424     execvp (argv[0], argv);
425     perror (argv[0]);
426     _exit (1);
427   }
428
429   /* Parent process. */
430   close (so_fd[1]);
431   close (se_fd[1]);
432
433   FD_ZERO (&rset);
434   FD_SET (so_fd[0], &rset);
435   FD_SET (se_fd[0], &rset);
436
437   quit = 0;
438   while (quit < 2) {
439     rset2 = rset;
440     r = select (MAX (so_fd[0], se_fd[0]) + 1, &rset2, NULL, NULL, NULL);
441     if (r == -1) {
442       perror ("select");
443       close (so_fd[0]);
444       close (se_fd[0]);
445       waitpid (pid, NULL, 0);
446       return -1;
447     }
448
449     if (FD_ISSET (so_fd[0], &rset2)) { /* something on stdout */
450       r = read (so_fd[0], buf, sizeof buf);
451       if (r == -1) {
452         perror ("read");
453         close (so_fd[0]);
454         close (se_fd[0]);
455         waitpid (pid, NULL, 0);
456         return -1;
457       }
458       if (r == 0) { FD_CLR (so_fd[0], &rset); quit++; }
459
460       if (r > 0 && stdoutput) {
461         so_size += r;
462         *stdoutput = realloc (*stdoutput, so_size);
463         if (*stdoutput == NULL) {
464           perror ("realloc");
465           *stdoutput = NULL;
466           continue;
467         }
468         memcpy (*stdoutput + so_size - r, buf, r);
469       }
470     }
471
472     if (FD_ISSET (se_fd[0], &rset2)) { /* something on stderr */
473       r = read (se_fd[0], buf, sizeof buf);
474       if (r == -1) {
475         perror ("read");
476         close (so_fd[0]);
477         close (se_fd[0]);
478         waitpid (pid, NULL, 0);
479         return -1;
480       }
481       if (r == 0) { FD_CLR (se_fd[0], &rset); quit++; }
482
483       if (r > 0 && stderror) {
484         se_size += r;
485         *stderror = realloc (*stderror, se_size);
486         if (*stderror == NULL) {
487           perror ("realloc");
488           *stderror = NULL;
489           continue;
490         }
491         memcpy (*stderror + se_size - r, buf, r);
492       }
493     }
494   }
495
496   close (so_fd[0]);
497   close (se_fd[0]);
498
499   /* Make sure the output buffers are \0-terminated.  Also remove any
500    * trailing \n characters from the error buffer (not from stdout).
501    */
502   if (stdoutput) {
503     *stdoutput = realloc (*stdoutput, so_size+1);
504     if (*stdoutput == NULL) {
505       perror ("realloc");
506       *stdoutput = NULL;
507     } else
508       (*stdoutput)[so_size] = '\0';
509   }
510   if (stderror) {
511     *stderror = realloc (*stderror, se_size+1);
512     if (*stderror == NULL) {
513       perror ("realloc");
514       *stderror = NULL;
515     } else {
516       (*stderror)[se_size] = '\0';
517       se_size--;
518       while (se_size >= 0 && (*stderror)[se_size] == '\n')
519         (*stderror)[se_size--] = '\0';
520     }
521   }
522
523   /* Get the exit status of the command. */
524   waitpid (pid, &r, 0);
525
526   if (WIFEXITED (r)) {
527     if (WEXITSTATUS (r) == 0)
528       return 0;
529     else
530       return -1;
531   } else
532     return -1;
533 }
534
535 /* Quote 'in' for the shell, and write max len-1 bytes to out.  The
536  * result will be NUL-terminated, even if it is truncated.
537  *
538  * Returns number of bytes needed, so if result >= len then the buffer
539  * should have been longer.
540  *
541  * XXX This doesn't quote \n correctly (but is still safe).
542  */
543 int
544 shell_quote (char *out, int len, const char *in)
545 {
546 #define SAFE(c) (isalnum((c)) ||                                        \
547                  (c) == '/' || (c) == '-' || (c) == '_' || (c) == '.')
548   int i, j;
549   int outlen = strlen (in);
550
551   /* Calculate how much output space this really needs. */
552   for (i = 0; in[i]; ++i)
553     if (!SAFE (in[i])) outlen++;
554
555   /* Now copy the string, but only up to len-1 bytes. */
556   for (i = 0, j = 0; in[i]; ++i) {
557     int is_safe = SAFE (in[i]);
558
559     /* Enough space left to write this character? */
560     if (j >= len-1 || (!is_safe && j >= len-2))
561       break;
562
563     if (!is_safe) out[j++] = '\\';
564     out[j++] = in[i];
565   }
566
567   out[j] = '\0';
568
569   return outlen;
570 }