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