parse.c
2.81 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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include "http/request_parser.h"
#include "interface/class.h"
#define REMAINS(pars,done) \
((pars)->buffer_used - ((done) - (pars)->buffer))
static
inline
char *
httpRequestParserGetLine(char ** data)
{
char * line_end = strstr(*data, "\r\n");
char * ret = *data;
if (NULL == line_end) {
return NULL;
}
*line_end = 0;
*data = line_end + 2;
return ret;
}
static
inline
void
httpRequestSkip(char ** data)
{
for (; 0 != **data && ! isalpha(**data); (*data)++);
}
void httpRequestParserGetRequestLine(HttpRequest, char *);
void
httpRequestParserParse(HttpRequestParser this)
{
static HttpRequest request = NULL;
static char * data; // static pointer to unprocessed data
char * line;
int cont = 1;
while(cont) {
switch(this->state) {
case HTTP_REQUEST_GARBAGE:
data = this->buffer; // initialize static pointer
httpRequestSkip(&data);
request = new(HttpRequest);
this->state = HTTP_REQUEST_START;
break;
case HTTP_REQUEST_START:
if (NULL == (line = httpRequestParserGetLine(&data))) {
cont = 0;
break;
}
httpRequestParserGetRequestLine(request, line);
this->state = HTTP_REQUEST_REQUEST_LINE_DONE;
break;
case HTTP_REQUEST_REQUEST_LINE_DONE:
if (NULL == (line = httpRequestParserGetLine(&data))) {
cont = 0;
break;
}
if (0 == strlen(line)) {
this->state = HTTP_REQUEST_HEADERS_DONE;
break;
}
httpRequestParserGetHeader(request, line);
break;
case HTTP_REQUEST_HEADERS_DONE:
httpHeaderSort(request->header, request->nheader);
{
char * nbody;
if (0 == request->nbody) {
nbody = httpHeaderGet(
request->header,
request->nheader,
"Content-Length");
if (NULL == nbody) {
this->state = HTTP_REQUEST_DONE;
break;
}
else {
request->nbody = atoi(nbody);
}
}
if (REMAINS(this, data) >= request->nbody) {
request->body = calloc(1, request->nbody + 1);
memcpy(request->body, data, request->nbody);
data += request->nbody;
this->state = HTTP_REQUEST_DONE;
}
}
break;
case HTTP_REQUEST_DONE:
/**
* enqueue current request
*/
this->request_queue->requests[(this->request_queue->nrequests)++] =
request;
/**
* remove processed stuff from input buffer.
*/
memmove(this->buffer, data, REMAINS(this, data));
this->buffer_used -= data - this->buffer;
/**
* dont continue loop if input buffer is empty
*/
if (0 == this->buffer_used) {
cont = 0;
}
/**
* prepare for next request
*/
this->state = HTTP_REQUEST_GARBAGE;
break;
default:
break;
}
}
}
// vim: set ts=4 sw=4: