1 /* vi: set sw=4 ts=4: */
5 * Copyright (C) 1999-2005 by Erik Andersen <andersen@codepoet.org>
7 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
12 /* Used by NOFORK applets (e.g. cat) - must not use xmalloc.
13 * size < 0 means "ignore write errors", used by tar --to-command
14 * size = 0 means "copy till EOF"
16 static off_t bb_full_fd_action(int src_fd, int dst_fd, off_t size)
20 #if CONFIG_FEATURE_COPYBUF_KB <= 4
21 char buffer[CONFIG_FEATURE_COPYBUF_KB * 1024];
22 enum { buffer_size = sizeof(buffer) };
26 bool continue_on_write_error = 0;
30 continue_on_write_error = 1;
33 if (size > 0 && size <= 4 * 1024)
35 /* We want page-aligned buffer, just in case kernel is clever
36 * and can do page-aligned io more efficiently */
37 buffer = mmap(NULL, CONFIG_FEATURE_COPYBUF_KB * 1024,
38 PROT_READ | PROT_WRITE,
39 MAP_PRIVATE | MAP_ANON,
40 /* ignored: */ -1, 0);
41 buffer_size = CONFIG_FEATURE_COPYBUF_KB * 1024;
42 if (buffer == MAP_FAILED) {
44 buffer = alloca(4 * 1024);
45 buffer_size = 4 * 1024;
54 status = 1; /* copy until eof */
60 rd = safe_read(src_fd, buffer, size > buffer_size ? buffer_size : size);
62 if (!rd) { /* eof - all done */
67 bb_perror_msg(bb_msg_read_error);
70 /* dst_fd == -1 is a fake, else... */
72 ssize_t wr = full_write(dst_fd, buffer, rd);
74 if (!continue_on_write_error) {
75 bb_perror_msg(bb_msg_write_error);
82 if (status < 0) { /* if we aren't copying till EOF... */
85 /* 'size' bytes copied - all done */
93 #if CONFIG_FEATURE_COPYBUF_KB > 4
94 if (buffer_size != 4 * 1024)
95 munmap(buffer, buffer_size);
97 return status ? -1 : total;
102 void FAST_FUNC complain_copyfd_and_die(off_t sz)
105 bb_error_msg_and_die("short read");
106 /* if sz == -1, bb_copyfd_XX already complained */
111 off_t FAST_FUNC bb_copyfd_size(int fd1, int fd2, off_t size)
114 return bb_full_fd_action(fd1, fd2, size);
119 void FAST_FUNC bb_copyfd_exact_size(int fd1, int fd2, off_t size)
121 off_t sz = bb_copyfd_size(fd1, fd2, size);
122 if (sz == (size >= 0 ? size : -size))
125 bb_error_msg_and_die("short read");
126 /* if sz == -1, bb_copyfd_XX already complained */
130 off_t FAST_FUNC bb_copyfd_eof(int fd1, int fd2)
132 return bb_full_fd_action(fd1, fd2, 0);