-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.c
More file actions
315 lines (291 loc) · 10.9 KB
/
Copy pathhttp.c
File metadata and controls
315 lines (291 loc) · 10.9 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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
#include <sys/socket.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "http.h"
#include <dirent.h>
#include <stdlib.h>
#include <sys/wait.h>
int handle_client(int fd, ServerConfig *config) {
char buffer[4096];
ssize_t recvRes = recv(fd, buffer, sizeof(buffer)-1, 0);
if (recvRes > 0 ){
buffer[recvRes] = '\0';
HttpRequest req;
if (parse_request(buffer,&req) == -1){
send_error(fd, 400, "Bad Request", config->root);
return 0;
}
if(strcmp(req.version, "HTTP/1.1")!=0) {
send_error(fd, 505, "HTTP Version Not Supported", config->root);
return 0;
}
printf("%s %s %s\n", req.method, req.uri, req.version);
if (config->redirect_code > 0) {
char response[1024];
int len = snprintf(response, sizeof response, "HTTP/1.1 %d Redirect\r\nLocation: %s\r\nContent-Length: 0\r\n\r\n",
config->redirect_code, config->redirect_url);
send(fd, response, len, 0 );
return 0;
}
if (sanitize_uri(req.uri) == -1) {
send_error(fd,403, "Forbidden", config->root);
return 0;
}
if(strcmp(req.method, "GET") !=0 && strcmp(req.method, "DELETE") != 0 && strcmp(req.method, "POST")!=0) {
send_error(fd, 405, "Method Not Allowed", config->root);
return 0;
}
if (strcmp(req.method, "DELETE")==0) {
char path[512];
snprintf(path, sizeof path, "%s%s",config->root, req.uri);
int bad = remove(path);
if (bad) {
send_error(fd, 404, "Not Found", config->root);
}else{
char body[128];
int body_len = snprintf(body, sizeof body, "%d %s\n", 200, "OK");
char response[512];
int len = snprintf(response, sizeof response, "HTTP/1.1 %d %s\r\nContent-Length: %d\r\n\r\n%s",
200, "OK",body_len,body );
send(fd, response, len, 0);
}
return req.keep_alive;
}
if (strcmp(req.method, "POST")==0){
char *body = strstr(buffer, "\r\n\r\n");
if(!body) {
send_error(fd, 400, "Bad Request", config->root);
return 0;
}
body+=4;
char decoded[65536];
int body_len;
if (req.chunked) {
body_len = decode_chunked(body,decoded, sizeof decoded);
if (body_len == -1) {
send_error(fd, 400, "Bad Request", config->root);
return 0;
}
body = decoded;
}else{
if (req.content_length <= 0) {
send_error(fd, 411, "Length Required", config->root);
return 0;
}
if (req.content_length > config->max_body_size) {
send_error(fd, 413, "Payload Too Large", config->root);
return 0;
}
body_len = req.content_length;
}
char path[512];
snprintf(path, sizeof path, "%s/uploads%s", config->root,req.uri);
FILE *file = fopen(path, "wb");
if(!file) {
send_error(fd, 500, "Internal Server Error", config->root);
return 0;
}
fwrite(body,1,body_len,file);
fclose(file);
char resp_body[128];
int resp_body_len = snprintf(resp_body, sizeof resp_body, "201 Created\n");
char resp[512];
int len =snprintf(resp, sizeof resp, "HTTP/1.1 201 Created\r\nContent-Length: %d\r\n\r\n%s", resp_body_len, resp_body);
send(fd, resp, len, 0);
return req.keep_alive;
}
char path[512];
char *q = strchr(req.uri, '?');
if(q) {
*q ='\0';
q++;
}
snprintf(path, sizeof(path), "%s%s",config->root, req.uri);
size_t path_len = strlen(path);
if (path[path_len -1] == '/'){
strncat(path, "index.html", sizeof(path) - path_len -1);
}
const char *ext = strrchr(path, '.');
if (ext && strcmp(ext, ".py") == 0) {
handle_cgi(fd, path, req.method, q,config, &req);
return req.keep_alive;
}
FILE *file = fopen(path, "rb");
if (file == NULL){
char dir_path[512];
snprintf(dir_path, sizeof dir_path, "%s%s",config->root, req.uri);
DIR *dir = opendir(dir_path);
if (dir){
closedir(dir);
send_dir_listing(fd, dir_path, req.uri, config->root);
}else{
send_error(fd, 404, "Not Found", config->root);
}
}else{
fseek(file, 0, SEEK_END);
long file_size = ftell(file);
fseek(file, 0, SEEK_SET);
char header[512];
int header_len = snprintf(header, sizeof header, "HTTP/1.1 200 OK\r\nContent-Type: %s\r\nContent-Length: %ld\r\n\r\n"
,get_mime_type(path), file_size);
send(fd,header,header_len,0);
char chunk[4096];
size_t n;
while ((n = fread(chunk, 1, sizeof chunk, file)) > 0) {
send(fd, chunk, n, 0);
}
fclose(file);
}
return req.keep_alive;
}
return 0;
}
int parse_request(const char *raw, HttpRequest *req) {
req->content_length = 0;
req->keep_alive = 1;
req->chunked =0;
char *EOR = strstr(raw, "\r\n");
if(!EOR) return -1;
EOR+=2;
int scan = sscanf(raw, "%15s %255s %15s", req->method, req->uri, req->version);
if (scan !=3){
return -1;
}
while(*EOR != '\r') {
if (strncmp(EOR, "Host: ", 6)==0){
sscanf(EOR, "Host: %255s", req->host );
}else if (strncmp(EOR, "Content-Length: ", 16)==0){
sscanf(EOR,"Content-Length: %d", &req->content_length);
}else if (strncmp(EOR, "Connection: ", 12) == 0) {
if (strstr(EOR, "keep-alive"))
req->keep_alive = 1;
else
req-> keep_alive = 0;
}else if (strncmp(EOR, "Transfer-Encoding: chunked", 26)==0){
req->chunked = 1;
}
EOR = strstr(EOR, "\r\n");
if (!EOR) break;
EOR += 2;
}
return 0;
}
void send_error(int fd, int status_code, const char *status_text, const char *root){
char path[128];
char body[128];
int body_len;
snprintf(path, sizeof path, "%s/errors/%d.html",root,status_code);
FILE *file = fopen(path, "rb");
if (!file){
body_len = snprintf(body, sizeof body, "%d %s\n", status_code, status_text);
char response[512];
int len = snprintf(response, sizeof response,
"HTTP/1.1 %d %s\r\nContent-Length: %d\r\n\r\n%s",status_code,status_text, body_len, body);
send(fd, response, len, 0);
}else{
fseek(file,0,SEEK_END);
int body_len = ftell(file);
fseek(file,0,SEEK_SET);
char *buffer = malloc(body_len);
size_t read_length = fread(buffer, 1, body_len, file);
char response[8192];
int len = snprintf(response, sizeof response,
"HTTP/1.1 %d %s\r\nContent-Type: text/html\r\nContent-Length: %d\r\n\r\n",
status_code, status_text, (int)read_length);
memcpy(response + len, buffer, read_length);
send(fd, response, read_length+len, 0);
free(buffer);
fclose(file);
}
}
void send_dir_listing(int fd, const char *path, const char *uri, char *root){
DIR *dir = opendir(path);
if (!dir) {
send_error(fd, 403, "Forbidden", root);
return;
}
char body[8192];
int body_len = snprintf(body, sizeof body, "<html><body><h1>Index of %s</h1><ul>", uri);
struct dirent *entry;
while ((entry = readdir(dir)) != NULL){
body_len += snprintf(body+body_len, sizeof body-body_len, "<li><a href=\"%s\">%s</a></li>",entry->d_name, entry->d_name);
}
body_len += snprintf(body+body_len, sizeof body- body_len, "</ul></body></html>");
closedir(dir);
char response[16384];
int len = snprintf(response, sizeof response, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: %d\r\n\r\n%s",body_len, body);
send(fd, response, len, 0);
}
void handle_cgi(int fd, const char *script_path, const char *method, const char *query_string, ServerConfig *config,
HttpRequest *req){
int pipefd[2];
pipe(pipefd);
pid_t pid = fork();
if (pid == 0) {
close(pipefd[0]);
dup2(pipefd[1], STDOUT_FILENO);
close(pipefd[1]);
setenv("REQUEST_METHOD", method, 1);
setenv("QUERY_STRING", query_string ? query_string : "", 1);
setenv("SERVER_PROTOCOL", "HTTP/1.1", 1);
setenv("GATEWAY_INTERFACE", "CGI/1.1", 1);
setenv("SERVER_NAME", config->server_name, 1);
setenv("REQUEST_URI", req->uri, 1);
setenv("PATH_INFO", req->uri, 1);
char cl_str[32];
snprintf(cl_str, sizeof cl_str, "%d", req->content_length);
setenv("CONTENT_LENGTH", cl_str, 1);
char port_str[16];
snprintf(port_str, sizeof port_str, "%d", config->port);
setenv("SERVER_PORT", port_str, 1);
execl("/usr/bin/env", "env", "python3", script_path, (char *) NULL);
perror("execl failed");
_exit(1);
}
close(pipefd[1]);
char cgi_output[8192];
int total = 0;
int n;
while ((n=read(pipefd[0], cgi_output + total, sizeof(cgi_output)-total - 1))>0){
total +=n;
}
cgi_output[total] = '\0';
close(pipefd[0]);
waitpid(pid, NULL, 0);
char *body_start = strstr(cgi_output, "\r\n\r\n");
if (!body_start) {
send_error(fd, 500, "Internal Server Error", "www");
return;
}
body_start += 4;
int body_len = total - (body_start - cgi_output);
int cgi_headers_len = body_start - cgi_output;
char response[16384];
int len = snprintf(response, sizeof response,
"HTTP/1.1 200 OK\r\n"
"Content-Length: %d\r\n"
"%.*s",
body_len, cgi_headers_len, cgi_output);
memcpy(response + len, body_start, body_len);
send(fd, response, len+body_len, 0);
}
int decode_chunked(const char *raw, char *out, int max_size) {
//chunked encoding 格式: [数据大小(16进制)] + \r\n + [真实数据内容] + \r\n
int total = 0;
const char *p = raw;
while(1) {
//读取块大小(十六进制)
int chunk_size = 0;
sscanf(p, "%x", &chunk_size);
if (chunk_size == 0) break;
p = strstr(p, "\r\n");
if (!p) return -1;
p += 2;
if (total + chunk_size > max_size) return -1;
memcpy(out+total, p, chunk_size);
total += chunk_size;
p += chunk_size + 2;
}
return total;
}