Debian Codegraph @

src/main/org/h2/server/web/WebThread.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.server.web;
7
8 import java.io.BufferedInputStream;
9 import java.io.BufferedOutputStream;
10 import java.io.IOException;
11 import java.io.InputStream;
12 import java.io.OutputStream;
13 import java.net.Socket;
14 import java.net.UnknownHostException;
15 import java.nio.charset.StandardCharsets;
16 import java.util.Iterator;
17 import java.util.Locale;
18 import java.util.Properties;
19 import java.util.StringTokenizer;
20
21 import org.h2.engine.SysProperties;
22 import org.h2.message.DbException;
23 import org.h2.util.IOUtils;
24 import org.h2.util.NetUtils;
25 import org.h2.util.NetworkConnectionInfo;
26 import org.h2.util.StringUtils;
27 import org.h2.util.Utils;
28
29 /**
30 * For each connection to a session, an object of this class is created.
31 * This class is used by the H2 Console.
32 */
33 class WebThread extends WebApp implements Runnable {
34
35 private static final byte[] RN = { '\r', '\n' };
36
37 private static final byte[] RNRN = { '\r', '\n', '\r', '\n' };
38
39 protected OutputStream output;
40 protected final Socket socket;
41 private final Thread thread;
42 private InputStream input;
43 private String host;
44 private int dataLength;
45 private String ifModifiedSince;
46
47 WebThread(Socket socket, WebServer server) {
48 super(server);
49 this.socket = socket;
50 thread = new Thread(this, "H2 Console thread");
51 }
52
53 /**
54 * Start the thread.
55 */
56 void start() {
57 thread.start();
58 }
59
60 /**
61 * Wait until the thread is stopped.
62 *
63 * @param millis the maximum number of milliseconds to wait
64 * @throws InterruptedException if interrupted
65 */
66 void join(int millis) throws InterruptedException {
67 thread.join(millis);
68 }
69
70 /**
71 * Close the connection now.
72 */
73 void stopNow() {
74 this.stop = true;
75 try {
76 socket.close();
77 } catch (IOException e) {
78 // ignore
79 }
80 }
81
82 private String getAllowedFile(String requestedFile) {
83 if (!allow()) {
84 return "notAllowed.jsp";
85 }
86 if (requestedFile.length() == 0) {
87 return "index.do";
88 }
89 if (requestedFile.charAt(0) == '?') {
90 return "index.do" + requestedFile;
91 }
92 return requestedFile;
93 }
94
95 @Override
96 public void run() {
97 try {
98 input = new BufferedInputStream(socket.getInputStream());
99 output = new BufferedOutputStream(socket.getOutputStream());
100 while (!stop) {
101 if (!process()) {
102 break;
103 }
104 }
105 } catch (Exception e) {
106 DbException.traceThrowable(e);
107 }
108 IOUtils.closeSilently(output);
109 IOUtils.closeSilently(input);
110 try {
111 socket.close();
112 } catch (IOException e) {
113 // ignore
114 } finally {
115 server.remove(this);
116 }
117 }
118
119 @SuppressWarnings("unchecked")
120 private boolean process() throws IOException {
121 String head = readHeaderLine();
122 boolean get = head.startsWith("GET ");
123 if ((!get && !head.startsWith("POST ")) || !head.endsWith(" HTTP/1.1")) {
124 writeSimple("HTTP/1.1 400 Bad Request", "Bad request");
125 return false;
126 }
127 String file = StringUtils.trimSubstring(head, get ? 4 : 5, head.length() - 9);
128 if (file.isEmpty() || file.charAt(0) != '/') {
129 writeSimple("HTTP/1.1 400 Bad Request", "Bad request");
130 return false;
131 }
132 attributes = new Properties();
133 boolean keepAlive = parseHeader();
134 if (!checkHost(host)) {
135 return false;
136 }
137 file = file.substring(1);
138 trace(head + ": " + file);
139 file = getAllowedFile(file);
140 int paramIndex = file.indexOf('?');
141 session = null;
142 String key = null;
143 if (paramIndex >= 0) {
144 String attrib = file.substring(paramIndex + 1);
145 parseAttributes(attrib);
146 String sessionId = attributes.getProperty("jsessionid");
147 key = attributes.getProperty("key");
148 file = file.substring(0, paramIndex);
149 session = server.getSession(sessionId);
150 }
151 parseBodyAttributes();
152 file = processRequest(file,
153 new NetworkConnectionInfo(
154 NetUtils.ipToShortForm(new StringBuilder(server.getSSL() ? "https://" : "http://"),
155 socket.getLocalAddress().getAddress(), true) //
156 .append(':').append(socket.getLocalPort()).toString(), //
157 socket.getInetAddress().getAddress(), socket.getPort(), null));
158 if (file.length() == 0) {
159 // asynchronous request
160 return true;
161 }
162 String message;
163 if (cache && ifModifiedSince != null && ifModifiedSince.equals(server.getStartDateTime())) {
164 writeSimple("HTTP/1.1 304 Not Modified", (byte[]) null);
165 return keepAlive;
166 }
167 byte[] bytes = server.getFile(file);
168 if (bytes == null) {
169 writeSimple("HTTP/1.1 404 Not Found", "File not found: " + file);
170 return keepAlive;
171 }
172 if (session != null && file.endsWith(".jsp")) {
173 if (key != null) {
174 session.put("key", key);
175 }
176 String page = new String(bytes, StandardCharsets.UTF_8);
177 if (SysProperties.CONSOLE_STREAM) {
178 Iterator<String> it = (Iterator<String>) session.map.remove("chunks");
179 if (it != null) {
180 message = "HTTP/1.1 200 OK\r\n";
181 message += "Content-Type: " + mimeType + "\r\n";
182 message += "Cache-Control: no-cache\r\n";
183 message += "Transfer-Encoding: chunked\r\n";
184 message += "\r\n";
185 trace(message);
186 output.write(message.getBytes(StandardCharsets.ISO_8859_1));
187 while (it.hasNext()) {
188 String s = it.next();
189 s = PageParser.parse(s, session.map);
190 bytes = s.getBytes(StandardCharsets.UTF_8);
191 if (bytes.length == 0) {
192 continue;
193 }
194 output.write(Integer.toHexString(bytes.length).getBytes(StandardCharsets.ISO_8859_1));
195 output.write(RN);
196 output.write(bytes);
197 output.write(RN);
198 output.flush();
199 }
200 output.write('0');
201 output.write(RNRN);
202 output.flush();
203 return keepAlive;
204 }
205 }
206 page = PageParser.parse(page, session.map);
207 bytes = page.getBytes(StandardCharsets.UTF_8);
208 }
209 message = "HTTP/1.1 200 OK\r\n";
210 message += "Content-Type: " + mimeType + "\r\n";
211 if (!cache) {
212 message += "Cache-Control: no-cache\r\n";
213 } else {
214 message += "Cache-Control: max-age=10\r\n";
215 message += "Last-Modified: " + server.getStartDateTime() + "\r\n";
216 }
217 message += "Content-Length: " + bytes.length + "\r\n";
218 message += "\r\n";
219 trace(message);
220 output.write(message.getBytes(StandardCharsets.ISO_8859_1));
221 output.write(bytes);
222 output.flush();
223 return keepAlive;
224 }
225
226 private void writeSimple(String status, String text) throws IOException {
227 writeSimple(status, text != null ? text.getBytes(StandardCharsets.UTF_8) : null);
228 }
229
230 private void writeSimple(String status, byte[] bytes) throws IOException {
231 trace(status);
232 output.write(status.getBytes(StandardCharsets.ISO_8859_1));
233 if (bytes != null) {
234 output.write(RN);
235 String contentLength = "Content-Length: " + bytes.length;
236 trace(contentLength);
237 output.write(contentLength.getBytes(StandardCharsets.ISO_8859_1));
238 output.write(RNRN);
239 output.write(bytes);
240 } else {
241 output.write(RNRN);
242 }
243 output.flush();
244 }
245
246 private boolean checkHost(String host) throws IOException {
247 if (host == null) {
248 writeSimple("HTTP/1.1 400 Bad Request", "Bad request");
249 return false;
250 }
251 int index = host.indexOf(':');
252 if (index >= 0) {
253 host = host.substring(0, index);
254 }
255 if (host.isEmpty()) {
256 return false;
257 }
258 host = StringUtils.toLowerEnglish(host);
259 if (host.equals(server.getHost()) || host.equals("localhost") || host.equals("127.0.0.1")) {
260 return true;
261 }
262 String externalNames = server.getExternalNames();
263 if (externalNames != null && !externalNames.isEmpty()) {
264 for (String s : externalNames.split(",")) {
265 if (host.equals(s.trim())) {
266 return true;
267 }
268 }
269 }
270 writeSimple("HTTP/1.1 404 Not Found", "Host " + host + " not found");
271 return false;
272 }
273
274 private String readHeaderLine() throws IOException {
275 StringBuilder buff = new StringBuilder();
276 while (true) {
277 int c = input.read();
278 if (c == -1) {
279 throw new IOException("Unexpected EOF");
280 } else if (c == '\r') {
281 if (input.read() == '\n') {
282 return buff.length() > 0 ? buff.toString() : null;
283 }
284 } else if (c == '\n') {
285 return buff.length() > 0 ? buff.toString() : null;
286 } else {
287 buff.append((char) c);
288 }
289 }
290 }
291
292 private void parseBodyAttributes() throws IOException {
293 if (dataLength > 0) {
294 byte[] bytes = Utils.newBytes(dataLength);
295 for (int pos = 0; pos < dataLength;) {
296 pos += input.read(bytes, pos, dataLength - pos);
297 }
298 String s = new String(bytes, StandardCharsets.UTF_8);
299 parseAttributes(s);
300 }
301 }
302
303 private void parseAttributes(String s) {
304 trace("data=" + s);
305 while (s != null) {
306 int idx = s.indexOf('=');
307 if (idx >= 0) {
308 String property = s.substring(0, idx);
309 s = s.substring(idx + 1);
310 idx = s.indexOf('&');
311 String value;
312 if (idx >= 0) {
313 value = s.substring(0, idx);
314 s = s.substring(idx + 1);
315 } else {
316 value = s;
317 }
318 String attr = StringUtils.urlDecode(value);
319 attributes.put(property, attr);
320 } else {
321 break;
322 }
323 }
324 trace(attributes.toString());
325 }
326
327 private boolean parseHeader() throws IOException {
328 boolean keepAlive = false;
329 trace("parseHeader");
330 int len = 0;
331 host = null;
332 ifModifiedSince = null;
333 boolean multipart = false;
334 for (String line; (line = readHeaderLine()) != null;) {
335 trace(" " + line);
336 String lower = StringUtils.toLowerEnglish(line);
337 if (lower.startsWith("host")) {
338 host = getHeaderLineValue(line);
339 } else if (lower.startsWith("if-modified-since")) {
340 ifModifiedSince = getHeaderLineValue(line);
341 } else if (lower.startsWith("connection")) {
342 String conn = getHeaderLineValue(line);
343 if ("keep-alive".equals(conn)) {
344 keepAlive = true;
345 }
346 } else if (lower.startsWith("content-type")) {
347 String type = getHeaderLineValue(line);
348 if (type.startsWith("multipart/form-data")) {
349 multipart = true;
350 }
351 } else if (lower.startsWith("content-length")) {
352 len = Integer.parseInt(getHeaderLineValue(line));
353 trace("len=" + len);
354 } else if (lower.startsWith("user-agent")) {
355 boolean isWebKit = lower.contains("webkit/");
356 if (isWebKit && session != null) {
357 // workaround for what seems to be a WebKit bug:
358 // https://bugs.chromium.org/p/chromium/issues/detail?id=6402
359 session.put("frame-border", "1");
360 session.put("frameset-border", "2");
361 }
362 } else if (lower.startsWith("accept-language")) {
363 Locale locale = session == null ? null : session.locale;
364 if (locale == null) {
365 String languages = getHeaderLineValue(line);
366 StringTokenizer tokenizer = new StringTokenizer(languages, ",;");
367 while (tokenizer.hasMoreTokens()) {
368 String token = tokenizer.nextToken();
369 if (!token.startsWith("q=")) {
370 if (server.supportsLanguage(token)) {
371 int dash = token.indexOf('-');
372 if (dash >= 0) {
373 String language = token.substring(0, dash);
374 String country = token.substring(dash + 1);
375 locale = new Locale(language, country);
376 } else {
377 locale = new Locale(token, "");
378 }
379 headerLanguage = locale.getLanguage();
380 if (session != null) {
381 session.locale = locale;
382 session.put("language", headerLanguage);
383 server.readTranslations(session, headerLanguage);
384 }
385 break;
386 }
387 }
388 }
389 }
390 } else if (StringUtils.isWhitespaceOrEmpty(line)) {
391 break;
392 }
393 }
394 dataLength = 0;
395 if (multipart) {
396 // not supported
397 } else if (len > 0) {
398 dataLength = len;
399 }
400 return keepAlive;
401 }
402
403 private static String getHeaderLineValue(String line) {
404 return StringUtils.trimSubstring(line, line.indexOf(':') + 1);
405 }
406
407 @Override
408 protected String adminShutdown() {
409 stopNow();
410 return super.adminShutdown();
411 }
412
413 private boolean allow() {
414 if (server.getAllowOthers()) {
415 return true;
416 }
417 try {
418 return NetUtils.isLocalAddress(socket);
419 } catch (UnknownHostException e) {
420 server.traceError(e);
421 return false;
422 }
423 }
424
425 private void trace(String s) {
426 server.trace(s);
427 }
428 }