copyfd.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  20. */
  21. #include <errno.h>
  22. #include <stdlib.h>
  23. #include <string.h>
  24. #include <unistd.h>
  25. #include "busybox.h"
  26. #include "libbb.h"
  27. #if BUFSIZ < 4096
  28. #undef BUFSIZ
  29. #define BUFSIZ 4096
  30. #endif
  31. static size_t bb_full_fd_action(int src_fd, int dst_fd, const size_t size2)
  32. {
  33. int status;
  34. size_t xread, wrote, total, size = size2;
  35. if (src_fd < 0) {
  36. return -1;
  37. }
  38. if (size == 0) {
  39. /* If size is 0 copy until EOF */
  40. size = ULONG_MAX;
  41. }
  42. {
  43. RESERVE_CONFIG_BUFFER(buffer,BUFSIZ);
  44. total = 0;
  45. wrote = 0;
  46. status = -1;
  47. while (total < size)
  48. {
  49. xread = BUFSIZ;
  50. if (size < (total + BUFSIZ))
  51. xread = size - total;
  52. xread = bb_full_read(src_fd, buffer, xread);
  53. if (xread > 0) {
  54. if (dst_fd < 0) {
  55. /* A -1 dst_fd means we need to fake it... */
  56. wrote = xread;
  57. } else {
  58. wrote = bb_full_write(dst_fd, buffer, xread);
  59. }
  60. if (wrote < xread) {
  61. bb_perror_msg(bb_msg_write_error);
  62. break;
  63. }
  64. total += wrote;
  65. } else if (xread < 0) {
  66. bb_perror_msg(bb_msg_read_error);
  67. break;
  68. } else if (xread == 0) {
  69. /* All done. */
  70. status = 0;
  71. break;
  72. }
  73. }
  74. RELEASE_CONFIG_BUFFER(buffer);
  75. }
  76. if (status == 0 || total)
  77. return total;
  78. /* Some sortof error occured */
  79. return -1;
  80. }
  81. extern int bb_copyfd_size(int fd1, int fd2, const off_t size)
  82. {
  83. if (size) {
  84. return(bb_full_fd_action(fd1, fd2, size));
  85. }
  86. return(0);
  87. }
  88. extern int bb_copyfd_eof(int fd1, int fd2)
  89. {
  90. return(bb_full_fd_action(fd1, fd2, 0));
  91. }