[PR-194] - tidy up code, create a generic write wrapper to simplify code.

Fix #1177
This commit is contained in:
Adam Sutton 2012-12-30 12:17:34 +00:00
parent 16db6f132f
commit 051e404da5
4 changed files with 32 additions and 38 deletions

View file

@ -181,31 +181,16 @@ int
tcp_write_queue(int fd, htsbuf_queue_t *q)
{
htsbuf_data_t *hd;
int l, r = 0, l2;
uint8_t* p;
int l, r = 0;
void *p;
while((hd = TAILQ_FIRST(&q->hq_q)) != NULL) {
TAILQ_REMOVE(&q->hq_q, hd, hd_link);
l = hd->hd_data_len - hd->hd_data_off;
p = hd->hd_data + hd->hd_data_off;
while(l > 0) {
l2 = write(fd, p, l);
if(l2 < 0) {
perror("tcp_write_queue");
if(errno == EINTR) {
continue;
} else {
break;
}
}
l -= l2;
p += l2;
}
if(l == 0) {
r = 1;
if (!r) {
l = hd->hd_data_len - hd->hd_data_off;
p = hd->hd_data + hd->hd_data_off;
r = tvh_write(fd, p, l);
}
free(hd->hd_data);

View file

@ -454,6 +454,8 @@ int tvh_socket(int domain, int type, int protocol);
int tvh_pipe(int flags, th_pipe_t *pipe);
int tvh_write(int fd, void *buf, size_t len);
void hexdump(const char *pfx, const uint8_t *data, int len);
uint32_t tvh_crc32(uint8_t *data, size_t datalen, uint32_t crc);

View file

@ -98,12 +98,12 @@ page_root2(http_connection_t *hc, const char *remain, void *opaque)
static int
page_static_file(http_connection_t *hc, const char *remain, void *opaque)
{
int ret = 0, r;
int ret = 0;
const char *base = opaque;
char path[500];
ssize_t size;
const char *content = NULL, *postfix;
char buf[4096], *p;
char buf[4096];
const char *gzip;
if(remain == NULL)
@ -139,21 +139,7 @@ page_static_file(http_connection_t *hc, const char *remain, void *opaque)
ret = 500;
break;
}
p = buf;
while(c > 0) {
r = write(hc->hc_fd, p, c);
if(r < 0) {
perror("page_static_file");
if(errno == EINTR) {
continue;
} else {
break;
}
}
c -= r;
p += r;
}
if (c != 0) {
if (tvh_write(hc->hc_fd, buf, c)) {
ret = 500;
break;
}

View file

@ -48,3 +48,24 @@ tvh_pipe(int flags, th_pipe_t *p)
pthread_mutex_unlock(&fork_lock);
return err;
}
int
tvh_write(int fd, void *buf, size_t len)
{
ssize_t c;
while (len) {
c = write(fd, buf, len);
if (c < 0) {
if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) {
usleep(100);
continue;
}
break;
}
len -= c;
buf += c;
}
return len ? 1 : 0;
}