1#include <unistd.h>
2#include <sys/types.h>
3
4static ssize_t
5sendfile(int out, int in, off_t *offset, size_t count)
6{
7 off_t start;
8 char buf[4096];
9 ssize_t rw, rr;
10 size_t c, max, written;
11
12 /* XXX: Technically, sendfile should not modify the file offset if
13 * offset is not NULL, this implementation ignore this requirement. */
14
15 if (offset) {
16 start = *offset;
17 if (lseek(in, start, SEEK_SET) == -1)
18 return -1;
19 }
20
21 written = 0;
22 for (c = count; c > 0; c -= rw) {
23 if ((max = sizeof(buf)) > c)
24 max = c;
25
26 rr = read(in, buf, max);
27 if (rr == 0)
28 break;
29 else if (rr == -1)
30 return -1;
31
32 if ((rw = write(out, buf, rr)) == -1)
33 return -1;
34 written += rw;
35
36 /* If a short write occured, seek back and return */
37 if (rw < rr) {
38 if (lseek(in, rw - rr, SEEK_CUR) == -1)
39 return -1;
40 break;
41 }
42 }
43
44 if (offset)
45 *offset = start + written;
46 return written;
47}