Don't stash strings in the handle.
[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/stat.h>
33 #include <sys/select.h>
34
35 #include <rpc/types.h>
36 #include <rpc/xdr.h>
37
38 #ifdef HAVE_ERRNO_H
39 #include <errno.h>
40 #endif
41
42 #ifdef HAVE_SYS_TYPES_H
43 #include <sys/types.h>
44 #endif
45
46 #ifdef HAVE_SYS_WAIT_H
47 #include <sys/wait.h>
48 #endif
49
50 #ifdef HAVE_SYS_SOCKET_H
51 #include <sys/socket.h>
52 #endif
53
54 #ifdef HAVE_SYS_UN_H
55 #include <sys/un.h>
56 #endif
57
58 #include "guestfs.h"
59 #include "guestfs_protocol.h"
60
61 #define error guestfs_error
62 #define perrorf guestfs_perrorf
63 #define safe_malloc guestfs_safe_malloc
64 #define safe_realloc guestfs_safe_realloc
65 #define safe_strdup guestfs_safe_strdup
66 #define safe_memdup guestfs_safe_memdup
67
68 static void default_error_cb (guestfs_h *g, void *data, const char *msg);
69 static void stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
70 static void sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
71 static void sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
72
73 static void close_handles (void);
74
75 static int select_add_handle (guestfs_main_loop *ml, guestfs_h *g, int fd, int events, guestfs_handle_event_cb cb, void *data);
76 static int select_remove_handle (guestfs_main_loop *ml, guestfs_h *g, int watch);
77 static int select_add_timeout (guestfs_main_loop *ml, guestfs_h *g, int interval, guestfs_handle_timeout_cb cb, void *data);
78 static int select_remove_timeout (guestfs_main_loop *ml, guestfs_h *g, int timer);
79 static int select_main_loop_run (guestfs_main_loop *ml, guestfs_h *g);
80 static int select_main_loop_quit (guestfs_main_loop *ml, guestfs_h *g);
81
82 /* Default select-based main loop. */
83 struct select_handle_cb_data {
84   guestfs_handle_event_cb cb;
85   guestfs_h *g;
86   void *data;
87 };
88
89 struct select_main_loop {
90   /* NB. These fields must be the same as in struct guestfs_main_loop: */
91   guestfs_add_handle_cb add_handle;
92   guestfs_remove_handle_cb remove_handle;
93   guestfs_add_timeout_cb add_timeout;
94   guestfs_remove_timeout_cb remove_timeout;
95   guestfs_main_loop_run_cb main_loop_run;
96   guestfs_main_loop_quit_cb main_loop_quit;
97
98   /* Additional private data: */
99   int is_running;
100
101   fd_set rset;
102   fd_set wset;
103   fd_set xset;
104
105   int max_fd;
106   int nr_fds;
107   struct select_handle_cb_data *handle_cb_data;
108 };
109
110 /* Default main loop. */
111 static struct select_main_loop default_main_loop = {
112   .add_handle = select_add_handle,
113   .remove_handle = select_remove_handle,
114   .add_timeout = select_add_timeout,
115   .remove_timeout = select_remove_timeout,
116   .main_loop_run = select_main_loop_run,
117   .main_loop_quit = select_main_loop_quit,
118
119   /* XXX hopefully .rset, .wset, .xset are initialized to the empty
120    * set by the normal action of everything being initialized to zero.
121    */
122   .is_running = 0,
123   .max_fd = -1,
124   .nr_fds = 0,
125   .handle_cb_data = NULL,
126 };
127
128 #define UNIX_PATH_MAX 108
129
130 /* Also in guestfsd.c */
131 #define VMCHANNEL_PORT 6666
132 #define VMCHANNEL_ADDR "10.0.2.4"
133
134 /* GuestFS handle and connection. */
135 enum state { CONFIG, LAUNCHING, READY, BUSY, NO_HANDLE };
136
137 struct guestfs_h
138 {
139   struct guestfs_h *next;       /* Linked list of open handles. */
140
141   /* State: see the state machine diagram in the man page guestfs(3). */
142   enum state state;
143
144   int fd[2];                    /* Stdin/stdout of qemu. */
145   int sock;                     /* Daemon communications socket. */
146   pid_t pid;                    /* Qemu PID. */
147   pid_t recoverypid;            /* Recovery process PID. */
148   time_t start_t;               /* The time when we started qemu. */
149
150   int stdout_watch;             /* Watches qemu stdout for log messages. */
151   int sock_watch;               /* Watches daemon comm socket. */
152
153   char *tmpdir;                 /* Temporary directory containing socket. */
154
155   char **cmdline;               /* Qemu command line. */
156   int cmdline_size;
157
158   int verbose;
159   int autosync;
160
161   char *path;                   /* Path to kernel, initrd. */
162   char *qemu;                   /* Qemu binary. */
163   char *append;                 /* Append to kernel command line. */
164
165   char *last_error;
166
167   /* Callbacks. */
168   guestfs_abort_cb           abort_cb;
169   guestfs_error_handler_cb   error_cb;
170   void *                     error_cb_data;
171   guestfs_send_cb            send_cb;
172   void *                     send_cb_data;
173   guestfs_reply_cb           reply_cb;
174   void *                     reply_cb_data;
175   guestfs_log_message_cb     log_message_cb;
176   void *                     log_message_cb_data;
177   guestfs_subprocess_quit_cb subprocess_quit_cb;
178   void *                     subprocess_quit_cb_data;
179   guestfs_launch_done_cb     launch_done_cb;
180   void *                     launch_done_cb_data;
181
182   /* Main loop used by this handle. */
183   guestfs_main_loop *main_loop;
184
185   /* Messages sent and received from the daemon. */
186   char *msg_in;
187   int msg_in_size, msg_in_allocated;
188   char *msg_out;
189   int msg_out_size, msg_out_pos;
190
191   int msg_next_serial;
192 };
193
194 static guestfs_h *handles = NULL;
195 static int atexit_handler_set = 0;
196
197 guestfs_h *
198 guestfs_create (void)
199 {
200   guestfs_h *g;
201   const char *str;
202
203   g = malloc (sizeof (*g));
204   if (!g) return NULL;
205
206   memset (g, 0, sizeof (*g));
207
208   g->state = CONFIG;
209
210   g->fd[0] = -1;
211   g->fd[1] = -1;
212   g->sock = -1;
213   g->stdout_watch = -1;
214   g->sock_watch = -1;
215
216   g->abort_cb = abort;
217   g->error_cb = default_error_cb;
218   g->error_cb_data = NULL;
219
220   str = getenv ("LIBGUESTFS_DEBUG");
221   g->verbose = str != NULL && strcmp (str, "1") == 0;
222
223   str = getenv ("LIBGUESTFS_PATH");
224   g->path = str != NULL ? strdup (str) : strdup (GUESTFS_DEFAULT_PATH);
225   if (!g->path) goto error;
226
227   str = getenv ("LIBGUESTFS_QEMU");
228   g->qemu = str != NULL ? strdup (str) : strdup (QEMU);
229   if (!g->qemu) goto error;
230
231   str = getenv ("LIBGUESTFS_APPEND");
232   if (str) {
233     g->append = strdup (str);
234     if (!g->append) goto error;
235   }
236
237   g->main_loop = guestfs_get_default_main_loop ();
238
239   /* Start with large serial numbers so they are easy to spot
240    * inside the protocol.
241    */
242   g->msg_next_serial = 0x00123400;
243
244   /* Link the handles onto a global list.  This is the one area
245    * where the library needs to be made thread-safe. (XXX)
246    */
247   /* acquire mutex (XXX) */
248   g->next = handles;
249   handles = g;
250   if (!atexit_handler_set) {
251     atexit (close_handles);
252     atexit_handler_set = 1;
253   }
254   /* release mutex (XXX) */
255
256   if (g->verbose)
257     fprintf (stderr, "new guestfs handle %p\n", g);
258
259   return g;
260
261  error:
262   free (g->path);
263   free (g->qemu);
264   free (g->append);
265   free (g);
266   return NULL;
267 }
268
269 void
270 guestfs_close (guestfs_h *g)
271 {
272   int i;
273   char filename[256];
274   guestfs_h *gg;
275
276   if (g->state == NO_HANDLE) {
277     /* Not safe to call 'error' here, so ... */
278     fprintf (stderr, "guestfs_close: called twice on the same handle\n");
279     return;
280   }
281
282   if (g->verbose)
283     fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
284
285   /* Try to sync if autosync flag is set. */
286   if (g->autosync && g->state == READY) {
287     guestfs_umount_all (g);
288     guestfs_sync (g);
289   }
290
291   /* Remove any handlers that might be called back before we kill the
292    * subprocess.
293    */
294   g->log_message_cb = NULL;
295
296   if (g->state != CONFIG)
297     guestfs_kill_subprocess (g);
298
299   if (g->tmpdir) {
300     snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
301     unlink (filename);
302
303     rmdir (g->tmpdir);
304
305     free (g->tmpdir);
306   }
307
308   if (g->cmdline) {
309     for (i = 0; i < g->cmdline_size; ++i)
310       free (g->cmdline[i]);
311     free (g->cmdline);
312   }
313
314   /* Mark the handle as dead before freeing it. */
315   g->state = NO_HANDLE;
316
317   /* acquire mutex (XXX) */
318   if (handles == g)
319     handles = g->next;
320   else {
321     for (gg = handles; gg->next != g; gg = gg->next)
322       ;
323     gg->next = g->next;
324   }
325   /* release mutex (XXX) */
326
327   free (g->msg_in);
328   free (g->msg_out);
329   free (g->last_error);
330   free (g->path);
331   free (g->qemu);
332   free (g->append);
333   free (g);
334 }
335
336 /* Close all open handles (called from atexit(3)). */
337 static void
338 close_handles (void)
339 {
340   while (handles) guestfs_close (handles);
341 }
342
343 const char *
344 guestfs_last_error (guestfs_h *g)
345 {
346   return g->last_error;
347 }
348
349 static void
350 set_last_error (guestfs_h *g, const char *msg)
351 {
352   free (g->last_error);
353   g->last_error = strdup (msg);
354 }
355
356 static void
357 default_error_cb (guestfs_h *g, void *data, const char *msg)
358 {
359   fprintf (stderr, "libguestfs: error: %s\n", msg);
360 }
361
362 void
363 guestfs_error (guestfs_h *g, const char *fs, ...)
364 {
365   va_list args;
366   char *msg;
367
368   va_start (args, fs);
369   vasprintf (&msg, fs, args);
370   va_end (args);
371
372   if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
373   set_last_error (g, msg);
374
375   free (msg);
376 }
377
378 void
379 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
380 {
381   va_list args;
382   char *msg;
383   int err = errno;
384
385   va_start (args, fs);
386   vasprintf (&msg, fs, args);
387   va_end (args);
388
389 #ifndef _GNU_SOURCE
390   char buf[256];
391   strerror_r (err, buf, sizeof buf);
392 #else
393   char _buf[256];
394   char *buf;
395   buf = strerror_r (err, _buf, sizeof _buf);
396 #endif
397
398   msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
399   strcat (msg, ": ");
400   strcat (msg, buf);
401
402   if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
403   set_last_error (g, msg);
404
405   free (msg);
406 }
407
408 void *
409 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
410 {
411   void *ptr = malloc (nbytes);
412   if (!ptr) g->abort_cb ();
413   return ptr;
414 }
415
416 void *
417 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
418 {
419   void *p = realloc (ptr, nbytes);
420   if (!p) g->abort_cb ();
421   return p;
422 }
423
424 char *
425 guestfs_safe_strdup (guestfs_h *g, const char *str)
426 {
427   char *s = strdup (str);
428   if (!s) g->abort_cb ();
429   return s;
430 }
431
432 void *
433 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
434 {
435   void *p = malloc (size);
436   if (!p) g->abort_cb ();
437   memcpy (p, ptr, size);
438   return p;
439 }
440
441 static int
442 xwrite (int fd, const void *buf, size_t len)
443 {
444   int r;
445
446   while (len > 0) {
447     r = write (fd, buf, len);
448     if (r == -1)
449       return -1;
450
451     buf += r;
452     len -= r;
453   }
454
455   return 0;
456 }
457
458 static int
459 xread (int fd, void *buf, size_t len)
460 {
461   int r;
462
463   while (len > 0) {
464     r = read (fd, buf, len);
465     if (r == -1) {
466       if (errno == EINTR || errno == EAGAIN)
467         continue;
468       return -1;
469     }
470
471     buf += r;
472     len -= r;
473   }
474
475   return 0;
476 }
477
478 void
479 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
480 {
481   g->abort_cb = cb;
482 }
483
484 guestfs_abort_cb
485 guestfs_get_out_of_memory_handler (guestfs_h *g)
486 {
487   return g->abort_cb;
488 }
489
490 void
491 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
492 {
493   g->error_cb = cb;
494   g->error_cb_data = data;
495 }
496
497 guestfs_error_handler_cb
498 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
499 {
500   if (data_rtn) *data_rtn = g->error_cb_data;
501   return g->error_cb;
502 }
503
504 int
505 guestfs_set_verbose (guestfs_h *g, int v)
506 {
507   g->verbose = !!v;
508   return 0;
509 }
510
511 int
512 guestfs_get_verbose (guestfs_h *g)
513 {
514   return g->verbose;
515 }
516
517 int
518 guestfs_set_autosync (guestfs_h *g, int a)
519 {
520   g->autosync = !!a;
521   return 0;
522 }
523
524 int
525 guestfs_get_autosync (guestfs_h *g)
526 {
527   return g->autosync;
528 }
529
530 int
531 guestfs_set_path (guestfs_h *g, const char *path)
532 {
533   free (g->path);
534   g->path = NULL;
535
536   g->path =
537     path == NULL ?
538     safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
539   return 0;
540 }
541
542 const char *
543 guestfs_get_path (guestfs_h *g)
544 {
545   return g->path;
546 }
547
548 int
549 guestfs_set_qemu (guestfs_h *g, const char *qemu)
550 {
551   free (g->qemu);
552   g->qemu = NULL;
553
554   g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
555   return 0;
556 }
557
558 const char *
559 guestfs_get_qemu (guestfs_h *g)
560 {
561   return g->qemu;
562 }
563
564 int
565 guestfs_set_append (guestfs_h *g, const char *append)
566 {
567   free (g->append);
568   g->append = NULL;
569
570   g->append = append ? safe_strdup (g, append) : NULL;
571   return 0;
572 }
573
574 const char *
575 guestfs_get_append (guestfs_h *g)
576 {
577   return g->append;
578 }
579
580 /* Add a string to the current command line. */
581 static void
582 incr_cmdline_size (guestfs_h *g)
583 {
584   if (g->cmdline == NULL) {
585     /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
586     g->cmdline_size = 1;
587     g->cmdline = safe_malloc (g, sizeof (char *));
588     g->cmdline[0] = NULL;
589   }
590
591   g->cmdline_size++;
592   g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
593 }
594
595 static int
596 add_cmdline (guestfs_h *g, const char *str)
597 {
598   if (g->state != CONFIG) {
599     error (g, "command line cannot be altered after qemu subprocess launched");
600     return -1;
601   }
602
603   incr_cmdline_size (g);
604   g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
605   return 0;
606 }
607
608 int
609 guestfs_config (guestfs_h *g,
610                 const char *qemu_param, const char *qemu_value)
611 {
612   if (qemu_param[0] != '-') {
613     error (g, "guestfs_config: parameter must begin with '-' character");
614     return -1;
615   }
616
617   /* A bit fascist, but the user will probably break the extra
618    * parameters that we add if they try to set any of these.
619    */
620   if (strcmp (qemu_param, "-kernel") == 0 ||
621       strcmp (qemu_param, "-initrd") == 0 ||
622       strcmp (qemu_param, "-nographic") == 0 ||
623       strcmp (qemu_param, "-serial") == 0 ||
624       strcmp (qemu_param, "-vnc") == 0 ||
625       strcmp (qemu_param, "-full-screen") == 0 ||
626       strcmp (qemu_param, "-std-vga") == 0 ||
627       strcmp (qemu_param, "-vnc") == 0) {
628     error (g, "guestfs_config: parameter '%s' isn't allowed", qemu_param);
629     return -1;
630   }
631
632   if (add_cmdline (g, qemu_param) != 0) return -1;
633
634   if (qemu_value != NULL) {
635     if (add_cmdline (g, qemu_value) != 0) return -1;
636   }
637
638   return 0;
639 }
640
641 int
642 guestfs_add_drive (guestfs_h *g, const char *filename)
643 {
644   size_t len = strlen (filename) + 64;
645   char buf[len];
646
647   if (strchr (filename, ',') != NULL) {
648     error (g, "filename cannot contain ',' (comma) character");
649     return -1;
650   }
651
652   if (access (filename, F_OK) == -1) {
653     perrorf (g, "%s", filename);
654     return -1;
655   }
656
657   snprintf (buf, len, "file=%s", filename);
658
659   return guestfs_config (g, "-drive", buf);
660 }
661
662 int
663 guestfs_add_cdrom (guestfs_h *g, const char *filename)
664 {
665   if (strchr (filename, ',') != NULL) {
666     error (g, "filename cannot contain ',' (comma) character");
667     return -1;
668   }
669
670   if (access (filename, F_OK) == -1) {
671     perrorf (g, "%s", filename);
672     return -1;
673   }
674
675   return guestfs_config (g, "-cdrom", filename);
676 }
677
678 int
679 guestfs_launch (guestfs_h *g)
680 {
681   static const char *dir_template = "/tmp/libguestfsXXXXXX";
682   int r, i, pmore, memsize;
683   size_t len;
684   int wfd[2], rfd[2];
685   int tries;
686   const char *kernel_name = "vmlinuz." REPO "." host_cpu;
687   const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
688   char *path, *pelem, *pend;
689   char *kernel = NULL, *initrd = NULL;
690   char unixsock[256];
691   struct sockaddr_un addr;
692
693   /* Configured? */
694   if (!g->cmdline) {
695     error (g, "you must call guestfs_add_drive before guestfs_launch");
696     return -1;
697   }
698
699   if (g->state != CONFIG) {
700     error (g, "qemu has already been launched");
701     return -1;
702   }
703
704   /* Search g->path for the kernel and initrd. */
705   pelem = path = safe_strdup (g, g->path);
706   do {
707     pend = strchrnul (pelem, ':');
708     pmore = *pend == ':';
709     *pend = '\0';
710     len = pend - pelem;
711
712     /* Empty element or "." means cwd. */
713     if (len == 0 || (len == 1 && *pelem == '.')) {
714       if (g->verbose)
715         fprintf (stderr,
716                  "looking for kernel and initrd in current directory\n");
717       if (access (kernel_name, F_OK) == 0 && access (initrd_name, F_OK) == 0) {
718         kernel = safe_strdup (g, kernel_name);
719         initrd = safe_strdup (g, initrd_name);
720         break;
721       }
722     }
723     /* Look at <path>/kernel etc. */
724     else {
725       kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
726       initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
727       sprintf (kernel, "%s/%s", pelem, kernel_name);
728       sprintf (initrd, "%s/%s", pelem, initrd_name);
729
730       if (g->verbose)
731         fprintf (stderr, "looking for %s and %s\n", kernel, initrd);
732
733       if (access (kernel, F_OK) == 0 && access (initrd, F_OK) == 0)
734         break;
735       free (kernel);
736       free (initrd);
737       kernel = initrd = NULL;
738     }
739
740     pelem = pend + 1;
741   } while (pmore);
742
743   free (path);
744
745   if (kernel == NULL || initrd == NULL) {
746     error (g, "cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)",
747            kernel_name, initrd_name, g->path);
748     goto cleanup0;
749   }
750
751   /* Choose a suitable memory size.  Previously we tried to choose
752    * a minimal memory size, but this isn't really necessary since
753    * recent QEMU and KVM don't do anything nasty like locking
754    * memory into core any more.  This we can safely choose a
755    * large, generous amount of memory, and it'll just get swapped
756    * on smaller systems.
757    */
758   memsize = 384;
759
760   /* Make the temporary directory containing the socket. */
761   if (!g->tmpdir) {
762     g->tmpdir = safe_strdup (g, dir_template);
763     if (mkdtemp (g->tmpdir) == NULL) {
764       perrorf (g, "%s: cannot create temporary directory", dir_template);
765       goto cleanup0;
766     }
767   }
768
769   snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
770   unlink (unixsock);
771
772   if (pipe (wfd) == -1 || pipe (rfd) == -1) {
773     perrorf (g, "pipe");
774     goto cleanup0;
775   }
776
777   r = fork ();
778   if (r == -1) {
779     perrorf (g, "fork");
780     close (wfd[0]);
781     close (wfd[1]);
782     close (rfd[0]);
783     close (rfd[1]);
784     goto cleanup0;
785   }
786
787   if (r == 0) {                 /* Child (qemu). */
788     char vmchannel[256];
789     char append[256];
790     char memsize_str[256];
791
792     /* Set up the full command line.  Do this in the subprocess so we
793      * don't need to worry about cleaning up.
794      */
795     g->cmdline[0] = g->qemu;
796
797     /* Construct the -net channel parameter for qemu. */
798     snprintf (vmchannel, sizeof vmchannel,
799               "channel,%d:unix:%s,server,nowait",
800               VMCHANNEL_PORT, unixsock);
801
802     /* Linux kernel command line. */
803     snprintf (append, sizeof append,
804               "panic=1 console=ttyS0 guestfs=%s:%d%s%s%s",
805               VMCHANNEL_ADDR, VMCHANNEL_PORT,
806               g->verbose ? " guestfs_verbose=1" : "",
807               g->append ? " " : "", g->append ? g->append : "");
808
809     snprintf (memsize_str, sizeof memsize_str, "%d", memsize);
810
811     add_cmdline (g, "-m");
812     add_cmdline (g, memsize_str);
813 #if 0
814     add_cmdline (g, "-no-kqemu"); /* Avoids a warning. */
815 #endif
816     add_cmdline (g, "-no-reboot"); /* Force exit instead of reboot on panic */
817     add_cmdline (g, "-kernel");
818     add_cmdline (g, (char *) kernel);
819     add_cmdline (g, "-initrd");
820     add_cmdline (g, (char *) initrd);
821     add_cmdline (g, "-append");
822     add_cmdline (g, append);
823     add_cmdline (g, "-nographic");
824     add_cmdline (g, "-serial");
825     add_cmdline (g, "stdio");
826     add_cmdline (g, "-net");
827     add_cmdline (g, vmchannel);
828     add_cmdline (g, "-net");
829     add_cmdline (g, "user,vlan=0");
830     add_cmdline (g, "-net");
831     add_cmdline (g, "nic,model=virtio,vlan=0");
832     incr_cmdline_size (g);
833     g->cmdline[g->cmdline_size-1] = NULL;
834
835     if (g->verbose) {
836       fprintf (stderr, "%s", g->qemu);
837       for (i = 0; g->cmdline[i]; ++i)
838         fprintf (stderr, " %s", g->cmdline[i]);
839       fprintf (stderr, "\n");
840     }
841
842     /* Set up stdin, stdout. */
843     close (0);
844     close (1);
845     close (wfd[1]);
846     close (rfd[0]);
847     dup (wfd[0]);
848     dup (rfd[1]);
849     close (wfd[0]);
850     close (rfd[1]);
851
852 #if 0
853     /* Set up a new process group, so we can signal this process
854      * and all subprocesses (eg. if qemu is really a shell script).
855      */
856     setpgid (0, 0);
857 #endif
858
859     execv (g->qemu, g->cmdline); /* Run qemu. */
860     perror (g->qemu);
861     _exit (1);
862   }
863
864   /* Parent (library). */
865   g->pid = r;
866
867   free (kernel);
868   kernel = NULL;
869   free (initrd);
870   initrd = NULL;
871
872   /* Fork the recovery process off which will kill qemu if the parent
873    * process fails to do so (eg. if the parent segfaults).
874    */
875   r = fork ();
876   if (r == 0) {
877     pid_t qemu_pid = g->pid;
878     pid_t parent_pid = getppid ();
879
880     /* Writing to argv is hideously complicated and error prone.  See:
881      * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
882      */
883
884     /* Loop around waiting for one or both of the other processes to
885      * disappear.  It's fair to say this is very hairy.  The PIDs that
886      * we are looking at might be reused by another process.  We are
887      * effectively polling.  Is the cure worse than the disease?
888      */
889     for (;;) {
890       if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
891         _exit (0);
892       if (kill (parent_pid, 0) == -1) {
893         /* Parent's gone away, qemu still around, so kill qemu. */
894         kill (qemu_pid, 9);
895         _exit (0);
896       }
897       sleep (2);
898     }
899   }
900
901   /* Don't worry, if the fork failed, this will be -1.  The recovery
902    * process isn't essential.
903    */
904   g->recoverypid = r;
905
906   /* Start the clock ... */
907   time (&g->start_t);
908
909   /* Close the other ends of the pipe. */
910   close (wfd[0]);
911   close (rfd[1]);
912
913   if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
914       fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
915     perrorf (g, "fcntl");
916     goto cleanup1;
917   }
918
919   g->fd[0] = wfd[1];            /* stdin of child */
920   g->fd[1] = rfd[0];            /* stdout of child */
921
922   /* Open the Unix socket.  The vmchannel implementation that got
923    * merged with qemu sucks in a number of ways.  Both ends do
924    * connect(2), which means that no one knows what, if anything, is
925    * connected to the other end, or if it becomes disconnected.  Even
926    * worse, we have to wait some indeterminate time for qemu to create
927    * the socket and connect to it (which happens very early in qemu's
928    * start-up), so any code that uses vmchannel is inherently racy.
929    * Hence this silly loop.
930    */
931   g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
932   if (g->sock == -1) {
933     perrorf (g, "socket");
934     goto cleanup1;
935   }
936
937   if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
938     perrorf (g, "fcntl");
939     goto cleanup2;
940   }
941
942   addr.sun_family = AF_UNIX;
943   strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
944   addr.sun_path[UNIX_PATH_MAX-1] = '\0';
945
946   tries = 100;
947   /* Always sleep at least once to give qemu a small chance to start up. */
948   usleep (10000);
949   while (tries > 0) {
950     r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
951     if ((r == -1 && errno == EINPROGRESS) || r == 0)
952       goto connected;
953
954     if (errno != ENOENT)
955       perrorf (g, "connect");
956     tries--;
957     usleep (100000);
958   }
959
960   error (g, "failed to connect to vmchannel socket");
961   goto cleanup2;
962
963  connected:
964   /* Watch the file descriptors. */
965   free (g->msg_in);
966   g->msg_in = NULL;
967   g->msg_in_size = g->msg_in_allocated = 0;
968
969   free (g->msg_out);
970   g->msg_out = NULL;
971   g->msg_out_size = 0;
972   g->msg_out_pos = 0;
973
974   g->stdout_watch =
975     g->main_loop->add_handle (g->main_loop, g, g->fd[1],
976                               GUESTFS_HANDLE_READABLE,
977                               stdout_event, NULL);
978   if (g->stdout_watch == -1) {
979     error (g, "could not watch qemu stdout");
980     goto cleanup3;
981   }
982
983   if (guestfs__switch_to_receiving (g) == -1)
984     goto cleanup3;
985
986   g->state = LAUNCHING;
987   return 0;
988
989  cleanup3:
990   if (g->stdout_watch >= 0)
991     g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
992   if (g->sock_watch >= 0)
993     g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
994
995  cleanup2:
996   close (g->sock);
997
998  cleanup1:
999   close (wfd[1]);
1000   close (rfd[0]);
1001   kill (g->pid, 9);
1002   if (g->recoverypid > 0) kill (g->recoverypid, 9);
1003   waitpid (g->pid, NULL, 0);
1004   if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1005   g->fd[0] = -1;
1006   g->fd[1] = -1;
1007   g->sock = -1;
1008   g->pid = 0;
1009   g->recoverypid = 0;
1010   g->start_t = 0;
1011   g->stdout_watch = -1;
1012   g->sock_watch = -1;
1013
1014  cleanup0:
1015   free (kernel);
1016   free (initrd);
1017   return -1;
1018 }
1019
1020 static void
1021 finish_wait_ready (guestfs_h *g, void *vp)
1022 {
1023   if (g->verbose)
1024     fprintf (stderr, "finish_wait_ready called, %p, vp = %p\n", g, vp);
1025
1026   *((int *)vp) = 1;
1027   g->main_loop->main_loop_quit (g->main_loop, g);
1028 }
1029
1030 int
1031 guestfs_wait_ready (guestfs_h *g)
1032 {
1033   int finished = 0, r;
1034
1035   if (g->state == READY) return 0;
1036
1037   if (g->state == BUSY) {
1038     error (g, "qemu has finished launching already");
1039     return -1;
1040   }
1041
1042   if (g->state != LAUNCHING) {
1043     error (g, "qemu has not been launched yet");
1044     return -1;
1045   }
1046
1047   g->launch_done_cb = finish_wait_ready;
1048   g->launch_done_cb_data = &finished;
1049   r = g->main_loop->main_loop_run (g->main_loop, g);
1050   g->launch_done_cb = NULL;
1051   g->launch_done_cb_data = NULL;
1052
1053   if (r == -1) return -1;
1054
1055   if (finished != 1) {
1056     error (g, "guestfs_wait_ready failed, see earlier error messages");
1057     return -1;
1058   }
1059
1060   /* This is possible in some really strange situations, such as
1061    * guestfsd starts up OK but then qemu immediately exits.  Check for
1062    * it because the caller is probably expecting to be able to send
1063    * commands after this function returns.
1064    */
1065   if (g->state != READY) {
1066     error (g, "qemu launched and contacted daemon, but state != READY");
1067     return -1;
1068   }
1069
1070   return 0;
1071 }
1072
1073 int
1074 guestfs_kill_subprocess (guestfs_h *g)
1075 {
1076   if (g->state == CONFIG) {
1077     error (g, "no subprocess to kill");
1078     return -1;
1079   }
1080
1081   if (g->verbose)
1082     fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1083
1084   kill (g->pid, SIGTERM);
1085   if (g->recoverypid > 0) kill (g->recoverypid, 9);
1086
1087   return 0;
1088 }
1089
1090 /* Access current state. */
1091 int
1092 guestfs_is_config (guestfs_h *g)
1093 {
1094   return g->state == CONFIG;
1095 }
1096
1097 int
1098 guestfs_is_launching (guestfs_h *g)
1099 {
1100   return g->state == LAUNCHING;
1101 }
1102
1103 int
1104 guestfs_is_ready (guestfs_h *g)
1105 {
1106   return g->state == READY;
1107 }
1108
1109 int
1110 guestfs_is_busy (guestfs_h *g)
1111 {
1112   return g->state == BUSY;
1113 }
1114
1115 int
1116 guestfs_get_state (guestfs_h *g)
1117 {
1118   return g->state;
1119 }
1120
1121 int
1122 guestfs_set_ready (guestfs_h *g)
1123 {
1124   if (g->state != BUSY) {
1125     error (g, "guestfs_set_ready: called when in state %d != BUSY", g->state);
1126     return -1;
1127   }
1128   g->state = READY;
1129   return 0;
1130 }
1131
1132 int
1133 guestfs_set_busy (guestfs_h *g)
1134 {
1135   if (g->state != READY) {
1136     error (g, "guestfs_set_busy: called when in state %d != READY", g->state);
1137     return -1;
1138   }
1139   g->state = BUSY;
1140   return 0;
1141 }
1142
1143 int
1144 guestfs_end_busy (guestfs_h *g)
1145 {
1146   switch (g->state)
1147     {
1148     case BUSY:
1149       g->state = READY;
1150       break;
1151     case CONFIG:
1152     case READY:
1153       break;
1154     case LAUNCHING:
1155     case NO_HANDLE:
1156       error (g, "guestfs_end_busy: called when in state %d", g->state);
1157       return -1;
1158     }
1159   return 0;
1160 }
1161
1162 /* Structure-freeing functions.  These rely on the fact that the
1163  * structure format is identical to the XDR format.  See note in
1164  * generator.ml.
1165  */
1166 void
1167 guestfs_free_int_bool (struct guestfs_int_bool *x)
1168 {
1169   free (x);
1170 }
1171
1172 void
1173 guestfs_free_lvm_pv_list (struct guestfs_lvm_pv_list *x)
1174 {
1175   xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_pv_list, (char *) x);
1176   free (x);
1177 }
1178
1179 void
1180 guestfs_free_lvm_vg_list (struct guestfs_lvm_vg_list *x)
1181 {
1182   xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_vg_list, (char *) x);
1183   free (x);
1184 }
1185
1186 void
1187 guestfs_free_lvm_lv_list (struct guestfs_lvm_lv_list *x)
1188 {
1189   xdr_free ((xdrproc_t) xdr_guestfs_lvm_int_lv_list, (char *) x);
1190   free (x);
1191 }
1192
1193 /* We don't know if stdout_event or sock_read_event will be the
1194  * first to receive EOF if the qemu process dies.  This function
1195  * has the common cleanup code for both.
1196  */
1197 static void
1198 child_cleanup (guestfs_h *g)
1199 {
1200   if (g->verbose)
1201     fprintf (stderr, "stdout_event: %p: child process died\n", g);
1202   /*kill (g->pid, SIGTERM);*/
1203   if (g->recoverypid > 0) kill (g->recoverypid, 9);
1204   waitpid (g->pid, NULL, 0);
1205   if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1206   if (g->stdout_watch >= 0)
1207     g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1208   if (g->sock_watch >= 0)
1209     g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1210   close (g->fd[0]);
1211   close (g->fd[1]);
1212   close (g->sock);
1213   g->fd[0] = -1;
1214   g->fd[1] = -1;
1215   g->sock = -1;
1216   g->pid = 0;
1217   g->recoverypid = 0;
1218   g->start_t = 0;
1219   g->stdout_watch = -1;
1220   g->sock_watch = -1;
1221   g->state = CONFIG;
1222   if (g->subprocess_quit_cb)
1223     g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1224 }
1225
1226 /* This function is called whenever qemu prints something on stdout.
1227  * Qemu's stdout is also connected to the guest's serial console, so
1228  * we see kernel messages here too.
1229  */
1230 static void
1231 stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1232               int watch, int fd, int events)
1233 {
1234   char buf[4096];
1235   int n;
1236
1237 #if 0
1238   if (g->verbose)
1239     fprintf (stderr,
1240              "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1241              g, g->state, fd, events);
1242 #endif
1243
1244   if (g->fd[1] != fd) {
1245     error (g, "stdout_event: internal error: %d != %d", g->fd[1], fd);
1246     return;
1247   }
1248
1249   n = read (fd, buf, sizeof buf);
1250   if (n == 0) {
1251     /* Hopefully this indicates the qemu child process has died. */
1252     child_cleanup (g);
1253     return;
1254   }
1255
1256   if (n == -1) {
1257     if (errno != EINTR && errno != EAGAIN)
1258       perrorf (g, "read");
1259     return;
1260   }
1261
1262   /* In verbose mode, copy all log messages to stderr. */
1263   if (g->verbose)
1264     write (2, buf, n);
1265
1266   /* It's an actual log message, send it upwards if anyone is listening. */
1267   if (g->log_message_cb)
1268     g->log_message_cb (g, g->log_message_cb_data, buf, n);
1269 }
1270
1271 /* The function is called whenever we can read something on the
1272  * guestfsd (daemon inside the guest) communication socket.
1273  */
1274 static void
1275 sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1276                  int watch, int fd, int events)
1277 {
1278   XDR xdr;
1279   u_int32_t len;
1280   int n;
1281
1282   if (g->verbose)
1283     fprintf (stderr,
1284              "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1285              g, g->state, fd, events);
1286
1287   if (g->sock != fd) {
1288     error (g, "sock_read_event: internal error: %d != %d", g->sock, fd);
1289     return;
1290   }
1291
1292   if (g->msg_in_size <= g->msg_in_allocated) {
1293     g->msg_in_allocated += 4096;
1294     g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
1295   }
1296   n = read (g->sock, g->msg_in + g->msg_in_size,
1297             g->msg_in_allocated - g->msg_in_size);
1298   if (n == 0) {
1299     /* Disconnected. */
1300     child_cleanup (g);
1301     return;
1302   }
1303
1304   if (n == -1) {
1305     if (errno != EINTR && errno != EAGAIN)
1306       perrorf (g, "read");
1307     return;
1308   }
1309
1310   g->msg_in_size += n;
1311
1312   /* Have we got enough of a message to be able to process it yet? */
1313  again:
1314   if (g->msg_in_size < 4) return;
1315
1316   xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
1317   if (!xdr_uint32_t (&xdr, &len)) {
1318     error (g, "can't decode length word");
1319     goto cleanup;
1320   }
1321
1322   /* Length is normally the length of the message, but when guestfsd
1323    * starts up it sends a "magic" value (longer than any possible
1324    * message).  Check for this.
1325    */
1326   if (len == GUESTFS_LAUNCH_FLAG) {
1327     if (g->state != LAUNCHING)
1328       error (g, "received magic signature from guestfsd, but in state %d",
1329              g->state);
1330     else if (g->msg_in_size != 4)
1331       error (g, "received magic signature from guestfsd, but msg size is %d",
1332              g->msg_in_size);
1333     else {
1334       g->state = READY;
1335       if (g->launch_done_cb)
1336         g->launch_done_cb (g, g->launch_done_cb_data);
1337     }
1338
1339     goto cleanup;
1340   }
1341
1342   /* This can happen if a cancellation happens right at the end
1343    * of us sending a FileIn parameter to the daemon.  Discard.  The
1344    * daemon should send us an error message next.
1345    */
1346   if (len == GUESTFS_CANCEL_FLAG) {
1347     g->msg_in_size -= 4;
1348     memmove (g->msg_in, g->msg_in+4, g->msg_in_size);
1349     goto again;
1350   }
1351
1352   /* If this happens, it's pretty bad and we've probably lost
1353    * synchronization.
1354    */
1355   if (len > GUESTFS_MESSAGE_MAX) {
1356     error (g, "message length (%u) > maximum possible size (%d)",
1357            len, GUESTFS_MESSAGE_MAX);
1358     goto cleanup;
1359   }
1360
1361   if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1362
1363   /* Got the full message, begin processing it. */
1364 #if 0
1365   if (g->verbose) {
1366     int i, j;
1367
1368     for (i = 0; i < g->msg_in_size; i += 16) {
1369       printf ("%04x: ", i);
1370       for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1371         printf ("%02x ", (unsigned char) g->msg_in[j]);
1372       for (; j < i+16; ++j)
1373         printf ("   ");
1374       printf ("|");
1375       for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1376         if (isprint (g->msg_in[j]))
1377           printf ("%c", g->msg_in[j]);
1378         else
1379           printf (".");
1380       for (; j < i+16; ++j)
1381         printf (" ");
1382       printf ("|\n");
1383     }
1384   }
1385 #endif
1386
1387   /* Not in the expected state. */
1388   if (g->state != BUSY)
1389     error (g, "state %d != BUSY", g->state);
1390
1391   /* Push the message up to the higher layer. */
1392   if (g->reply_cb)
1393     g->reply_cb (g, g->reply_cb_data, &xdr);
1394   else
1395     /* This message (probably) should never be printed. */
1396     fprintf (stderr, "libguesfs: sock_read_event: !!! dropped message !!!\n");
1397
1398   g->msg_in_size -= len + 4;
1399   memmove (g->msg_in, g->msg_in+len+4, g->msg_in_size);
1400   if (g->msg_in_size > 0) goto again;
1401
1402  cleanup:
1403   /* Free the message buffer if it's grown excessively large. */
1404   if (g->msg_in_allocated > 65536) {
1405     free (g->msg_in);
1406     g->msg_in = NULL;
1407     g->msg_in_size = g->msg_in_allocated = 0;
1408   } else
1409     g->msg_in_size = 0;
1410
1411   xdr_destroy (&xdr);
1412 }
1413
1414 /* The function is called whenever we can write something on the
1415  * guestfsd (daemon inside the guest) communication socket.
1416  */
1417 static void
1418 sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1419                   int watch, int fd, int events)
1420 {
1421   int n;
1422
1423   if (g->verbose)
1424     fprintf (stderr,
1425              "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1426              g, g->state, fd, events);
1427
1428   if (g->sock != fd) {
1429     error (g, "sock_write_event: internal error: %d != %d", g->sock, fd);
1430     return;
1431   }
1432
1433   if (g->state != BUSY) {
1434     error (g, "sock_write_event: state %d != BUSY", g->state);
1435     return;
1436   }
1437
1438   if (g->verbose)
1439     fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1440              g->msg_out_size - g->msg_out_pos);
1441
1442   n = write (g->sock, g->msg_out + g->msg_out_pos,
1443              g->msg_out_size - g->msg_out_pos);
1444   if (n == -1) {
1445     if (errno != EAGAIN)
1446       perrorf (g, "write");
1447     return;
1448   }
1449
1450   if (g->verbose)
1451     fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1452
1453   g->msg_out_pos += n;
1454
1455   /* More to write? */
1456   if (g->msg_out_pos < g->msg_out_size)
1457     return;
1458
1459   if (g->verbose)
1460     fprintf (stderr, "sock_write_event: done writing, calling send_cb\n");
1461
1462   free (g->msg_out);
1463   g->msg_out = NULL;
1464   g->msg_out_pos = g->msg_out_size = 0;
1465
1466   /* Done writing, call the higher layer. */
1467   if (g->send_cb)
1468     g->send_cb (g, g->send_cb_data);
1469 }
1470
1471 void
1472 guestfs_set_send_callback (guestfs_h *g,
1473                            guestfs_send_cb cb, void *opaque)
1474 {
1475   g->send_cb = cb;
1476   g->send_cb_data = opaque;
1477 }
1478
1479 void
1480 guestfs_set_reply_callback (guestfs_h *g,
1481                             guestfs_reply_cb cb, void *opaque)
1482 {
1483   g->reply_cb = cb;
1484   g->reply_cb_data = opaque;
1485 }
1486
1487 void
1488 guestfs_set_log_message_callback (guestfs_h *g,
1489                                   guestfs_log_message_cb cb, void *opaque)
1490 {
1491   g->log_message_cb = cb;
1492   g->log_message_cb_data = opaque;
1493 }
1494
1495 void
1496 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1497                                       guestfs_subprocess_quit_cb cb, void *opaque)
1498 {
1499   g->subprocess_quit_cb = cb;
1500   g->subprocess_quit_cb_data = opaque;
1501 }
1502
1503 void
1504 guestfs_set_launch_done_callback (guestfs_h *g,
1505                                   guestfs_launch_done_cb cb, void *opaque)
1506 {
1507   g->launch_done_cb = cb;
1508   g->launch_done_cb_data = opaque;
1509 }
1510
1511 /* Access to the handle's main loop and the default main loop. */
1512 void
1513 guestfs_set_main_loop (guestfs_h *g, guestfs_main_loop *main_loop)
1514 {
1515   g->main_loop = main_loop;
1516 }
1517
1518 guestfs_main_loop *
1519 guestfs_get_main_loop (guestfs_h *g)
1520 {
1521   return g->main_loop;
1522 }
1523
1524 guestfs_main_loop *
1525 guestfs_get_default_main_loop (void)
1526 {
1527   return (guestfs_main_loop *) &default_main_loop;
1528 }
1529
1530 /* Change the daemon socket handler so that we are now writing.
1531  * This sets the handle to sock_write_event.
1532  */
1533 int
1534 guestfs__switch_to_sending (guestfs_h *g)
1535 {
1536   if (g->sock_watch >= 0) {
1537     if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1538       error (g, "remove_handle failed");
1539       g->sock_watch = -1;
1540       return -1;
1541     }
1542   }
1543
1544   g->sock_watch =
1545     g->main_loop->add_handle (g->main_loop, g, g->sock,
1546                               GUESTFS_HANDLE_WRITABLE,
1547                               sock_write_event, NULL);
1548   if (g->sock_watch == -1) {
1549     error (g, "add_handle failed");
1550     return -1;
1551   }
1552
1553   return 0;
1554 }
1555
1556 int
1557 guestfs__switch_to_receiving (guestfs_h *g)
1558 {
1559   if (g->sock_watch >= 0) {
1560     if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1561       error (g, "remove_handle failed");
1562       g->sock_watch = -1;
1563       return -1;
1564     }
1565   }
1566
1567   g->sock_watch =
1568     g->main_loop->add_handle (g->main_loop, g, g->sock,
1569                               GUESTFS_HANDLE_READABLE,
1570                               sock_read_event, NULL);
1571   if (g->sock_watch == -1) {
1572     error (g, "add_handle failed");
1573     return -1;
1574   }
1575
1576   return 0;
1577 }
1578
1579 /* Dispatch a call (len + header + args) to the remote daemon,
1580  * synchronously (ie. using the guest's main loop to wait until
1581  * it has been sent).  Returns -1 for error, or the serial
1582  * number of the message.
1583  */
1584 static void
1585 send_cb (guestfs_h *g, void *data)
1586 {
1587   guestfs_main_loop *ml = guestfs_get_main_loop (g);
1588
1589   *((int *)data) = 1;
1590   ml->main_loop_quit (ml, g);
1591 }
1592
1593 int
1594 guestfs__send_sync (guestfs_h *g, int proc_nr,
1595                     xdrproc_t xdrp, char *args)
1596 {
1597   struct guestfs_message_header hdr;
1598   XDR xdr;
1599   u_int32_t len;
1600   int serial = g->msg_next_serial++;
1601   int sent;
1602   guestfs_main_loop *ml = guestfs_get_main_loop (g);
1603
1604   if (g->state != BUSY) {
1605     error (g, "guestfs__send_sync: state %d != BUSY", g->state);
1606     return -1;
1607   }
1608
1609   /* This is probably an internal error.  Or perhaps we should just
1610    * free the buffer anyway?
1611    */
1612   if (g->msg_out != NULL) {
1613     error (g, "guestfs__send_sync: msg_out should be NULL");
1614     return -1;
1615   }
1616
1617   /* We have to allocate this message buffer on the heap because
1618    * it is quite large (although will be mostly unused).  We
1619    * can't allocate it on the stack because in some environments
1620    * we have quite limited stack space available, notably when
1621    * running in the JVM.
1622    */
1623   g->msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
1624   xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
1625
1626   /* Serialize the header. */
1627   hdr.prog = GUESTFS_PROGRAM;
1628   hdr.vers = GUESTFS_PROTOCOL_VERSION;
1629   hdr.proc = proc_nr;
1630   hdr.direction = GUESTFS_DIRECTION_CALL;
1631   hdr.serial = serial;
1632   hdr.status = GUESTFS_STATUS_OK;
1633
1634   if (!xdr_guestfs_message_header (&xdr, &hdr)) {
1635     error (g, "xdr_guestfs_message_header failed");
1636     goto cleanup1;
1637   }
1638
1639   /* Serialize the args.  If any, because some message types
1640    * have no parameters.
1641    */
1642   if (xdrp) {
1643     if (!(*xdrp) (&xdr, args)) {
1644       error (g, "dispatch failed to marshal args");
1645       goto cleanup1;
1646     }
1647   }
1648
1649   /* Get the actual length of the message, resize the buffer to match
1650    * the actual length, and write the length word at the beginning.
1651    */
1652   len = xdr_getpos (&xdr);
1653   xdr_destroy (&xdr);
1654
1655   g->msg_out = safe_realloc (g, g->msg_out, len + 4);
1656   g->msg_out_size = len + 4;
1657   g->msg_out_pos = 0;
1658
1659   xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1660   xdr_uint32_t (&xdr, &len);
1661
1662   if (guestfs__switch_to_sending (g) == -1)
1663     goto cleanup1;
1664
1665   sent = 0;
1666   guestfs_set_send_callback (g, send_cb, &sent);
1667   if (ml->main_loop_run (ml, g) == -1)
1668     goto cleanup1;
1669   if (sent != 1) {
1670     error (g, "send failed, see earlier error messages");
1671     goto cleanup1;
1672   }
1673
1674   return serial;
1675
1676  cleanup1:
1677   free (g->msg_out);
1678   g->msg_out = NULL;
1679   g->msg_out_size = 0;
1680   return -1;
1681 }
1682
1683 static int cancel = 0; /* XXX Implement file cancellation. */
1684 static int send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t len);
1685 static int send_file_data_sync (guestfs_h *g, const char *buf, size_t len);
1686 static int send_file_cancellation_sync (guestfs_h *g);
1687 static int send_file_complete_sync (guestfs_h *g);
1688
1689 /* Synchronously send a file.
1690  * Returns:
1691  *   0 OK
1692  *   -1 error
1693  *   -2 daemon cancelled (we must read the error message)
1694  */
1695 int
1696 guestfs__send_file_sync (guestfs_h *g, const char *filename)
1697 {
1698   char buf[GUESTFS_MAX_CHUNK_SIZE];
1699   int fd, r, err;
1700
1701   fd = open (filename, O_RDONLY);
1702   if (fd == -1) {
1703     perrorf (g, "open: %s", filename);
1704     send_file_cancellation_sync (g);
1705     /* Daemon sees cancellation and won't reply, so caller can
1706      * just return here.
1707      */
1708     return -1;
1709   }
1710
1711   /* Send file in chunked encoding. */
1712   while (!cancel) {
1713     r = read (fd, buf, sizeof buf);
1714     if (r == -1 && (errno == EINTR || errno == EAGAIN))
1715       continue;
1716     if (r <= 0) break;
1717     err = send_file_data_sync (g, buf, r);
1718     if (err < 0) {
1719       if (err == -2)            /* daemon sent cancellation */
1720         send_file_cancellation_sync (g);
1721       return err;
1722     }
1723   }
1724
1725   if (cancel) {                 /* cancel from either end */
1726     send_file_cancellation_sync (g);
1727     return -1;
1728   }
1729
1730   if (r == -1) {
1731     perrorf (g, "read: %s", filename);
1732     send_file_cancellation_sync (g);
1733     return -1;
1734   }
1735
1736   /* End of file, but before we send that, we need to close
1737    * the file and check for errors.
1738    */
1739   if (close (fd) == -1) {
1740     perrorf (g, "close: %s", filename);
1741     send_file_cancellation_sync (g);
1742     return -1;
1743   }
1744
1745   return send_file_complete_sync (g);
1746 }
1747
1748 /* Send a chunk of file data. */
1749 static int
1750 send_file_data_sync (guestfs_h *g, const char *buf, size_t len)
1751 {
1752   return send_file_chunk_sync (g, 0, buf, len);
1753 }
1754
1755 /* Send a cancellation message. */
1756 static int
1757 send_file_cancellation_sync (guestfs_h *g)
1758 {
1759   return send_file_chunk_sync (g, 1, NULL, 0);
1760 }
1761
1762 /* Send a file complete chunk. */
1763 static int
1764 send_file_complete_sync (guestfs_h *g)
1765 {
1766   char buf[1];
1767   return send_file_chunk_sync (g, 0, buf, 0);
1768 }
1769
1770 /* Send a chunk, cancellation or end of file, synchronously (ie. wait
1771  * for it to go).
1772  */
1773 static int check_for_daemon_cancellation (guestfs_h *g);
1774
1775 static int
1776 send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t buflen)
1777 {
1778   u_int32_t len;
1779   int sent;
1780   guestfs_chunk chunk;
1781   XDR xdr;
1782   guestfs_main_loop *ml = guestfs_get_main_loop (g);
1783
1784   if (g->state != BUSY) {
1785     error (g, "send_file_chunk_sync: state %d != READY", g->state);
1786     return -1;
1787   }
1788
1789   /* This is probably an internal error.  Or perhaps we should just
1790    * free the buffer anyway?
1791    */
1792   if (g->msg_out != NULL) {
1793     error (g, "guestfs__send_sync: msg_out should be NULL");
1794     return -1;
1795   }
1796
1797   /* Did the daemon send a cancellation message? */
1798   if (check_for_daemon_cancellation (g)) {
1799     if (g->verbose)
1800       fprintf (stderr, "got daemon cancellation\n");
1801     return -2;
1802   }
1803
1804   /* Allocate the chunk buffer.  Don't use the stack to avoid
1805    * excessive stack usage and unnecessary copies.
1806    */
1807   g->msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
1808   xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
1809
1810   /* Serialize the chunk. */
1811   chunk.cancel = cancel;
1812   chunk.data.data_len = buflen;
1813   chunk.data.data_val = (char *) buf;
1814
1815   if (!xdr_guestfs_chunk (&xdr, &chunk)) {
1816     error (g, "xdr_guestfs_chunk failed (buf = %p, buflen = %zu)",
1817            buf, buflen);
1818     xdr_destroy (&xdr);
1819     goto cleanup1;
1820   }
1821
1822   len = xdr_getpos (&xdr);
1823   xdr_destroy (&xdr);
1824
1825   /* Reduce the size of the outgoing message buffer to the real length. */
1826   g->msg_out = safe_realloc (g, g->msg_out, len + 4);
1827   g->msg_out_size = len + 4;
1828   g->msg_out_pos = 0;
1829
1830   xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
1831   xdr_uint32_t (&xdr, &len);
1832
1833   if (guestfs__switch_to_sending (g) == -1)
1834     goto cleanup1;
1835
1836   sent = 0;
1837   guestfs_set_send_callback (g, send_cb, &sent);
1838   if (ml->main_loop_run (ml, g) == -1)
1839     goto cleanup1;
1840   if (sent != 1) {
1841     error (g, "send file chunk failed, see earlier error messages");
1842     goto cleanup1;
1843   }
1844
1845   return 0;
1846
1847  cleanup1:
1848   free (g->msg_out);
1849   g->msg_out = NULL;
1850   g->msg_out_size = 0;
1851   return -1;
1852 }
1853
1854 /* At this point we are sending FileIn file(s) to the guest, and not
1855  * expecting to read anything, so if we do read anything, it must be
1856  * a cancellation message.  This checks for this case without blocking.
1857  */
1858 static int
1859 check_for_daemon_cancellation (guestfs_h *g)
1860 {
1861   fd_set rset;
1862   struct timeval tv;
1863   int r;
1864   char buf[4];
1865   uint32_t flag;
1866   XDR xdr;
1867
1868   FD_ZERO (&rset);
1869   FD_SET (g->sock, &rset);
1870   tv.tv_sec = 0;
1871   tv.tv_usec = 0;
1872   r = select (g->sock+1, &rset, NULL, NULL, &tv);
1873   if (r == -1) {
1874     perrorf (g, "select");
1875     return 0;
1876   }
1877   if (r == 0)
1878     return 0;
1879
1880   /* Read the message from the daemon. */
1881   r = xread (g->sock, buf, sizeof buf);
1882   if (r == -1) {
1883     perrorf (g, "read");
1884     return 0;
1885   }
1886
1887   xdrmem_create (&xdr, buf, sizeof buf, XDR_DECODE);
1888   xdr_uint32_t (&xdr, &flag);
1889   xdr_destroy (&xdr);
1890
1891   if (flag != GUESTFS_CANCEL_FLAG) {
1892     error (g, "check_for_daemon_cancellation: read 0x%x from daemon, expected 0x%x\n",
1893            flag, GUESTFS_CANCEL_FLAG);
1894     return 0;
1895   }
1896
1897   return 1;
1898 }
1899
1900 /* Synchronously receive a file. */
1901
1902 /* Returns -1 = error, 0 = EOF, 1 = more data */
1903 static int receive_file_data_sync (guestfs_h *g, void **buf, size_t *len);
1904
1905 int
1906 guestfs__receive_file_sync (guestfs_h *g, const char *filename)
1907 {
1908   void *buf;
1909   int fd, r;
1910   size_t len;
1911
1912   fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
1913   if (fd == -1) {
1914     perrorf (g, "open: %s", filename);
1915     goto cancel;
1916   }
1917
1918   /* Receive the file in chunked encoding. */
1919   while ((r = receive_file_data_sync (g, &buf, &len)) >= 0) {
1920     if (xwrite (fd, buf, len) == -1) {
1921       perrorf (g, "%s: write", filename);
1922       free (buf);
1923       goto cancel;
1924     }
1925     free (buf);
1926     if (r == 0) break; /* End of file. */
1927   }
1928
1929   if (r == -1) {
1930     error (g, "%s: error in chunked encoding", filename);
1931     return -1;
1932   }
1933
1934   if (close (fd) == -1) {
1935     perrorf (g, "close: %s", filename);
1936     return -1;
1937   }
1938
1939   return 0;
1940
1941  cancel: ;
1942   /* Send cancellation message to daemon, then wait until it
1943    * cancels (just throwing away data).
1944    */
1945   XDR xdr;
1946   char fbuf[4];
1947   uint32_t flag = GUESTFS_CANCEL_FLAG;
1948
1949   xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
1950   xdr_uint32_t (&xdr, &flag);
1951   xdr_destroy (&xdr);
1952
1953   if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
1954     perrorf (g, "write to daemon socket");
1955     return -1;
1956   }
1957
1958   while ((r = receive_file_data_sync (g, NULL, NULL)) > 0)
1959     ;                           /* just discard it */
1960
1961   return -1;
1962 }
1963
1964 /* Note that the reply callback can be called multiple times before
1965  * the main loop quits and we get back to the synchronous code.  So
1966  * we have to be prepared to save multiple chunks on a list here.
1967  */
1968 struct receive_file_ctx {
1969   int count;                    /* 0 if receive_file_cb not called, or
1970                                  * else count number of chunks.
1971                                  */
1972   guestfs_chunk *chunks;        /* Array of chunks. */
1973 };
1974
1975 static void
1976 free_chunks (struct receive_file_ctx *ctx)
1977 {
1978   int i;
1979
1980   for (i = 0; i < ctx->count; ++i)
1981     free (ctx->chunks[i].data.data_val);
1982
1983   free (ctx->chunks);
1984 }
1985
1986 static void
1987 receive_file_cb (guestfs_h *g, void *data, XDR *xdr)
1988 {
1989   guestfs_main_loop *ml = guestfs_get_main_loop (g);
1990   struct receive_file_ctx *ctx = (struct receive_file_ctx *) data;
1991   guestfs_chunk chunk;
1992
1993   if (ctx->count == -1)         /* Parse error occurred previously. */
1994     return;
1995
1996   ml->main_loop_quit (ml, g);
1997
1998   memset (&chunk, 0, sizeof chunk);
1999
2000   if (!xdr_guestfs_chunk (xdr, &chunk)) {
2001     error (g, "failed to parse file chunk");
2002     free_chunks (ctx);
2003     ctx->chunks = NULL;
2004     ctx->count = -1;
2005     return;
2006   }
2007
2008   /* Copy the chunk to the list. */
2009   ctx->chunks = safe_realloc (g, ctx->chunks,
2010                               sizeof (guestfs_chunk) * (ctx->count+1));
2011   ctx->chunks[ctx->count] = chunk;
2012   ctx->count++;
2013 }
2014
2015 /* Receive a chunk of file data. */
2016 /* Returns -1 = error, 0 = EOF, 1 = more data */
2017 static int
2018 receive_file_data_sync (guestfs_h *g, void **buf, size_t *len_r)
2019 {
2020   struct receive_file_ctx ctx;
2021   guestfs_main_loop *ml = guestfs_get_main_loop (g);
2022   int i;
2023   size_t len;
2024
2025   ctx.count = 0;
2026   ctx.chunks = NULL;
2027
2028   guestfs_set_reply_callback (g, receive_file_cb, &ctx);
2029   (void) ml->main_loop_run (ml, g);
2030   guestfs_set_reply_callback (g, NULL, NULL);
2031
2032   if (ctx.count == 0) {
2033     error (g, "receive_file_data_sync: reply callback not called\n");
2034     return -1;
2035   }
2036
2037   if (ctx.count == -1) {
2038     error (g, "receive_file_data_sync: parse error in reply callback\n");
2039     /* callback already freed the chunks */
2040     return -1;
2041   }
2042
2043   if (g->verbose)
2044     fprintf (stderr, "receive_file_data_sync: got %d chunks\n", ctx.count);
2045
2046   /* Process each chunk in the list. */
2047   if (buf) *buf = NULL;         /* Accumulate data in this buffer. */
2048   len = 0;
2049
2050   for (i = 0; i < ctx.count; ++i) {
2051     if (ctx.chunks[i].cancel) {
2052       error (g, "file receive cancelled by daemon");
2053       free_chunks (&ctx);
2054       if (buf) free (*buf);
2055       if (len_r) *len_r = 0;
2056       return -1;
2057     }
2058
2059     if (ctx.chunks[i].data.data_len == 0) { /* end of transfer */
2060       free_chunks (&ctx);
2061       if (len_r) *len_r = len;
2062       return 0;
2063     }
2064
2065     if (buf) {
2066       *buf = safe_realloc (g, *buf, len + ctx.chunks[i].data.data_len);
2067       memcpy (*buf+len, ctx.chunks[i].data.data_val,
2068               ctx.chunks[i].data.data_len);
2069     }
2070     len += ctx.chunks[i].data.data_len;
2071   }
2072
2073   if (len_r) *len_r = len;
2074   free_chunks (&ctx);
2075   return 1;
2076 }
2077
2078 /* This is the default main loop implementation, using select(2). */
2079
2080 static int
2081 select_add_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd, int events,
2082                    guestfs_handle_event_cb cb, void *data)
2083 {
2084   struct select_main_loop *ml = (struct select_main_loop *) mlv;
2085
2086   if (fd < 0 || fd >= FD_SETSIZE) {
2087     error (g, "fd %d is out of range", fd);
2088     return -1;
2089   }
2090
2091   if ((events & ~(GUESTFS_HANDLE_READABLE |
2092                   GUESTFS_HANDLE_WRITABLE |
2093                   GUESTFS_HANDLE_HANGUP |
2094                   GUESTFS_HANDLE_ERROR)) != 0) {
2095     error (g, "set of events (0x%x) contains unknown events", events);
2096     return -1;
2097   }
2098
2099   if (events == 0) {
2100     error (g, "set of events is empty");
2101     return -1;
2102   }
2103
2104   if (FD_ISSET (fd, &ml->rset) ||
2105       FD_ISSET (fd, &ml->wset) ||
2106       FD_ISSET (fd, &ml->xset)) {
2107     error (g, "fd %d is already registered", fd);
2108     return -1;
2109   }
2110
2111   if (cb == NULL) {
2112     error (g, "callback is NULL");
2113     return -1;
2114   }
2115
2116   if ((events & GUESTFS_HANDLE_READABLE))
2117     FD_SET (fd, &ml->rset);
2118   if ((events & GUESTFS_HANDLE_WRITABLE))
2119     FD_SET (fd, &ml->wset);
2120   if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
2121     FD_SET (fd, &ml->xset);
2122
2123   if (fd > ml->max_fd) {
2124     ml->max_fd = fd;
2125     ml->handle_cb_data =
2126       safe_realloc (g, ml->handle_cb_data,
2127                     sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2128   }
2129   ml->handle_cb_data[fd].cb = cb;
2130   ml->handle_cb_data[fd].g = g;
2131   ml->handle_cb_data[fd].data = data;
2132
2133   ml->nr_fds++;
2134
2135   /* Any integer >= 0 can be the handle, and this is as good as any ... */
2136   return fd;
2137 }
2138
2139 static int
2140 select_remove_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd)
2141 {
2142   struct select_main_loop *ml = (struct select_main_loop *) mlv;
2143
2144   if (fd < 0 || fd >= FD_SETSIZE) {
2145     error (g, "fd %d is out of range", fd);
2146     return -1;
2147   }
2148
2149   if (!FD_ISSET (fd, &ml->rset) &&
2150       !FD_ISSET (fd, &ml->wset) &&
2151       !FD_ISSET (fd, &ml->xset)) {
2152     error (g, "fd %d was not registered", fd);
2153     return -1;
2154   }
2155
2156   FD_CLR (fd, &ml->rset);
2157   FD_CLR (fd, &ml->wset);
2158   FD_CLR (fd, &ml->xset);
2159
2160   if (fd == ml->max_fd) {
2161     ml->max_fd--;
2162     ml->handle_cb_data =
2163       safe_realloc (g, ml->handle_cb_data,
2164                     sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2165   }
2166
2167   ml->nr_fds--;
2168
2169   return 0;
2170 }
2171
2172 static int
2173 select_add_timeout (guestfs_main_loop *mlv, guestfs_h *g, int interval,
2174                     guestfs_handle_timeout_cb cb, void *data)
2175 {
2176   //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2177
2178   abort ();                     /* XXX not implemented yet */
2179 }
2180
2181 static int
2182 select_remove_timeout (guestfs_main_loop *mlv, guestfs_h *g, int timer)
2183 {
2184   //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2185
2186   abort ();                     /* XXX not implemented yet */
2187 }
2188
2189 /* The 'g' parameter is just used for error reporting.  Events
2190  * for multiple handles can be dispatched by running the main
2191  * loop.
2192  */
2193 static int
2194 select_main_loop_run (guestfs_main_loop *mlv, guestfs_h *g)
2195 {
2196   struct select_main_loop *ml = (struct select_main_loop *) mlv;
2197   int fd, r, events;
2198   fd_set rset2, wset2, xset2;
2199
2200   if (ml->is_running) {
2201     error (g, "select_main_loop_run: this cannot be called recursively");
2202     return -1;
2203   }
2204
2205   ml->is_running = 1;
2206
2207   while (ml->is_running) {
2208     if (ml->nr_fds == 0)
2209       break;
2210
2211     rset2 = ml->rset;
2212     wset2 = ml->wset;
2213     xset2 = ml->xset;
2214     r = select (ml->max_fd+1, &rset2, &wset2, &xset2, NULL);
2215     if (r == -1) {
2216       if (errno == EINTR || errno == EAGAIN)
2217         continue;
2218       perrorf (g, "select");
2219       ml->is_running = 0;
2220       return -1;
2221     }
2222
2223     for (fd = 0; r > 0 && fd <= ml->max_fd; ++fd) {
2224       events = 0;
2225       if (FD_ISSET (fd, &rset2))
2226         events |= GUESTFS_HANDLE_READABLE;
2227       if (FD_ISSET (fd, &wset2))
2228         events |= GUESTFS_HANDLE_WRITABLE;
2229       if (FD_ISSET (fd, &xset2))
2230         events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
2231       if (events) {
2232         r--;
2233         ml->handle_cb_data[fd].cb ((guestfs_main_loop *) ml,
2234                                    ml->handle_cb_data[fd].g,
2235                                    ml->handle_cb_data[fd].data,
2236                                    fd, fd, events);
2237       }
2238     }
2239   }
2240
2241   ml->is_running = 0;
2242   return 0;
2243 }
2244
2245 static int
2246 select_main_loop_quit (guestfs_main_loop *mlv, guestfs_h *g)
2247 {
2248   struct select_main_loop *ml = (struct select_main_loop *) mlv;
2249
2250   /* Note that legitimately ml->is_running can be zero when
2251    * this function is called.
2252    */
2253
2254   ml->is_running = 0;
2255   return 0;
2256 }