2
0
Fork 0
lighttpd2/src/network.c

117 lines
2.6 KiB
C
Raw Normal View History

2008-08-05 15:08:32 +00:00
#include "base.h"
2008-08-05 15:08:32 +00:00
/** repeats write after EINTR */
ssize_t net_write(int fd, void *buf, ssize_t nbyte) {
2008-08-05 15:08:32 +00:00
ssize_t r;
while (-1 == (r = write(fd, buf, nbyte))) {
switch (errno) {
case EINTR:
/* Try again */
break;
default:
/* report error */
return r;
}
}
/* return bytes written */
return r;
}
/** repeats read after EINTR */
ssize_t net_read(int fd, void *buf, ssize_t nbyte) {
2008-08-05 15:08:32 +00:00
ssize_t r;
while (-1 == (r = read(fd, buf, nbyte))) {
switch (errno) {
case EINTR:
/* Try again */
break;
default:
/* report error */
return r;
}
}
/* return bytes read */
return r;
}
network_status_t network_write(vrequest *vr, int fd, chunkqueue *cq) {
network_status_t res;
#ifdef TCP_CORK
int corked = 0;
#endif
#ifdef TCP_CORK
/* Linux: put a cork into the socket as we want to combine the write() calls
* but only if we really have multiple chunks
*/
if (cq->queue->length > 1) {
corked = 1;
setsockopt(fd, IPPROTO_TCP, TCP_CORK, &corked, sizeof(corked));
}
#endif
/* res = network_write_writev(con, fd, cq); */
res = network_write_sendfile(vr, fd, cq);
#ifdef TCP_CORK
if (corked) {
corked = 0;
setsockopt(fd, IPPROTO_TCP, TCP_CORK, &corked, sizeof(corked));
}
#endif
return res;
}
network_status_t network_read(vrequest *vr, int fd, chunkqueue *cq) {
2008-08-05 15:08:32 +00:00
const ssize_t blocksize = 16*1024; /* 16k */
const off_t max_read = 16 * blocksize; /* 256k */
ssize_t r;
2008-08-06 18:46:42 +00:00
off_t len = 0;
worker *wrk;
ev_tstamp ts;
2008-08-05 15:08:32 +00:00
do {
GString *buf = g_string_sized_new(blocksize);
2008-08-06 18:46:42 +00:00
g_string_set_size(buf, blocksize);
2008-08-05 15:08:32 +00:00
if (-1 == (r = net_read(fd, buf->str, blocksize))) {
g_string_free(buf, TRUE);
switch (errno) {
case EAGAIN:
#if EWOULDBLOCK != EAGAIN
2008-09-23 11:09:07 +00:00
case EWOULDBLOCK:
2008-08-05 15:08:32 +00:00
#endif
return len ? NETWORK_STATUS_SUCCESS : NETWORK_STATUS_WAIT_FOR_EVENT;
case ECONNRESET:
return NETWORK_STATUS_CONNECTION_CLOSE;
default:
VR_ERROR(vr, "oops, read from fd=%d failed: %s", fd, g_strerror(errno) );
2008-08-05 15:08:32 +00:00
return NETWORK_STATUS_FATAL_ERROR;
}
} else if (0 == r) {
g_string_free(buf, TRUE);
return len ? NETWORK_STATUS_SUCCESS : NETWORK_STATUS_CONNECTION_CLOSE;
}
g_string_truncate(buf, r);
chunkqueue_append_string(cq, buf);
len += r;
/* stats */
wrk = vr->con->wrk;
wrk->stats.bytes_in += r;
vr->con->stats.bytes_in += r;
/* update 5s stats */
ts = CUR_TS(wrk);
if ((ts - vr->con->stats.last_avg) > 5) {
vr->con->stats.bytes_in_5s_diff = vr->con->stats.bytes_in - vr->con->stats.bytes_in_5s;
vr->con->stats.bytes_in_5s = vr->con->stats.bytes_in;
vr->con->stats.last_avg = ts;
}
2008-08-05 15:08:32 +00:00
} while (r == blocksize && len < max_read);
return NETWORK_STATUS_SUCCESS;
}