logo

utils-std

Collection of commonly available Unix tools git clone https://anongit.hacktivis.me/git/utils-std.git

sendfile_freebsd.c (910B)


  1. // utils-std: Collection of commonly available Unix tools
  2. // SPDX-FileCopyrightText: 2017 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
  3. // SPDX-License-Identifier: MPL-2.0
  4. #define _DEFAULT_SOURCE
  5. #include "./fs.h"
  6. // for sendfile
  7. #include <sys/socket.h>
  8. #include <sys/types.h>
  9. #include <sys/uio.h>
  10. // generic
  11. #include <errno.h>
  12. #include <stddef.h> // NULL
  13. #include <limits.h> // SSIZE_MAX
  14. ssize_t
  15. auto_fd_copy(int fd_in, int fd_out, size_t len)
  16. {
  17. off_t off = 0;
  18. if(len == SSIZE_MAX) len = 0;
  19. while(1)
  20. {
  21. off_t sbytes = 0;
  22. ssize_t ret = sendfile(fd_out, fd_in, off, len, NULL, &sbytes, 0);
  23. if(ret < 0)
  24. {
  25. switch(errno)
  26. {
  27. case EINVAL:
  28. case EBADF:
  29. errno = 0;
  30. return manual_copy(fd_in, fd_out, len, 0);
  31. case EAGAIN:
  32. errno = 0;
  33. off += sbytes;
  34. if(len != 0) len -= sbytes;
  35. continue;
  36. default:
  37. return ret;
  38. }
  39. }
  40. return ret;
  41. }
  42. return -1;
  43. }