-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.c
127 lines (95 loc) · 2.41 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
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
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <ctype.h>
#include <sys/socket.h>
#include "http.h"
void parse_route(HTTPRequest* http) {
char current_character;
int j = 0;
while(true) {
current_character = http->raw[http->current_position];
if(isalnum(current_character) || ispunct(current_character)) {
http->route.value[j] = current_character;
http->route.length++;
j++;
}
else {
return;
}
http->current_position++;
}
}
void parse_method(HTTPRequest* http) {
char current_character;
while(true) {
current_character = http->raw[http->current_position];
if(!isspace(current_character) && current_character == 'G') {
http->method = GET;
return;
}
else {
perror("Sorry this method is not ready yet");
}
}
}
void parse_http_request(HTTPRequest* http) {
char current_character = ' ';
http->current_position = 0;
http->route.length = 0;
while(current_character != '\0') {
current_character = http->raw[http->current_position];
if(http->current_position == 0) {
parse_method(http);
}
else if(current_character == '/' && http->route.length == 0) {
parse_route(http);
}
http->current_position++;
}
http->route.value[http->route.length] = '\0';
}
int send_all(int response_socket, char* value, size_t length) {
int send_length = 0;
while((size_t)send_length < length) {
send_length = send(response_socket,value,length,0);
if(send_length == -1) {
return -1;
}
}
return 1;
}
void process_request(int newfd, RequestWrangler* request_wrangler) {
HTTP http;
while(true) {
int recv_length = recv(newfd,http.request.raw,9000,0);
if(recv_length == 0 ) {
break;
}
else if( recv_length == -1) {
perror("recv");
break;
}
parse_http_request(&http.request);
request_handler(&http, request_wrangler);
int success;
success = send_all(newfd,http.response.header.value,http.response.header.length);
if(success == -1) {
perror("send");
break;
}
success = send_all(newfd,"\r\n",2);
if(success == -1) {
perror("send");
break;
}
success = send_all(newfd,http.response.body.value,http.response.body.length);
if(success == -1) {
perror("send");
break;
}
free(http.response.body.value);
break;
}
}