3
0

copyfd.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Utility routines.
  4. *
  5. * Copyright (C) 1999-2005 by Erik Andersen <andersen@codepoet.org>
  6. *
  7. * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  8. */
  9. #include <errno.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include <unistd.h>
  13. #include "libbb.h"
  14. #if BUFSIZ < 4096
  15. #undef BUFSIZ
  16. #define BUFSIZ 4096
  17. #endif
  18. static off_t bb_full_fd_action(int src_fd, int dst_fd, off_t size)
  19. {
  20. int status = -1;
  21. off_t total = 0;
  22. RESERVE_CONFIG_BUFFER(buffer, BUFSIZ);
  23. if (src_fd < 0) goto out;
  24. if (!size) {
  25. size = BUFSIZ;
  26. status = 1; /* copy until eof */
  27. }
  28. while (1) {
  29. ssize_t rd;
  30. rd = safe_read(src_fd, buffer, size > BUFSIZ ? BUFSIZ : size);
  31. if (!rd) { /* eof - all done */
  32. status = 0;
  33. break;
  34. }
  35. if (rd < 0) {
  36. bb_perror_msg(bb_msg_read_error);
  37. break;
  38. }
  39. /* dst_fd == -1 is a fake, else... */
  40. if (dst_fd >= 0) {
  41. ssize_t wr = full_write(dst_fd, buffer, rd);
  42. if (wr < rd) {
  43. bb_perror_msg(bb_msg_write_error);
  44. break;
  45. }
  46. }
  47. total += rd;
  48. if (status < 0) { /* if we aren't copying till EOF... */
  49. size -= rd;
  50. if (!size) {
  51. /* 'size' bytes copied - all done */
  52. status = 0;
  53. break;
  54. }
  55. }
  56. }
  57. out:
  58. RELEASE_CONFIG_BUFFER(buffer);
  59. return status ? -1 : total;
  60. }
  61. #if 0
  62. void complain_copyfd_and_die(off_t sz)
  63. {
  64. if (sz != -1)
  65. bb_error_msg_and_die("short read");
  66. /* if sz == -1, bb_copyfd_XX already complained */
  67. exit(xfunc_error_retval);
  68. }
  69. #endif
  70. off_t bb_copyfd_size(int fd1, int fd2, off_t size)
  71. {
  72. if (size) {
  73. return bb_full_fd_action(fd1, fd2, size);
  74. }
  75. return 0;
  76. }
  77. void bb_copyfd_exact_size(int fd1, int fd2, off_t size)
  78. {
  79. off_t sz = bb_copyfd_size(fd1, fd2, size);
  80. if (sz == size)
  81. return;
  82. if (sz != -1)
  83. bb_error_msg_and_die("short read");
  84. /* if sz == -1, bb_copyfd_XX already complained */
  85. exit(xfunc_error_retval);
  86. }
  87. off_t bb_copyfd_eof(int fd1, int fd2)
  88. {
  89. return bb_full_fd_action(fd1, fd2, 0);
  90. }