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