WebThread.java
13 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
package org.legrog.util;
// Code copied from org.h2.server.web.WebThread
/*
* Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
//package org.h2.server.web;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Iterator;
import java.util.Locale;
import java.util.Properties;
import java.util.StringTokenizer;
import org.h2.engine.Constants;
import org.h2.engine.SysProperties;
import org.h2.message.DbException;
import org.h2.mvstore.DataUtils;
import org.h2.util.IOUtils;
import org.h2.util.NetUtils;
import org.h2.util.StringUtils;
//import org.h2.server.web.*;
/**
* For each connection to a session, an object of this class is created.
* This class is used by the H2 Console.
*/
class WebThread extends WebApp implements Runnable {
protected OutputStream output;
protected final Socket socket;
private final Thread thread;
private InputStream input;
private String ifModifiedSince;
WebThread(Socket socket, WebServer server) {
super(server);
this.socket = socket;
thread = new Thread(this, "H2 Console thread");
}
/**
* Start the thread.
*/
void start() {
thread.start();
}
/**
* Wait until the thread is stopped.
*
* @param millis the maximum number of milliseconds to wait
*/
void join(int millis) throws InterruptedException {
thread.join(millis);
}
/**
* Close the connection now.
*/
void stopNow() {
this.stop = true;
try {
socket.close();
} catch (IOException e) {
// ignore
}
}
private String getAllowedFile(String requestedFile) {
if (!allow()) {
return "notAllowed.jsp";
}
if (requestedFile.length() == 0) {
return "index.do";
}
return requestedFile;
}
@Override
public void run() {
try {
input = new BufferedInputStream(socket.getInputStream());
output = new BufferedOutputStream(socket.getOutputStream());
while (!stop) {
if (!process()) {
break;
}
}
} catch (Exception e) {
DbException.traceThrowable(e);
}
IOUtils.closeSilently(output);
IOUtils.closeSilently(input);
try {
socket.close();
} catch (IOException e) {
// ignore
} finally {
server.remove(this);
}
}
@SuppressWarnings("unchecked")
private boolean process() throws IOException {
boolean keepAlive = false;
String head = readHeaderLine();
if (head.startsWith("GET ") || head.startsWith("POST ")) {
int begin = head.indexOf('/'), end = head.lastIndexOf(' ');
String file;
if (begin < 0 || end < begin) {
file = "";
} else {
file = head.substring(begin + 1, end).trim();
}
trace(head + ": " + file);
file = getAllowedFile(file);
attributes = new Properties();
int paramIndex = file.indexOf("?");
session = null;
if (paramIndex >= 0) {
String attrib = file.substring(paramIndex + 1);
parseAttributes(attrib);
String sessionId = attributes.getProperty("jsessionid");
file = file.substring(0, paramIndex);
session = server.getSession(sessionId);
}
keepAlive = parseHeader();
String hostAddr = socket.getInetAddress().getHostAddress();
file = processRequest(file, hostAddr);
if (file.length() == 0) {
// asynchronous request
return true;
}
String message;
byte[] bytes;
if (cache && ifModifiedSince != null &&
ifModifiedSince.equals(server.getStartDateTime())) {
bytes = null;
message = "HTTP/1.1 304 Not Modified\r\n";
} else {
bytes = server.getFile(file);
if (bytes == null) {
message = "HTTP/1.1 404 Not Found\r\n";
bytes = ("File not found: " + file).getBytes(Constants.UTF8);
message += "Content-Length: " + bytes.length + "\r\n";
} else {
if (session != null && file.endsWith(".jsp")) {
String page = new String(bytes, Constants.UTF8);
if (SysProperties.CONSOLE_STREAM) {
Iterator<String> it = (Iterator<String>) session.map.remove("chunks");
if (it != null) {
message = "HTTP/1.1 200 OK\r\n";
message += "Content-Type: " + mimeType + "\r\n";
message += "Cache-Control: no-cache\r\n";
message += "Transfer-Encoding: chunked\r\n";
message += "\r\n";
trace(message);
output.write(message.getBytes());
while (it.hasNext()) {
String s = it.next();
s = PageParser.parse(s, session.map);
bytes = s.getBytes(Constants.UTF8);
if (bytes.length == 0) {
continue;
}
output.write(Integer.toHexString(bytes.length).getBytes());
output.write("\r\n".getBytes());
output.write(bytes);
output.write("\r\n".getBytes());
output.flush();
}
output.write("0\r\n\r\n".getBytes());
output.flush();
return keepAlive;
}
}
page = PageParser.parse(page, session.map);
bytes = page.getBytes(Constants.UTF8);
}
message = "HTTP/1.1 200 OK\r\n";
message += "Content-Type: " + mimeType + "\r\n";
if (!cache) {
message += "Cache-Control: no-cache\r\n";
} else {
message += "Cache-Control: max-age=10\r\n";
message += "Last-Modified: " + server.getStartDateTime() + "\r\n";
}
message += "Content-Length: " + bytes.length + "\r\n";
}
}
message += "\r\n";
trace(message);
output.write(message.getBytes());
if (bytes != null) {
output.write(bytes);
}
output.flush();
}
return keepAlive;
}
private String readHeaderLine() throws IOException {
StringBuilder buff = new StringBuilder();
while (true) {
int c = input.read();
if (c == -1) {
throw new IOException("Unexpected EOF");
} else if (c == '\r') {
if (input.read() == '\n') {
return buff.length() > 0 ? buff.toString() : null;
}
} else if (c == '\n') {
return buff.length() > 0 ? buff.toString() : null;
} else {
buff.append((char) c);
}
}
}
private void parseAttributes(String s) {
trace("data=" + s);
while (s != null) {
int idx = s.indexOf('=');
if (idx >= 0) {
String property = s.substring(0, idx);
s = s.substring(idx + 1);
idx = s.indexOf('&');
String value;
if (idx >= 0) {
value = s.substring(0, idx);
s = s.substring(idx + 1);
} else {
value = s;
}
String attr = StringUtils.urlDecode(value);
attributes.put(property, attr);
} else {
break;
}
}
trace(attributes.toString());
}
private boolean parseHeader() throws IOException {
boolean keepAlive = false;
trace("parseHeader");
int len = 0;
ifModifiedSince = null;
boolean multipart = false;
while (true) {
String line = readHeaderLine();
if (line == null) {
break;
}
trace(" " + line);
String lower = StringUtils.toLowerEnglish(line);
if (lower.startsWith("if-modified-since")) {
ifModifiedSince = getHeaderLineValue(line);
} else if (lower.startsWith("connection")) {
String conn = getHeaderLineValue(line);
if ("keep-alive".equals(conn)) {
keepAlive = true;
}
} else if (lower.startsWith("content-type")) {
String type = getHeaderLineValue(line);
if (type.startsWith("multipart/form-data")) {
multipart = true;
}
} else if (lower.startsWith("content-length")) {
len = Integer.parseInt(getHeaderLineValue(line));
trace("len=" + len);
} else if (lower.startsWith("user-agent")) {
boolean isWebKit = lower.contains("webkit/");
if (isWebKit && session != null) {
// workaround for what seems to be a WebKit bug:
// http://code.google.com/p/chromium/issues/detail?id=6402
session.put("frame-border", "1");
session.put("frameset-border", "2");
}
} else if (lower.startsWith("accept-language")) {
Locale locale = session == null ? null : session.locale;
if (locale == null) {
String languages = getHeaderLineValue(line);
StringTokenizer tokenizer = new StringTokenizer(languages, ",;");
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if (!token.startsWith("q=")) {
if (server.supportsLanguage(token)) {
int dash = token.indexOf('-');
if (dash >= 0) {
String language = token.substring(0, dash);
String country = token.substring(dash + 1);
locale = new Locale(language, country);
} else {
locale = new Locale(token, "");
}
headerLanguage = locale.getLanguage();
if (session != null) {
session.locale = locale;
session.put("language", headerLanguage);
server.readTranslations(session, headerLanguage);
}
break;
}
}
}
}
} else if (line.trim().length() == 0) {
break;
}
}
if (multipart) {
// not supported
} else if (session != null && len > 0) {
byte[] bytes = DataUtils.newBytes(len);
for (int pos = 0; pos < len;) {
pos += input.read(bytes, pos, len - pos);
}
String s = new String(bytes);
parseAttributes(s);
}
return keepAlive;
}
private static String getHeaderLineValue(String line) {
return line.substring(line.indexOf(':') + 1).trim();
}
@Override
protected String adminShutdown() {
stopNow();
return super.adminShutdown();
}
private boolean allow() {
if (server.getAllowOthers()) {
return true;
}
try {
return NetUtils.isLocalAddress(socket);
} catch (UnknownHostException e) {
server.traceError(e);
return false;
}
}
private void trace(String s) {
server.trace(s);
}
}