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