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