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
|
import
std.socket,
std.file,
std.string,
std.format,
std.path;
enum ClientState {
START,
REQUEST_LINE,
END_REQUEST,
DONE,
ERROR
};
enum ResponseCode {
OKAY = 200,
NOTFOUND = 404,
NOTIMPLEMENTED = 501
};
class Request {
string method;
string path;
string vers;
string[] header_lines;
auto this(char[] line) {
line = strip(line);
string tpath;
formattedRead(line, "%s %s %s", &method, &tpath, &vers);
if (tpath[0] == '/')
path = buildNormalizedPath(getcwd() ~ tpath);
else
path = buildNormalizedPath(getcwd() ~ "/" ~ tpath);
}
ResponseCode check() {
try {
bool isfile = path.isFile();
if (!isfile)
return ResponseCode.NOTFOUND;
}
catch (FileException e) {
return ResponseCode.NOTFOUND;
}
return ResponseCode.OKAY;
}
}
class ClientContext {
ClientState state;
Socket pair;
Request request;
auto this(Socket p) {
pair = p;
state = ClientState.START;
}
void handle() {
while(true) {
switch(state) {
case ClientState.START:
char[255] line;
auto len = pair.receive(line);
auto request_line = line[0 .. len];
request = new Request(request_line);
state = ClientState.REQUEST_LINE;
break;
case ClientState.REQUEST_LINE:
char[255] line;
auto len = pair.receive(line);
if (len < 3) //FIXME: A better test needed for newline
state = ClientState.END_REQUEST;
else {
auto header_line = line[0 .. len];
header_line = strip(line);
request.header_lines ~= cast(string) header_line;
}
break;
case ClientState.END_REQUEST:
switch (request.check()) {
case ResponseCode.OKAY:
pair.send(readText(request.path));
break;
case ResponseCode.NOTFOUND:
pair.send("404 File Not Found");
break;
case ResponseCode.NOTIMPLEMENTED:
pair.send("501 Method Not Implemented");
break;
default:
pair.send("500 Internal Server Error");
break;
}
state = ClientState.DONE;
break;
case ClientState.DONE:
return;
break;
default:
break;
}
}
}
}
|