write.c
2.71 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
#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/response.h"
#include "http/response/writer.h"
HttpResponse
httpResponseWriterWrite(HttpResponseWriter this, int fd)
{
HttpMessageQueue respq = this->response_queue;
int cont = 1;
HttpResponse retval = NULL;
while (cont) {
switch (this->state) {
case HTTP_RESPONSE_NO:
if (NULL == this->cur_response && 0 < respq->nmsgs) {
retval = this->cur_response = (HttpResponse)respq->msgs[0];
memmove(respq->msgs,
&(respq->msgs[1]),
sizeof(void*) * (--respq->nmsgs + 1));
this->state = HTTP_RESPONSE_START;
}
else {
cont = 0;
}
break;
case HTTP_RESPONSE_START:
if (HTTP_MESSAGE_PIPED ==
((HttpMessage)(this->cur_response))->type) {
struct stat st;
HttpMessage message = (HttpMessage)this->cur_response;
char buffer[200];
message->handle =
open("./assets/waldschrat.jpg", O_RDONLY);
fstat(message->handle, &st);
message->nbody = st.st_size;
sprintf(buffer, "%d", message->nbody);
httpHeaderAdd(&(message->header),
new(HttpHeader, "Content-Length", buffer));
}
this->state = HTTP_RESPONSE_PIPE;
break;
case HTTP_RESPONSE_PIPE:
{
HttpMessage message = (HttpMessage)(this->cur_response);
size_t headsize = httpResponseSizeGet(this->cur_response);
this->buffer = malloc(headsize + message->nbody);
httpResponseToString(this->cur_response, this->buffer);
this->rpipe = headsize;
if (HTTP_MESSAGE_PIPED == message->type &&
0 != message->handle) {
char * data = &(this->buffer[headsize]);
size_t togo = message->nbody;
size_t rsize = read(message->handle, data, togo);
while (rsize < togo) {
data += rsize;
togo -= rsize;
rsize = read(message->handle, data, togo);
}
this->wpipe = 0;
this->rpipe += message->nbody;
close(message->handle);
message->handle = 0;
}
{
char * data = &(this->buffer[this->wpipe]);
size_t written;
written = write(fd, data, this->rpipe - this->wpipe);
data += written;
this->wpipe += written;
if (this->rpipe == this->wpipe) {
this->rpipe = 0;
this->wpipe = 0;
free (this->buffer);
this->buffer = NULL;
this->state = HTTP_RESPONSE_DONE;
}
else {
cont = 0;
}
}
}
break;
case HTTP_RESPONSE_DONE:
this->state = HTTP_RESPONSE_NO;
this->cur_response = NULL;
cont = 0;
break;
}
}
return retval;
}
// vim: set ts=4 sw=4: