forked from huanghaihui/6858-lab
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.c
525 lines (445 loc) · 12.6 KB
/
http.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
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
#include "http.h"
#include <sys/param.h>
#ifndef BSD
#include <sys/sendfile.h>
#endif
#include <sys/uio.h>
#include <ctype.h>
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
void touch(const char *name) {
if (access("/tmp/grading", F_OK) < 0)
return;
char pn[1024];
snprintf(pn, 1024, "/tmp/%s", name);
int fd = open(pn, O_RDWR | O_CREAT | O_NOFOLLOW, 0666);
if (fd >= 0)
close(fd);
}
int http_read_line(int fd, char *buf, size_t size)
{
size_t i = 0;
for (;;)
{
int cc = read(fd, &buf[i], 1);
if (cc <= 0)
break;
if (buf[i] == '\r')
{
buf[i] = '\0'; /* skip */
continue;
}
if (buf[i] == '\n')
{
buf[i] = '\0';
return 0;
}
if (i >= size - 1)
{
buf[i] = '\0';
return 0;
}
i++;
}
return -1;
}
const char *http_request_line(int fd, char *reqpath, char *env, size_t *env_len)
{
static char buf[8192]; /* static variables are not on the stack */
char *sp1, *sp2, *qp, *envp = env;
char *envp_end = envp + 8192;
/* For lab 2: don't remove this line. */
touch("http_request_line");
if (http_read_line(fd, buf, sizeof(buf)) < 0)
return "Socket IO error";
/* Parse request like "GET /foo.html HTTP/1.0" */
sp1 = strchr(buf, ' ');
if (!sp1)
return "Cannot parse HTTP request (1)";
*sp1 = '\0';
sp1++;
if (*sp1 != '/')
return "Bad request path";
sp2 = strchr(sp1, ' ');
if (!sp2)
return "Cannot parse HTTP request (2)";
*sp2 = '\0';
sp2++;
/* We only support GET and POST requests */
if (strcmp(buf, "GET") && strcmp(buf, "POST"))
return "Unsupported request (not GET or POST)";
envp += snprintf(envp, envp_end-envp, "REQUEST_METHOD=%s", buf) + 1;
envp += snprintf(envp, envp_end-envp, "SERVER_PROTOCOL=%s", sp2) + 1;
/* parse out query string, e.g. "foo.py?user=bob" */
if ((qp = strchr(sp1, '?')))
{
*qp = '\0';
envp += snprintf(envp, envp_end-envp, "QUERY_STRING=%s", qp + 1) + 1;
}
/* decode URL escape sequences in the requested path into reqpath */
url_decode(reqpath, sp1, 2048);
envp += snprintf(envp, envp_end-envp, "REQUEST_URI=%s", reqpath) + 1;
envp += snprintf(envp, envp_end-envp, "SERVER_NAME=zoobar.org") + 1;
*envp = 0;
*env_len = envp - env + 1;
return NULL;
}
const char *http_request_headers(int fd)
{
static char buf[8192]; /* static variables are not on the stack */
int i;
char value[512];
char envvar[512];
/* For lab 2: don't remove this line. */
touch("http_request_headers");
/* Now parse HTTP headers */
for (;;)
{
if (http_read_line(fd, buf, sizeof(buf)) < 0)
return "Socket IO error";
if (buf[0] == '\0') /* end of headers */
break;
/* Parse things like "Cookie: foo bar" */
char *sp = strchr(buf, ' ');
if (!sp)
return "Header parse error (1)";
*sp = '\0';
sp++;
/* Strip off the colon, making sure it's there */
if (strlen(buf) == 0)
return "Header parse error (2)";
char *colon = &buf[strlen(buf) - 1];
if (*colon != ':')
return "Header parse error (3)";
*colon = '\0';
/* Set the header name to uppercase and replace hyphens with underscores */
for (i = 0; i < strlen(buf); i++) {
buf[i] = toupper(buf[i]);
if (buf[i] == '-')
buf[i] = '_';
}
/* Decode URL escape sequences in the value */
url_decode(value, sp, 512);
/* Store header in env. variable for application code */
/* Some special headers don't use the HTTP_ prefix. */
if (strcmp(buf, "CONTENT_TYPE") != 0 &&
strcmp(buf, "CONTENT_LENGTH") != 0) {
snprintf(envvar, 512, "HTTP_%s", buf);
setenv(envvar, value, 1);
} else {
setenv(buf, value, 1);
}
}
return 0;
}
void http_err(int fd, int code, char *fmt, ...)
{
fdprintf(fd, "HTTP/1.0 %d Error\r\n", code);
fdprintf(fd, "Content-Type: text/html\r\n");
fdprintf(fd, "\r\n");
fdprintf(fd, "<H1>An error occurred</H1>\r\n");
char *msg = 0;
va_list ap;
va_start(ap, fmt);
vasprintf(&msg, fmt, ap);
va_end(ap);
fdprintf(fd, "%s\n", msg);
close(fd);
warnx("[%d] Request failed: %s", getpid(), msg);
free(msg);
}
/* split path into script name and path info */
void split_path(char *pn)
{
struct stat st;
char *slash = NULL;
for (;;) {
/*
* Stop searching if we find a file at a prefix,
* or if we get an unexpected error.
*/
int r = stat(pn, &st);
if (r < 0) {
if (errno != ENOTDIR && errno != ENOENT)
break;
} else {
if (S_ISREG(st.st_mode))
break;
}
/* Set the last '/' in pn to a null, and see if that helps.
If so, we set the remainder of the string to PATH_INFO.
If not, iterate and set the previous '/' to a null, etc. */
if (slash)
*slash = '/';
else
slash = pn + strlen(pn);
while (--slash > pn) {
if (*slash == '/') {
*slash = '\0';
break;
}
}
if (slash == pn) {
slash = NULL;
break;
}
}
if (slash) {
*slash = '/';
setenv("PATH_INFO", slash, 1);
*slash = '\0';
}
setenv("SCRIPT_NAME", pn + strlen(getenv("DOCUMENT_ROOT")), 1);
setenv("SCRIPT_FILENAME", pn, 1);
}
void http_serve(int fd, const char *name)
{
void (*handler)(int, const char *) = http_serve_none;
char pn[1024];
struct stat st;
getcwd(pn, sizeof(pn));
setenv("DOCUMENT_ROOT", pn, 1);
strncat(pn, name, (sizeof(pn) - strlen(pn)) - 1);
split_path(pn);
if (!stat(pn, &st))
{
/* executable bits -- run as CGI script */
if (S_ISREG(st.st_mode) && (st.st_mode & S_IXUSR))
handler = http_serve_executable;
else if (S_ISDIR(st.st_mode))
handler = http_serve_directory;
else
handler = http_serve_file;
}
handler(fd, pn);
}
void http_serve_none(int fd, const char *pn)
{
http_err(fd, 404, "File does not exist: %s", pn);
}
void http_serve_file(int fd, const char *pn)
{
int filefd;
off_t len = 0;
if (getenv("PATH_INFO")) {
/* only attempt PATH_INFO on dynamic resources */
char buf[1024];
snprintf(buf, 1024, "%s%s", pn, getenv("PATH_INFO"));
http_serve_none(fd, buf);
return;
}
if ((filefd = open(pn, O_RDONLY)) < 0)
return http_err(fd, 500, "open %s: %s", pn, strerror(errno));
const char *ext = strrchr(pn, '.');
const char *mimetype = "text/html";
if (ext && !strcmp(ext, ".css"))
mimetype = "text/css";
if (ext && !strcmp(ext, ".jpg"))
mimetype = "image/jpeg";
fdprintf(fd, "HTTP/1.0 200 OK\r\n");
fdprintf(fd, "Content-Type: %s\r\n", mimetype);
fdprintf(fd, "\r\n");
#ifndef BSD
struct stat st;
if (!fstat(filefd, &st))
len = st.st_size;
if (sendfile(fd, filefd, 0, len) < 0)
#else
if (sendfile(filefd, fd, 0, &len, 0, 0) < 0)
#endif
err(1, "sendfile");
close(filefd);
}
void dir_join(char *dst, const char *dirname, const char *filename) {
strcpy(dst, dirname);
if (dst[strlen(dst) - 1] != '/')
strcat(dst, "/");
strcat(dst, filename);
}
void http_serve_directory(int fd, const char *pn) {
/* for directories, use index.html or similar in that directory */
static const char * const indices[] = {"index.html", "index.php", "index.cgi", NULL};
char name[1024];
struct stat st;
int i;
for (i = 0; indices[i]; i++) {
dir_join(name, pn, indices[i]);
if (stat(name, &st) == 0 && S_ISREG(st.st_mode)) {
dir_join(name, getenv("SCRIPT_NAME"), indices[i]);
break;
}
}
if (indices[i] == NULL) {
http_err(fd, 403, "No index file in %s", pn);
return;
}
http_serve(fd, name);
}
void http_serve_executable(int fd, const char *pn)
{
char buf[1024], headers[4096], *pheaders = headers;
int pipefd[2], statusprinted = 0, ret, headerslen = 4096;
pipe(pipefd);
switch (fork()) {
case -1:
http_err(fd, 500, "fork: %s", strerror(errno));
return;
case 0:
signal(SIGPIPE, SIG_DFL);
signal(SIGCHLD, SIG_DFL);
dup2(fd, 0);
close(fd);
dup2(pipefd[1], 1);
close(pipefd[0]);
close(pipefd[1]);
execl(pn, pn, NULL);
http_err(1, 500, "execl %s: %s", pn, strerror(errno));
exit(1);
default:
close(pipefd[1]);
while (1) {
if (http_read_line(pipefd[0], buf, 1024) < 0) {
http_err(fd, 500, "Premature end of script headers");
close(pipefd[0]);
return;
}
if (!*buf)
break;
if (!statusprinted && strncasecmp("Status: ", buf, 8) == 0) {
fdprintf(fd, "HTTP/1.0 %s\r\n%s", buf + 8, headers);
statusprinted = 1;
} else if (statusprinted) {
fdprintf(fd, "%s\r\n", buf);
} else {
ret = snprintf(pheaders, headerslen, "%s\r\n", buf);
pheaders += ret;
headerslen -= ret;
if (headerslen == 0) {
http_err(fd, 500, "Too many script headers");
close(pipefd[0]);
return;
}
}
}
if (statusprinted)
fdprintf(fd, "\r\n");
else
fdprintf(fd, "HTTP/1.0 200 OK\r\n%s\r\n", headers);
while ((ret = read(pipefd[0], buf, 1024)) > 0) {
write(fd, buf, ret);
}
close(fd);
close(pipefd[0]);
}
}
void url_decode(char *dst, const char *src, size_t len)
{
size_t i = 0;
for (;;)
{
if (i == len - 1) {
*dst = '\0';
break;
}
if (src[0] == '%' && src[1] && src[2])
{
char hexbuf[3];
hexbuf[0] = src[1];
hexbuf[1] = src[2];
hexbuf[2] = '\0';
*dst = strtol(&hexbuf[0], 0, 16);
src += 3;
}
else if (src[0] == '+')
{
*dst = ' ';
src++;
}
else
{
*dst = *src;
src++;
if (*dst == '\0')
break;
}
dst++;
i++;
}
}
void env_deserialize(const char *env, size_t len)
{
for (;;)
{
char *p = strchr(env, '=');
if (p == 0 || p - env > len)
break;
*p++ = 0;
setenv(env, p, 1);
p += strlen(p)+1;
len -= (p - env);
env = p;
}
setenv("GATEWAY_INTERFACE", "CGI/1.1", 1);
setenv("REDIRECT_STATUS", "200", 1);
}
void fdprintf(int fd, char *fmt, ...)
{
char *s = 0;
va_list ap;
va_start(ap, fmt);
vasprintf(&s, fmt, ap);
va_end(ap);
write(fd, s, strlen(s));
free(s);
}
ssize_t sendfd(int socket, const void *buffer, size_t length, int fd)
{
struct iovec iov = {(void *)buffer, length};
char buf[CMSG_LEN(sizeof(int))];
struct cmsghdr *cmsg = (struct cmsghdr *)buf;
ssize_t r;
cmsg->cmsg_len = sizeof(buf);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
*((int *)CMSG_DATA(cmsg)) = fd;
struct msghdr msg = {0};
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = cmsg;
msg.msg_controllen = cmsg->cmsg_len;
r = sendmsg(socket, &msg, 0);
if (r < 0)
warn("sendmsg");
return r;
}
ssize_t recvfd(int socket, void *buffer, size_t length, int *fd)
{
struct iovec iov = {buffer, length};
char buf[CMSG_LEN(sizeof(int))];
struct cmsghdr *cmsg = (struct cmsghdr *)buf;
ssize_t r;
cmsg->cmsg_len = sizeof(buf);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
struct msghdr msg = {0};
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = cmsg;
msg.msg_controllen = cmsg->cmsg_len;
again:
r = recvmsg(socket, &msg, 0);
if (r < 0 && errno == EINTR)
goto again;
if (r < 0)
warn("recvmsg");
else
*fd = *((int*)CMSG_DATA(cmsg));
return r;
}