[core] cleanup: consolidate FAM code in stat_cache
[lighttpd.git] / src / network_write_no_mmap.c
blob2268cc939aeecb34111f9c77266af9cb467a8397
1 #include "first.h"
3 #include "network_backends.h"
4 #include "log.h"
5 #include "sys-socket.h"
7 #include <unistd.h>
8 #include <errno.h>
9 #include <string.h>
11 int network_write_file_chunk_no_mmap(server *srv, connection *con, int fd, chunkqueue *cq, off_t *p_max_bytes) {
12 chunk* const c = cq->first;
13 off_t offset, toSend;
14 ssize_t r;
15 UNUSED(con);
17 force_assert(NULL != c);
18 force_assert(FILE_CHUNK == c->type);
19 force_assert(c->offset >= 0 && c->offset <= c->file.length);
21 offset = c->file.start + c->offset;
22 toSend = c->file.length - c->offset;
23 if (toSend > 64*1024) toSend = 64*1024; /* max read 64kb in one step */
24 if (toSend > *p_max_bytes) toSend = *p_max_bytes;
26 if (0 == toSend) {
27 chunkqueue_remove_finished_chunks(cq);
28 return 0;
31 if (0 != chunkqueue_open_file_chunk(srv, cq)) return -1;
33 buffer_string_prepare_copy(srv->tmp_buf, toSend);
35 if (-1 == lseek(c->file.fd, offset, SEEK_SET)) {
36 log_error_write(srv, __FILE__, __LINE__, "ss", "lseek: ", strerror(errno));
37 return -1;
39 if (-1 == (toSend = read(c->file.fd, srv->tmp_buf->ptr, toSend))) {
40 log_error_write(srv, __FILE__, __LINE__, "ss", "read: ", strerror(errno));
41 return -1;
44 #if defined(__WIN32)
45 if ((r = send(fd, srv->tmp_buf->ptr, toSend, 0)) < 0) {
46 int lastError = WSAGetLastError();
47 switch (lastError) {
48 case WSAEINTR:
49 case WSAEWOULDBLOCK:
50 break;
51 case WSAECONNRESET:
52 case WSAETIMEDOUT:
53 case WSAECONNABORTED:
54 return -2;
55 default:
56 log_error_write(srv, __FILE__, __LINE__, "sdd",
57 "send failed: ", lastError, fd);
58 return -1;
61 #else /* __WIN32 */
62 if ((r = write(fd, srv->tmp_buf->ptr, toSend)) < 0) {
63 switch (errno) {
64 case EAGAIN:
65 case EINTR:
66 break;
67 case EPIPE:
68 case ECONNRESET:
69 return -2;
70 default:
71 log_error_write(srv, __FILE__, __LINE__, "ssd",
72 "write failed:", strerror(errno), fd);
73 return -1;
76 #endif /* __WIN32 */
78 if (r >= 0) {
79 *p_max_bytes -= r;
80 chunkqueue_mark_written(cq, r);
83 return (r > 0 && r == toSend) ? 0 : -3;