2 * Copyright (C) 2009-2010 Red Hat Inc.
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.
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.
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
21 #define _BSD_SOURCE /* for mkdtemp, usleep */
34 #include <sys/select.h>
38 #include <rpc/types.h>
45 #ifdef HAVE_SYS_TYPES_H
46 #include <sys/types.h>
49 #ifdef HAVE_SYS_WAIT_H
53 #ifdef HAVE_SYS_SOCKET_H
54 #include <sys/socket.h>
61 #include <arpa/inet.h>
62 #include <netinet/in.h>
65 #include "glthread/lock.h"
66 #include "ignore-value.h"
69 #include "guestfs-internal.h"
70 #include "guestfs-internal-actions.h"
71 #include "guestfs_protocol.h"
73 /* Size of guestfs_progress message on the wire. */
74 #define PROGRESS_MESSAGE_SIZE 24
76 /* This is the code used to send and receive RPC messages and (for
77 * certain types of message) to perform file transfers. This code is
78 * driven from the generated actions (src/actions.c). There
79 * are five different cases to consider:
81 * (1) A non-daemon function. There is no RPC involved at all, it's
82 * all handled inside the library.
84 * (2) A simple RPC (eg. "mount"). We write the request, then read
85 * the reply. The sequence of calls is:
92 * (3) An RPC with FileOut parameters (eg. "upload"). We write the
93 * request, then write the file(s), then read the reply. The sequence
98 * guestfs___send_file (possibly multiple times)
102 * (4) An RPC with FileIn parameters (eg. "download"). We write the
103 * request, then read the reply, then read the file(s). The sequence
109 * guestfs___recv_file (possibly multiple times)
112 * (5) Both FileOut and FileIn parameters. There are no calls like
113 * this in the current API, but they would be implemented as a
114 * combination of cases (3) and (4).
116 * During all writes and reads, we also select(2) on qemu stdout
117 * looking for messages (guestfsd stderr and guest kernel dmesg), and
118 * anything received is passed up through the log_message_cb. This is
119 * also the reason why all the sockets are non-blocking. We also have
120 * to check for EOF (qemu died). All of this is handled by the
121 * functions send_to_daemon and recv_from_daemon.
125 xwrite (int fd, const void *v_buf, size_t len)
127 const char *buf = v_buf;
131 r = write (fd, buf, len);
143 guestfs___set_busy (guestfs_h *g)
145 if (g->state != READY) {
146 error (g, _("guestfs_set_busy: called when in state %d != READY"),
155 guestfs___end_busy (guestfs_h *g)
169 error (g, _("guestfs_end_busy: called when in state %d"), g->state);
175 /* This is called if we detect EOF, ie. qemu died. */
177 child_cleanup (guestfs_h *g)
179 debug (g, "child_cleanup: %p: child process died", g);
181 /*if (g->pid > 0) kill (g->pid, SIGTERM);*/
182 if (g->recoverypid > 0) kill (g->recoverypid, 9);
183 waitpid (g->pid, NULL, 0);
184 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
185 if (g->fd[0] >= 0) close (g->fd[0]);
186 if (g->fd[1] >= 0) close (g->fd[1]);
193 memset (&g->launch_t, 0, sizeof g->launch_t);
195 guestfs___call_callbacks_void (g, GUESTFS_EVENT_SUBPROCESS_QUIT);
199 read_log_message_or_eof (guestfs_h *g, int fd, int error_if_eof)
205 debug (g, "read_log_message_or_eof: %p g->state = %d, fd = %d",
209 /* QEMU's console emulates a 16550A serial port. The real 16550A
210 * device has a small FIFO buffer (16 bytes) which means here we see
211 * lots of small reads of 1-16 bytes in length, usually single
214 n = read (fd, buf, sizeof buf);
216 /* Hopefully this indicates the qemu child process has died. */
220 /* We weren't expecting eof here (called from launch) so place
221 * something in the error buffer. RHBZ#588851.
223 error (g, "child process died unexpectedly");
229 if (errno == EINTR || errno == EAGAIN)
236 /* It's an actual log message, send it upwards if anyone is listening. */
237 guestfs___call_callbacks_message (g, GUESTFS_EVENT_APPLIANCE, buf, n);
242 /* Read 'n' bytes, setting the socket to blocking temporarily so
243 * that we really read the number of bytes requested.
244 * Returns: 0 == EOF while reading
245 * -1 == error, error() function has been called
246 * n == read 'n' bytes in full
249 really_read_from_socket (guestfs_h *g, int sock, char *buf, size_t n)
255 /* Set socket to blocking. */
256 flags = fcntl (sock, F_GETFL);
258 perrorf (g, "fcntl");
261 if (fcntl (sock, F_SETFL, flags & ~O_NONBLOCK) == -1) {
262 perrorf (g, "fcntl");
268 r = read (sock, &buf[got], n-got);
278 /* Restore original socket flags. */
279 if (fcntl (sock, F_SETFL, flags) == -1) {
280 perrorf (g, "fcntl");
284 return (ssize_t) got;
288 send_progress_message (guestfs_h *g, const guestfs_progress *message)
292 array[0] = message->proc;
293 array[1] = message->serial;
294 array[2] = message->position;
295 array[3] = message->total;
297 guestfs___call_callbacks_array (g, GUESTFS_EVENT_PROGRESS,
298 array, sizeof array / sizeof array[0]);
302 check_for_daemon_cancellation_or_eof (guestfs_h *g, int fd)
309 debug (g, "check_for_daemon_cancellation_or_eof: %p g->state = %d, fd = %d",
312 n = really_read_from_socket (g, fd, buf, 4);
316 /* Hopefully this indicates the qemu child process has died. */
321 xdrmem_create (&xdr, buf, 4, XDR_DECODE);
322 xdr_uint32_t (&xdr, &flag);
325 /* Read and process progress messages that happen during FileIn. */
326 if (flag == GUESTFS_PROGRESS_FLAG) {
327 char buf[PROGRESS_MESSAGE_SIZE];
329 n = really_read_from_socket (g, fd, buf, PROGRESS_MESSAGE_SIZE);
337 if (g->state == BUSY) {
338 guestfs_progress message;
340 xdrmem_create (&xdr, buf, PROGRESS_MESSAGE_SIZE, XDR_DECODE);
341 xdr_guestfs_progress (&xdr, &message);
344 send_progress_message (g, &message);
350 if (flag != GUESTFS_CANCEL_FLAG) {
351 error (g, _("check_for_daemon_cancellation_or_eof: read 0x%x from daemon, expected 0x%x\n"),
352 flag, GUESTFS_CANCEL_FLAG);
359 /* This writes the whole N bytes of BUF to the daemon socket.
361 * If the whole write is successful, it returns 0.
362 * If there was an error, it returns -1.
363 * If the daemon sent a cancellation message, it returns -2.
365 * It also checks qemu stdout for log messages and passes those up
366 * through log_message_cb.
368 * It also checks for EOF (qemu died) and passes that up through the
369 * child_cleanup function above.
372 guestfs___send_to_daemon (guestfs_h *g, const void *v_buf, size_t n)
374 const char *buf = v_buf;
378 debug (g, "send_to_daemon: %p g->state = %d, n = %zu", g, g->state, n);
383 if (g->fd[1] >= 0) /* Read qemu stdout for log messages & EOF. */
384 FD_SET (g->fd[1], &rset);
385 FD_SET (g->sock, &rset); /* Read socket for cancellation & EOF. */
386 FD_SET (g->sock, &wset); /* Write to socket to send the data. */
388 int max_fd = MAX (g->sock, g->fd[1]);
393 int r = select (max_fd+1, &rset2, &wset2, NULL, NULL);
395 if (errno == EINTR || errno == EAGAIN)
397 perrorf (g, "select");
401 if (g->fd[1] >= 0 && FD_ISSET (g->fd[1], &rset2)) {
402 if (read_log_message_or_eof (g, g->fd[1], 0) == -1)
405 if (FD_ISSET (g->sock, &rset2)) {
406 r = check_for_daemon_cancellation_or_eof (g, g->sock);
410 if (FD_ISSET (g->sock, &wset2)) {
411 r = write (g->sock, buf, n);
413 if (errno == EINTR || errno == EAGAIN)
415 perrorf (g, "write");
416 if (errno == EPIPE) /* Disconnected from guest (RHBZ#508713). */
428 /* This reads a single message, file chunk, launch flag or
429 * cancellation flag from the daemon. If something was read, it
430 * returns 0, otherwise -1.
432 * Both size_rtn and buf_rtn must be passed by the caller as non-NULL.
434 * *size_rtn returns the size of the returned message or it may be
435 * GUESTFS_LAUNCH_FLAG or GUESTFS_CANCEL_FLAG.
437 * *buf_rtn is returned containing the message (if any) or will be set
438 * to NULL. *buf_rtn must be freed by the caller.
440 * It also checks qemu stdout for log messages and passes those up
441 * through log_message_cb.
443 * It also checks for EOF (qemu died) and passes that up through the
444 * child_cleanup function above.
446 * Progress notifications are handled transparently by this function.
447 * If the callback exists, it is called. The caller of this function
448 * will not see GUESTFS_PROGRESS_FLAG.
452 guestfs___recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn)
456 debug (g, "recv_from_daemon: %p g->state = %d, size_rtn = %p, buf_rtn = %p",
457 g, g->state, size_rtn, buf_rtn);
461 if (g->fd[1] >= 0) /* Read qemu stdout for log messages & EOF. */
462 FD_SET (g->fd[1], &rset);
463 FD_SET (g->sock, &rset); /* Read socket for data & EOF. */
465 int max_fd = MAX (g->sock, g->fd[1]);
471 /* nr is the size of the message, but we prime it as -4 because we
472 * have to read the message length word first.
477 ssize_t message_size =
478 *size_rtn != GUESTFS_PROGRESS_FLAG ?
479 *size_rtn : PROGRESS_MESSAGE_SIZE;
480 if (nr >= message_size)
484 int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
486 if (errno == EINTR || errno == EAGAIN)
488 perrorf (g, "select");
494 if (g->fd[1] >= 0 && FD_ISSET (g->fd[1], &rset2)) {
495 if (read_log_message_or_eof (g, g->fd[1], 0) == -1) {
501 if (FD_ISSET (g->sock, &rset2)) {
502 if (nr < 0) { /* Have we read the message length word yet? */
503 r = read (g->sock, lenbuf+nr+4, -nr);
505 if (errno == EINTR || errno == EAGAIN)
509 /* Under some circumstances we see "Connection reset by peer"
510 * here when the child dies suddenly. Catch this and call
511 * the cleanup function, same as for EOF.
513 if (err == ECONNRESET)
518 error (g, _("unexpected end of file when reading from daemon"));
524 if (nr < 0) /* Still not got the whole length word. */
528 xdrmem_create (&xdr, lenbuf, 4, XDR_DECODE);
529 xdr_uint32_t (&xdr, size_rtn);
532 /* *size_rtn changed, recalculate message_size */
534 *size_rtn != GUESTFS_PROGRESS_FLAG ?
535 *size_rtn : PROGRESS_MESSAGE_SIZE;
537 if (*size_rtn == GUESTFS_LAUNCH_FLAG) {
538 if (g->state != LAUNCHING)
539 error (g, _("received magic signature from guestfsd, but in state %d"),
543 guestfs___call_callbacks_void (g, GUESTFS_EVENT_LAUNCH_DONE);
547 else if (*size_rtn == GUESTFS_CANCEL_FLAG)
549 else if (*size_rtn == GUESTFS_PROGRESS_FLAG)
551 /* If this happens, it's pretty bad and we've probably lost
554 else if (*size_rtn > GUESTFS_MESSAGE_MAX) {
555 error (g, _("message length (%u) > maximum possible size (%d)"),
556 (unsigned) *size_rtn, GUESTFS_MESSAGE_MAX);
560 /* Allocate the complete buffer, size now known. */
561 *buf_rtn = safe_malloc (g, message_size);
565 size_t sizetoread = message_size - nr;
566 if (sizetoread > BUFSIZ) sizetoread = BUFSIZ;
568 r = read (g->sock, (char *) (*buf_rtn) + nr, sizetoread);
570 if (errno == EINTR || errno == EAGAIN)
578 error (g, _("unexpected end of file when reading from daemon"));
588 /* Got the full message, caller can start processing it. */
589 #ifdef ENABLE_PACKET_DUMP
593 for (i = 0; i < nr; i += 16) {
594 printf ("%04zx: ", i);
595 for (j = i; j < MIN (i+16, nr); ++j)
596 printf ("%02x ", (*(unsigned char **)buf_rtn)[j]);
597 for (; j < i+16; ++j)
600 for (j = i; j < MIN (i+16, nr); ++j)
601 if (c_isprint ((*(char **)buf_rtn)[j]))
602 printf ("%c", (*(char **)buf_rtn)[j]);
605 for (; j < i+16; ++j)
612 if (*size_rtn == GUESTFS_PROGRESS_FLAG) {
613 if (g->state == BUSY) {
614 guestfs_progress message;
616 xdrmem_create (&xdr, *buf_rtn, PROGRESS_MESSAGE_SIZE, XDR_DECODE);
617 xdr_guestfs_progress (&xdr, &message);
620 send_progress_message (g, &message);
626 /* Process next message. */
627 return guestfs___recv_from_daemon (g, size_rtn, buf_rtn);
633 /* This is very much like recv_from_daemon above, but g->sock is
634 * a listening socket and we are accepting a new connection on
635 * that socket instead of reading anything. Returns the newly
639 guestfs___accept_from_daemon (guestfs_h *g)
643 debug (g, "accept_from_daemon: %p g->state = %d", g, g->state);
647 if (g->fd[1] >= 0) /* Read qemu stdout for log messages & EOF. */
648 FD_SET (g->fd[1], &rset);
649 FD_SET (g->sock, &rset); /* Read socket for accept. */
651 int max_fd = MAX (g->sock, g->fd[1]);
655 /* If the qemu process has died, clean up the zombie (RHBZ#579155).
656 * By partially polling in the select below we ensure that this
657 * function will be called eventually.
659 waitpid (g->pid, NULL, WNOHANG);
663 struct timeval tv = { .tv_sec = 1, .tv_usec = 0 };
664 int r = select (max_fd+1, &rset2, NULL, NULL, &tv);
666 if (errno == EINTR || errno == EAGAIN)
668 perrorf (g, "select");
672 if (g->fd[1] >= 0 && FD_ISSET (g->fd[1], &rset2)) {
673 if (read_log_message_or_eof (g, g->fd[1], 1) == -1)
676 if (FD_ISSET (g->sock, &rset2)) {
677 sock = accept (g->sock, NULL, NULL);
679 if (errno == EINTR || errno == EAGAIN)
681 perrorf (g, "accept");
691 guestfs___send (guestfs_h *g, int proc_nr,
692 uint64_t progress_hint, uint64_t optargs_bitmask,
693 xdrproc_t xdrp, char *args)
695 struct guestfs_message_header hdr;
698 int serial = g->msg_next_serial++;
703 if (g->state != BUSY) {
704 error (g, _("guestfs___send: state %d != BUSY"), g->state);
708 /* We have to allocate this message buffer on the heap because
709 * it is quite large (although will be mostly unused). We
710 * can't allocate it on the stack because in some environments
711 * we have quite limited stack space available, notably when
712 * running in the JVM.
714 msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
715 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
717 /* Serialize the header. */
718 hdr.prog = GUESTFS_PROGRAM;
719 hdr.vers = GUESTFS_PROTOCOL_VERSION;
721 hdr.direction = GUESTFS_DIRECTION_CALL;
723 hdr.status = GUESTFS_STATUS_OK;
724 hdr.progress_hint = progress_hint;
725 hdr.optargs_bitmask = optargs_bitmask;
727 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
728 error (g, _("xdr_guestfs_message_header failed"));
732 /* Serialize the args. If any, because some message types
733 * have no parameters.
736 if (!(*xdrp) (&xdr, args)) {
737 error (g, _("dispatch failed to marshal args"));
742 /* Get the actual length of the message, resize the buffer to match
743 * the actual length, and write the length word at the beginning.
745 len = xdr_getpos (&xdr);
748 msg_out = safe_realloc (g, msg_out, len + 4);
749 msg_out_size = len + 4;
751 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
752 xdr_uint32_t (&xdr, &len);
755 r = guestfs___send_to_daemon (g, msg_out, msg_out_size);
756 if (r == -2) /* Ignore stray daemon cancellations. */
769 static int cancel = 0; /* XXX Implement file cancellation. */
770 static int send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t len);
771 static int send_file_data (guestfs_h *g, const char *buf, size_t len);
772 static int send_file_cancellation (guestfs_h *g);
773 static int send_file_complete (guestfs_h *g);
779 * -2 daemon cancelled (we must read the error message)
782 guestfs___send_file (guestfs_h *g, const char *filename)
784 char buf[GUESTFS_MAX_CHUNK_SIZE];
787 fd = open (filename, O_RDONLY);
789 perrorf (g, "open: %s", filename);
790 send_file_cancellation (g);
791 /* Daemon sees cancellation and won't reply, so caller can
797 /* Send file in chunked encoding. */
799 r = read (fd, buf, sizeof buf);
800 if (r == -1 && (errno == EINTR || errno == EAGAIN))
803 err = send_file_data (g, buf, r);
805 if (err == -2) /* daemon sent cancellation */
806 send_file_cancellation (g);
811 if (cancel) { /* cancel from either end */
812 send_file_cancellation (g);
817 perrorf (g, "read: %s", filename);
818 send_file_cancellation (g);
822 /* End of file, but before we send that, we need to close
823 * the file and check for errors.
825 if (close (fd) == -1) {
826 perrorf (g, "close: %s", filename);
827 send_file_cancellation (g);
831 return send_file_complete (g);
834 /* Send a chunk of file data. */
836 send_file_data (guestfs_h *g, const char *buf, size_t len)
838 return send_file_chunk (g, 0, buf, len);
841 /* Send a cancellation message. */
843 send_file_cancellation (guestfs_h *g)
845 return send_file_chunk (g, 1, NULL, 0);
848 /* Send a file complete chunk. */
850 send_file_complete (guestfs_h *g)
853 return send_file_chunk (g, 0, buf, 0);
857 send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t buflen)
866 if (g->state != BUSY) {
867 error (g, _("send_file_chunk: state %d != READY"), g->state);
871 /* Allocate the chunk buffer. Don't use the stack to avoid
872 * excessive stack usage and unnecessary copies.
874 msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
875 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
877 /* Serialize the chunk. */
878 chunk.cancel = cancel;
879 chunk.data.data_len = buflen;
880 chunk.data.data_val = (char *) buf;
882 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
883 error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
889 len = xdr_getpos (&xdr);
892 /* Reduce the size of the outgoing message buffer to the real length. */
893 msg_out = safe_realloc (g, msg_out, len + 4);
894 msg_out_size = len + 4;
896 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
897 xdr_uint32_t (&xdr, &len);
899 r = guestfs___send_to_daemon (g, msg_out, msg_out_size);
901 /* Did the daemon send a cancellation message? */
903 debug (g, "got daemon cancellation");
919 /* Receive a reply. */
921 guestfs___recv (guestfs_h *g, const char *fn,
922 guestfs_message_header *hdr,
923 guestfs_message_error *err,
924 xdrproc_t xdrp, char *ret)
932 r = guestfs___recv_from_daemon (g, &size, &buf);
936 /* This can happen if a cancellation happens right at the end
937 * of us sending a FileIn parameter to the daemon. Discard. The
938 * daemon should send us an error message next.
940 if (size == GUESTFS_CANCEL_FLAG)
943 if (size == GUESTFS_LAUNCH_FLAG) {
944 error (g, "%s: received unexpected launch flag from daemon when expecting reply", fn);
948 xdrmem_create (&xdr, buf, size, XDR_DECODE);
950 if (!xdr_guestfs_message_header (&xdr, hdr)) {
951 error (g, "%s: failed to parse reply header", fn);
956 if (hdr->status == GUESTFS_STATUS_ERROR) {
957 if (!xdr_guestfs_message_error (&xdr, err)) {
958 error (g, "%s: failed to parse reply error", fn);
964 if (xdrp && ret && !xdrp (&xdr, ret)) {
965 error (g, "%s: failed to parse reply", fn);
977 /* Receive a file. */
979 /* Returns -1 = error, 0 = EOF, > 0 = more data */
980 static ssize_t receive_file_data (guestfs_h *g, void **buf);
983 guestfs___recv_file (guestfs_h *g, const char *filename)
988 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
990 perrorf (g, "open: %s", filename);
994 /* Receive the file in chunked encoding. */
995 while ((r = receive_file_data (g, &buf)) > 0) {
996 if (xwrite (fd, buf, r) == -1) {
997 perrorf (g, "%s: write", filename);
1005 error (g, _("%s: error in chunked encoding"), filename);
1009 if (close (fd) == -1) {
1010 perrorf (g, "close: %s", filename);
1017 /* Send cancellation message to daemon, then wait until it
1018 * cancels (just throwing away data).
1022 uint32_t flag = GUESTFS_CANCEL_FLAG;
1024 debug (g, "%s: waiting for daemon to acknowledge cancellation",
1027 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
1028 xdr_uint32_t (&xdr, &flag);
1031 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
1032 perrorf (g, _("write to daemon socket"));
1036 while (receive_file_data (g, NULL) > 0)
1037 ; /* just discard it */
1042 /* Receive a chunk of file data. */
1043 /* Returns -1 = error, 0 = EOF, > 0 = more data */
1045 receive_file_data (guestfs_h *g, void **buf_r)
1051 guestfs_chunk chunk;
1053 r = guestfs___recv_from_daemon (g, &len, &buf);
1055 error (g, _("receive_file_data: parse error in reply callback"));
1059 if (len == GUESTFS_LAUNCH_FLAG || len == GUESTFS_CANCEL_FLAG) {
1060 error (g, _("receive_file_data: unexpected flag received when reading file chunks"));
1064 memset (&chunk, 0, sizeof chunk);
1066 xdrmem_create (&xdr, buf, len, XDR_DECODE);
1067 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
1068 error (g, _("failed to parse file chunk"));
1073 /* After decoding, the original buffer is no longer used. */
1077 error (g, _("file receive cancelled by daemon"));
1078 free (chunk.data.data_val);
1082 if (chunk.data.data_len == 0) { /* end of transfer */
1083 free (chunk.data.data_val);
1087 if (buf_r) *buf_r = chunk.data.data_val;
1088 else free (chunk.data.data_val); /* else caller frees */
1090 return chunk.data.data_len;