-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathTHttpD.java
More file actions
181 lines (153 loc) · 6.23 KB
/
THttpD.java
File metadata and controls
181 lines (153 loc) · 6.23 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
package org.sfj;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.nio.charset.StandardCharsets.US_ASCII;
public class THttpD implements Runnable {
private static final Logger LOGGER = Logger.getLogger(THttpD.class.getName());
private static final int CONNECTION_BUFFER_SIZE = 2048;
private final Selector selector = Selector.open();
public THttpD(Path root, int port) throws IOException {
SocketAddress bindAddress = new InetSocketAddress(port);
LOGGER.log(Level.INFO, "THttpD binding to {0}", bindAddress);
ServerSocketChannel.open().bind(bindAddress).configureBlocking(false).register(selector, SelectionKey.OP_ACCEPT, (Attachment) key -> {
SocketChannel incoming = ((ServerSocketChannel) key.channel()).accept();
if (incoming != null) {
incoming.configureBlocking(false).register(selector, SelectionKey.OP_READ, new RequestReader(root));
}
});
}
public void stop() throws IOException {
try {
selector.close();
} finally {
selector.wakeup();
}
}
public void run() {
while (selector.isOpen()) {
try {
selector.select(100);
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Exception retrieving active keys", e);
}
selector.selectedKeys().forEach(k -> {
try {
((Attachment) k.attachment()).process(k);
} catch (IOException e) {
try {
k.channel().close();
} catch (IOException f) {
e.addSuppressed(f);
}
LOGGER.log(Level.SEVERE, "Exception processing selection key: " + k, e);
}
});
}
}
private static class RequestReader implements Attachment {
private static final Pattern METHOD = Pattern.compile("(?<method>[\\p{ASCII}&&[^\\p{Cntrl}\\t \\Q<>@,;:\"/[]?={}\\E]]+)");
private static final Pattern REQUEST_URI = Pattern.compile("/+(?<uri>\\S*)"); //needs correcting
private static final Pattern HTTP_VERSION = Pattern.compile("HTTP/(?<version>\\d+\\.\\d+)");
private static final Pattern REQUEST_PATTERN = Pattern.compile("^" + METHOD + "[ ]+" + REQUEST_URI + "[ ]+" + HTTP_VERSION + "?$", Pattern.MULTILINE);
private final ByteBuffer dataBuffer = (ByteBuffer) ByteBuffer.allocateDirect(CONNECTION_BUFFER_SIZE).position(CONNECTION_BUFFER_SIZE);
private final CharBuffer requestBuffer = CharBuffer.allocate(CONNECTION_BUFFER_SIZE);
private final CharsetDecoder decoder = US_ASCII.newDecoder().onMalformedInput(CodingErrorAction.REPORT);
private final StringBuilder request = new StringBuilder();
private final Path root;
private RequestReader(Path root) {
this.root = root;
}
@Override
public void process(SelectionKey key) throws IOException {
if (((SocketChannel) key.channel()).read(dataBuffer.compact()) > 0) {
decoder.decode((ByteBuffer) dataBuffer.flip(), (CharBuffer) requestBuffer.clear(), false);
Matcher matcher = REQUEST_PATTERN.matcher(request.append(requestBuffer.flip()));
if (matcher.lookingAt()) {
Path resource = root.resolve(Paths.get(matcher.group("uri")));
if (resource.startsWith(root) && Files.isRegularFile(resource) && Files.isReadable(resource)) {
LOGGER.log(Level.INFO, "Serving:\n {0}", request);
switch (matcher.group("method")) {
case "GET":
key.interestOps(SelectionKey.OP_WRITE).attach(new GetResponseWriter(resource));
break;
case "HEAD":
key.interestOps(SelectionKey.OP_WRITE).attach(new ResponseHeaderWriter("HTTP/1.0 200 OK"));
break;
default:
key.interestOps(SelectionKey.OP_WRITE).attach(new ResponseHeaderWriter("HTTP/1.0 501 Not Implemented"));
break;
}
} else {
key.interestOps(SelectionKey.OP_WRITE).attach(new ResponseHeaderWriter("HTTP/1.0 404 Not Found"));
}
}
}
}
}
private static class ResponseHeaderWriter implements Attachment {
private final ByteBuffer header;
public ResponseHeaderWriter(String header) {
this.header = US_ASCII.encode(header + "\r\n");
}
@Override
public void process(SelectionKey key) throws IOException {
if (writeHeader(key)) {
key.channel().close();
}
}
protected boolean writeHeader(SelectionKey key) throws IOException {
((SocketChannel) key.channel()).write(header);
return !header.hasRemaining();
}
}
private static class GetResponseWriter extends ResponseHeaderWriter {
private final Path resource;
public GetResponseWriter(Path resource) {
super("HTTP/1.0 200 OK\r\n");
this.resource = resource;
}
@Override
public void process(SelectionKey key) throws IOException {
if (writeHeader(key)) {
key.attach(new ResponseBodyWriter(FileChannel.open(resource)));
}
}
}
private static class ResponseBodyWriter implements Attachment {
private final FileChannel data;
public ResponseBodyWriter(FileChannel channel) {
this.data = channel;
}
@Override
public void process(SelectionKey key) throws IOException {
long written = data.transferTo(data.position(), CONNECTION_BUFFER_SIZE, (WritableByteChannel) key.channel());
if (data.position(data.position() + written).position() == data.size()) {
key.channel().close();
}
}
}
public static void main(String[] args) throws IOException {
new THttpD(Paths.get(args[0]), 8080).run();
}
interface Attachment {
void process(SelectionKey key) throws IOException;
}
}