-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathWebServer.java
More file actions
362 lines (351 loc) · 11.6 KB
/
Copy pathWebServer.java
File metadata and controls
362 lines (351 loc) · 11.6 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
package javaforce.service;
import java.io.*;
import java.net.*;
import java.util.*;
import java.security.*;
import javax.net.ssl.*;
import javaforce.*;
import static javaforce.service.WebSocketHandler.*;
/**
* Web server.
*
* Created : Aug 23, 2013
*/
public class WebServer {
private WebHandler api;
private WebSocketHandler wsapi;
private ServerSocket ss;
private boolean secure;
private boolean active = true;
private ArrayList<Connection> clients = new ArrayList<>();
private Object clientsLock = new Object();
public static boolean config_enable_gzip = true;
public static boolean debug = false;
private static String upload_folder;
/** Start web server on non-secure port. */
public boolean start(WebHandler api, int port) {
return start(api, port, null);
}
/** Start web server on secure port using provided keys. */
public boolean start(WebHandler api, int port, KeyMgmt keys) {
secure = true;
this.api = api;
try {
if (keys != null) {
ss = JF.createServerSocketSSL(port, keys);
} else {
ss = new ServerSocket(port);
}
if (ss == null) {
throw new Exception("Failed to start server on port:" + port);
}
new Server(this).start();
} catch (Exception e) {
JFLog.log(e);
return false;
}
return true;
}
public void setWebSocketHandler(WebSocketHandler wsapi) {
this.wsapi = wsapi;
}
public void setUploadFolder(String folder) {
upload_folder = folder;
}
public void stop() {
active = false;
if (ss != null) {
try { ss.close(); } catch (Exception e) {}
ss = null;
}
//NOTE:this could be Connection thread callback so stop threads in another thread
new Thread() {public void run() {
while (clients.size() > 0) {
synchronized (clientsLock) {
if (clients.size() == 0) break;
Connection conn = clients.get(0);
conn.cancel();
}
JF.sleep(100);
}
}}.start();
}
public void setClientVerify(boolean state) {
SSLServerSocket ssl = (SSLServerSocket)ss;
ssl.setNeedClientAuth(state);
}
private static class Server extends Thread {
private WebServer web;
public Server(WebServer web) {
this.web = web;
}
public void run() {
setName("WebServer.Server");
Socket s;
while (web.active) {
try {
s = web.ss.accept();
Connection conn = new Connection(web, s);
synchronized (web.clientsLock) {
web.clients.add(conn);
}
conn.start();
} catch (SocketException e) {
if (debug) JFLog.log("WebServer.Server:disconnected");
} catch (Exception e) {
JFLog.log(e);
}
}
}
}
private static class Connection extends Thread {
private Socket s;
private InputStream is;
private WebServer web;
public Connection(WebServer web, Socket s) {
this.web = web;
this.s = s;
}
public void run() {
setName("WebServer.Connection");
//read request and pass to WebHandler
try {
StringBuilder request = new StringBuilder();
is = s.getInputStream();
while (web.active && s.isConnected()) {
int ch = is.read();
if (ch == -1) break;
request.append((char)ch);
if (!request.toString().endsWith("\r\n\r\n")) continue;
if (debug) JFLog.log("WebServer:Request detected!");
WebRequest req = new WebRequest();
req.secure = web.secure;
req.request = request.toString();
req.fields = req.request.split("\r\n");
req.is = is;
req.serverIP = s.getLocalAddress().getHostAddress();
if (req.serverIP.equals("0:0:0:0:0:0:0:1")) req.serverIP = "127.0.0.1";
req.serverPort = s.getLocalPort();
req.remoteIP = s.getInetAddress().getHostAddress();
req.remotePort = s.getPort();
WebResponse res = new WebResponse();
res.os = s.getOutputStream();
req.fields0 = req.fields[0].split(" ");
req.init(res);
if (isWebSocketRequest(req)) {
String url = req.getURL();
if (debug) JFLog.log("WebServer:WEB_SOCKET:" + url);
WebSocket socket = new WebSocket(s.getLocalAddress().getHostAddress(), s.getInetAddress().getHostAddress(), is, res.os, req.getHost(), req.fields0[1], req.cookies);
int action = WebSocketHandler.REJECT;
if (web.wsapi != null) {
action = web.wsapi.doWebSocketConnect(socket);
}
switch (action) {
case ACCEPT:
sendWebSocketAccepted(req, res);
processWebSocket(web, socket);
break;
case REJECT:
sendWebSocketDenied(req, res);
break;
case DETACH:
sendWebSocketAccepted(req, res);
s = null; //do not close
break;
}
break;
}
else if (WebUpload.isMultipartContent(req)) {
if (debug) JFLog.log("WebServer:Upload detected!");
if (upload_folder == null) {
res.setStatus(501, "Error - Uploads disabled");
} else {
WebUpload upload = new WebUpload();
req.files = upload.processRequest(req, upload_folder);
}
}
else if (req.fields0[0].equals("GET")) {
if (debug) JFLog.log("WebServer:GET:" + req.getQueryString());
req.method = "GET";
web.api.doGet(req, res);
}
else if (req.fields0[0].equals("POST")) {
if (debug) JFLog.log("WebServer:POST:" + req.getQueryString());
req.method = "POST";
web.api.doPost(req, res);
}
else {
if (debug) JFLog.log("WebServer:Unknown request!");
res.setStatus(501, "Error - Unsupported Method");
}
res.writeAll(req);
if (req.fields0[2].equals("HTTP/1.0")) break;
request.setLength(0);
}
if (s != null) {
s.close();
s = null;
}
} catch (SSLHandshakeException ssl) {
if (debug) JFLog.log("WebServer.Connection:SSL error");
} catch (SocketException e) {
if (debug) JFLog.log("WebServer.Connection:disconnected");
} catch (Exception e) {
JFLog.log(e);
}
synchronized (web.clientsLock) {
web.clients.remove(this);
}
}
public void cancel() {
if (s != null) {
try {s.close();} catch (Exception e) {}
s = null;
}
}
private boolean isWebSocketRequest(WebRequest req) {
boolean upgrade = false;
boolean websocket = false;
boolean haveKey = false;
for(int a=0;a<req.fields.length;a++) {
String field = req.fields[a];
if (field.startsWith("Connection:") && field.indexOf("Upgrade") != -1) upgrade = true;
if (field.startsWith("Upgrade:") && field.indexOf("websocket") != -1) websocket = true;
if (field.startsWith("Sec-WebSocket-Key:")) haveKey = true;
}
return upgrade && websocket && haveKey;
}
private String encodeKey(String inKey) {
//input: Sec-WebSocket-Key: inkey
//output: Sec-WebSocket-Accept: outkey
// outkey = base64(SHA1(inkey + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'))
inKey += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-1");
}
catch(NoSuchAlgorithmException e) {
JFLog.log(e);
}
byte[] sha1 = md.digest(inKey.getBytes());
String base64 = new String(javaforce.Base64.encode(sha1));
return base64;
}
private void sendWebSocketAccepted(WebRequest req, WebResponse res) {
res.setStatus(101, "Switching Protocols");
res.addHeader("Upgrade: websocket");
res.addHeader("Connection: Upgrade");
String inKey = null;
String[] protocols = null;
for(int a=0;a<req.fields.length;a++) {
String field = req.fields[a];
if (field.startsWith("Sec-WebSocket-Key:")) {
inKey = field.substring(18).trim();
}
if (field.startsWith("Sec-WebSocket-Protcol:")) {
protocols = field.substring(22).trim().split(",");
}
}
String outKey = encodeKey(inKey);
res.addHeader("Sec-WebSocket-Accept: " + outKey);
try {
res.writeAll(req);
} catch (Exception e) {
JFLog.log(e);
}
}
private void sendWebSocketDenied(WebRequest req, WebResponse res) {
res.setStatus(403, "Access Denied");
try {
res.writeAll(req);
} catch (Exception e) {
JFLog.log(e);
}
}
}
private static void processWebSocket(WebServer web, WebSocket socket) {
//keep reading packets and deliver to WebHandler
byte[] maskKey = new byte[4];
try {
while (web.active) {
int opcode = socket.is.read();
if (opcode == -1) throw new Exception("socket error");
boolean fin = (opcode & 0x80) == 0x80;
opcode &= 0xf;
if (opcode == WebSocket.TYPE_CLOSE) break; //closed
long length = 0;
int len7 = socket.is.read();
if (len7 == -1) throw new Exception("socket error");
boolean hasMask = (len7 & WebSocket.MASK) == WebSocket.MASK;
len7 &= 0x7f;
switch (len7) {
case 126: //16bits = payload
for(int a=0;a<2;a++) {
int len8 = socket.is.read();
if (len8 == -1) throw new Exception("socket error");
length <<= 8;
length |= len8;
}
break;
case 127: //64bits = payload
for(int a=0;a<8;a++) {
long len8 = socket.is.read();
if (len8 == -1) throw new Exception("socket error");
length <<= 8;
length |= len8;
}
break;
default:
length = len7;
}
if (hasMask) {
for(int a=0;a<4;a++) {
int mask8 = socket.is.read();
if (mask8 == -1) throw new Exception("socket error");
maskKey[a] = (byte)mask8;
}
} else {
throw new Exception("WebSocket message without mask");
}
if (length > 16777216) {
throw new Exception("WebSocket message > 16MB");
}
//now read data
byte[] data = JF.readAll(socket.is, (int)length);
//unmask data
for(int a=0;a<length;a++) {
data[a] ^= maskKey[a % 4];
}
if (opcode == WebSocket.TYPE_PING) {
//ping message
socket.write(data, WebSocket.TYPE_PONG);
continue;
}
if (opcode > 0x8) continue; //other control message
web.wsapi.doWebSocketMessage(socket, data, opcode);
}
} catch (SocketException e) {
if (debug) JFLog.log("WebServer.Websocket:disconnected");
} catch (Exception e) {
JFLog.log(e);
}
web.wsapi.doWebSocketClosed(socket);
}
/** Returns a chunk header for a block of data for transmission in Transfer-Encoding: chunked
* Make sure to send \r\n after actual block of data.
*/
public static byte[] chunkHeader(byte[] in) {
return String.format("%x\r\n", in.length).getBytes();
}
/** Process WebSocket within WebUIServlet context.
*
* This method creates a new Thread that runs in the WebUIServlet ClassLoader.
*/
public void attachWebSocket(WebSocket socket) {
new Thread() {
public void run() {
processWebSocket(WebServer.this, socket);
}
}.start();
}
}