Repository navigation
Expand file tree
/
Copy pathHttpsServerApp.java
More file actions
213 lines (187 loc) · 9 KB
/
Copy pathHttpsServerApp.java
File metadata and controls
213 lines (187 loc) · 9 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
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
public class HttpsServerApp {
private static final int PORT = 8443;
private static final int THREAD_POOL_SIZE = 16;
private static final String KEYSTORE_PATH = "keystore.p12";
private static final char[] KEYSTORE_PASSWORD = "changeit".toCharArray();
public static void main(String[] args) throws Exception {
SSLServerSocketFactory factory = createSslServerSocketFactory(KEYSTORE_PATH, KEYSTORE_PASSWORD);
ExecutorService pool = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
try (SSLServerSocket serverSocket = (SSLServerSocket) factory.createServerSocket(PORT)) {
serverSocket.setReuseAddress(true);
serverSocket.setEnabledProtocols(new String[]{"TLSv1.3", "TLSv1.2"});
System.out.println("Multithreaded HTTPS server listening on HTTPS://localhost:" + PORT);
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("Shutting down HHTPS server...");
shutdownPool(pool);
}));
while (!serverSocket.isClosed()) {
Socket clientSocket = serverSocket.accept();
pool.submit(() -> handleClient(clientSocket));
}
} catch (IOException e) {
if (!pool.isShutdown()) {
System.err.println("HTTPS server socket error: " + e.getMessage());
}
} finally {
shutdownPool(pool);
}
}
private static SSLServerSocketFactory createSslServerSocketFactory(String path, char[] password)
throws IOException, GeneralSecurityException {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
try (InputStream kStream = new FileInputStream(path)) {
keyStore.load(kStream, password);
}
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, password);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), null, null);
return sslContext.getServerSocketFactory();
}
private static void handleClient(Socket socket) {
try (socket) {
socket.setSoTimeout(5000);
if (socket instanceof SSLSocket sslSocket) {
sslSocket.startHandshake();
}
try (BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream(), StandardCharsets.ISO_8859_1));
OutputStream rawOut = socket.getOutputStream();
BufferedOutputStream out = new BufferedOutputStream(rawOut)) {
String requestLine = in.readLine();
if (requestLine == null || requestLine.isBlank()) {
return;
}
String[] parts = requestLine.split("\\s+");
if (parts.length < 2) {
sendResponse(out, 400, "Bad Request", "text/plain; charset=utf-8", "Malformed request line");
return ;
}
String method = parts[0];
String target = parts[1];
Map<String, String> headers = new HashMap<>();
String line;
while ((line = in.readLine()) != null && !line.isEmpty()) {
int colonIdx = line.indexOf(':');
if (colonIdx > 0) {
String name = line.substring(0, colonIdx).trim().toLowerCase();
String value = line.substring(colonIdx + 1).trim();
headers.put(name, value);
}
}
int contentLength = 0;
if (headers.containsKey("content-length")) {
try {
contentLength = Math.max(0, Integer.parseInt(headers.get("content-length")));
} catch (NumberFormatException ignored) {
sendResponse(out,400, "Bad Request", "text/plain; charset=utf-8", "Invalid Content-Length");
return;
}
}
String body = "";
if (contentLength > 0) {
char[] buf = new char[Math.min(contentLength, 1_048_576)];
int totalRead = 0;
StringBuilder bodyBuilder = new StringBuilder(Math.min(contentLength, 4096));
while (totalRead < contentLength) {
int toRead = Math.min(buf.length, contentLength - totalRead);
int read = in.read(buf, 0, toRead);
if (read == -1) break;
bodyBuilder.append(buf, 0, read);
totalRead += read;
}
body = bodyBuilder.toString();
}
routeRequest(method,target, body, out);
}
} catch (IOException e) {
System.err.print("Client TLS/HTTP error (" + socket.getRemoteSocketAddress() + "): " + e.getMessage());
}
}
private static void routeRequest(String method, String target, String body, OutputStream out)
throws IOException {
String path = target.split("\\?", 2)[0];
switch (path) {
case "/" -> { // paths 200 & 405
if ("GET".equalsIgnoreCase(method)) {
String html = "<h1>Java Multithreaded HHTPS Server</h1><p>Thread: "
+ Thread.currentThread().getName() + "</p>";
sendResponse(out, 200, "OK", "text/html; charset=utf-8", html);
} else {
sendResponse(out, 405, "Method not allowed", "text/plain; charset=utf-8",
"Method not allowed for /: " + method, "GET");
}
}
case "/health" -> { // health
if ("GET".equalsIgnoreCase(method)) {
sendResponse(out, 200, "OK", "application/json; charset=utf-8", "{\"status\":\"up\"}");
} else {
sendResponse(out, 405, "Method not allowed", "text/plain; charset=utf-8",
"Method not allowed for /health: " + method, "GET");
}
}
case "/echo" -> { // POST
if ("POST".equalsIgnoreCase(method)) {
sendResponse(out, 200, "OK", "text/plain; charset=utf-8", body);
} else {
sendResponse(out, 405, "Method not allowed", "text/plain; charset=utf-8",
"Method not allowed for /echo: " + method, "POST");
}
}
default -> sendResponse(out, 404, "Not Found", "text/plain; charset=utf-8",
"Route not found: " + path);
}
}
private static void sendResponse(OutputStream out, int statusCode, String reason,
String contentType, String body) throws IOException {
sendResponse(out, statusCode, reason, contentType, body, null);
}
private static void sendResponse(OutputStream out, int statusCode, String reason,
String contentType, String body, String allowedHeader)
throws IOException {
byte[] bodyBytes = body.getBytes(StandardCharsets.UTF_8);
StringBuilder headers = new StringBuilder()
.append("HTTP/1.1 ").append(statusCode).append(" ").append(reason).append("\r\n")
.append("Content-Type: ").append(contentType).append("\r\n")
.append("Content-Length: ").append(bodyBytes.length).append("\r\n");
if (allowedHeader != null && !allowedHeader.isBlank()) {
headers.append("Allowed: ").append(allowedHeader).append("\r\n");
}
headers.append("Connection: close\r\n\r\n");
out.write(headers.toString().getBytes(StandardCharsets.US_ASCII));
out.write(bodyBytes);
out.flush();
}
private static void shutdownPool(ExecutorService pool) {
pool.shutdown();
try {
if (!pool.awaitTermination(5, TimeUnit.SECONDS)) {
pool.shutdown();
}
} catch (InterruptedException e) {
pool.shutdownNow();
Thread.currentThread().interrupt();
}
}
}