18f62838ec69a91888fd9baba0f216e576c78d0e
[oweals/busybox.git] / libbb / read.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Utility routines.
4  *
5  * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
6  *
7  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
8  */
9
10 #include "libbb.h"
11 #if ENABLE_FEATURE_MODPROBE_SMALL_ZIPPED
12 #include "unarchive.h"
13 #endif
14
15 ssize_t FAST_FUNC safe_read(int fd, void *buf, size_t count)
16 {
17         ssize_t n;
18
19         do {
20                 n = read(fd, buf, count);
21         } while (n < 0 && errno == EINTR);
22
23         return n;
24 }
25
26 /* Suppose that you are a shell. You start child processes.
27  * They work and eventually exit. You want to get user input.
28  * You read stdin. But what happens if last child switched
29  * its stdin into O_NONBLOCK mode?
30  *
31  * *** SURPRISE! It will affect the parent too! ***
32  * *** BIG SURPRISE! It stays even after child exits! ***
33  *
34  * This is a design bug in UNIX API.
35  *      fcntl(0, F_SETFL, fcntl(0, F_GETFL, 0) | O_NONBLOCK);
36  * will set nonblocking mode not only on _your_ stdin, but
37  * also on stdin of your parent, etc.
38  *
39  * In general,
40  *      fd2 = dup(fd1);
41  *      fcntl(fd2, F_SETFL, fcntl(fd2, F_GETFL, 0) | O_NONBLOCK);
42  * sets both fd1 and fd2 to O_NONBLOCK. This includes cases
43  * where duping is done implicitly by fork() etc.
44  *
45  * We need
46  *      fcntl(fd2, F_SETFD, fcntl(fd2, F_GETFD, 0) | O_NONBLOCK);
47  * (note SETFD, not SETFL!) but such thing doesn't exist.
48  *
49  * Alternatively, we need nonblocking_read(fd, ...) which doesn't
50  * require O_NONBLOCK dance at all. Actually, it exists:
51  *      n = recv(fd, buf, len, MSG_DONTWAIT);
52  *      "MSG_DONTWAIT:
53  *      Enables non-blocking operation; if the operation
54  *      would block, EAGAIN is returned."
55  * but recv() works only for sockets!
56  *
57  * So far I don't see any good solution, I can only propose
58  * that affected readers should be careful and use this routine,
59  * which detects EAGAIN and uses poll() to wait on the fd.
60  * Thankfully, poll() doesn't care about O_NONBLOCK flag.
61  */
62 ssize_t FAST_FUNC nonblock_safe_read(int fd, void *buf, size_t count)
63 {
64         struct pollfd pfd[1];
65         ssize_t n;
66
67         while (1) {
68                 n = safe_read(fd, buf, count);
69                 if (n >= 0 || errno != EAGAIN)
70                         return n;
71                 /* fd is in O_NONBLOCK mode. Wait using poll and repeat */
72                 pfd[0].fd = fd;
73                 pfd[0].events = POLLIN;
74                 safe_poll(pfd, 1, -1);
75         }
76 }
77
78 /*
79  * Read all of the supplied buffer from a file.
80  * This does multiple reads as necessary.
81  * Returns the amount read, or -1 on an error.
82  * A short read is returned on an end of file.
83  */
84 ssize_t FAST_FUNC full_read(int fd, void *buf, size_t len)
85 {
86         ssize_t cc;
87         ssize_t total;
88
89         total = 0;
90
91         while (len) {
92                 cc = safe_read(fd, buf, len);
93
94                 if (cc < 0) {
95                         if (total) {
96                                 /* we already have some! */
97                                 /* user can do another read to know the error code */
98                                 return total;
99                         }
100                         return cc; /* read() returns -1 on failure. */
101                 }
102                 if (cc == 0)
103                         break;
104                 buf = ((char *)buf) + cc;
105                 total += cc;
106                 len -= cc;
107         }
108
109         return total;
110 }
111
112 /* Die with an error message if we can't read the entire buffer. */
113 void FAST_FUNC xread(int fd, void *buf, size_t count)
114 {
115         if (count) {
116                 ssize_t size = full_read(fd, buf, count);
117                 if ((size_t)size != count)
118                         bb_error_msg_and_die("short read");
119         }
120 }
121
122 /* Die with an error message if we can't read one character. */
123 unsigned char FAST_FUNC xread_char(int fd)
124 {
125         char tmp;
126         xread(fd, &tmp, 1);
127         return tmp;
128 }
129
130 // Reads one line a-la fgets (but doesn't save terminating '\n').
131 // Reads byte-by-byte. Useful when it is important to not read ahead.
132 // Bytes are appended to pfx (which must be malloced, or NULL).
133 char* FAST_FUNC xmalloc_reads(int fd, char *buf, size_t *maxsz_p)
134 {
135         char *p;
136         size_t sz = buf ? strlen(buf) : 0;
137         size_t maxsz = maxsz_p ? *maxsz_p : MAXINT(size_t);
138
139         goto jump_in;
140         while (sz < maxsz) {
141                 if ((size_t)(p - buf) == sz) {
142  jump_in:
143                         buf = xrealloc(buf, sz + 128);
144                         p = buf + sz;
145                         sz += 128;
146                 }
147                 /* nonblock_safe_read() because we are used by e.g. shells */
148                 if (nonblock_safe_read(fd, p, 1) != 1) { /* EOF/error */
149                         if (p == buf) { /* we read nothing */
150                                 free(buf);
151                                 return NULL;
152                         }
153                         break;
154                 }
155                 if (*p == '\n')
156                         break;
157                 p++;
158         }
159         *p = '\0';
160         if (maxsz_p)
161                 *maxsz_p  = p - buf;
162         p++;
163         return xrealloc(buf, p - buf);
164 }
165
166 ssize_t FAST_FUNC read_close(int fd, void *buf, size_t size)
167 {
168         /*int e;*/
169         size = full_read(fd, buf, size);
170         /*e = errno;*/
171         close(fd);
172         /*errno = e;*/
173         return size;
174 }
175
176 ssize_t FAST_FUNC open_read_close(const char *filename, void *buf, size_t size)
177 {
178         int fd = open(filename, O_RDONLY);
179         if (fd < 0)
180                 return fd;
181         return read_close(fd, buf, size);
182 }
183
184
185 // Read (potentially big) files in one go. File size is estimated
186 // by stat. Extra '\0' byte is appended.
187 void* FAST_FUNC xmalloc_read(int fd, size_t *maxsz_p)
188 {
189         char *buf;
190         size_t size, rd_size, total;
191         size_t to_read;
192         struct stat st;
193
194         to_read = maxsz_p ? *maxsz_p : MAXINT(ssize_t); /* max to read */
195
196         /* Estimate file size */
197         st.st_size = 0; /* in case fstat fails, assume 0 */
198         fstat(fd, &st);
199         /* /proc/N/stat files report st_size 0 */
200         /* In order to make such files readable, we add small const */
201         size = (st.st_size | 0x3ff) + 1;
202
203         total = 0;
204         buf = NULL;
205         while (1) {
206                 if (to_read < size)
207                         size = to_read;
208                 buf = xrealloc(buf, total + size + 1);
209                 rd_size = full_read(fd, buf + total, size);
210                 if ((ssize_t)rd_size == (ssize_t)(-1)) { /* error */
211                         free(buf);
212                         return NULL;
213                 }
214                 total += rd_size;
215                 if (rd_size < size) /* EOF */
216                         break;
217                 if (to_read <= rd_size)
218                         break;
219                 to_read -= rd_size;
220                 /* grow by 1/8, but in [1k..64k] bounds */
221                 size = ((total / 8) | 0x3ff) + 1;
222                 if (size > 64*1024)
223                         size = 64*1024;
224         }
225         xrealloc(buf, total + 1);
226         buf[total] = '\0';
227
228         if (maxsz_p)
229                 *maxsz_p = total;
230         return buf;
231 }
232
233 #ifdef USING_LSEEK_TO_GET_SIZE
234 /* Alternatively, file size can be obtained by lseek to the end.
235  * The code is slightly bigger. Retained in case fstat approach
236  * will not work for some weird cases (/proc, block devices, etc).
237  * (NB: lseek also can fail to work for some weird files) */
238
239 // Read (potentially big) files in one go. File size is estimated by
240 // lseek to end.
241 void* FAST_FUNC xmalloc_open_read_close(const char *filename, size_t *maxsz_p)
242 {
243         char *buf;
244         size_t size;
245         int fd;
246         off_t len;
247
248         fd = open(filename, O_RDONLY);
249         if (fd < 0)
250                 return NULL;
251
252         /* /proc/N/stat files report len 0 here */
253         /* In order to make such files readable, we add small const */
254         size = 0x3ff; /* read only 1k on unseekable files */
255         len = lseek(fd, 0, SEEK_END) | 0x3ff; /* + up to 1k */
256         if (len != (off_t)-1) {
257                 xlseek(fd, 0, SEEK_SET);
258                 size = maxsz_p ? *maxsz_p : INT_MAX;
259                 if (len < size)
260                         size = len;
261         }
262
263         buf = xmalloc(size + 1);
264         size = read_close(fd, buf, size);
265         if ((ssize_t)size < 0) {
266                 free(buf);
267                 return NULL;
268         }
269         xrealloc(buf, size + 1);
270         buf[size] = '\0';
271
272         if (maxsz_p)
273                 *maxsz_p = size;
274         return buf;
275 }
276 #endif
277
278 // Read (potentially big) files in one go. File size is estimated
279 // by stat.
280 void* FAST_FUNC xmalloc_open_read_close(const char *filename, size_t *maxsz_p)
281 {
282         char *buf;
283         int fd;
284
285         fd = open(filename, O_RDONLY);
286         if (fd < 0)
287                 return NULL;
288
289         buf = xmalloc_read(fd, maxsz_p);
290         close(fd);
291         return buf;
292 }
293
294 void* FAST_FUNC xmalloc_xopen_read_close(const char *filename, size_t *maxsz_p)
295 {
296         void *buf = xmalloc_open_read_close(filename, maxsz_p);
297         if (!buf)
298                 bb_perror_msg_and_die("can't read '%s'", filename);
299         return buf;
300 }
301
302 #if ENABLE_FEATURE_MODPROBE_SMALL_ZIPPED
303 void* FAST_FUNC xmalloc_open_zipped_read_close(const char *fname, size_t *maxsz_p)
304 {
305         char *image;
306         char *suffix;
307
308         int fd = open(fname, O_RDONLY);
309         if (fd < 0)
310                 return NULL;
311
312         suffix = strrchr(fname, '.');
313         if (suffix) {
314                 if (strcmp(suffix, ".gz") == 0)
315                         open_transformer(fd, unpack_gz_stream, "gunzip");
316                 else if (strcmp(suffix, ".bz2") == 0)
317                         open_transformer(fd, unpack_bz2_stream, "bunzip2");
318         }
319
320         image = xmalloc_read(fd, maxsz_p);
321         if (!image)
322                 bb_perror_msg("read error from '%s'", fname);
323         close(fd);
324
325         return image;
326 }
327 #endif