write.c
2.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "class.h"
#include "interface/class.h"
#include "http/message.h"
#include "http/response.h"
#include "http/response/writer.h"
#include "cbuf.h"
#define MIN(x,y) ((x) < (y) ? (x) : (y))
#define MAX(x,y) ((x) > (y) ? (x) : (y))
#define _PSIZE(x) (MAX((x),RESPONSE_WRITER_MAX_BUF))
#define PSIZE _PSIZE(this->nheader+message->nbody)
ssize_t
httpResponseWriterWrite(HttpResponseWriter this, int fd)
{
HttpMessageQueue respq = this->response_queue;
HttpMessage message = (HttpMessage)this->cur_response;
int cont = 1;
while (cont) {
switch (this->state) {
case HTTP_RESPONSE_GET:
if (NULL == this->cur_response && 0 < respq->nmsgs) {
message = respq->msgs[0];
this->cur_response = (HttpResponse)message;
this->written = 0;
this->nbody = 0;
this->nheader = httpMessageHeaderSizeGet(message);
httpMessageHeaderToString(message, cbufGetWrite(this->buffer));
cbufIncWrite(this->buffer, this->nheader);
this->state = HTTP_RESPONSE_WRITE;
}
else {
cont = 0;
}
break;
case HTTP_RESPONSE_WRITE:
/**
* read
*/
if (this->nbody < message->nbody) {
size_t size = MIN(
message->nbody - this->nbody,
cbufGetFree(this->buffer));
switch (message->type) {
case HTTP_MESSAGE_BUFFERED:
cbufSetData(this->buffer,
message->body + this->nbody,
size);
break;
case HTTP_MESSAGE_PIPED:
size = cbufRead(this->buffer, message->handle);
break;
default:
return -1;
}
this->nbody += size;
}
/**
* write
*/
{
ssize_t written = cbufWrite(this->buffer, fd);
if (0 <= written) {
this->written += written;
}
else {
return -1;
}
}
if (this->written == message->nbody + this->nheader) {
this->state = HTTP_RESPONSE_DONE;
}
else {
cont = 0;
}
break;
case HTTP_RESPONSE_DONE:
if (HTTP_MESSAGE_PIPED == message->type) {
close(message->handle);
}
this->state = HTTP_RESPONSE_GET;
memmove(respq->msgs,
&(respq->msgs[1]),
sizeof(void*) * (--respq->nmsgs + 1));
if (! httpMessageHasKeepAlive(message)) {
/**
* if the message did not have the keep-alive feature
* we don't care about further pipelined messages and
* return to the caller with a 0 indicating that the
* underlying connection should be closed.
*/
delete(&this->cur_response);
return -1;
}
delete(&this->cur_response);
break;
}
}
return respq->nmsgs;
}
// vim: set ts=4 sw=4: