1
2
3
4
5
6
7
8
9#include "libbb.h"
10#if ENABLE_FEATURE_USE_SENDFILE
11# include <sys/sendfile.h>
12#else
13# define sendfile(a,b,c,d) (-1)
14#endif
15
16
17
18
19
20
21
22
23#define SENDFILE_BIGBUF (16*1024*1024)
24
25
26
27
28
29static off_t bb_full_fd_action(int src_fd, int dst_fd, off_t size)
30{
31 int status = -1;
32 off_t total = 0;
33 bool continue_on_write_error = 0;
34 ssize_t sendfile_sz;
35#if CONFIG_FEATURE_COPYBUF_KB > 4
36 char *buffer = buffer;
37 int buffer_size = 0;
38#else
39 char buffer[CONFIG_FEATURE_COPYBUF_KB * 1024];
40 enum { buffer_size = sizeof(buffer) };
41#endif
42
43 if (size < 0) {
44 size = -size;
45 continue_on_write_error = 1;
46 }
47
48 if (src_fd < 0)
49 goto out;
50
51 sendfile_sz = !ENABLE_FEATURE_USE_SENDFILE
52 ? 0
53 : SENDFILE_BIGBUF;
54 if (!size) {
55 size = SENDFILE_BIGBUF;
56 status = 1;
57 }
58
59 while (1) {
60 ssize_t rd;
61
62 if (sendfile_sz) {
63
64 if (dst_fd >= 0) {
65 rd = sendfile(dst_fd, src_fd, NULL,
66 size > sendfile_sz ? sendfile_sz : size);
67 if (rd >= 0)
68 goto read_ok;
69 }
70 sendfile_sz = 0;
71 }
72#if CONFIG_FEATURE_COPYBUF_KB > 4
73 if (buffer_size == 0) {
74 if (size > 0 && size <= 4 * 1024)
75 goto use_small_buf;
76
77
78 buffer = mmap_anon(CONFIG_FEATURE_COPYBUF_KB * 1024);
79 buffer_size = CONFIG_FEATURE_COPYBUF_KB * 1024;
80 if (buffer == MAP_FAILED) {
81 use_small_buf:
82 buffer = alloca(4 * 1024);
83 buffer_size = 4 * 1024;
84 }
85 }
86#endif
87 rd = safe_read(src_fd, buffer,
88 size > buffer_size ? buffer_size : size);
89 if (rd < 0) {
90 bb_simple_perror_msg(bb_msg_read_error);
91 break;
92 }
93 read_ok:
94 if (!rd) {
95 status = 0;
96 break;
97 }
98
99 if (dst_fd >= 0 && !sendfile_sz) {
100 ssize_t wr = full_write(dst_fd, buffer, rd);
101 if (wr < rd) {
102 if (!continue_on_write_error) {
103 bb_simple_perror_msg(bb_msg_write_error);
104 break;
105 }
106 dst_fd = -1;
107 }
108 }
109 total += rd;
110 if (status < 0) {
111 size -= rd;
112 if (!size) {
113
114 status = 0;
115 break;
116 }
117 }
118 }
119 out:
120
121
122#if CONFIG_FEATURE_COPYBUF_KB > 4
123 if (buffer_size > 4 * 1024)
124 munmap(buffer, buffer_size);
125#endif
126 return status ? -1 : total;
127}
128
129
130#if 0
131void FAST_FUNC complain_copyfd_and_die(off_t sz)
132{
133 if (sz != -1)
134 bb_error_msg_and_die("short read");
135
136 xfunc_die();
137}
138#endif
139
140off_t FAST_FUNC bb_copyfd_size(int fd1, int fd2, off_t size)
141{
142 if (size) {
143 return bb_full_fd_action(fd1, fd2, size);
144 }
145 return 0;
146}
147
148void FAST_FUNC bb_copyfd_exact_size(int fd1, int fd2, off_t size)
149{
150 off_t sz = bb_copyfd_size(fd1, fd2, size);
151 if (sz == (size >= 0 ? size : -size))
152 return;
153 if (sz != -1)
154 bb_simple_error_msg_and_die("short read");
155
156 xfunc_die();
157}
158
159off_t FAST_FUNC bb_copyfd_eof(int fd1, int fd2)
160{
161 return bb_full_fd_action(fd1, fd2, 0);
162}
163