copyfd.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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 "libbb.h"
  10. #if BUFSIZ < 4096
  11. #undef BUFSIZ
  12. #define BUFSIZ 4096
  13. #endif
  14. /* Used by NOFORK applets (e.g. cat) - must not use xmalloc */
  15. static off_t bb_full_fd_action(int src_fd, int dst_fd, off_t size)
  16. {
  17. int status = -1;
  18. off_t total = 0;
  19. char buffer[BUFSIZ];
  20. if (src_fd < 0)
  21. goto out;
  22. if (!size) {
  23. size = BUFSIZ;
  24. status = 1; /* copy until eof */
  25. }
  26. while (1) {
  27. ssize_t rd;
  28. rd = safe_read(src_fd, buffer, size > BUFSIZ ? BUFSIZ : size);
  29. if (!rd) { /* eof - all done */
  30. status = 0;
  31. break;
  32. }
  33. if (rd < 0) {
  34. bb_perror_msg(bb_msg_read_error);
  35. break;
  36. }
  37. /* dst_fd == -1 is a fake, else... */
  38. if (dst_fd >= 0) {
  39. ssize_t wr = full_write(dst_fd, buffer, rd);
  40. if (wr < rd) {
  41. bb_perror_msg(bb_msg_write_error);
  42. break;
  43. }
  44. }
  45. total += rd;
  46. if (status < 0) { /* if we aren't copying till EOF... */
  47. size -= rd;
  48. if (!size) {
  49. /* 'size' bytes copied - all done */
  50. status = 0;
  51. break;
  52. }
  53. }
  54. }
  55. out:
  56. return status ? -1 : total;
  57. }
  58. #if 0
  59. void complain_copyfd_and_die(off_t sz)
  60. {
  61. if (sz != -1)
  62. bb_error_msg_and_die("short read");
  63. /* if sz == -1, bb_copyfd_XX already complained */
  64. xfunc_die();
  65. }
  66. #endif
  67. off_t bb_copyfd_size(int fd1, int fd2, off_t size)
  68. {
  69. if (size) {
  70. return bb_full_fd_action(fd1, fd2, size);
  71. }
  72. return 0;
  73. }
  74. void bb_copyfd_exact_size(int fd1, int fd2, off_t size)
  75. {
  76. off_t sz = bb_copyfd_size(fd1, fd2, size);
  77. if (sz == size)
  78. return;
  79. if (sz != -1)
  80. bb_error_msg_and_die("short read");
  81. /* if sz == -1, bb_copyfd_XX already complained */
  82. xfunc_die();
  83. }
  84. off_t bb_copyfd_eof(int fd1, int fd2)
  85. {
  86. return bb_full_fd_action(fd1, fd2, 0);
  87. }