daemon: expose file upload logic

Allows other modules to use the same logic for uploading files.

Signed-off-by: Matteo Cafasso <noxdafox@gmail.com>
This commit is contained in:
Matteo Cafasso
2017-04-25 23:02:59 +03:00
committed by Richard W.M. Jones
parent d0344f3522
commit 29af0500c2
2 changed files with 40 additions and 29 deletions

View File

@@ -261,6 +261,9 @@ extern int64_t ntfs_minimum_size (const char *device);
extern int swap_set_uuid (const char *device, const char *uuid);
extern int swap_set_label (const char *device, const char *label);
/*-- in upload.c --*/
extern int upload_to_fd (int fd, const char *filename);
/* ordinary daemon functions use these to indicate errors
* NB: you don't need to prefix the string with the current command,
* it is added automatically by the client-side RPC stubs.

View File

@@ -56,19 +56,50 @@ write_cb (void *data_vp, const void *buf, size_t len)
return 0;
}
int
upload_to_fd (int fd, const char *filename)
{
int r, err;
struct write_cb_data data = { .fd = fd, .written = 0 };
r = receive_file (write_cb, &data);
if (r == -1) { /* write error */
err = errno;
ignore_value (cancel_receive ());
errno = err;
reply_with_error ("write error: %s", filename);
close (fd);
return -1;
}
if (r == -2) { /* cancellation from library */
/* This error is ignored by the library since it initiated the
* cancel. Nevertheless we must send an error reply here.
*/
reply_with_error ("file upload cancelled");
close (fd);
return -1;
}
if (close (fd) == -1) {
reply_with_perror ("close");
return -1;
}
return 0;
}
/* Has one FileIn parameter. */
static int
upload (const char *filename, int flags, int64_t offset)
{
struct write_cb_data data = { .written = 0 };
int err, r, is_dev;
int err, is_dev, fd;
is_dev = STRPREFIX (filename, "/dev/");
if (!is_dev) CHROOT_IN;
data.fd = open (filename, flags, 0666);
fd = open (filename, flags, 0666);
if (!is_dev) CHROOT_OUT;
if (data.fd == -1) {
if (fd == -1) {
err = errno;
ignore_value (cancel_receive ());
errno = err;
@@ -77,7 +108,7 @@ upload (const char *filename, int flags, int64_t offset)
}
if (offset) {
if (lseek (data.fd, offset, SEEK_SET) == -1) {
if (lseek (fd, offset, SEEK_SET) == -1) {
err = errno;
ignore_value (cancel_receive ());
errno = err;
@@ -86,30 +117,7 @@ upload (const char *filename, int flags, int64_t offset)
}
}
r = receive_file (write_cb, &data);
if (r == -1) { /* write error */
err = errno;
ignore_value (cancel_receive ());
errno = err;
reply_with_error ("write error: %s", filename);
close (data.fd);
return -1;
}
if (r == -2) { /* cancellation from library */
/* This error is ignored by the library since it initiated the
* cancel. Nevertheless we must send an error reply here.
*/
reply_with_error ("file upload cancelled");
close (data.fd);
return -1;
}
if (close (data.fd) == -1) {
reply_with_perror ("close: %s", filename);
return -1;
}
return 0;
return upload_to_fd (fd, filename);
}
/* Has one FileIn parameter. */