author | dbuck |
Mon, 21 Dec 2015 21:14:19 +0100 | |
changeset 34778 | 45c1293ab19a |
parent 29920 | f81c14f472ab |
child 35313 | 9e703c485544 |
permissions | -rw-r--r-- |
2 | 1 |
/* |
27720
aa3983c8fbee
8015692: java.net.BindException is thrown on Windows XP when HTTP server is started and stopped in the loop.
msheppar
parents:
25859
diff
changeset
|
2 |
* Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved. |
2 | 3 |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. |
4 |
* |
|
5 |
* This code is free software; you can redistribute it and/or modify it |
|
6 |
* under the terms of the GNU General Public License version 2 only, as |
|
5506 | 7 |
* published by the Free Software Foundation. Oracle designates this |
2 | 8 |
* particular file as subject to the "Classpath" exception as provided |
5506 | 9 |
* by Oracle in the LICENSE file that accompanied this code. |
2 | 10 |
* |
11 |
* This code is distributed in the hope that it will be useful, but WITHOUT |
|
12 |
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
|
13 |
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
|
14 |
* version 2 for more details (a copy is included in the LICENSE file that |
|
15 |
* accompanied this code). |
|
16 |
* |
|
17 |
* You should have received a copy of the GNU General Public License version |
|
18 |
* 2 along with this work; if not, write to the Free Software Foundation, |
|
19 |
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. |
|
20 |
* |
|
5506 | 21 |
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA |
22 |
* or visit www.oracle.com if you need additional information or have any |
|
23 |
* questions. |
|
2 | 24 |
*/ |
25 |
||
26 |
package sun.net.httpserver; |
|
27 |
||
28 |
import java.net.*; |
|
29 |
import java.io.*; |
|
30 |
import java.nio.channels.*; |
|
31 |
import java.util.*; |
|
32 |
import java.util.concurrent.*; |
|
33 |
import java.util.logging.Logger; |
|
34 |
import java.util.logging.Level; |
|
35 |
import javax.net.ssl.*; |
|
36 |
import com.sun.net.httpserver.*; |
|
18212
22f8c33b0690
8001318: Socket.getLocalAddress not consistent with InetAddress.getLocalHost
khazra
parents:
11014
diff
changeset
|
37 |
import java.security.AccessController; |
22f8c33b0690
8001318: Socket.getLocalAddress not consistent with InetAddress.getLocalHost
khazra
parents:
11014
diff
changeset
|
38 |
import java.security.PrivilegedAction; |
29920
f81c14f472ab
8042322: Enhance thread contexts in networking and nio
chegar
parents:
27779
diff
changeset
|
39 |
import sun.misc.ManagedLocalsThread; |
7271 | 40 |
import sun.net.httpserver.HttpConnection.State; |
2 | 41 |
|
42 |
/** |
|
43 |
* Provides implementation for both HTTP and HTTPS |
|
44 |
*/ |
|
45 |
class ServerImpl implements TimeSource { |
|
46 |
||
47 |
private String protocol; |
|
48 |
private boolean https; |
|
49 |
private Executor executor; |
|
50 |
private HttpsConfigurator httpsConfig; |
|
51 |
private SSLContext sslContext; |
|
52 |
private ContextList contexts; |
|
53 |
private InetSocketAddress address; |
|
54 |
private ServerSocketChannel schan; |
|
55 |
private Selector selector; |
|
56 |
private SelectionKey listenerKey; |
|
57 |
private Set<HttpConnection> idleConnections; |
|
58 |
private Set<HttpConnection> allConnections; |
|
7271 | 59 |
/* following two are used to keep track of the times |
60 |
* when a connection/request is first received |
|
61 |
* and when we start to send the response |
|
62 |
*/ |
|
63 |
private Set<HttpConnection> reqConnections; |
|
64 |
private Set<HttpConnection> rspConnections; |
|
2 | 65 |
private List<Event> events; |
66 |
private Object lolock = new Object(); |
|
67 |
private volatile boolean finished = false; |
|
68 |
private volatile boolean terminating = false; |
|
69 |
private boolean bound = false; |
|
70 |
private boolean started = false; |
|
71 |
private volatile long time; /* current time */ |
|
7271 | 72 |
private volatile long subticks = 0; |
2 | 73 |
private volatile long ticks; /* number of clock ticks since server started */ |
74 |
private HttpServer wrapper; |
|
75 |
||
76 |
final static int CLOCK_TICK = ServerConfig.getClockTick(); |
|
77 |
final static long IDLE_INTERVAL = ServerConfig.getIdleInterval(); |
|
78 |
final static int MAX_IDLE_CONNECTIONS = ServerConfig.getMaxIdleConnections(); |
|
7271 | 79 |
final static long TIMER_MILLIS = ServerConfig.getTimerMillis (); |
80 |
final static long MAX_REQ_TIME=getTimeMillis(ServerConfig.getMaxReqTime()); |
|
81 |
final static long MAX_RSP_TIME=getTimeMillis(ServerConfig.getMaxRspTime()); |
|
82 |
final static boolean timer1Enabled = MAX_REQ_TIME != -1 || MAX_RSP_TIME != -1; |
|
2 | 83 |
|
7271 | 84 |
private Timer timer, timer1; |
2 | 85 |
private Logger logger; |
27720
aa3983c8fbee
8015692: java.net.BindException is thrown on Windows XP when HTTP server is started and stopped in the loop.
msheppar
parents:
25859
diff
changeset
|
86 |
private Thread dispatcherThread; |
2 | 87 |
|
88 |
ServerImpl ( |
|
89 |
HttpServer wrapper, String protocol, InetSocketAddress addr, int backlog |
|
90 |
) throws IOException { |
|
91 |
||
92 |
this.protocol = protocol; |
|
93 |
this.wrapper = wrapper; |
|
94 |
this.logger = Logger.getLogger ("com.sun.net.httpserver"); |
|
7271 | 95 |
ServerConfig.checkLegacyProperties (logger); |
2 | 96 |
https = protocol.equalsIgnoreCase ("https"); |
97 |
this.address = addr; |
|
98 |
contexts = new ContextList(); |
|
99 |
schan = ServerSocketChannel.open(); |
|
100 |
if (addr != null) { |
|
101 |
ServerSocket socket = schan.socket(); |
|
102 |
socket.bind (addr, backlog); |
|
103 |
bound = true; |
|
104 |
} |
|
105 |
selector = Selector.open (); |
|
106 |
schan.configureBlocking (false); |
|
107 |
listenerKey = schan.register (selector, SelectionKey.OP_ACCEPT); |
|
108 |
dispatcher = new Dispatcher(); |
|
109 |
idleConnections = Collections.synchronizedSet (new HashSet<HttpConnection>()); |
|
110 |
allConnections = Collections.synchronizedSet (new HashSet<HttpConnection>()); |
|
7271 | 111 |
reqConnections = Collections.synchronizedSet (new HashSet<HttpConnection>()); |
112 |
rspConnections = Collections.synchronizedSet (new HashSet<HttpConnection>()); |
|
2 | 113 |
time = System.currentTimeMillis(); |
114 |
timer = new Timer ("server-timer", true); |
|
115 |
timer.schedule (new ServerTimerTask(), CLOCK_TICK, CLOCK_TICK); |
|
7271 | 116 |
if (timer1Enabled) { |
117 |
timer1 = new Timer ("server-timer1", true); |
|
118 |
timer1.schedule (new ServerTimerTask1(),TIMER_MILLIS,TIMER_MILLIS); |
|
119 |
logger.config ("HttpServer timer1 enabled period in ms: "+TIMER_MILLIS); |
|
120 |
logger.config ("MAX_REQ_TIME: "+MAX_REQ_TIME); |
|
121 |
logger.config ("MAX_RSP_TIME: "+MAX_RSP_TIME); |
|
122 |
} |
|
2 | 123 |
events = new LinkedList<Event>(); |
124 |
logger.config ("HttpServer created "+protocol+" "+ addr); |
|
125 |
} |
|
126 |
||
127 |
public void bind (InetSocketAddress addr, int backlog) throws IOException { |
|
128 |
if (bound) { |
|
129 |
throw new BindException ("HttpServer already bound"); |
|
130 |
} |
|
131 |
if (addr == null) { |
|
132 |
throw new NullPointerException ("null address"); |
|
133 |
} |
|
134 |
ServerSocket socket = schan.socket(); |
|
135 |
socket.bind (addr, backlog); |
|
136 |
bound = true; |
|
137 |
} |
|
138 |
||
139 |
public void start () { |
|
140 |
if (!bound || started || finished) { |
|
141 |
throw new IllegalStateException ("server in wrong state"); |
|
142 |
} |
|
143 |
if (executor == null) { |
|
144 |
executor = new DefaultExecutor(); |
|
145 |
} |
|
29920
f81c14f472ab
8042322: Enhance thread contexts in networking and nio
chegar
parents:
27779
diff
changeset
|
146 |
dispatcherThread = new ManagedLocalsThread(dispatcher); |
2 | 147 |
started = true; |
27720
aa3983c8fbee
8015692: java.net.BindException is thrown on Windows XP when HTTP server is started and stopped in the loop.
msheppar
parents:
25859
diff
changeset
|
148 |
dispatcherThread.start(); |
2 | 149 |
} |
150 |
||
151 |
public void setExecutor (Executor executor) { |
|
152 |
if (started) { |
|
153 |
throw new IllegalStateException ("server already started"); |
|
154 |
} |
|
155 |
this.executor = executor; |
|
156 |
} |
|
157 |
||
158 |
private static class DefaultExecutor implements Executor { |
|
159 |
public void execute (Runnable task) { |
|
160 |
task.run(); |
|
161 |
} |
|
162 |
} |
|
163 |
||
164 |
public Executor getExecutor () { |
|
165 |
return executor; |
|
166 |
} |
|
167 |
||
168 |
public void setHttpsConfigurator (HttpsConfigurator config) { |
|
169 |
if (config == null) { |
|
170 |
throw new NullPointerException ("null HttpsConfigurator"); |
|
171 |
} |
|
172 |
if (started) { |
|
173 |
throw new IllegalStateException ("server already started"); |
|
174 |
} |
|
175 |
this.httpsConfig = config; |
|
176 |
sslContext = config.getSSLContext(); |
|
177 |
} |
|
178 |
||
179 |
public HttpsConfigurator getHttpsConfigurator () { |
|
180 |
return httpsConfig; |
|
181 |
} |
|
182 |
||
183 |
public void stop (int delay) { |
|
184 |
if (delay < 0) { |
|
185 |
throw new IllegalArgumentException ("negative delay parameter"); |
|
186 |
} |
|
187 |
terminating = true; |
|
188 |
try { schan.close(); } catch (IOException e) {} |
|
189 |
selector.wakeup(); |
|
190 |
long latest = System.currentTimeMillis() + delay * 1000; |
|
191 |
while (System.currentTimeMillis() < latest) { |
|
192 |
delay(); |
|
193 |
if (finished) { |
|
194 |
break; |
|
195 |
} |
|
196 |
} |
|
197 |
finished = true; |
|
198 |
selector.wakeup(); |
|
199 |
synchronized (allConnections) { |
|
200 |
for (HttpConnection c : allConnections) { |
|
201 |
c.close(); |
|
202 |
} |
|
203 |
} |
|
204 |
allConnections.clear(); |
|
205 |
idleConnections.clear(); |
|
206 |
timer.cancel(); |
|
7271 | 207 |
if (timer1Enabled) { |
208 |
timer1.cancel(); |
|
209 |
} |
|
27779
e269428daa22
8066130: com.sun.net.httpserver stop() throws NullPointerException if it is not started
msheppar
parents:
27720
diff
changeset
|
210 |
if (dispatcherThread != null) { |
e269428daa22
8066130: com.sun.net.httpserver stop() throws NullPointerException if it is not started
msheppar
parents:
27720
diff
changeset
|
211 |
try { |
e269428daa22
8066130: com.sun.net.httpserver stop() throws NullPointerException if it is not started
msheppar
parents:
27720
diff
changeset
|
212 |
dispatcherThread.join(); |
e269428daa22
8066130: com.sun.net.httpserver stop() throws NullPointerException if it is not started
msheppar
parents:
27720
diff
changeset
|
213 |
} catch (InterruptedException e) { |
e269428daa22
8066130: com.sun.net.httpserver stop() throws NullPointerException if it is not started
msheppar
parents:
27720
diff
changeset
|
214 |
Thread.currentThread().interrupt(); |
e269428daa22
8066130: com.sun.net.httpserver stop() throws NullPointerException if it is not started
msheppar
parents:
27720
diff
changeset
|
215 |
logger.log(Level.FINER, "ServerImpl.stop: ", e); |
e269428daa22
8066130: com.sun.net.httpserver stop() throws NullPointerException if it is not started
msheppar
parents:
27720
diff
changeset
|
216 |
} |
27720
aa3983c8fbee
8015692: java.net.BindException is thrown on Windows XP when HTTP server is started and stopped in the loop.
msheppar
parents:
25859
diff
changeset
|
217 |
} |
2 | 218 |
} |
219 |
||
220 |
Dispatcher dispatcher; |
|
221 |
||
222 |
public synchronized HttpContextImpl createContext (String path, HttpHandler handler) { |
|
223 |
if (handler == null || path == null) { |
|
224 |
throw new NullPointerException ("null handler, or path parameter"); |
|
225 |
} |
|
226 |
HttpContextImpl context = new HttpContextImpl (protocol, path, handler, this); |
|
227 |
contexts.add (context); |
|
228 |
logger.config ("context created: " + path); |
|
229 |
return context; |
|
230 |
} |
|
231 |
||
232 |
public synchronized HttpContextImpl createContext (String path) { |
|
233 |
if (path == null) { |
|
234 |
throw new NullPointerException ("null path parameter"); |
|
235 |
} |
|
236 |
HttpContextImpl context = new HttpContextImpl (protocol, path, null, this); |
|
237 |
contexts.add (context); |
|
238 |
logger.config ("context created: " + path); |
|
239 |
return context; |
|
240 |
} |
|
241 |
||
242 |
public synchronized void removeContext (String path) throws IllegalArgumentException { |
|
243 |
if (path == null) { |
|
244 |
throw new NullPointerException ("null path parameter"); |
|
245 |
} |
|
246 |
contexts.remove (protocol, path); |
|
247 |
logger.config ("context removed: " + path); |
|
248 |
} |
|
249 |
||
250 |
public synchronized void removeContext (HttpContext context) throws IllegalArgumentException { |
|
251 |
if (!(context instanceof HttpContextImpl)) { |
|
252 |
throw new IllegalArgumentException ("wrong HttpContext type"); |
|
253 |
} |
|
254 |
contexts.remove ((HttpContextImpl)context); |
|
255 |
logger.config ("context removed: " + context.getPath()); |
|
256 |
} |
|
257 |
||
258 |
public InetSocketAddress getAddress() { |
|
18212
22f8c33b0690
8001318: Socket.getLocalAddress not consistent with InetAddress.getLocalHost
khazra
parents:
11014
diff
changeset
|
259 |
return AccessController.doPrivileged( |
22f8c33b0690
8001318: Socket.getLocalAddress not consistent with InetAddress.getLocalHost
khazra
parents:
11014
diff
changeset
|
260 |
new PrivilegedAction<InetSocketAddress>() { |
22f8c33b0690
8001318: Socket.getLocalAddress not consistent with InetAddress.getLocalHost
khazra
parents:
11014
diff
changeset
|
261 |
public InetSocketAddress run() { |
22f8c33b0690
8001318: Socket.getLocalAddress not consistent with InetAddress.getLocalHost
khazra
parents:
11014
diff
changeset
|
262 |
return |
22f8c33b0690
8001318: Socket.getLocalAddress not consistent with InetAddress.getLocalHost
khazra
parents:
11014
diff
changeset
|
263 |
(InetSocketAddress)schan.socket() |
22f8c33b0690
8001318: Socket.getLocalAddress not consistent with InetAddress.getLocalHost
khazra
parents:
11014
diff
changeset
|
264 |
.getLocalSocketAddress(); |
22f8c33b0690
8001318: Socket.getLocalAddress not consistent with InetAddress.getLocalHost
khazra
parents:
11014
diff
changeset
|
265 |
} |
22f8c33b0690
8001318: Socket.getLocalAddress not consistent with InetAddress.getLocalHost
khazra
parents:
11014
diff
changeset
|
266 |
}); |
2 | 267 |
} |
268 |
||
269 |
Selector getSelector () { |
|
270 |
return selector; |
|
271 |
} |
|
272 |
||
273 |
void addEvent (Event r) { |
|
274 |
synchronized (lolock) { |
|
275 |
events.add (r); |
|
276 |
selector.wakeup(); |
|
277 |
} |
|
278 |
} |
|
279 |
||
280 |
/* main server listener task */ |
|
281 |
||
282 |
class Dispatcher implements Runnable { |
|
283 |
||
284 |
private void handleEvent (Event r) { |
|
285 |
ExchangeImpl t = r.exchange; |
|
286 |
HttpConnection c = t.getConnection(); |
|
287 |
try { |
|
288 |
if (r instanceof WriteFinishedEvent) { |
|
289 |
||
290 |
int exchanges = endExchange(); |
|
291 |
if (terminating && exchanges == 0) { |
|
292 |
finished = true; |
|
293 |
} |
|
7271 | 294 |
responseCompleted (c); |
2 | 295 |
LeftOverInputStream is = t.getOriginalInputStream(); |
296 |
if (!is.isEOF()) { |
|
297 |
t.close = true; |
|
298 |
} |
|
299 |
if (t.close || idleConnections.size() >= MAX_IDLE_CONNECTIONS) { |
|
300 |
c.close(); |
|
301 |
allConnections.remove (c); |
|
302 |
} else { |
|
303 |
if (is.isDataBuffered()) { |
|
304 |
/* don't re-enable the interestops, just handle it */ |
|
7271 | 305 |
requestStarted (c); |
2 | 306 |
handle (c.getChannel(), c); |
307 |
} else { |
|
7271 | 308 |
connsToRegister.add (c); |
2 | 309 |
} |
310 |
} |
|
311 |
} |
|
312 |
} catch (IOException e) { |
|
313 |
logger.log ( |
|
314 |
Level.FINER, "Dispatcher (1)", e |
|
315 |
); |
|
316 |
c.close(); |
|
317 |
} |
|
318 |
} |
|
319 |
||
7271 | 320 |
final LinkedList<HttpConnection> connsToRegister = |
321 |
new LinkedList<HttpConnection>(); |
|
322 |
||
323 |
void reRegister (HttpConnection c) { |
|
324 |
/* re-register with selector */ |
|
325 |
try { |
|
326 |
SocketChannel chan = c.getChannel(); |
|
327 |
chan.configureBlocking (false); |
|
328 |
SelectionKey key = chan.register (selector, SelectionKey.OP_READ); |
|
329 |
key.attach (c); |
|
330 |
c.selectionKey = key; |
|
331 |
c.time = getTime() + IDLE_INTERVAL; |
|
332 |
idleConnections.add (c); |
|
333 |
} catch (IOException e) { |
|
334 |
dprint(e); |
|
335 |
logger.log(Level.FINER, "Dispatcher(8)", e); |
|
336 |
c.close(); |
|
337 |
} |
|
338 |
} |
|
339 |
||
2 | 340 |
public void run() { |
341 |
while (!finished) { |
|
342 |
try { |
|
7271 | 343 |
List<Event> list = null; |
344 |
synchronized (lolock) { |
|
345 |
if (events.size() > 0) { |
|
346 |
list = events; |
|
347 |
events = new LinkedList<Event>(); |
|
348 |
} |
|
349 |
} |
|
350 |
||
351 |
if (list != null) { |
|
352 |
for (Event r: list) { |
|
2 | 353 |
handleEvent (r); |
354 |
} |
|
355 |
} |
|
356 |
||
17463
9392f1567896
8014254: Selector in HttpServer introduces a 1000 ms delay when using KeepAlive
khazra
parents:
11014
diff
changeset
|
357 |
for (HttpConnection c : connsToRegister) { |
9392f1567896
8014254: Selector in HttpServer introduces a 1000 ms delay when using KeepAlive
khazra
parents:
11014
diff
changeset
|
358 |
reRegister(c); |
9392f1567896
8014254: Selector in HttpServer introduces a 1000 ms delay when using KeepAlive
khazra
parents:
11014
diff
changeset
|
359 |
} |
9392f1567896
8014254: Selector in HttpServer introduces a 1000 ms delay when using KeepAlive
khazra
parents:
11014
diff
changeset
|
360 |
connsToRegister.clear(); |
9392f1567896
8014254: Selector in HttpServer introduces a 1000 ms delay when using KeepAlive
khazra
parents:
11014
diff
changeset
|
361 |
|
9392f1567896
8014254: Selector in HttpServer introduces a 1000 ms delay when using KeepAlive
khazra
parents:
11014
diff
changeset
|
362 |
selector.select(1000); |
9392f1567896
8014254: Selector in HttpServer introduces a 1000 ms delay when using KeepAlive
khazra
parents:
11014
diff
changeset
|
363 |
|
2 | 364 |
/* process the selected list now */ |
365 |
Set<SelectionKey> selected = selector.selectedKeys(); |
|
366 |
Iterator<SelectionKey> iter = selected.iterator(); |
|
367 |
while (iter.hasNext()) { |
|
368 |
SelectionKey key = iter.next(); |
|
369 |
iter.remove (); |
|
370 |
if (key.equals (listenerKey)) { |
|
371 |
if (terminating) { |
|
372 |
continue; |
|
373 |
} |
|
374 |
SocketChannel chan = schan.accept(); |
|
10130
254e206a89d8
7068416: Lightweight HTTP Server should support TCP_NODELAY
chegar
parents:
7668
diff
changeset
|
375 |
|
254e206a89d8
7068416: Lightweight HTTP Server should support TCP_NODELAY
chegar
parents:
7668
diff
changeset
|
376 |
// Set TCP_NODELAY, if appropriate |
254e206a89d8
7068416: Lightweight HTTP Server should support TCP_NODELAY
chegar
parents:
7668
diff
changeset
|
377 |
if (ServerConfig.noDelay()) { |
254e206a89d8
7068416: Lightweight HTTP Server should support TCP_NODELAY
chegar
parents:
7668
diff
changeset
|
378 |
chan.socket().setTcpNoDelay(true); |
254e206a89d8
7068416: Lightweight HTTP Server should support TCP_NODELAY
chegar
parents:
7668
diff
changeset
|
379 |
} |
254e206a89d8
7068416: Lightweight HTTP Server should support TCP_NODELAY
chegar
parents:
7668
diff
changeset
|
380 |
|
2 | 381 |
if (chan == null) { |
382 |
continue; /* cancel something ? */ |
|
383 |
} |
|
384 |
chan.configureBlocking (false); |
|
385 |
SelectionKey newkey = chan.register (selector, SelectionKey.OP_READ); |
|
386 |
HttpConnection c = new HttpConnection (); |
|
387 |
c.selectionKey = newkey; |
|
388 |
c.setChannel (chan); |
|
389 |
newkey.attach (c); |
|
7271 | 390 |
requestStarted (c); |
2 | 391 |
allConnections.add (c); |
392 |
} else { |
|
393 |
try { |
|
394 |
if (key.isReadable()) { |
|
395 |
boolean closed; |
|
396 |
SocketChannel chan = (SocketChannel)key.channel(); |
|
397 |
HttpConnection conn = (HttpConnection)key.attachment(); |
|
7271 | 398 |
|
399 |
key.cancel(); |
|
400 |
chan.configureBlocking (true); |
|
401 |
if (idleConnections.remove(conn)) { |
|
402 |
// was an idle connection so add it |
|
403 |
// to reqConnections set. |
|
404 |
requestStarted (conn); |
|
405 |
} |
|
2 | 406 |
handle (chan, conn); |
407 |
} else { |
|
408 |
assert false; |
|
409 |
} |
|
7271 | 410 |
} catch (CancelledKeyException e) { |
411 |
handleException(key, null); |
|
2 | 412 |
} catch (IOException e) { |
7271 | 413 |
handleException(key, e); |
2 | 414 |
} |
415 |
} |
|
416 |
} |
|
7271 | 417 |
// call the selector just to process the cancelled keys |
418 |
selector.selectNow(); |
|
419 |
} catch (IOException e) { |
|
420 |
logger.log (Level.FINER, "Dispatcher (4)", e); |
|
907
11f377f9319d
6728076: Test case for 6536211 is failing on all platforms
michaelm
parents:
905
diff
changeset
|
421 |
} catch (Exception e) { |
7271 | 422 |
logger.log (Level.FINER, "Dispatcher (7)", e); |
2 | 423 |
} |
424 |
} |
|
11014 | 425 |
try {selector.close(); } catch (Exception e) {} |
2 | 426 |
} |
427 |
||
7271 | 428 |
private void handleException (SelectionKey key, Exception e) { |
429 |
HttpConnection conn = (HttpConnection)key.attachment(); |
|
430 |
if (e != null) { |
|
431 |
logger.log (Level.FINER, "Dispatcher (2)", e); |
|
432 |
} |
|
433 |
closeConnection(conn); |
|
434 |
} |
|
435 |
||
2 | 436 |
public void handle (SocketChannel chan, HttpConnection conn) |
437 |
throws IOException |
|
438 |
{ |
|
439 |
try { |
|
440 |
Exchange t = new Exchange (chan, protocol, conn); |
|
441 |
executor.execute (t); |
|
442 |
} catch (HttpError e1) { |
|
907
11f377f9319d
6728076: Test case for 6536211 is failing on all platforms
michaelm
parents:
905
diff
changeset
|
443 |
logger.log (Level.FINER, "Dispatcher (4)", e1); |
7271 | 444 |
closeConnection(conn); |
2 | 445 |
} catch (IOException e) { |
907
11f377f9319d
6728076: Test case for 6536211 is failing on all platforms
michaelm
parents:
905
diff
changeset
|
446 |
logger.log (Level.FINER, "Dispatcher (5)", e); |
7271 | 447 |
closeConnection(conn); |
2 | 448 |
} |
449 |
} |
|
450 |
} |
|
451 |
||
452 |
static boolean debug = ServerConfig.debugEnabled (); |
|
453 |
||
454 |
static synchronized void dprint (String s) { |
|
455 |
if (debug) { |
|
456 |
System.out.println (s); |
|
457 |
} |
|
458 |
} |
|
459 |
||
460 |
static synchronized void dprint (Exception e) { |
|
461 |
if (debug) { |
|
462 |
System.out.println (e); |
|
463 |
e.printStackTrace(); |
|
464 |
} |
|
465 |
} |
|
466 |
||
467 |
Logger getLogger () { |
|
468 |
return logger; |
|
469 |
} |
|
470 |
||
7271 | 471 |
private void closeConnection(HttpConnection conn) { |
472 |
conn.close(); |
|
473 |
allConnections.remove(conn); |
|
474 |
switch (conn.getState()) { |
|
475 |
case REQUEST: |
|
476 |
reqConnections.remove(conn); |
|
477 |
break; |
|
478 |
case RESPONSE: |
|
479 |
rspConnections.remove(conn); |
|
480 |
break; |
|
481 |
case IDLE: |
|
482 |
idleConnections.remove(conn); |
|
483 |
break; |
|
484 |
} |
|
485 |
assert !reqConnections.remove(conn); |
|
486 |
assert !rspConnections.remove(conn); |
|
487 |
assert !idleConnections.remove(conn); |
|
488 |
} |
|
489 |
||
490 |
/* per exchange task */ |
|
2 | 491 |
|
492 |
class Exchange implements Runnable { |
|
493 |
SocketChannel chan; |
|
494 |
HttpConnection connection; |
|
495 |
HttpContextImpl context; |
|
496 |
InputStream rawin; |
|
497 |
OutputStream rawout; |
|
498 |
String protocol; |
|
499 |
ExchangeImpl tx; |
|
500 |
HttpContextImpl ctx; |
|
501 |
boolean rejected = false; |
|
502 |
||
503 |
Exchange (SocketChannel chan, String protocol, HttpConnection conn) throws IOException { |
|
504 |
this.chan = chan; |
|
505 |
this.connection = conn; |
|
506 |
this.protocol = protocol; |
|
507 |
} |
|
508 |
||
509 |
public void run () { |
|
510 |
/* context will be null for new connections */ |
|
511 |
context = connection.getHttpContext(); |
|
512 |
boolean newconnection; |
|
513 |
SSLEngine engine = null; |
|
514 |
String requestLine = null; |
|
515 |
SSLStreams sslStreams = null; |
|
516 |
try { |
|
517 |
if (context != null ) { |
|
518 |
this.rawin = connection.getInputStream(); |
|
519 |
this.rawout = connection.getRawOutputStream(); |
|
520 |
newconnection = false; |
|
521 |
} else { |
|
522 |
/* figure out what kind of connection this is */ |
|
523 |
newconnection = true; |
|
524 |
if (https) { |
|
525 |
if (sslContext == null) { |
|
526 |
logger.warning ("SSL connection received. No https contxt created"); |
|
527 |
throw new HttpError ("No SSL context established"); |
|
528 |
} |
|
529 |
sslStreams = new SSLStreams (ServerImpl.this, sslContext, chan); |
|
530 |
rawin = sslStreams.getInputStream(); |
|
531 |
rawout = sslStreams.getOutputStream(); |
|
532 |
engine = sslStreams.getSSLEngine(); |
|
2612
d7fb0809c7e4
6630639: lightweight HttpServer leaks file descriptors on no-data connections
michaelm
parents:
2
diff
changeset
|
533 |
connection.sslStreams = sslStreams; |
2 | 534 |
} else { |
535 |
rawin = new BufferedInputStream( |
|
536 |
new Request.ReadStream ( |
|
537 |
ServerImpl.this, chan |
|
538 |
)); |
|
539 |
rawout = new Request.WriteStream ( |
|
540 |
ServerImpl.this, chan |
|
541 |
); |
|
542 |
} |
|
2612
d7fb0809c7e4
6630639: lightweight HttpServer leaks file descriptors on no-data connections
michaelm
parents:
2
diff
changeset
|
543 |
connection.raw = rawin; |
d7fb0809c7e4
6630639: lightweight HttpServer leaks file descriptors on no-data connections
michaelm
parents:
2
diff
changeset
|
544 |
connection.rawout = rawout; |
2 | 545 |
} |
546 |
Request req = new Request (rawin, rawout); |
|
547 |
requestLine = req.requestLine(); |
|
548 |
if (requestLine == null) { |
|
549 |
/* connection closed */ |
|
7271 | 550 |
closeConnection(connection); |
2 | 551 |
return; |
552 |
} |
|
553 |
int space = requestLine.indexOf (' '); |
|
554 |
if (space == -1) { |
|
555 |
reject (Code.HTTP_BAD_REQUEST, |
|
556 |
requestLine, "Bad request line"); |
|
557 |
return; |
|
558 |
} |
|
559 |
String method = requestLine.substring (0, space); |
|
560 |
int start = space+1; |
|
561 |
space = requestLine.indexOf(' ', start); |
|
562 |
if (space == -1) { |
|
563 |
reject (Code.HTTP_BAD_REQUEST, |
|
564 |
requestLine, "Bad request line"); |
|
565 |
return; |
|
566 |
} |
|
567 |
String uriStr = requestLine.substring (start, space); |
|
568 |
URI uri = new URI (uriStr); |
|
569 |
start = space+1; |
|
570 |
String version = requestLine.substring (start); |
|
571 |
Headers headers = req.headers(); |
|
572 |
String s = headers.getFirst ("Transfer-encoding"); |
|
1511
65ddd8f149f3
6756771: com.sun.net.httpserver.HttpServer should handle POSTs larger than 2Gig
chegar
parents:
1247
diff
changeset
|
573 |
long clen = 0L; |
2 | 574 |
if (s !=null && s.equalsIgnoreCase ("chunked")) { |
1511
65ddd8f149f3
6756771: com.sun.net.httpserver.HttpServer should handle POSTs larger than 2Gig
chegar
parents:
1247
diff
changeset
|
575 |
clen = -1L; |
2 | 576 |
} else { |
577 |
s = headers.getFirst ("Content-Length"); |
|
578 |
if (s != null) { |
|
1511
65ddd8f149f3
6756771: com.sun.net.httpserver.HttpServer should handle POSTs larger than 2Gig
chegar
parents:
1247
diff
changeset
|
579 |
clen = Long.parseLong(s); |
2 | 580 |
} |
7271 | 581 |
if (clen == 0) { |
582 |
requestCompleted (connection); |
|
583 |
} |
|
2 | 584 |
} |
585 |
ctx = contexts.findContext (protocol, uri.getPath()); |
|
586 |
if (ctx == null) { |
|
587 |
reject (Code.HTTP_NOT_FOUND, |
|
588 |
requestLine, "No context found for request"); |
|
589 |
return; |
|
590 |
} |
|
591 |
connection.setContext (ctx); |
|
592 |
if (ctx.getHandler() == null) { |
|
593 |
reject (Code.HTTP_INTERNAL_ERROR, |
|
594 |
requestLine, "No handler for context"); |
|
595 |
return; |
|
596 |
} |
|
597 |
tx = new ExchangeImpl ( |
|
598 |
method, uri, req, clen, connection |
|
599 |
); |
|
600 |
String chdr = headers.getFirst("Connection"); |
|
601 |
Headers rheaders = tx.getResponseHeaders(); |
|
602 |
||
603 |
if (chdr != null && chdr.equalsIgnoreCase ("close")) { |
|
604 |
tx.close = true; |
|
605 |
} |
|
606 |
if (version.equalsIgnoreCase ("http/1.0")) { |
|
607 |
tx.http10 = true; |
|
608 |
if (chdr == null) { |
|
609 |
tx.close = true; |
|
610 |
rheaders.set ("Connection", "close"); |
|
611 |
} else if (chdr.equalsIgnoreCase ("keep-alive")) { |
|
612 |
rheaders.set ("Connection", "keep-alive"); |
|
10596
39b3a979e600
7090158: Networking Libraries don't build with javac -Werror
chegar
parents:
10130
diff
changeset
|
613 |
int idle=(int)(ServerConfig.getIdleInterval()/1000); |
39b3a979e600
7090158: Networking Libraries don't build with javac -Werror
chegar
parents:
10130
diff
changeset
|
614 |
int max=ServerConfig.getMaxIdleConnections(); |
2 | 615 |
String val = "timeout="+idle+", max="+max; |
616 |
rheaders.set ("Keep-Alive", val); |
|
617 |
} |
|
618 |
} |
|
619 |
||
620 |
if (newconnection) { |
|
621 |
connection.setParameters ( |
|
622 |
rawin, rawout, chan, engine, sslStreams, |
|
623 |
sslContext, protocol, ctx, rawin |
|
624 |
); |
|
625 |
} |
|
626 |
/* check if client sent an Expect 100 Continue. |
|
627 |
* In that case, need to send an interim response. |
|
628 |
* In future API may be modified to allow app to |
|
629 |
* be involved in this process. |
|
630 |
*/ |
|
631 |
String exp = headers.getFirst("Expect"); |
|
632 |
if (exp != null && exp.equalsIgnoreCase ("100-continue")) { |
|
633 |
logReply (100, requestLine, null); |
|
634 |
sendReply ( |
|
635 |
Code.HTTP_CONTINUE, false, null |
|
636 |
); |
|
637 |
} |
|
638 |
/* uf is the list of filters seen/set by the user. |
|
639 |
* sf is the list of filters established internally |
|
640 |
* and which are not visible to the user. uc and sc |
|
641 |
* are the corresponding Filter.Chains. |
|
642 |
* They are linked together by a LinkHandler |
|
643 |
* so that they can both be invoked in one call. |
|
644 |
*/ |
|
645 |
List<Filter> sf = ctx.getSystemFilters(); |
|
646 |
List<Filter> uf = ctx.getFilters(); |
|
647 |
||
648 |
Filter.Chain sc = new Filter.Chain(sf, ctx.getHandler()); |
|
649 |
Filter.Chain uc = new Filter.Chain(uf, new LinkHandler (sc)); |
|
650 |
||
651 |
/* set up the two stream references */ |
|
652 |
tx.getRequestBody(); |
|
653 |
tx.getResponseBody(); |
|
654 |
if (https) { |
|
655 |
uc.doFilter (new HttpsExchangeImpl (tx)); |
|
656 |
} else { |
|
657 |
uc.doFilter (new HttpExchangeImpl (tx)); |
|
658 |
} |
|
659 |
||
660 |
} catch (IOException e1) { |
|
661 |
logger.log (Level.FINER, "ServerImpl.Exchange (1)", e1); |
|
7271 | 662 |
closeConnection(connection); |
2 | 663 |
} catch (NumberFormatException e3) { |
664 |
reject (Code.HTTP_BAD_REQUEST, |
|
665 |
requestLine, "NumberFormatException thrown"); |
|
666 |
} catch (URISyntaxException e) { |
|
667 |
reject (Code.HTTP_BAD_REQUEST, |
|
668 |
requestLine, "URISyntaxException thrown"); |
|
669 |
} catch (Exception e4) { |
|
670 |
logger.log (Level.FINER, "ServerImpl.Exchange (2)", e4); |
|
7271 | 671 |
closeConnection(connection); |
2 | 672 |
} |
673 |
} |
|
674 |
||
675 |
/* used to link to 2 or more Filter.Chains together */ |
|
676 |
||
677 |
class LinkHandler implements HttpHandler { |
|
678 |
Filter.Chain nextChain; |
|
679 |
||
680 |
LinkHandler (Filter.Chain nextChain) { |
|
681 |
this.nextChain = nextChain; |
|
682 |
} |
|
683 |
||
684 |
public void handle (HttpExchange exchange) throws IOException { |
|
685 |
nextChain.doFilter (exchange); |
|
686 |
} |
|
687 |
} |
|
688 |
||
689 |
void reject (int code, String requestStr, String message) { |
|
690 |
rejected = true; |
|
691 |
logReply (code, requestStr, message); |
|
692 |
sendReply ( |
|
7271 | 693 |
code, false, "<h1>"+code+Code.msg(code)+"</h1>"+message |
2 | 694 |
); |
7271 | 695 |
closeConnection(connection); |
2 | 696 |
} |
697 |
||
698 |
void sendReply ( |
|
699 |
int code, boolean closeNow, String text) |
|
700 |
{ |
|
701 |
try { |
|
7271 | 702 |
StringBuilder builder = new StringBuilder (512); |
703 |
builder.append ("HTTP/1.1 ") |
|
704 |
.append (code).append (Code.msg(code)).append ("\r\n"); |
|
705 |
||
2 | 706 |
if (text != null && text.length() != 0) { |
7271 | 707 |
builder.append ("Content-Length: ") |
708 |
.append (text.length()).append ("\r\n") |
|
709 |
.append ("Content-Type: text/html\r\n"); |
|
2 | 710 |
} else { |
7271 | 711 |
builder.append ("Content-Length: 0\r\n"); |
2 | 712 |
text = ""; |
713 |
} |
|
714 |
if (closeNow) { |
|
7271 | 715 |
builder.append ("Connection: close\r\n"); |
2 | 716 |
} |
7271 | 717 |
builder.append ("\r\n").append (text); |
718 |
String s = builder.toString(); |
|
2 | 719 |
byte[] b = s.getBytes("ISO8859_1"); |
720 |
rawout.write (b); |
|
721 |
rawout.flush(); |
|
722 |
if (closeNow) { |
|
7271 | 723 |
closeConnection(connection); |
2 | 724 |
} |
725 |
} catch (IOException e) { |
|
726 |
logger.log (Level.FINER, "ServerImpl.sendReply", e); |
|
7271 | 727 |
closeConnection(connection); |
2 | 728 |
} |
729 |
} |
|
730 |
||
731 |
} |
|
732 |
||
733 |
void logReply (int code, String requestStr, String text) { |
|
7271 | 734 |
if (!logger.isLoggable(Level.FINE)) { |
735 |
return; |
|
736 |
} |
|
2 | 737 |
if (text == null) { |
738 |
text = ""; |
|
739 |
} |
|
7271 | 740 |
String r; |
741 |
if (requestStr.length() > 80) { |
|
742 |
r = requestStr.substring (0, 80) + "<TRUNCATED>"; |
|
743 |
} else { |
|
744 |
r = requestStr; |
|
745 |
} |
|
746 |
String message = r + " [" + code + " " + |
|
2 | 747 |
Code.msg(code) + "] ("+text+")"; |
748 |
logger.fine (message); |
|
749 |
} |
|
750 |
||
751 |
long getTicks() { |
|
752 |
return ticks; |
|
753 |
} |
|
754 |
||
755 |
public long getTime() { |
|
756 |
return time; |
|
757 |
} |
|
758 |
||
759 |
void delay () { |
|
760 |
Thread.yield(); |
|
761 |
try { |
|
762 |
Thread.sleep (200); |
|
763 |
} catch (InterruptedException e) {} |
|
764 |
} |
|
765 |
||
766 |
private int exchangeCount = 0; |
|
767 |
||
768 |
synchronized void startExchange () { |
|
769 |
exchangeCount ++; |
|
770 |
} |
|
771 |
||
772 |
synchronized int endExchange () { |
|
773 |
exchangeCount --; |
|
774 |
assert exchangeCount >= 0; |
|
775 |
return exchangeCount; |
|
776 |
} |
|
777 |
||
778 |
HttpServer getWrapper () { |
|
779 |
return wrapper; |
|
780 |
} |
|
781 |
||
7271 | 782 |
void requestStarted (HttpConnection c) { |
783 |
c.creationTime = getTime(); |
|
784 |
c.setState (State.REQUEST); |
|
785 |
reqConnections.add (c); |
|
786 |
} |
|
787 |
||
788 |
// called after a request has been completely read |
|
789 |
// by the server. This stops the timer which would |
|
790 |
// close the connection if the request doesn't arrive |
|
791 |
// quickly enough. It then starts the timer |
|
792 |
// that ensures the client reads the response in a timely |
|
793 |
// fashion. |
|
794 |
||
795 |
void requestCompleted (HttpConnection c) { |
|
796 |
assert c.getState() == State.REQUEST; |
|
797 |
reqConnections.remove (c); |
|
798 |
c.rspStartedTime = getTime(); |
|
799 |
rspConnections.add (c); |
|
800 |
c.setState (State.RESPONSE); |
|
801 |
} |
|
802 |
||
803 |
// called after response has been sent |
|
804 |
void responseCompleted (HttpConnection c) { |
|
805 |
assert c.getState() == State.RESPONSE; |
|
806 |
rspConnections.remove (c); |
|
807 |
c.setState (State.IDLE); |
|
808 |
} |
|
809 |
||
2 | 810 |
/** |
811 |
* TimerTask run every CLOCK_TICK ms |
|
812 |
*/ |
|
813 |
class ServerTimerTask extends TimerTask { |
|
814 |
public void run () { |
|
815 |
LinkedList<HttpConnection> toClose = new LinkedList<HttpConnection>(); |
|
816 |
time = System.currentTimeMillis(); |
|
817 |
ticks ++; |
|
818 |
synchronized (idleConnections) { |
|
819 |
for (HttpConnection c : idleConnections) { |
|
820 |
if (c.time <= time) { |
|
821 |
toClose.add (c); |
|
822 |
} |
|
823 |
} |
|
824 |
for (HttpConnection c : toClose) { |
|
825 |
idleConnections.remove (c); |
|
826 |
allConnections.remove (c); |
|
827 |
c.close(); |
|
828 |
} |
|
829 |
} |
|
830 |
} |
|
831 |
} |
|
7271 | 832 |
|
833 |
class ServerTimerTask1 extends TimerTask { |
|
834 |
||
835 |
// runs every TIMER_MILLIS |
|
836 |
public void run () { |
|
837 |
LinkedList<HttpConnection> toClose = new LinkedList<HttpConnection>(); |
|
838 |
time = System.currentTimeMillis(); |
|
839 |
synchronized (reqConnections) { |
|
840 |
if (MAX_REQ_TIME != -1) { |
|
841 |
for (HttpConnection c : reqConnections) { |
|
842 |
if (c.creationTime + TIMER_MILLIS + MAX_REQ_TIME <= time) { |
|
843 |
toClose.add (c); |
|
844 |
} |
|
845 |
} |
|
846 |
for (HttpConnection c : toClose) { |
|
847 |
logger.log (Level.FINE, "closing: no request: " + c); |
|
848 |
reqConnections.remove (c); |
|
849 |
allConnections.remove (c); |
|
850 |
c.close(); |
|
851 |
} |
|
852 |
} |
|
853 |
} |
|
854 |
toClose = new LinkedList<HttpConnection>(); |
|
855 |
synchronized (rspConnections) { |
|
856 |
if (MAX_RSP_TIME != -1) { |
|
857 |
for (HttpConnection c : rspConnections) { |
|
858 |
if (c.rspStartedTime + TIMER_MILLIS +MAX_RSP_TIME <= time) { |
|
859 |
toClose.add (c); |
|
860 |
} |
|
861 |
} |
|
862 |
for (HttpConnection c : toClose) { |
|
863 |
logger.log (Level.FINE, "closing: no response: " + c); |
|
864 |
rspConnections.remove (c); |
|
865 |
allConnections.remove (c); |
|
866 |
c.close(); |
|
867 |
} |
|
868 |
} |
|
869 |
} |
|
870 |
} |
|
871 |
} |
|
872 |
||
873 |
void logStackTrace (String s) { |
|
874 |
logger.finest (s); |
|
875 |
StringBuilder b = new StringBuilder (); |
|
876 |
StackTraceElement[] e = Thread.currentThread().getStackTrace(); |
|
877 |
for (int i=0; i<e.length; i++) { |
|
878 |
b.append (e[i].toString()).append("\n"); |
|
879 |
} |
|
880 |
logger.finest (b.toString()); |
|
881 |
} |
|
882 |
||
883 |
static long getTimeMillis(long secs) { |
|
884 |
if (secs == -1) { |
|
885 |
return -1; |
|
886 |
} else { |
|
887 |
return secs * 1000; |
|
888 |
} |
|
889 |
} |
|
2 | 890 |
} |