2017-06-22 21:58:32 +00:00
|
|
|
#ifndef ZM_SENDFILE_H
|
|
|
|
#define ZM_SENDFILE_H
|
|
|
|
|
2023-01-17 21:09:30 +00:00
|
|
|
#if defined(HAVE_SENDFILE) && defined(HAVE_SENDFILE4_SUPPORT)
|
2015-02-24 14:20:55 +00:00
|
|
|
#include <sys/sendfile.h>
|
2023-01-17 21:09:30 +00:00
|
|
|
#elif defined(HAVE_SENDFILE) && defined(HAVE_SENDFILE7_SUPPORT)
|
2015-02-24 14:20:55 +00:00
|
|
|
#include <sys/types.h>
|
|
|
|
#include <sys/socket.h>
|
|
|
|
#include <sys/uio.h>
|
2022-02-16 19:16:25 +00:00
|
|
|
#else
|
|
|
|
#include <unistd.h>
|
2023-01-17 21:09:30 +00:00
|
|
|
#include <stdio.h>
|
2022-02-16 19:16:25 +00:00
|
|
|
#endif
|
|
|
|
|
|
|
|
/* Function to send the contents of a file. Will use sendfile or fall back to reading/writing */
|
|
|
|
|
2023-01-17 21:09:30 +00:00
|
|
|
ssize_t zm_sendfile(int out_fd, int in_fd, off_t *offset, size_t size) {
|
|
|
|
#if defined(HAVE_SENDFILE) && defined(HAVE_SENDFILE4_SUPPORT)
|
2022-02-16 19:16:25 +00:00
|
|
|
ssize_t err = sendfile(out_fd, in_fd, offset, size);
|
|
|
|
if (err < 0) {
|
|
|
|
return -errno;
|
|
|
|
}
|
|
|
|
return err;
|
|
|
|
|
2023-01-17 21:09:30 +00:00
|
|
|
#elif defined(HAVE_SENDFILE) && defined(HAVE_SENDFILE7_SUPPORT)
|
|
|
|
off_t sbytes;
|
|
|
|
ssize_t err = sendfile(in_fd, out_fd, (offset ? *offset: 0), size, nullptr, &sbytes, 0);
|
2017-06-22 13:55:45 +00:00
|
|
|
if (err && errno != EAGAIN)
|
|
|
|
return -errno;
|
2022-07-16 10:05:46 +00:00
|
|
|
return sbytes;
|
2022-02-16 19:16:25 +00:00
|
|
|
#else
|
2023-01-17 21:09:30 +00:00
|
|
|
uint8_t buffer[4096];
|
2023-01-18 21:01:42 +00:00
|
|
|
ssize_t chunk_size = (size > 4096 ? 4096 : size);
|
2023-01-17 21:09:30 +00:00
|
|
|
|
|
|
|
ssize_t err = read(in_fd, buffer, chunk_size);
|
2022-02-16 19:16:25 +00:00
|
|
|
if (err < 0) {
|
2023-01-17 21:09:30 +00:00
|
|
|
Error("Unable to read %zu bytes of %zu: %s", chunk_size, size, strerror(errno));
|
2022-02-16 19:16:25 +00:00
|
|
|
return -errno;
|
2017-06-22 13:55:45 +00:00
|
|
|
}
|
2023-01-17 21:09:30 +00:00
|
|
|
if (!err) {
|
2023-01-18 21:01:42 +00:00
|
|
|
Error("Got EOF despite wanting to read %d bytes", 4096);
|
2023-01-17 21:09:30 +00:00
|
|
|
return err;
|
|
|
|
}
|
2015-02-24 14:20:55 +00:00
|
|
|
|
2023-01-17 21:09:30 +00:00
|
|
|
chunk_size = err;
|
|
|
|
|
|
|
|
err = write(out_fd, buffer, chunk_size);
|
2022-02-16 19:16:25 +00:00
|
|
|
if (err < 0) {
|
2023-01-17 21:09:30 +00:00
|
|
|
Error("Unable to write %zu bytes: %s", chunk_size, strerror(errno));
|
2022-02-16 19:16:25 +00:00
|
|
|
return -errno;
|
2023-01-17 21:09:30 +00:00
|
|
|
} else if (err != chunk_size) {
|
|
|
|
Debug(1, "Sent less than desired %zu < %zu", err, chunk_size);
|
2022-02-16 19:16:25 +00:00
|
|
|
}
|
2023-01-17 21:09:30 +00:00
|
|
|
|
2022-02-16 19:16:25 +00:00
|
|
|
return err;
|
2015-02-24 14:20:55 +00:00
|
|
|
#endif
|
2022-02-16 19:16:25 +00:00
|
|
|
}
|
2017-06-22 21:58:32 +00:00
|
|
|
|
2021-06-05 12:37:52 +00:00
|
|
|
#endif // ZM_SENDFILE_H
|