Many non-daemon functions are now auto-generated.
[libguestfs.git] / src / guestfs.c
1 /* libguestfs
2  * Copyright (C) 2009 Red Hat Inc. 
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library 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 GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  */
18
19 #include <config.h>
20
21 #define _BSD_SOURCE /* for mkdtemp, usleep */
22 #define _GNU_SOURCE /* for vasprintf, GNU strerror_r, strchrnul */
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <stdarg.h>
27 #include <unistd.h>
28 #include <ctype.h>
29 #include <string.h>
30 #include <fcntl.h>
31 #include <time.h>
32 #include <sys/select.h>
33 #include <rpc/types.h>
34 #include <rpc/xdr.h>
35
36 #ifdef HAVE_ERRNO_H
37 #include <errno.h>
38 #endif
39
40 #ifdef HAVE_SYS_TYPES_H
41 #include <sys/types.h>
42 #endif
43
44 #ifdef HAVE_SYS_WAIT_H
45 #include <sys/wait.h>
46 #endif
47
48 #ifdef HAVE_SYS_SOCKET_H
49 #include <sys/socket.h>
50 #endif
51
52 #ifdef HAVE_SYS_UN_H
53 #include <sys/un.h>
54 #endif
55
56 #include "guestfs.h"
57 #include "guestfs_protocol.h"
58
59 static void error (guestfs_h *g, const char *fs, ...);
60 static void perrorf (guestfs_h *g, const char *fs, ...);
61 static void *safe_malloc (guestfs_h *g, size_t nbytes);
62 static void *safe_realloc (guestfs_h *g, void *ptr, int nbytes);
63 static char *safe_strdup (guestfs_h *g, const char *str);
64 static void *safe_memdup (guestfs_h *g, void *ptr, size_t size);
65
66 static void default_error_cb (guestfs_h *g, void *data, const char *msg);
67 static void stdout_event (void *data, int watch, int fd, int events);
68 static void sock_read_event (void *data, int watch, int fd, int events);
69 static void sock_write_event (void *data, int watch, int fd, int events);
70
71 static void close_handles (void);
72
73 static int select_add_handle (guestfs_h *g, int fd, int events, guestfs_handle_event_cb cb, void *data);
74 static int select_remove_handle (guestfs_h *g, int watch);
75 static int select_add_timeout (guestfs_h *g, int interval, guestfs_handle_timeout_cb cb, void *data);
76 static int select_remove_timeout (guestfs_h *g, int timer);
77 static void select_main_loop_run (guestfs_h *g);
78 static void select_main_loop_quit (guestfs_h *g);
79
80 #define UNIX_PATH_MAX 108
81
82 /* Also in guestfsd.c */
83 #define VMCHANNEL_PORT 6666
84 #define VMCHANNEL_ADDR "10.0.2.4"
85
86 /* Current main loop. */
87 static guestfs_main_loop main_loop = {
88   .add_handle = select_add_handle,
89   .remove_handle = select_remove_handle,
90   .add_timeout = select_add_timeout,
91   .remove_timeout = select_remove_timeout,
92   .main_loop_run = select_main_loop_run,
93   .main_loop_quit = select_main_loop_quit,
94 };
95
96 /* GuestFS handle and connection. */
97 enum state { CONFIG, LAUNCHING, READY, BUSY, NO_HANDLE };
98
99 struct guestfs_h
100 {
101   struct guestfs_h *next;       /* Linked list of open handles. */
102
103   /* State: see the state machine diagram in the man page guestfs(3). */
104   enum state state;
105
106   int fd[2];                    /* Stdin/stdout of qemu. */
107   int sock;                     /* Daemon communications socket. */
108   int pid;                      /* Qemu PID. */
109   time_t start_t;               /* The time when we started qemu. */
110
111   int stdout_watch;             /* Watches qemu stdout for log messages. */
112   int sock_watch;               /* Watches daemon comm socket. */
113
114   char *tmpdir;                 /* Temporary directory containing socket. */
115
116   char **cmdline;               /* Qemu command line. */
117   int cmdline_size;
118
119   int verbose;
120   int autosync;
121
122   const char *path;
123
124   /* Callbacks. */
125   guestfs_abort_cb           abort_cb;
126   guestfs_error_handler_cb   error_cb;
127   void *                     error_cb_data;
128   guestfs_reply_cb           reply_cb;
129   void *                     reply_cb_data;
130   guestfs_log_message_cb     log_message_cb;
131   void *                     log_message_cb_data;
132   guestfs_subprocess_quit_cb subprocess_quit_cb;
133   void *                     subprocess_quit_cb_data;
134   guestfs_launch_done_cb     launch_done_cb;
135   void *                     launch_done_cb_data;
136
137   /* These callbacks are called before reply_cb and launch_done_cb,
138    * and are used to implement the high-level API without needing to
139    * interfere with callbacks that the user might have set.
140    */
141   guestfs_reply_cb           reply_cb_internal;
142   void *                     reply_cb_internal_data;
143   guestfs_launch_done_cb     launch_done_cb_internal;
144   void *                     launch_done_cb_internal_data;
145
146   /* Messages sent and received from the daemon. */
147   char *msg_in;
148   int msg_in_size, msg_in_allocated;
149   char *msg_out;
150   int msg_out_size, msg_out_pos;
151
152   int msg_next_serial;
153 };
154
155 static guestfs_h *handles = NULL;
156 static int atexit_handler_set = 0;
157
158 guestfs_h *
159 guestfs_create (void)
160 {
161   guestfs_h *g;
162   const char *str;
163
164   g = malloc (sizeof (*g));
165   if (!g) return NULL;
166
167   memset (g, 0, sizeof (*g));
168
169   g->state = CONFIG;
170
171   g->fd[0] = -1;
172   g->fd[1] = -1;
173   g->sock = -1;
174   g->stdout_watch = -1;
175   g->sock_watch = -1;
176
177   g->abort_cb = abort;
178   g->error_cb = default_error_cb;
179   g->error_cb_data = NULL;
180
181   str = getenv ("LIBGUESTFS_DEBUG");
182   g->verbose = str != NULL && strcmp (str, "1") == 0;
183
184   str = getenv ("LIBGUESTFS_PATH");
185   g->path = str != NULL ? str : GUESTFS_DEFAULT_PATH;
186   /* XXX We should probably make QEMU configurable as well. */
187
188   /* Start with large serial numbers so they are easy to spot
189    * inside the protocol.
190    */
191   g->msg_next_serial = 0x00123400;
192
193   /* Link the handles onto a global list.  This is the one area
194    * where the library needs to be made thread-safe. (XXX)
195    */
196   /* acquire mutex (XXX) */
197   g->next = handles;
198   handles = g;
199   if (!atexit_handler_set) {
200     atexit (close_handles);
201     atexit_handler_set = 1;
202   }
203   /* release mutex (XXX) */
204
205   if (g->verbose)
206     fprintf (stderr, "new guestfs handle %p\n", g);
207
208   return g;
209 }
210
211 void
212 guestfs_close (guestfs_h *g)
213 {
214   int i;
215   char filename[256];
216   guestfs_h *gg;
217
218   if (g->state == NO_HANDLE) {
219     /* Not safe to call 'error' here, so ... */
220     fprintf (stderr, "guestfs_close: called twice on the same handle\n");
221     return;
222   }
223
224   if (g->verbose)
225     fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
226
227   /* Try to sync if autosync flag is set. */
228   if (g->autosync && g->state == READY)
229     guestfs_sync (g);
230
231   /* Remove any handlers that might be called back before we kill the
232    * subprocess.
233    */
234   g->log_message_cb = NULL;
235
236   if (g->state != CONFIG)
237     guestfs_kill_subprocess (g);
238
239   if (g->tmpdir) {
240     snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
241     unlink (filename);
242
243     rmdir (g->tmpdir);
244
245     free (g->tmpdir);
246   }
247
248   if (g->cmdline) {
249     for (i = 0; i < g->cmdline_size; ++i)
250       free (g->cmdline[i]);
251     free (g->cmdline);
252   }
253
254   /* Mark the handle as dead before freeing it. */
255   g->state = NO_HANDLE;
256
257   /* acquire mutex (XXX) */
258   if (handles == g)
259     handles = g->next;
260   else {
261     for (gg = handles; gg->next != g; gg = gg->next)
262       ;
263     gg->next = g->next;
264   }
265   /* release mutex (XXX) */
266
267   free (g);
268 }
269
270 /* Close all open handles (called from atexit(3)). */
271 static void
272 close_handles (void)
273 {
274   while (handles) guestfs_close (handles);
275 }
276
277 static void
278 default_error_cb (guestfs_h *g, void *data, const char *msg)
279 {
280   fprintf (stderr, "libguestfs: error: %s\n", msg);
281 }
282
283 static void
284 error (guestfs_h *g, const char *fs, ...)
285 {
286   va_list args;
287   char *msg;
288
289   if (!g->error_cb) return;
290
291   va_start (args, fs);
292   vasprintf (&msg, fs, args);
293   va_end (args);
294
295   g->error_cb (g, g->error_cb_data, msg);
296
297   free (msg);
298 }
299
300 static void
301 perrorf (guestfs_h *g, const char *fs, ...)
302 {
303   va_list args;
304   char *msg;
305   int err = errno;
306
307   if (!g->error_cb) return;
308
309   va_start (args, fs);
310   vasprintf (&msg, fs, args);
311   va_end (args);
312
313 #ifndef _GNU_SOURCE
314   char buf[256];
315   strerror_r (err, buf, sizeof buf);
316 #else
317   char _buf[256];
318   char *buf;
319   buf = strerror_r (err, _buf, sizeof _buf);
320 #endif
321
322   msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
323   strcat (msg, ": ");
324   strcat (msg, buf);
325
326   g->error_cb (g, g->error_cb_data, msg);
327
328   free (msg);
329 }
330
331 static void *
332 safe_malloc (guestfs_h *g, size_t nbytes)
333 {
334   void *ptr = malloc (nbytes);
335   if (!ptr) g->abort_cb ();
336   return ptr;
337 }
338
339 static void *
340 safe_realloc (guestfs_h *g, void *ptr, int nbytes)
341 {
342   void *p = realloc (ptr, nbytes);
343   if (!p) g->abort_cb ();
344   return p;
345 }
346
347 static char *
348 safe_strdup (guestfs_h *g, const char *str)
349 {
350   char *s = strdup (str);
351   if (!s) g->abort_cb ();
352   return s;
353 }
354
355 static void *
356 safe_memdup (guestfs_h *g, void *ptr, size_t size)
357 {
358   void *p = malloc (size);
359   if (!p) g->abort_cb ();
360   memcpy (p, ptr, size);
361   return p;
362 }
363
364 void
365 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
366 {
367   g->abort_cb = cb;
368 }
369
370 guestfs_abort_cb
371 guestfs_get_out_of_memory_handler (guestfs_h *g)
372 {
373   return g->abort_cb;
374 }
375
376 void
377 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
378 {
379   g->error_cb = cb;
380   g->error_cb_data = data;
381 }
382
383 guestfs_error_handler_cb
384 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
385 {
386   if (data_rtn) *data_rtn = g->error_cb_data;
387   return g->error_cb;
388 }
389
390 int
391 guestfs_set_verbose (guestfs_h *g, int v)
392 {
393   g->verbose = !!v;
394   return 0;
395 }
396
397 int
398 guestfs_get_verbose (guestfs_h *g)
399 {
400   return g->verbose;
401 }
402
403 int
404 guestfs_set_autosync (guestfs_h *g, int a)
405 {
406   g->autosync = !!a;
407   return 0;
408 }
409
410 int
411 guestfs_get_autosync (guestfs_h *g)
412 {
413   return g->autosync;
414 }
415
416 int
417 guestfs_set_path (guestfs_h *g, const char *path)
418 {
419   if (path == NULL)
420     g->path = GUESTFS_DEFAULT_PATH;
421   else
422     g->path = path;
423   return 0;
424 }
425
426 const char *
427 guestfs_get_path (guestfs_h *g)
428 {
429   return g->path;
430 }
431
432 /* Add a string to the current command line. */
433 static void
434 incr_cmdline_size (guestfs_h *g)
435 {
436   if (g->cmdline == NULL) {
437     /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
438     g->cmdline_size = 1;
439     g->cmdline = safe_malloc (g, sizeof (char *));
440     g->cmdline[0] = NULL;
441   }
442
443   g->cmdline_size++;
444   g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
445 }
446
447 static int
448 add_cmdline (guestfs_h *g, const char *str)
449 {
450   if (g->state != CONFIG) {
451     error (g, "command line cannot be altered after qemu subprocess launched");
452     return -1;
453   }
454
455   incr_cmdline_size (g);
456   g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
457   return 0;
458 }
459
460 int
461 guestfs_config (guestfs_h *g,
462                 const char *qemu_param, const char *qemu_value)
463 {
464   if (qemu_param[0] != '-') {
465     error (g, "guestfs_config: parameter must begin with '-' character");
466     return -1;
467   }
468
469   /* A bit fascist, but the user will probably break the extra
470    * parameters that we add if they try to set any of these.
471    */
472   if (strcmp (qemu_param, "-kernel") == 0 ||
473       strcmp (qemu_param, "-initrd") == 0 ||
474       strcmp (qemu_param, "-nographic") == 0 ||
475       strcmp (qemu_param, "-serial") == 0 ||
476       strcmp (qemu_param, "-vnc") == 0 ||
477       strcmp (qemu_param, "-full-screen") == 0 ||
478       strcmp (qemu_param, "-std-vga") == 0 ||
479       strcmp (qemu_param, "-vnc") == 0) {
480     error (g, "guestfs_config: parameter '%s' isn't allowed", qemu_param);
481     return -1;
482   }
483
484   if (add_cmdline (g, qemu_param) != 0) return -1;
485
486   if (qemu_value != NULL) {
487     if (add_cmdline (g, qemu_value) != 0) return -1;
488   }
489
490   return 0;
491 }
492
493 int
494 guestfs_add_drive (guestfs_h *g, const char *filename)
495 {
496   int len = strlen (filename) + 64;
497   char buf[len];
498
499   if (strchr (filename, ',') != NULL) {
500     error (g, "filename cannot contain ',' (comma) character");
501     return -1;
502   }
503
504   if (access (filename, F_OK) == -1) {
505     perrorf (g, "%s", filename);
506     return -1;
507   }
508
509   snprintf (buf, len, "file=%s", filename);
510
511   return guestfs_config (g, "-drive", buf);
512 }
513
514 int
515 guestfs_add_cdrom (guestfs_h *g, const char *filename)
516 {
517   if (strchr (filename, ',') != NULL) {
518     error (g, "filename cannot contain ',' (comma) character");
519     return -1;
520   }
521
522   if (access (filename, F_OK) == -1) {
523     perrorf (g, "%s", filename);
524     return -1;
525   }
526
527   return guestfs_config (g, "-cdrom", filename);
528 }
529
530 int
531 guestfs_launch (guestfs_h *g)
532 {
533   static const char *dir_template = "/tmp/libguestfsXXXXXX";
534   int r, i, len, pmore;
535   int wfd[2], rfd[2];
536   int tries;
537   const char *kernel_name = "vmlinuz." REPO "." host_cpu;
538   const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
539   char *path, *pelem, *pend;
540   char *kernel = NULL, *initrd = NULL;
541   char unixsock[256];
542   struct sockaddr_un addr;
543
544   /* Configured? */
545   if (!g->cmdline) {
546     error (g, "you must call guestfs_add_drive before guestfs_launch");
547     return -1;
548   }
549
550   if (g->state != CONFIG) {
551     error (g, "qemu has already been launched");
552     return -1;
553   }
554
555   /* Search g->path for the kernel and initrd. */
556   pelem = path = safe_strdup (g, g->path);
557   do {
558     pend = strchrnul (pelem, ':');
559     pmore = *pend == ':';
560     *pend = '\0';
561     len = pend - pelem;
562
563     /* Empty element or "." means cwd. */
564     if (len == 0 || (len == 1 && *pelem == '.')) {
565       if (g->verbose)
566         fprintf (stderr,
567                  "looking for kernel and initrd in current directory\n");
568       if (access (kernel_name, F_OK) == 0 && access (initrd_name, F_OK) == 0) {
569         kernel = safe_strdup (g, kernel_name);
570         initrd = safe_strdup (g, initrd_name);
571         break;
572       }
573     }
574     /* Look at <path>/kernel etc. */
575     else {
576       kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
577       initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
578       sprintf (kernel, "%s/%s", pelem, kernel_name);
579       sprintf (initrd, "%s/%s", pelem, initrd_name);
580
581       if (g->verbose)
582         fprintf (stderr, "looking for %s and %s\n", kernel, initrd);
583
584       if (access (kernel, F_OK) == 0 && access (initrd, F_OK) == 0)
585         break;
586       free (kernel);
587       free (initrd);
588       kernel = initrd = NULL;
589     }
590
591     pelem = pend + 1;
592   } while (pmore);
593
594   free (path);
595
596   if (kernel == NULL || initrd == NULL) {
597     error (g, "cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)",
598            kernel_name, initrd_name, g->path);
599     goto cleanup0;
600   }
601
602   /* Make the temporary directory containing the socket. */
603   if (!g->tmpdir) {
604     g->tmpdir = safe_strdup (g, dir_template);
605     if (mkdtemp (g->tmpdir) == NULL) {
606       perrorf (g, "%s: cannot create temporary directory", dir_template);
607       goto cleanup0;
608     }
609   }
610
611   snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
612   unlink (unixsock);
613
614   if (pipe (wfd) == -1 || pipe (rfd) == -1) {
615     perrorf (g, "pipe");
616     goto cleanup0;
617   }
618
619   r = fork ();
620   if (r == -1) {
621     perrorf (g, "fork");
622     close (wfd[0]);
623     close (wfd[1]);
624     close (rfd[0]);
625     close (rfd[1]);
626     goto cleanup0;
627   }
628
629   if (r == 0) {                 /* Child (qemu). */
630     char vmchannel[256];
631     char append[256];
632
633     /* Set up the full command line.  Do this in the subprocess so we
634      * don't need to worry about cleaning up.
635      */
636     g->cmdline[0] = (char *) QEMU;
637
638     /* Construct the -net channel parameter for qemu. */
639     snprintf (vmchannel, sizeof vmchannel,
640               "channel,%d:unix:%s,server,nowait",
641               VMCHANNEL_PORT, unixsock);
642
643     /* Linux kernel command line. */
644     snprintf (append, sizeof append,
645               "console=ttyS0 guestfs=%s:%d", VMCHANNEL_ADDR, VMCHANNEL_PORT);
646
647     add_cmdline (g, "-m");
648     add_cmdline (g, "384");       /* XXX Choose best size. */
649     add_cmdline (g, "-no-kqemu"); /* Avoids a warning. */
650     add_cmdline (g, "-kernel");
651     add_cmdline (g, (char *) kernel);
652     add_cmdline (g, "-initrd");
653     add_cmdline (g, (char *) initrd);
654     add_cmdline (g, "-append");
655     add_cmdline (g, append);
656     add_cmdline (g, "-nographic");
657     add_cmdline (g, "-serial");
658     add_cmdline (g, "stdio");
659     add_cmdline (g, "-net");
660     add_cmdline (g, vmchannel);
661     add_cmdline (g, "-net");
662     add_cmdline (g, "user,vlan=0");
663     add_cmdline (g, "-net");
664     add_cmdline (g, "nic,vlan=0");
665     incr_cmdline_size (g);
666     g->cmdline[g->cmdline_size-1] = NULL;
667
668     if (g->verbose) {
669       fprintf (stderr, "%s", QEMU);
670       for (i = 0; g->cmdline[i]; ++i)
671         fprintf (stderr, " %s", g->cmdline[i]);
672       fprintf (stderr, "\n");
673     }
674
675     /* Set up stdin, stdout. */
676     close (0);
677     close (1);
678     close (wfd[1]);
679     close (rfd[0]);
680     dup (wfd[0]);
681     dup (rfd[1]);
682     close (wfd[0]);
683     close (rfd[1]);
684
685 #if 0
686     /* Set up a new process group, so we can signal this process
687      * and all subprocesses (eg. if qemu is really a shell script).
688      */
689     setpgid (0, 0);
690 #endif
691
692     execv (QEMU, g->cmdline);   /* Run qemu. */
693     perror (QEMU);
694     _exit (1);
695   }
696
697   /* Parent (library). */
698   g->pid = r;
699
700   /* Start the clock ... */
701   time (&g->start_t);
702
703   /* Close the other ends of the pipe. */
704   close (wfd[0]);
705   close (rfd[1]);
706
707   if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
708       fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
709     perrorf (g, "fcntl");
710     goto cleanup1;
711   }
712
713   g->fd[0] = wfd[1];            /* stdin of child */
714   g->fd[1] = rfd[0];            /* stdout of child */
715
716   /* Open the Unix socket.  The vmchannel implementation that got
717    * merged with qemu sucks in a number of ways.  Both ends do
718    * connect(2), which means that no one knows what, if anything, is
719    * connected to the other end, or if it becomes disconnected.  Even
720    * worse, we have to wait some indeterminate time for qemu to create
721    * the socket and connect to it (which happens very early in qemu's
722    * start-up), so any code that uses vmchannel is inherently racy.
723    * Hence this silly loop.
724    */
725   g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
726   if (g->sock == -1) {
727     perrorf (g, "socket");
728     goto cleanup1;
729   }
730
731   if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
732     perrorf (g, "fcntl");
733     goto cleanup2;
734   }
735
736   addr.sun_family = AF_UNIX;
737   strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
738   addr.sun_path[UNIX_PATH_MAX-1] = '\0';
739
740   tries = 100;
741   while (tries > 0) {
742     /* Always sleep at least once to give qemu a small chance to start up. */
743     usleep (10000);
744
745     r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
746     if ((r == -1 && errno == EINPROGRESS) || r == 0)
747       goto connected;
748
749     if (errno != ENOENT)
750       perrorf (g, "connect");
751     tries--;
752   }
753
754   error (g, "failed to connect to vmchannel socket");
755   goto cleanup2;
756
757  connected:
758   /* Watch the file descriptors. */
759   free (g->msg_in);
760   g->msg_in = NULL;
761   g->msg_in_size = g->msg_in_allocated = 0;
762
763   free (g->msg_out);
764   g->msg_out = NULL;
765   g->msg_out_size = 0;
766   g->msg_out_pos = 0;
767
768   g->stdout_watch =
769     main_loop.add_handle (g, g->fd[1],
770                           GUESTFS_HANDLE_READABLE,
771                           stdout_event, g);
772   if (g->stdout_watch == -1) {
773     error (g, "could not watch qemu stdout");
774     goto cleanup3;
775   }
776
777   g->sock_watch =
778     main_loop.add_handle (g, g->sock,
779                           GUESTFS_HANDLE_READABLE,
780                           sock_read_event, g);
781   if (g->sock_watch == -1) {
782     error (g, "could not watch daemon communications socket");
783     goto cleanup3;
784   }
785
786   g->state = LAUNCHING;
787   return 0;
788
789  cleanup3:
790   if (g->stdout_watch >= 0)
791     main_loop.remove_handle (g, g->stdout_watch);
792   if (g->sock_watch >= 0)
793     main_loop.remove_handle (g, g->sock_watch);
794
795  cleanup2:
796   close (g->sock);
797
798  cleanup1:
799   close (wfd[1]);
800   close (rfd[0]);
801   kill (g->pid, 9);
802   waitpid (g->pid, NULL, 0);
803   g->fd[0] = -1;
804   g->fd[1] = -1;
805   g->sock = -1;
806   g->pid = 0;
807   g->start_t = 0;
808   g->stdout_watch = -1;
809   g->sock_watch = -1;
810
811  cleanup0:
812   free (kernel);
813   free (initrd);
814   return -1;
815 }
816
817 static void
818 finish_wait_ready (guestfs_h *g, void *vp)
819 {
820   *((int *)vp) = 1;
821   main_loop.main_loop_quit (g);
822 }
823
824 int
825 guestfs_wait_ready (guestfs_h *g)
826 {
827   int r = 0;
828
829   if (g->state == READY) return 0;
830
831   if (g->state == BUSY) {
832     error (g, "qemu has finished launching already");
833     return -1;
834   }
835
836   if (g->state != LAUNCHING) {
837     error (g, "qemu has not been launched yet");
838     return -1;
839   }
840
841   g->launch_done_cb_internal = finish_wait_ready;
842   g->launch_done_cb_internal_data = &r;
843   main_loop.main_loop_run (g);
844   g->launch_done_cb_internal = NULL;
845   g->launch_done_cb_internal_data = NULL;
846
847   if (r != 1) {
848     error (g, "guestfs_wait_ready failed, see earlier error messages");
849     return -1;
850   }
851
852   /* This is possible in some really strange situations, such as
853    * guestfsd starts up OK but then qemu immediately exits.  Check for
854    * it because the caller is probably expecting to be able to send
855    * commands after this function returns.
856    */
857   if (g->state != READY) {
858     error (g, "qemu launched and contacted daemon, but state != READY");
859     return -1;
860   }
861
862   return 0;
863 }
864
865 int
866 guestfs_kill_subprocess (guestfs_h *g)
867 {
868   if (g->state == CONFIG) {
869     error (g, "no subprocess to kill");
870     return -1;
871   }
872
873   if (g->verbose)
874     fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
875
876   kill (g->pid, SIGTERM);
877
878   return 0;
879 }
880
881 /* This function is called whenever qemu prints something on stdout.
882  * Qemu's stdout is also connected to the guest's serial console, so
883  * we see kernel messages here too.
884  */
885 static void
886 stdout_event (void *data, int watch, int fd, int events)
887 {
888   guestfs_h *g = (guestfs_h *) data;
889   char buf[4096];
890   int n;
891
892 #if 0
893   if (g->verbose)
894     fprintf (stderr,
895              "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
896              g, g->state, fd, events);
897 #endif
898
899   if (g->fd[1] != fd) {
900     error (g, "stdout_event: internal error: %d != %d", g->fd[1], fd);
901     return;
902   }
903
904   n = read (fd, buf, sizeof buf);
905   if (n == 0) {
906     /* Hopefully this indicates the qemu child process has died. */
907     if (g->verbose)
908       fprintf (stderr, "stdout_event: %p: child process died\n", g);
909     /*kill (g->pid, SIGTERM);*/
910     waitpid (g->pid, NULL, 0);
911     if (g->stdout_watch >= 0)
912       main_loop.remove_handle (g, g->stdout_watch);
913     if (g->sock_watch >= 0)
914       main_loop.remove_handle (g, g->sock_watch);
915     close (g->fd[0]);
916     close (g->fd[1]);
917     close (g->sock);
918     g->fd[0] = -1;
919     g->fd[1] = -1;
920     g->sock = -1;
921     g->pid = 0;
922     g->start_t = 0;
923     g->stdout_watch = -1;
924     g->sock_watch = -1;
925     g->state = CONFIG;
926     if (g->subprocess_quit_cb)
927       g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
928     return;
929   }
930
931   if (n == -1) {
932     if (errno != EAGAIN)
933       perrorf (g, "read");
934     return;
935   }
936
937   /* In verbose mode, copy all log messages to stderr. */
938   if (g->verbose)
939     write (2, buf, n);
940
941   /* It's an actual log message, send it upwards if anyone is listening. */
942   if (g->log_message_cb)
943     g->log_message_cb (g, g->log_message_cb_data, buf, n);
944 }
945
946 /* The function is called whenever we can read something on the
947  * guestfsd (daemon inside the guest) communication socket.
948  */
949 static void
950 sock_read_event (void *data, int watch, int fd, int events)
951 {
952   guestfs_h *g = (guestfs_h *) data;
953   XDR xdr;
954   unsigned len;
955   int n;
956
957   if (g->verbose)
958     fprintf (stderr,
959              "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
960              g, g->state, fd, events);
961
962   if (g->sock != fd) {
963     error (g, "sock_read_event: internal error: %d != %d", g->sock, fd);
964     return;
965   }
966
967   if (g->msg_in_size <= g->msg_in_allocated) {
968     g->msg_in_allocated += 4096;
969     g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
970   }
971   n = read (g->sock, g->msg_in + g->msg_in_size,
972             g->msg_in_allocated - g->msg_in_size);
973   if (n == 0)
974     /* Disconnected?  Ignore it because stdout_watch will get called
975      * and will do the cleanup.
976      */
977     return;
978
979   if (n == -1) {
980     if (errno != EAGAIN)
981       perrorf (g, "read");
982     return;
983   }
984
985   g->msg_in_size += n;
986
987   /* Have we got enough of a message to be able to process it yet? */
988   if (g->msg_in_size < 4) return;
989
990   xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
991   if (!xdr_uint32_t (&xdr, &len)) {
992     error (g, "can't decode length word");
993     goto cleanup;
994   }
995
996   /* Length is normally the length of the message, but when guestfsd
997    * starts up it sends a "magic" value (longer than any possible
998    * message).  Check for this.
999    */
1000   if (len == 0xf5f55ff5) {
1001     if (g->state != LAUNCHING)
1002       error (g, "received magic signature from guestfsd, but in state %d",
1003              g->state);
1004     else if (g->msg_in_size != 4)
1005       error (g, "received magic signature from guestfsd, but msg size is %d",
1006              g->msg_in_size);
1007     else {
1008       g->state = READY;
1009       if (g->launch_done_cb_internal)
1010         g->launch_done_cb_internal (g, g->launch_done_cb_internal_data);
1011       if (g->launch_done_cb)
1012         g->launch_done_cb (g, g->launch_done_cb_data);
1013     }
1014
1015     goto cleanup;
1016   }
1017
1018   /* If this happens, it's pretty bad and we've probably lost synchronization.*/
1019   if (len > GUESTFS_MESSAGE_MAX) {
1020     error (g, "message length (%u) > maximum possible size (%d)",
1021            len, GUESTFS_MESSAGE_MAX);
1022     goto cleanup;
1023   }
1024
1025   if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1026
1027   /* This should not happen, and if it does it probably means we've
1028    * lost all hope of synchronization.
1029    */
1030   if (g->msg_in_size-4 > len) {
1031     error (g, "len = %d, but msg_in_size-4 = %d", len, g->msg_in_size-4);
1032     goto cleanup;
1033   }
1034
1035   /* Got the full message, begin processing it. */
1036   if (g->verbose) {
1037     int i, j;
1038
1039     for (i = 0; i < g->msg_in_size; i += 16) {
1040       printf ("%04x: ", i);
1041       for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1042         printf ("%02x ", (unsigned char) g->msg_in[j]);
1043       for (; j < i+16; ++j)
1044         printf ("   ");
1045       printf ("|");
1046       for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1047         if (isprint (g->msg_in[j]))
1048           printf ("%c", g->msg_in[j]);
1049         else
1050           printf (".");
1051       for (; j < i+16; ++j)
1052         printf (" ");
1053       printf ("|\n");
1054     }
1055   }
1056
1057   /* Not in the expected state. */
1058   if (g->state != BUSY)
1059     error (g, "state %d != BUSY", g->state);
1060
1061   /* Push the message up to the higher layer.  Note that unlike
1062    * launch_done_cb / launch_done_cb_internal, we only call at
1063    * most one of the callback functions here.
1064    */
1065   g->state = READY;
1066   if (g->reply_cb_internal)
1067     g->reply_cb_internal (g, g->reply_cb_internal_data, &xdr);
1068   else if (g->reply_cb)
1069     g->reply_cb (g, g->reply_cb, &xdr);
1070
1071  cleanup:
1072   /* Free the message buffer if it's grown excessively large. */
1073   if (g->msg_in_allocated > 65536) {
1074     free (g->msg_in);
1075     g->msg_in = NULL;
1076     g->msg_in_size = g->msg_in_allocated = 0;
1077   } else
1078     g->msg_in_size = 0;
1079
1080   xdr_destroy (&xdr);
1081 }
1082
1083 /* The function is called whenever we can write something on the
1084  * guestfsd (daemon inside the guest) communication socket.
1085  */
1086 static void
1087 sock_write_event (void *data, int watch, int fd, int events)
1088 {
1089   guestfs_h *g = (guestfs_h *) data;
1090   int n;
1091
1092   if (g->verbose)
1093     fprintf (stderr,
1094              "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1095              g, g->state, fd, events);
1096
1097   if (g->sock != fd) {
1098     error (g, "sock_write_event: internal error: %d != %d", g->sock, fd);
1099     return;
1100   }
1101
1102   if (g->state != BUSY) {
1103     error (g, "sock_write_event: state %d != BUSY", g->state);
1104     return;
1105   }
1106
1107   if (g->verbose)
1108     fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1109              g->msg_out_size - g->msg_out_pos);
1110
1111   n = write (g->sock, g->msg_out + g->msg_out_pos,
1112              g->msg_out_size - g->msg_out_pos);
1113   if (n == -1) {
1114     if (errno != EAGAIN)
1115       perrorf (g, "write");
1116     return;
1117   }
1118
1119   if (g->verbose)
1120     fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1121
1122   g->msg_out_pos += n;
1123
1124   /* More to write? */
1125   if (g->msg_out_pos < g->msg_out_size)
1126     return;
1127
1128   if (g->verbose)
1129     fprintf (stderr, "sock_write_event: done writing, switching back to reading events\n");
1130
1131   free (g->msg_out);
1132   g->msg_out_pos = g->msg_out_size = 0;
1133
1134   if (main_loop.remove_handle (g, g->sock_watch) == -1) {
1135     error (g, "remove_handle failed in sock_write_event");
1136     return;
1137   }
1138   g->sock_watch =
1139     main_loop.add_handle (g, g->sock,
1140                           GUESTFS_HANDLE_READABLE,
1141                           sock_read_event, g);
1142   if (g->sock_watch == -1) {
1143     error (g, "add_handle failed in sock_write_event");
1144     return;
1145   }
1146 }
1147
1148 /* Dispatch a call to the remote daemon.  This function just queues
1149  * the call in msg_out, to be sent when we next enter the main loop.
1150  * Returns -1 for error, or the message serial number.
1151  */
1152 static int
1153 dispatch (guestfs_h *g, int proc_nr, xdrproc_t xdrp, char *args)
1154 {
1155   char buffer[GUESTFS_MESSAGE_MAX];
1156   struct guestfs_message_header hdr;
1157   XDR xdr;
1158   unsigned len;
1159   int serial = g->msg_next_serial++;
1160
1161   if (g->state != READY) {
1162     error (g, "dispatch: state %d != READY", g->state);
1163     return -1;
1164   }
1165
1166   /* Serialize the header. */
1167   hdr.prog = GUESTFS_PROGRAM;
1168   hdr.vers = GUESTFS_PROTOCOL_VERSION;
1169   hdr.proc = proc_nr;
1170   hdr.direction = GUESTFS_DIRECTION_CALL;
1171   hdr.serial = serial;
1172   hdr.status = GUESTFS_STATUS_OK;
1173
1174   xdrmem_create (&xdr, buffer, sizeof buffer, XDR_ENCODE);
1175   if (!xdr_guestfs_message_header (&xdr, &hdr)) {
1176     error (g, "xdr_guestfs_message_header failed");
1177     return -1;
1178   }
1179
1180   /* Serialize the args.  If any, because some message types
1181    * have no parameters.
1182    */
1183   if (xdrp) {
1184     if (!(*xdrp) (&xdr, args)) {
1185       error (g, "dispatch failed to marshal args");
1186       return -1;
1187     }
1188   }
1189
1190   len = xdr_getpos (&xdr);
1191   xdr_destroy (&xdr);
1192
1193   /* Allocate the outgoing message buffer. */
1194   g->msg_out = safe_malloc (g, len + 4);
1195
1196   g->msg_out_size = len + 4;
1197   g->msg_out_pos = 0;
1198   g->state = BUSY;
1199
1200   xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1201   if (!xdr_uint32_t (&xdr, &len)) {
1202     error (g, "xdr_uint32_t failed in dispatch");
1203     goto cleanup1;
1204   }
1205
1206   memcpy (g->msg_out + 4, buffer, len);
1207
1208   /* Change the handle to sock_write_event. */
1209   if (main_loop.remove_handle (g, g->sock_watch) == -1) {
1210     error (g, "remove_handle failed in dispatch");
1211     goto cleanup1;
1212   }
1213   g->sock_watch =
1214     main_loop.add_handle (g, g->sock,
1215                           GUESTFS_HANDLE_WRITABLE,
1216                           sock_write_event, g);
1217   if (g->sock_watch == -1) {
1218     error (g, "add_handle failed in dispatch");
1219     goto cleanup1;
1220   }
1221
1222   return serial;
1223
1224  cleanup1:
1225   free (g->msg_out);
1226   g->msg_out = NULL;
1227   g->msg_out_size = 0;
1228   g->state = READY;
1229   return -1;
1230 }
1231
1232 /* Check the return message from a call for validity. */
1233 static int
1234 check_reply_header (guestfs_h *g,
1235                     const struct guestfs_message_header *hdr,
1236                     int proc_nr, int serial)
1237 {
1238   if (hdr->prog != GUESTFS_PROGRAM) {
1239     error (g, "wrong program (%d/%d)", hdr->prog, GUESTFS_PROGRAM);
1240     return -1;
1241   }
1242   if (hdr->vers != GUESTFS_PROTOCOL_VERSION) {
1243     error (g, "wrong protocol version (%d/%d)",
1244            hdr->vers, GUESTFS_PROTOCOL_VERSION);
1245     return -1;
1246   }
1247   if (hdr->direction != GUESTFS_DIRECTION_REPLY) {
1248     error (g, "unexpected message direction (%d/%d)",
1249            hdr->direction, GUESTFS_DIRECTION_REPLY);
1250     return -1;
1251   }
1252   if (hdr->proc != proc_nr) {
1253     error (g, "unexpected procedure number (%d/%d)", hdr->proc, proc_nr);
1254     return -1;
1255   }
1256   if (hdr->serial != serial) {
1257     error (g, "unexpected serial (%d/%d)", hdr->serial, serial);
1258     return -1;
1259   }
1260
1261   return 0;
1262 }
1263
1264 /* The high-level actions are autogenerated by generator.ml.  Include
1265  * them here.
1266  */
1267 #include "guestfs-actions.c"
1268
1269 /* Structure-freeing functions.  These rely on the fact that the
1270  * structure format is identical to the XDR format.  See note in
1271  * generator.ml.
1272  */
1273 void
1274 guestfs_free_lvm_pv_list (struct guestfs_lvm_pv_list *x)
1275 {
1276   xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_pv_list, (char *) x);
1277   free (x);
1278 }
1279
1280 void
1281 guestfs_free_lvm_vg_list (struct guestfs_lvm_vg_list *x)
1282 {
1283   xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_vg_list, (char *) x);
1284   free (x);
1285 }
1286
1287 void
1288 guestfs_free_lvm_lv_list (struct guestfs_lvm_lv_list *x)
1289 {
1290   xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_lv_list, (char *) x);
1291   free (x);
1292 }
1293
1294 /* This is the default main loop implementation, using select(2). */
1295
1296 struct handle_cb_data {
1297   guestfs_handle_event_cb cb;
1298   void *data;
1299 };
1300
1301 static fd_set rset;
1302 static fd_set wset;
1303 static fd_set xset;
1304 static int select_init_done = 0;
1305 static int max_fd = -1;
1306 static int nr_fds = 0;
1307 static struct handle_cb_data *handle_cb_data = NULL;
1308
1309 static void
1310 select_init (void)
1311 {
1312   if (!select_init_done) {
1313     FD_ZERO (&rset);
1314     FD_ZERO (&wset);
1315     FD_ZERO (&xset);
1316
1317     select_init_done = 1;
1318   }
1319 }
1320
1321 static int
1322 select_add_handle (guestfs_h *g, int fd, int events,
1323                    guestfs_handle_event_cb cb, void *data)
1324 {
1325   select_init ();
1326
1327   if (fd < 0 || fd >= FD_SETSIZE) {
1328     error (g, "fd %d is out of range", fd);
1329     return -1;
1330   }
1331
1332   if ((events & ~(GUESTFS_HANDLE_READABLE |
1333                   GUESTFS_HANDLE_WRITABLE |
1334                   GUESTFS_HANDLE_HANGUP |
1335                   GUESTFS_HANDLE_ERROR)) != 0) {
1336     error (g, "set of events (0x%x) contains unknown events", events);
1337     return -1;
1338   }
1339
1340   if (events == 0) {
1341     error (g, "set of events is empty");
1342     return -1;
1343   }
1344
1345   if (FD_ISSET (fd, &rset) || FD_ISSET (fd, &wset) || FD_ISSET (fd, &xset)) {
1346     error (g, "fd %d is already registered", fd);
1347     return -1;
1348   }
1349
1350   if (cb == NULL) {
1351     error (g, "callback is NULL");
1352     return -1;
1353   }
1354
1355   if ((events & GUESTFS_HANDLE_READABLE))
1356     FD_SET (fd, &rset);
1357   if ((events & GUESTFS_HANDLE_WRITABLE))
1358     FD_SET (fd, &wset);
1359   if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
1360     FD_SET (fd, &xset);
1361
1362   if (fd > max_fd) {
1363     max_fd = fd;
1364     handle_cb_data = safe_realloc (g, handle_cb_data,
1365                                    sizeof (struct handle_cb_data) * (max_fd+1));
1366   }
1367   handle_cb_data[fd].cb = cb;
1368   handle_cb_data[fd].data = data;
1369
1370   nr_fds++;
1371
1372   /* Any integer >= 0 can be the handle, and this is as good as any ... */
1373   return fd;
1374 }
1375
1376 static int
1377 select_remove_handle (guestfs_h *g, int fd)
1378 {
1379   select_init ();
1380
1381   if (fd < 0 || fd >= FD_SETSIZE) {
1382     error (g, "fd %d is out of range", fd);
1383     return -1;
1384   }
1385
1386   if (!FD_ISSET (fd, &rset) && !FD_ISSET (fd, &wset) && !FD_ISSET (fd, &xset)) {
1387     error (g, "fd %d was not registered", fd);
1388     return -1;
1389   }
1390
1391   FD_CLR (fd, &rset);
1392   FD_CLR (fd, &wset);
1393   FD_CLR (fd, &xset);
1394
1395   if (fd == max_fd) {
1396     max_fd--;
1397     handle_cb_data = safe_realloc (g, handle_cb_data,
1398                                    sizeof (struct handle_cb_data) * (max_fd+1));
1399   }
1400
1401   nr_fds--;
1402
1403   return 0;
1404 }
1405
1406 static int
1407 select_add_timeout (guestfs_h *g, int interval,
1408                     guestfs_handle_timeout_cb cb, void *data)
1409 {
1410   select_init ();
1411
1412   abort ();                     /* XXX not implemented yet */
1413 }
1414
1415 static int
1416 select_remove_timeout (guestfs_h *g, int timer)
1417 {
1418   select_init ();
1419
1420   abort ();                     /* XXX not implemented yet */
1421 }
1422
1423 /* Note that main loops can be nested. */
1424 static int level = 0;
1425
1426 static void
1427 select_main_loop_run (guestfs_h *g)
1428 {
1429   int old_level, fd, r, events;
1430   fd_set rset2, wset2, xset2;
1431
1432   select_init ();
1433
1434   old_level = level++;
1435   while (level > old_level) {
1436     if (nr_fds == 0) {
1437       level = old_level;
1438       break;
1439     }
1440
1441     rset2 = rset;
1442     wset2 = wset;
1443     xset2 = xset;
1444     r = select (max_fd+1, &rset2, &wset2, &xset2, NULL);
1445     if (r == -1) {
1446       perrorf (g, "select");
1447       level = old_level;
1448       break;
1449     }
1450
1451     for (fd = 0; r > 0 && fd <= max_fd; ++fd) {
1452       events = 0;
1453       if (FD_ISSET (fd, &rset2))
1454         events |= GUESTFS_HANDLE_READABLE;
1455       if (FD_ISSET (fd, &wset2))
1456         events |= GUESTFS_HANDLE_WRITABLE;
1457       if (FD_ISSET (fd, &xset2))
1458         events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
1459       if (events) {
1460         r--;
1461         handle_cb_data[fd].cb (handle_cb_data[fd].data,
1462                                fd, fd, events);
1463       }
1464     }
1465   }
1466 }
1467
1468 static void
1469 select_main_loop_quit (guestfs_h *g)
1470 {
1471   select_init ();
1472
1473   if (level == 0) {
1474     error (g, "cannot quit, we are not in a main loop");
1475     return;
1476   }
1477
1478   level--;
1479 }