+/* Read 'n' bytes, setting the socket to blocking temporarily so
+ * that we really read the number of bytes requested.
+ * Returns: 0 == EOF while reading
+ * -1 == error, error() function has been called
+ * n == read 'n' bytes in full
+ */
+static ssize_t
+really_read_from_socket (guestfs_h *g, int sock, char *buf, size_t n)
+{
+ long flags;
+ ssize_t r;
+ size_t got;
+
+ /* Set socket to blocking. */
+ flags = fcntl (sock, F_GETFL);
+ if (flags == -1) {
+ perrorf (g, "fcntl");
+ return -1;
+ }
+ if (fcntl (sock, F_SETFL, flags & ~O_NONBLOCK) == -1) {
+ perrorf (g, "fcntl");
+ return -1;
+ }
+
+ got = 0;
+ while (got < n) {
+ r = read (sock, &buf[got], n-got);
+ if (r == -1) {
+ perrorf (g, "read");
+ return -1;
+ }
+ if (r == 0)
+ return 0; /* EOF */
+ got += r;
+ }
+
+ /* Restore original socket flags. */
+ if (fcntl (sock, F_SETFL, flags) == -1) {
+ perrorf (g, "fcntl");
+ return -1;
+ }
+
+ return (ssize_t) got;
+}
+