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