-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.c
99 lines (84 loc) · 1.52 KB
/
request.c
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
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include "request.h"
static const char *reqtype[] = {
"GET",
"HEAD",
"POST",
"PUT",
"DELETE",
"CONNECT",
"OPTIONS",
"TRACE",
};
static char *chomp(char **start)
{
char *line = *start;
char *end = strchr(line, '\r');
if (!end) {
end = strchr(line, '\n');
if (!end)
return NULL;
}
while (*end == '\r' || *end == '\n')
*end++ = 0;
*start = end;
return line;
}
int parse_request(struct request *r, char *req)
{
/* type & uri */
char *line = chomp(&req);
if (!line)
return -1;
int i;
for (i = 0; i < REQ_MAX; i++) {
if (strncmp(line, reqtype[i], strlen(reqtype[i])) == 0)
break;
}
if (i == REQ_MAX)
return -1;
r->type = i;
line += strlen(reqtype[i]);
while (isspace(*line))
line++;
char *end = line;
while (*end && !isspace(*end))
end++;
if (*end == 0)
return -1;
*end = 0;
r->uri = line;
/* headers */
i = 0;
while ((line = chomp(&req))) {
if (line[0] == 0)
break;
if (i < 10) {
r->headers[i] = line;
i++;
}
}
for (; i < 10; i++)
r->headers[i] = NULL;
/* message */
r->message = line ? req : NULL;
#if 0
printf("type: %s\nuri: %s\n", reqtype[r->type], r->uri);
for (i = 0; i < 10; i++) {
if (r->headers[i])
printf("header: %s\n", r->headers[i]);
}
printf("message: %s\n", r->message);
#endif
return 0;
}
const char *find_header(struct request *r, const char *header)
{
for (int i = 0; i < 10; i++) {
if (r->headers[i] && strstr(r->headers[i], header))
return r->headers[i];
}
return NULL;
}