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
|
#define _POSIX_C_SOURCE 200809L
#define NL "\015\012"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main (int argc, char* argv[]) {
char* qs = getenv ("QUERY_STRING");
if (qs == NULL || *qs == '\0') {
fputs (
"HTTP/1.1 400 Bad Request" NL
"Content-Type: text/html" NL NL
"<html><head><title>400 Bad Request</title></head>" NL
"<body><p>Query string is missing</p>"
"</body></html>" NL, stdout);
return 1;
}
if (strncmp (qs, "filename=", 9)) {
fputs (
"HTTP/1.1 400 Bad Request" NL
"Content-Type: text/html" NL NL
"<html><head><title>400 Bad Request</title></head>" NL
"<body><p>Query string is not valid</p>"
"</body></html>" NL, stdout);
return 1;
}
char* fn = qs + 9;
int fd = open (fn, O_RDONLY);
if (fd < 0) {
switch (errno) {
case ENOENT:
printf (
"HTTP/1.1 404 Not Found" NL
"Content-Type: text/html" NL NL
"<html><head><title>404 Not Found</title></head>" NL
"<body><p>File `%s\' cannot be found on the system</p>" NL
"</body></html>" NL, fn);
return 2;
case EACCES:
printf (
"HTTP/1.1 403 Forbidden" NL
"Content-Type: text/html" NL NL
"<html><head><title>403 Forbidden</title></head>" NL
"<body><p>Access to `%s\' is denied</p>" NL
"</body></html>" NL, fn);
return 3;
default:
printf (
"HTTP/1.1 500 Internal Server Error" NL
"Content-Type: text/html" NL NL
"<html><head><title>500 Internal Server Error</title></head>" NL
"<body><p>%s</p>" NL
"</body></html>" NL, strerror (errno));
return 4;
}
}
fputs ("Content-Type: application/octet-stream" NL NL, stdout);
fflush (stdout);
char buf[4096];
ssize_t r;
for (; (r = read (fd, buf, 4096)) > 0; write (1, buf, r));
return 0;
}
|