-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpServer.java
More file actions
226 lines (195 loc) · 7.87 KB
/
HttpServer.java
File metadata and controls
226 lines (195 loc) · 7.87 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
import java.io.*;
import java.net.*;
import java.nio.file.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;
/**
* HTTP Server with multi-threading support
* Handles GET/POST requests and file transfers
*/
public class HttpServer {
private static final int DEFAULT_PORT = 8080;
private static final String DEFAULT_HOST = "127.0.0.1";
private static final int DEFAULT_THREAD_POOL_SIZE = 10;
private static final int MAX_REQUEST_SIZE = 8192;
private static final int CONNECTION_TIMEOUT = 30000; // 30 sec timeout
private static final int MAX_REQUESTS_PER_CONNECTION = 100;
private static final String RESOURCES_DIR = "resources";
private static final String UPLOADS_DIR = "resources/uploads";
public final String host;
public final int port;
private final int threadPoolSize;
private final ExecutorService threadPool;
private final BlockingQueue<Socket> connectionQueue;
private final AtomicInteger activeConnections;
private final SimpleDateFormat dateFormat;
private ServerSocket serverSocket;
private volatile boolean running;
// check for path traversal attempts
private static final Pattern PATH_TRAVERSAL_PATTERN = Pattern.compile(".*\\.\\..*|.*//.*|.*\\./.*");
public HttpServer(String host, int port, int threadPoolSize) {
this.host = host;
this.port = port;
this.threadPoolSize = threadPoolSize;
this.threadPool = Executors.newFixedThreadPool(threadPoolSize);
this.connectionQueue = new LinkedBlockingQueue<>();
this.activeConnections = new AtomicInteger(0);
this.dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
this.dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
}
public static void main(String[] args) {
// get command line args
int port = DEFAULT_PORT;
String host = DEFAULT_HOST;
int threadPoolSize = DEFAULT_THREAD_POOL_SIZE;
if (args.length > 0) {
try {
port = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.err.println("Invalid port number: " + args[0]);
System.exit(1);
}
}
if (args.length > 1) {
host = args[1];
}
if (args.length > 2) {
try {
threadPoolSize = Integer.parseInt(args[2]);
} catch (NumberFormatException e) {
System.err.println("Invalid thread pool size: " + args[2]);
System.exit(1);
}
}
HttpServer server = new HttpServer(host, port, threadPoolSize);
server.start();
}
public void start() {
try {
// make sure directories exist
createDirectories();
// start listening
serverSocket = new ServerSocket(port, 50, InetAddress.getByName(host));
running = true;
log("HTTP Server started on http://" + host + ":" + port);
log("Thread pool size: " + threadPoolSize);
log("Serving files from '" + RESOURCES_DIR + "' directory");
log("Press Ctrl+C to stop the server");
// handle connection queue
startConnectionProcessor();
// main accept loop
while (running) {
try {
Socket clientSocket = serverSocket.accept();
clientSocket.setSoTimeout(CONNECTION_TIMEOUT);
if (activeConnections.get() < threadPoolSize) {
activeConnections.incrementAndGet();
threadPool.submit(new ClientHandler(clientSocket, this));
} else {
connectionQueue.offer(clientSocket);
log("Warning: Thread pool saturated, queuing connection");
}
} catch (SocketException e) {
if (running) {
log("Server socket error: " + e.getMessage());
}
}
}
} catch (IOException e) {
log("Failed to start server: " + e.getMessage());
} finally {
shutdown();
}
}
private void createDirectories() {
try {
Files.createDirectories(Paths.get(RESOURCES_DIR));
Files.createDirectories(Paths.get(UPLOADS_DIR));
} catch (IOException e) {
log("Failed to create directories: " + e.getMessage());
}
}
private void startConnectionProcessor() {
Thread processor = new Thread(() -> {
while (running) {
try {
Socket clientSocket = connectionQueue.take();
if (activeConnections.get() < threadPoolSize) {
activeConnections.incrementAndGet();
threadPool.submit(new ClientHandler(clientSocket, this));
log("Connection dequeued, assigned to Thread-" + Thread.currentThread().getId());
} else {
connectionQueue.offer(clientSocket);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
});
processor.setDaemon(true);
processor.start();
}
public void connectionFinished() {
activeConnections.decrementAndGet();
}
public void log(String message) {
String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
System.out.println("[" + timestamp + "] " + message);
}
public void log(String threadName, String message) {
String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
System.out.println("[" + timestamp + "] [" + threadName + "] " + message);
}
public void shutdown() {
running = false;
try {
if (serverSocket != null && !serverSocket.isClosed()) {
serverSocket.close();
}
} catch (IOException e) {
log("Error closing server socket: " + e.getMessage());
}
threadPool.shutdown();
try {
if (!threadPool.awaitTermination(5, TimeUnit.SECONDS)) {
threadPool.shutdownNow();
}
} catch (InterruptedException e) {
threadPool.shutdownNow();
Thread.currentThread().interrupt();
}
log("Server shutdown complete");
}
public String getCurrentDate() {
return dateFormat.format(new Date());
}
public String getResourcesDir() {
return RESOURCES_DIR;
}
public String getUploadsDir() {
return UPLOADS_DIR;
}
public int getMaxRequestsPerConnection() {
return MAX_REQUESTS_PER_CONNECTION;
}
public int getMaxRequestSize() {
return MAX_REQUEST_SIZE;
}
public boolean isPathTraversal(String path) {
return PATH_TRAVERSAL_PATTERN.matcher(path).matches();
}
public boolean isValidHost(String hostHeader, String serverHost, int serverPort) {
if (hostHeader == null || hostHeader.trim().isEmpty()) {
return false;
}
String expectedHost = serverHost + ":" + serverPort;
return hostHeader.equals(expectedHost) ||
hostHeader.equals(serverHost) ||
(serverHost.equals("127.0.0.1") && hostHeader.equals("localhost:" + serverPort)) ||
(serverHost.equals("localhost") && hostHeader.equals("127.0.0.1:" + serverPort));
}
}