1 /* libguestfs - the guestfsd daemon
2 * Copyright (C) 2009 Red Hat Inc.
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program 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
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
27 #include <sys/types.h>
30 #include "../src/guestfs_protocol.h"
35 write_cb (void *fd_ptr, const void *buf, size_t len)
37 int fd = *(int *)fd_ptr;
38 return xwrite (fd, buf, len);
41 /* Has one FileIn parameter. */
43 do_upload (const char *filename)
45 int err, fd, r, is_dev;
47 is_dev = STRPREFIX (filename, "/dev/");
49 if (!is_dev) CHROOT_IN;
50 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
51 if (!is_dev) CHROOT_OUT;
54 r = cancel_receive ();
56 if (r != -2) reply_with_perror ("%s", filename);
60 r = receive_file (write_cb, &fd);
61 if (r == -1) { /* write error */
63 r = cancel_receive ();
65 if (r != -2) reply_with_error ("write error: %s", filename);
69 if (r == -2) { /* cancellation from library */
71 /* Do NOT send any error. */
75 if (close (fd) == -1) {
77 if (r == -1) /* if r == 0, file transfer ended already */
78 r = cancel_receive ();
81 reply_with_perror ("close: %s", filename);
88 /* Has one FileOut parameter. */
90 do_download (const char *filename)
93 char buf[GUESTFS_MAX_CHUNK_SIZE];
95 is_dev = STRPREFIX (filename, "/dev/");
97 if (!is_dev) CHROOT_IN;
98 fd = open (filename, O_RDONLY);
99 if (!is_dev) CHROOT_OUT;
101 reply_with_perror ("%s", filename);
105 /* Calculate the size of the file or device for notification messages. */
106 uint64_t total, sent = 0;
109 if (fstat (fd, &statbuf) == -1) {
110 reply_with_perror ("%s", filename);
114 total = statbuf.st_size;
116 int64_t size = do_blockdev_getsize64 (filename);
118 /* do_blockdev_getsize64 has already sent a reply. */
122 total = (uint64_t) size;
125 /* Now we must send the reply message, before the file contents. After
126 * this there is no opportunity in the protocol to send any error
127 * message back. Instead we can only cancel the transfer.
131 while ((r = read (fd, buf, sizeof buf)) > 0) {
132 if (send_file_write (buf, r) < 0) {
138 notify_progress (sent, total);
143 send_file_end (1); /* Cancel. */
148 if (close (fd) == -1) {
150 send_file_end (1); /* Cancel. */
154 if (send_file_end (0)) /* Normal end of file. */