-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClientHandler.java
More file actions
369 lines (308 loc) · 14.4 KB
/
ClientHandler.java
File metadata and controls
369 lines (308 loc) · 14.4 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
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
import java.io.*;
import java.net.*;
import java.nio.file.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Client connection handler
*/
public class ClientHandler implements Runnable {
private final Socket clientSocket;
private final HttpServer server;
private final String threadName;
private int requestCount = 0;
public ClientHandler(Socket clientSocket, HttpServer server) {
this.clientSocket = clientSocket;
this.server = server;
this.threadName = "Thread-" + Thread.currentThread().getId();
}
@Override
public void run() {
try {
handleClient();
} catch (Exception e) {
server.log(threadName, "Error handling client: " + e.getMessage());
} finally {
try {
clientSocket.close();
} catch (IOException e) {
server.log(threadName, "Error closing client socket: " + e.getMessage());
}
server.connectionFinished();
}
}
private void handleClient() throws IOException {
String clientAddress = clientSocket.getInetAddress().getHostAddress() + ":" + clientSocket.getPort();
server.log(threadName, "Connection from " + clientAddress);
BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
OutputStream outputStream = clientSocket.getOutputStream();
boolean keepAlive = true;
while (keepAlive && requestCount < server.getMaxRequestsPerConnection()) {
try {
HttpRequest request = parseRequest(reader);
if (request == null) {
break; // Connection closed or invalid request
}
requestCount++;
server.log(threadName, "Request: " + request.getMethod() + " " + request.getPath() + " " + request.getVersion());
// check host header
if (!server.isValidHost(request.getHeader("Host"), server.host, server.port)) {
if (request.getHeader("Host") == null) {
sendErrorResponse(outputStream, 400, "Bad Request", "Missing Host header");
} else {
server.log(threadName, "Host validation failed: " + request.getHeader("Host"));
sendErrorResponse(outputStream, 403, "Forbidden", "Host header mismatch");
}
break;
}
server.log(threadName, "Host validation: " + request.getHeader("Host") + " ✓");
// handle the request
HttpResponse response = processRequest(request);
sendResponse(outputStream, response);
// check if we should keep connection alive
String connectionHeader = request.getHeader("Connection");
if ("close".equalsIgnoreCase(connectionHeader)) {
keepAlive = false;
server.log(threadName, "Connection: close");
} else {
keepAlive = true;
server.log(threadName, "Connection: keep-alive");
}
} catch (SocketTimeoutException e) {
server.log(threadName, "Connection timeout");
break;
} catch (IOException e) {
server.log(threadName, "IO error: " + e.getMessage());
break;
}
}
if (requestCount >= server.getMaxRequestsPerConnection()) {
server.log(threadName, "Connection closed: max requests reached (" + requestCount + ")");
}
}
private HttpRequest parseRequest(BufferedReader reader) throws IOException {
String requestLine = reader.readLine();
if (requestLine == null || requestLine.trim().isEmpty()) {
return null;
}
// Parse request line
String[] parts = requestLine.split(" ");
if (parts.length != 3) {
return null;
}
String method = parts[0];
String path = parts[1];
String version = parts[2];
// Parse headers
Map<String, String> headers = new HashMap<>();
String line;
while ((line = reader.readLine()) != null && !line.trim().isEmpty()) {
int colonIndex = line.indexOf(':');
if (colonIndex > 0) {
String headerName = line.substring(0, colonIndex).trim();
String headerValue = line.substring(colonIndex + 1).trim();
headers.put(headerName, headerValue);
}
}
// Parse body for POST requests
String body = null;
if ("POST".equals(method)) {
String contentLengthStr = headers.get("Content-Length");
if (contentLengthStr != null) {
try {
int contentLength = Integer.parseInt(contentLengthStr);
if (contentLength > 0 && contentLength <= server.getMaxRequestSize()) {
char[] bodyChars = new char[contentLength];
int totalRead = 0;
while (totalRead < contentLength) {
int read = reader.read(bodyChars, totalRead, contentLength - totalRead);
if (read == -1) break;
totalRead += read;
}
body = new String(bodyChars, 0, totalRead);
}
} catch (NumberFormatException e) {
// Invalid content length
}
}
}
return new HttpRequest(method, path, version, headers, body);
}
private HttpResponse processRequest(HttpRequest request) {
// check for path traversal
if (server.isPathTraversal(request.getPath())) {
server.log(threadName, "Path traversal attempt blocked: " + request.getPath());
return new HttpResponse(403, "Forbidden", "Path traversal not allowed", "text/plain");
}
// clean up the path
String path = request.getPath();
if (path.equals("/")) {
path = "/index.html";
}
// remove leading slash
if (path.startsWith("/")) {
path = path.substring(1);
}
// make sure we stay in resources dir
Path resourcePath = Paths.get(server.getResourcesDir(), path).normalize();
Path resourcesDir = Paths.get(server.getResourcesDir()).normalize();
if (!resourcePath.startsWith(resourcesDir)) {
server.log(threadName, "Unauthorized path access attempt: " + request.getPath());
return new HttpResponse(403, "Forbidden", "Unauthorized path access", "text/plain");
}
switch (request.getMethod()) {
case "GET":
return handleGetRequest(resourcePath.toString());
case "POST":
return handlePostRequest(request);
default:
return new HttpResponse(405, "Method Not Allowed", "Method not allowed", "text/plain");
}
}
private HttpResponse handleGetRequest(String filePath) {
File file = new File(filePath);
if (!file.exists() || !file.isFile()) {
return new HttpResponse(404, "Not Found", "File not found", "text/plain");
}
String fileName = file.getName();
String extension = getFileExtension(fileName);
try {
if (isHtmlFile(extension)) {
return serveHtmlFile(file);
} else if (isBinaryFile(extension)) {
return serveBinaryFile(file);
} else {
return new HttpResponse(415, "Unsupported Media Type", "File type not supported", "text/plain");
}
} catch (IOException e) {
server.log(threadName, "Error serving file: " + e.getMessage());
return new HttpResponse(500, "Internal Server Error", "Error reading file", "text/plain");
}
}
private HttpResponse handlePostRequest(HttpRequest request) {
String contentType = request.getHeader("Content-Type");
if (contentType == null || !contentType.toLowerCase().contains("application/json")) {
return new HttpResponse(415, "Unsupported Media Type", "Only application/json is supported", "text/plain");
}
String body = request.getBody();
if (body == null || body.trim().isEmpty()) {
return new HttpResponse(400, "Bad Request", "Empty request body", "text/plain");
}
// basic json check
if (!isValidJson(body)) {
return new HttpResponse(400, "Bad Request", "Invalid JSON format", "text/plain");
}
try {
// create upload file
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String randomId = UUID.randomUUID().toString().substring(0, 8);
String fileName = "upload_" + timestamp + "_" + randomId + ".json";
String filePath = server.getUploadsDir() + "/" + fileName;
// write the json
try (FileWriter writer = new FileWriter(filePath)) {
writer.write(body);
}
// build response
String responseBody = String.format(
"{\n" +
" \"status\": \"success\",\n" +
" \"message\": \"File created successfully\",\n" +
" \"filepath\": \"/uploads/%s\"\n" +
"}", fileName
);
server.log(threadName, "File created: " + fileName);
return new HttpResponse(201, "Created", responseBody, "application/json");
} catch (IOException e) {
server.log(threadName, "Error creating upload file: " + e.getMessage());
return new HttpResponse(500, "Internal Server Error", "Error creating file", "text/plain");
}
}
private HttpResponse serveHtmlFile(File file) throws IOException {
String content = new String(Files.readAllBytes(file.toPath()), "UTF-8");
server.log(threadName, "Sending HTML file: " + file.getName() + " (" + content.length() + " bytes)");
return new HttpResponse(200, "OK", content, "text/html; charset=utf-8");
}
private HttpResponse serveBinaryFile(File file) throws IOException {
byte[] content = Files.readAllBytes(file.toPath());
server.log(threadName, "Sending binary file: " + file.getName() + " (" + content.length + " bytes)");
HttpResponse response = new HttpResponse(200, "OK", content, "application/octet-stream");
response.addHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
return response;
}
private void sendResponse(OutputStream outputStream, HttpResponse response) throws IOException {
StringBuilder responseBuilder = new StringBuilder();
// status line
responseBuilder.append("HTTP/1.1 ").append(response.getStatusCode())
.append(" ").append(response.getStatusMessage()).append("\r\n");
// headers
responseBuilder.append("Content-Type: ").append(response.getContentType()).append("\r\n");
responseBuilder.append("Content-Length: ").append(response.getContentLength()).append("\r\n");
responseBuilder.append("Date: ").append(server.getCurrentDate()).append("\r\n");
responseBuilder.append("Server: Multi-threaded HTTP Server\r\n");
responseBuilder.append("Connection: keep-alive\r\n");
responseBuilder.append("Keep-Alive: timeout=30, max=100\r\n");
// extra headers
for (Map.Entry<String, String> header : response.getHeaders().entrySet()) {
responseBuilder.append(header.getKey()).append(": ").append(header.getValue()).append("\r\n");
}
responseBuilder.append("\r\n");
// send headers
outputStream.write(responseBuilder.toString().getBytes("UTF-8"));
// send body
if (response.getContent() != null) {
outputStream.write(response.getContent());
}
outputStream.flush();
server.log(threadName, "Response: " + response.getStatusCode() + " " + response.getStatusMessage() +
" (" + response.getContentLength() + " bytes transferred)");
}
private void sendErrorResponse(OutputStream outputStream, int statusCode, String statusMessage, String body) throws IOException {
HttpResponse response = new HttpResponse(statusCode, statusMessage, body, "text/plain");
sendResponse(outputStream, response);
}
private String getFileExtension(String fileName) {
int lastDot = fileName.lastIndexOf('.');
return lastDot > 0 ? fileName.substring(lastDot + 1).toLowerCase() : "";
}
private boolean isHtmlFile(String extension) {
return "html".equals(extension) || "htm".equals(extension);
}
private boolean isBinaryFile(String extension) {
return "png".equals(extension) || "jpg".equals(extension) ||
"jpeg".equals(extension) || "txt".equals(extension);
}
private boolean isValidJson(String json) {
// simple json validation
json = json.trim();
if (!json.startsWith("{") || !json.endsWith("}")) {
return false;
}
int braceCount = 0;
boolean inString = false;
boolean escaped = false;
for (char c : json.toCharArray()) {
if (escaped) {
escaped = false;
continue;
}
if (c == '\\') {
escaped = true;
continue;
}
if (c == '"') {
inString = !inString;
continue;
}
if (!inString) {
if (c == '{') {
braceCount++;
} else if (c == '}') {
braceCount--;
}
}
}
return braceCount == 0;
}
}