0N/A/*
1042N/A * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
0N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
0N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
553N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
553N/A *
553N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
0N/A * or visit www.oracle.com if you need additional information or have any
0N/A * questions.
0N/A */
0N/A
0N/Apackage sun.net.httpserver;
0N/A
0N/Aimport java.net.*;
0N/Aimport java.io.*;
0N/Aimport java.nio.channels.*;
0N/Aimport java.util.*;
0N/Aimport java.util.concurrent.*;
0N/Aimport java.util.logging.Logger;
0N/Aimport java.util.logging.Level;
0N/Aimport javax.net.ssl.*;
0N/Aimport com.sun.net.httpserver.*;
0N/Aimport java.security.AccessController;
0N/Aimport java.security.PrivilegedAction;
0N/Aimport sun.net.httpserver.HttpConnection.State;
0N/A
0N/A/**
0N/A * Provides implementation for both HTTP and HTTPS
0N/A */
0N/Aclass ServerImpl implements TimeSource {
0N/A
0N/A private String protocol;
0N/A private boolean https;
0N/A private Executor executor;
0N/A private HttpsConfigurator httpsConfig;
0N/A private SSLContext sslContext;
0N/A private ContextList contexts;
0N/A private InetSocketAddress address;
0N/A private ServerSocketChannel schan;
0N/A private Selector selector;
0N/A private SelectionKey listenerKey;
0N/A private Set<HttpConnection> idleConnections;
0N/A private Set<HttpConnection> allConnections;
0N/A /* following two are used to keep track of the times
0N/A * when a connection/request is first received
0N/A * and when we start to send the response
0N/A */
0N/A private Set<HttpConnection> reqConnections;
0N/A private Set<HttpConnection> rspConnections;
0N/A private List<Event> events;
0N/A private Object lolock = new Object();
0N/A private volatile boolean finished = false;
0N/A private volatile boolean terminating = false;
0N/A private boolean bound = false;
0N/A private boolean started = false;
0N/A private volatile long time; /* current time */
0N/A private volatile long subticks = 0;
0N/A private volatile long ticks; /* number of clock ticks since server started */
0N/A private HttpServer wrapper;
0N/A
0N/A final static int CLOCK_TICK = ServerConfig.getClockTick();
0N/A final static long IDLE_INTERVAL = ServerConfig.getIdleInterval();
0N/A final static int MAX_IDLE_CONNECTIONS = ServerConfig.getMaxIdleConnections();
0N/A final static long TIMER_MILLIS = ServerConfig.getTimerMillis ();
0N/A final static long MAX_REQ_TIME=getTimeMillis(ServerConfig.getMaxReqTime());
0N/A final static long MAX_RSP_TIME=getTimeMillis(ServerConfig.getMaxRspTime());
0N/A final static boolean timer1Enabled = MAX_REQ_TIME != -1 || MAX_RSP_TIME != -1;
0N/A
0N/A private Timer timer, timer1;
0N/A private Logger logger;
0N/A
0N/A ServerImpl (
0N/A HttpServer wrapper, String protocol, InetSocketAddress addr, int backlog
0N/A ) throws IOException {
0N/A
0N/A this.protocol = protocol;
0N/A this.wrapper = wrapper;
0N/A this.logger = Logger.getLogger ("com.sun.net.httpserver");
0N/A ServerConfig.checkLegacyProperties (logger);
0N/A https = protocol.equalsIgnoreCase ("https");
0N/A this.address = addr;
0N/A contexts = new ContextList();
0N/A schan = ServerSocketChannel.open();
0N/A if (addr != null) {
0N/A ServerSocket socket = schan.socket();
0N/A socket.bind (addr, backlog);
0N/A bound = true;
0N/A }
0N/A selector = Selector.open ();
0N/A schan.configureBlocking (false);
0N/A listenerKey = schan.register (selector, SelectionKey.OP_ACCEPT);
0N/A dispatcher = new Dispatcher();
0N/A idleConnections = Collections.synchronizedSet (new HashSet<HttpConnection>());
0N/A allConnections = Collections.synchronizedSet (new HashSet<HttpConnection>());
0N/A reqConnections = Collections.synchronizedSet (new HashSet<HttpConnection>());
0N/A rspConnections = Collections.synchronizedSet (new HashSet<HttpConnection>());
0N/A time = System.currentTimeMillis();
0N/A timer = new Timer ("server-timer", true);
0N/A timer.schedule (new ServerTimerTask(), CLOCK_TICK, CLOCK_TICK);
0N/A if (timer1Enabled) {
0N/A timer1 = new Timer ("server-timer1", true);
0N/A timer1.schedule (new ServerTimerTask1(),TIMER_MILLIS,TIMER_MILLIS);
0N/A logger.config ("HttpServer timer1 enabled period in ms: "+TIMER_MILLIS);
0N/A logger.config ("MAX_REQ_TIME: "+MAX_REQ_TIME);
0N/A logger.config ("MAX_RSP_TIME: "+MAX_RSP_TIME);
0N/A }
0N/A events = new LinkedList<Event>();
0N/A logger.config ("HttpServer created "+protocol+" "+ addr);
0N/A }
0N/A
0N/A public void bind (InetSocketAddress addr, int backlog) throws IOException {
0N/A if (bound) {
388N/A throw new BindException ("HttpServer already bound");
388N/A }
388N/A if (addr == null) {
388N/A throw new NullPointerException ("null address");
388N/A }
388N/A ServerSocket socket = schan.socket();
388N/A socket.bind (addr, backlog);
388N/A bound = true;
0N/A }
0N/A
0N/A public void start () {
0N/A if (!bound || started || finished) {
0N/A throw new IllegalStateException ("server in wrong state");
0N/A }
0N/A if (executor == null) {
0N/A executor = new DefaultExecutor();
0N/A }
0N/A Thread t = new Thread (dispatcher);
0N/A started = true;
0N/A t.start();
0N/A }
0N/A
0N/A public void setExecutor (Executor executor) {
0N/A if (started) {
0N/A throw new IllegalStateException ("server already started");
0N/A }
0N/A this.executor = executor;
0N/A }
0N/A
0N/A private static class DefaultExecutor implements Executor {
0N/A public void execute (Runnable task) {
0N/A task.run();
0N/A }
0N/A }
0N/A
0N/A public Executor getExecutor () {
0N/A return executor;
0N/A }
0N/A
0N/A public void setHttpsConfigurator (HttpsConfigurator config) {
0N/A if (config == null) {
0N/A throw new NullPointerException ("null HttpsConfigurator");
0N/A }
0N/A if (started) {
0N/A throw new IllegalStateException ("server already started");
0N/A }
0N/A this.httpsConfig = config;
0N/A sslContext = config.getSSLContext();
0N/A }
0N/A
0N/A public HttpsConfigurator getHttpsConfigurator () {
0N/A return httpsConfig;
0N/A }
0N/A
0N/A public void stop (int delay) {
0N/A if (delay < 0) {
0N/A throw new IllegalArgumentException ("negative delay parameter");
0N/A }
0N/A terminating = true;
0N/A try { schan.close(); } catch (IOException e) {}
0N/A selector.wakeup();
0N/A long latest = System.currentTimeMillis() + delay * 1000;
0N/A while (System.currentTimeMillis() < latest) {
0N/A delay();
0N/A if (finished) {
0N/A break;
0N/A }
0N/A }
0N/A finished = true;
0N/A selector.wakeup();
0N/A synchronized (allConnections) {
0N/A for (HttpConnection c : allConnections) {
0N/A c.close();
1042N/A }
0N/A }
1042N/A allConnections.clear();
1042N/A idleConnections.clear();
1042N/A timer.cancel();
1042N/A if (timer1Enabled) {
1042N/A timer1.cancel();
0N/A }
0N/A }
0N/A
0N/A Dispatcher dispatcher;
0N/A
0N/A public synchronized HttpContextImpl createContext (String path, HttpHandler handler) {
139N/A if (handler == null || path == null) {
0N/A throw new NullPointerException ("null handler, or path parameter");
1042N/A }
0N/A HttpContextImpl context = new HttpContextImpl (protocol, path, handler, this);
1042N/A contexts.add (context);
1042N/A logger.config ("context created: " + path);
1042N/A return context;
0N/A }
0N/A
0N/A public synchronized HttpContextImpl createContext (String path) {
0N/A if (path == null) {
0N/A throw new NullPointerException ("null path parameter");
0N/A }
0N/A HttpContextImpl context = new HttpContextImpl (protocol, path, null, this);
0N/A contexts.add (context);
0N/A logger.config ("context created: " + path);
0N/A return context;
0N/A }
0N/A
0N/A public synchronized void removeContext (String path) throws IllegalArgumentException {
0N/A if (path == null) {
0N/A throw new NullPointerException ("null path parameter");
0N/A }
0N/A contexts.remove (protocol, path);
0N/A logger.config ("context removed: " + path);
0N/A }
0N/A
0N/A public synchronized void removeContext (HttpContext context) throws IllegalArgumentException {
0N/A if (!(context instanceof HttpContextImpl)) {
0N/A throw new IllegalArgumentException ("wrong HttpContext type");
0N/A }
0N/A contexts.remove ((HttpContextImpl)context);
0N/A logger.config ("context removed: " + context.getPath());
0N/A }
0N/A
0N/A public InetSocketAddress getAddress() {
0N/A return AccessController.doPrivileged(
0N/A new PrivilegedAction<InetSocketAddress>() {
0N/A public InetSocketAddress run() {
0N/A return
0N/A (InetSocketAddress)schan.socket()
0N/A .getLocalSocketAddress();
0N/A }
0N/A });
0N/A }
0N/A
0N/A Selector getSelector () {
0N/A return selector;
0N/A }
0N/A
0N/A void addEvent (Event r) {
0N/A synchronized (lolock) {
0N/A events.add (r);
0N/A selector.wakeup();
0N/A }
0N/A }
0N/A
0N/A /* main server listener task */
0N/A
0N/A class Dispatcher implements Runnable {
0N/A
0N/A private void handleEvent (Event r) {
0N/A ExchangeImpl t = r.exchange;
0N/A HttpConnection c = t.getConnection();
0N/A try {
0N/A if (r instanceof WriteFinishedEvent) {
0N/A
0N/A int exchanges = endExchange();
0N/A if (terminating && exchanges == 0) {
0N/A finished = true;
0N/A }
0N/A responseCompleted (c);
0N/A LeftOverInputStream is = t.getOriginalInputStream();
0N/A if (!is.isEOF()) {
0N/A t.close = true;
0N/A }
0N/A if (t.close || idleConnections.size() >= MAX_IDLE_CONNECTIONS) {
0N/A c.close();
0N/A allConnections.remove (c);
0N/A } else {
0N/A if (is.isDataBuffered()) {
0N/A /* don't re-enable the interestops, just handle it */
0N/A requestStarted (c);
0N/A handle (c.getChannel(), c);
0N/A } else {
0N/A connsToRegister.add (c);
0N/A }
0N/A }
0N/A }
0N/A } catch (IOException e) {
0N/A logger.log (
0N/A Level.FINER, "Dispatcher (1)", e
0N/A );
0N/A c.close();
0N/A }
0N/A }
0N/A
0N/A final LinkedList<HttpConnection> connsToRegister =
0N/A new LinkedList<HttpConnection>();
0N/A
0N/A void reRegister (HttpConnection c) {
0N/A /* re-register with selector */
0N/A try {
0N/A SocketChannel chan = c.getChannel();
0N/A chan.configureBlocking (false);
0N/A SelectionKey key = chan.register (selector, SelectionKey.OP_READ);
0N/A key.attach (c);
0N/A c.selectionKey = key;
0N/A c.time = getTime() + IDLE_INTERVAL;
0N/A idleConnections.add (c);
0N/A } catch (IOException e) {
0N/A dprint(e);
0N/A logger.log(Level.FINER, "Dispatcher(8)", e);
0N/A c.close();
0N/A }
0N/A }
0N/A
0N/A public void run() {
0N/A while (!finished) {
0N/A try {
0N/A ListIterator<HttpConnection> li =
0N/A connsToRegister.listIterator();
0N/A for (HttpConnection c : connsToRegister) {
0N/A reRegister(c);
0N/A }
0N/A connsToRegister.clear();
0N/A
0N/A List<Event> list = null;
0N/A selector.select(1000);
0N/A synchronized (lolock) {
0N/A if (events.size() > 0) {
0N/A list = events;
0N/A events = new LinkedList<Event>();
0N/A }
0N/A }
0N/A
0N/A if (list != null) {
0N/A for (Event r: list) {
0N/A handleEvent (r);
0N/A }
0N/A }
0N/A
0N/A /* process the selected list now */
0N/A
0N/A Set<SelectionKey> selected = selector.selectedKeys();
0N/A Iterator<SelectionKey> iter = selected.iterator();
0N/A while (iter.hasNext()) {
0N/A SelectionKey key = iter.next();
0N/A iter.remove ();
0N/A if (key.equals (listenerKey)) {
0N/A if (terminating) {
0N/A continue;
0N/A }
0N/A SocketChannel chan = schan.accept();
0N/A
0N/A // Set TCP_NODELAY, if appropriate
0N/A if (ServerConfig.noDelay()) {
0N/A chan.socket().setTcpNoDelay(true);
0N/A }
0N/A
0N/A if (chan == null) {
0N/A continue; /* cancel something ? */
0N/A }
0N/A chan.configureBlocking (false);
0N/A SelectionKey newkey = chan.register (selector, SelectionKey.OP_READ);
0N/A HttpConnection c = new HttpConnection ();
0N/A c.selectionKey = newkey;
0N/A c.setChannel (chan);
0N/A newkey.attach (c);
0N/A requestStarted (c);
0N/A allConnections.add (c);
0N/A } else {
0N/A try {
0N/A if (key.isReadable()) {
0N/A boolean closed;
0N/A SocketChannel chan = (SocketChannel)key.channel();
0N/A HttpConnection conn = (HttpConnection)key.attachment();
0N/A
0N/A key.cancel();
0N/A chan.configureBlocking (true);
0N/A if (idleConnections.remove(conn)) {
0N/A // was an idle connection so add it
0N/A // to reqConnections set.
0N/A requestStarted (conn);
0N/A }
0N/A handle (chan, conn);
0N/A } else {
0N/A assert false;
0N/A }
0N/A } catch (CancelledKeyException e) {
0N/A handleException(key, null);
0N/A } catch (IOException e) {
0N/A handleException(key, e);
0N/A }
0N/A }
0N/A }
0N/A // call the selector just to process the cancelled keys
0N/A selector.selectNow();
0N/A } catch (IOException e) {
0N/A logger.log (Level.FINER, "Dispatcher (4)", e);
0N/A } catch (Exception e) {
0N/A e.printStackTrace();
0N/A logger.log (Level.FINER, "Dispatcher (7)", e);
0N/A }
0N/A }
0N/A }
0N/A
0N/A private void handleException (SelectionKey key, Exception e) {
0N/A HttpConnection conn = (HttpConnection)key.attachment();
0N/A if (e != null) {
0N/A logger.log (Level.FINER, "Dispatcher (2)", e);
0N/A }
0N/A closeConnection(conn);
0N/A }
0N/A
0N/A public void handle (SocketChannel chan, HttpConnection conn)
0N/A throws IOException
0N/A {
0N/A try {
0N/A Exchange t = new Exchange (chan, protocol, conn);
0N/A executor.execute (t);
0N/A } catch (HttpError e1) {
0N/A logger.log (Level.FINER, "Dispatcher (4)", e1);
0N/A closeConnection(conn);
0N/A } catch (IOException e) {
388N/A logger.log (Level.FINER, "Dispatcher (5)", e);
388N/A closeConnection(conn);
0N/A }
0N/A }
0N/A }
0N/A
0N/A static boolean debug = ServerConfig.debugEnabled ();
0N/A
388N/A static synchronized void dprint (String s) {
388N/A if (debug) {
388N/A System.out.println (s);
388N/A }
388N/A }
0N/A
0N/A static synchronized void dprint (Exception e) {
388N/A if (debug) {
0N/A System.out.println (e);
0N/A e.printStackTrace();
0N/A }
0N/A }
0N/A
0N/A Logger getLogger () {
0N/A return logger;
0N/A }
0N/A
0N/A private void closeConnection(HttpConnection conn) {
0N/A conn.close();
0N/A allConnections.remove(conn);
0N/A switch (conn.getState()) {
0N/A case REQUEST:
0N/A reqConnections.remove(conn);
0N/A break;
0N/A case RESPONSE:
0N/A rspConnections.remove(conn);
0N/A break;
0N/A case IDLE:
0N/A idleConnections.remove(conn);
0N/A break;
0N/A }
0N/A assert !reqConnections.remove(conn);
0N/A assert !rspConnections.remove(conn);
0N/A assert !idleConnections.remove(conn);
0N/A }
0N/A
0N/A /* per exchange task */
0N/A
0N/A class Exchange implements Runnable {
0N/A SocketChannel chan;
0N/A HttpConnection connection;
0N/A HttpContextImpl context;
0N/A InputStream rawin;
0N/A OutputStream rawout;
0N/A String protocol;
0N/A ExchangeImpl tx;
0N/A HttpContextImpl ctx;
0N/A boolean rejected = false;
0N/A
0N/A Exchange (SocketChannel chan, String protocol, HttpConnection conn) throws IOException {
0N/A this.chan = chan;
0N/A this.connection = conn;
0N/A this.protocol = protocol;
0N/A }
0N/A
0N/A public void run () {
0N/A /* context will be null for new connections */
0N/A context = connection.getHttpContext();
0N/A boolean newconnection;
0N/A SSLEngine engine = null;
0N/A String requestLine = null;
0N/A SSLStreams sslStreams = null;
0N/A try {
0N/A if (context != null ) {
0N/A this.rawin = connection.getInputStream();
0N/A this.rawout = connection.getRawOutputStream();
0N/A newconnection = false;
0N/A } else {
0N/A /* figure out what kind of connection this is */
0N/A newconnection = true;
0N/A if (https) {
0N/A if (sslContext == null) {
0N/A logger.warning ("SSL connection received. No https contxt created");
0N/A throw new HttpError ("No SSL context established");
0N/A }
0N/A sslStreams = new SSLStreams (ServerImpl.this, sslContext, chan);
0N/A rawin = sslStreams.getInputStream();
0N/A rawout = sslStreams.getOutputStream();
0N/A engine = sslStreams.getSSLEngine();
0N/A connection.sslStreams = sslStreams;
0N/A } else {
0N/A rawin = new BufferedInputStream(
0N/A new Request.ReadStream (
0N/A ServerImpl.this, chan
0N/A ));
0N/A rawout = new Request.WriteStream (
0N/A ServerImpl.this, chan
0N/A );
0N/A }
0N/A connection.raw = rawin;
0N/A connection.rawout = rawout;
0N/A }
0N/A Request req = new Request (rawin, rawout);
0N/A requestLine = req.requestLine();
0N/A if (requestLine == null) {
0N/A /* connection closed */
0N/A closeConnection(connection);
0N/A return;
0N/A }
0N/A int space = requestLine.indexOf (' ');
0N/A if (space == -1) {
0N/A reject (Code.HTTP_BAD_REQUEST,
0N/A requestLine, "Bad request line");
0N/A return;
}
String method = requestLine.substring (0, space);
int start = space+1;
space = requestLine.indexOf(' ', start);
if (space == -1) {
reject (Code.HTTP_BAD_REQUEST,
requestLine, "Bad request line");
return;
}
String uriStr = requestLine.substring (start, space);
URI uri = new URI (uriStr);
start = space+1;
String version = requestLine.substring (start);
Headers headers = req.headers();
String s = headers.getFirst ("Transfer-encoding");
long clen = 0L;
if (s !=null && s.equalsIgnoreCase ("chunked")) {
clen = -1L;
} else {
s = headers.getFirst ("Content-Length");
if (s != null) {
clen = Long.parseLong(s);
}
if (clen == 0) {
requestCompleted (connection);
}
}
ctx = contexts.findContext (protocol, uri.getPath());
if (ctx == null) {
reject (Code.HTTP_NOT_FOUND,
requestLine, "No context found for request");
return;
}
connection.setContext (ctx);
if (ctx.getHandler() == null) {
reject (Code.HTTP_INTERNAL_ERROR,
requestLine, "No handler for context");
return;
}
tx = new ExchangeImpl (
method, uri, req, clen, connection
);
String chdr = headers.getFirst("Connection");
Headers rheaders = tx.getResponseHeaders();
if (chdr != null && chdr.equalsIgnoreCase ("close")) {
tx.close = true;
}
if (version.equalsIgnoreCase ("http/1.0")) {
tx.http10 = true;
if (chdr == null) {
tx.close = true;
rheaders.set ("Connection", "close");
} else if (chdr.equalsIgnoreCase ("keep-alive")) {
rheaders.set ("Connection", "keep-alive");
int idle=(int)ServerConfig.getIdleInterval()/1000;
int max=(int)ServerConfig.getMaxIdleConnections();
String val = "timeout="+idle+", max="+max;
rheaders.set ("Keep-Alive", val);
}
}
if (newconnection) {
connection.setParameters (
rawin, rawout, chan, engine, sslStreams,
sslContext, protocol, ctx, rawin
);
}
/* check if client sent an Expect 100 Continue.
* In that case, need to send an interim response.
* In future API may be modified to allow app to
* be involved in this process.
*/
String exp = headers.getFirst("Expect");
if (exp != null && exp.equalsIgnoreCase ("100-continue")) {
logReply (100, requestLine, null);
sendReply (
Code.HTTP_CONTINUE, false, null
);
}
/* uf is the list of filters seen/set by the user.
* sf is the list of filters established internally
* and which are not visible to the user. uc and sc
* are the corresponding Filter.Chains.
* They are linked together by a LinkHandler
* so that they can both be invoked in one call.
*/
List<Filter> sf = ctx.getSystemFilters();
List<Filter> uf = ctx.getFilters();
Filter.Chain sc = new Filter.Chain(sf, ctx.getHandler());
Filter.Chain uc = new Filter.Chain(uf, new LinkHandler (sc));
/* set up the two stream references */
tx.getRequestBody();
tx.getResponseBody();
if (https) {
uc.doFilter (new HttpsExchangeImpl (tx));
} else {
uc.doFilter (new HttpExchangeImpl (tx));
}
} catch (IOException e1) {
logger.log (Level.FINER, "ServerImpl.Exchange (1)", e1);
closeConnection(connection);
} catch (NumberFormatException e3) {
reject (Code.HTTP_BAD_REQUEST,
requestLine, "NumberFormatException thrown");
} catch (URISyntaxException e) {
reject (Code.HTTP_BAD_REQUEST,
requestLine, "URISyntaxException thrown");
} catch (Exception e4) {
logger.log (Level.FINER, "ServerImpl.Exchange (2)", e4);
closeConnection(connection);
}
}
/* used to link to 2 or more Filter.Chains together */
class LinkHandler implements HttpHandler {
Filter.Chain nextChain;
LinkHandler (Filter.Chain nextChain) {
this.nextChain = nextChain;
}
public void handle (HttpExchange exchange) throws IOException {
nextChain.doFilter (exchange);
}
}
void reject (int code, String requestStr, String message) {
rejected = true;
logReply (code, requestStr, message);
sendReply (
code, false, "<h1>"+code+Code.msg(code)+"</h1>"+message
);
closeConnection(connection);
}
void sendReply (
int code, boolean closeNow, String text)
{
try {
StringBuilder builder = new StringBuilder (512);
builder.append ("HTTP/1.1 ")
.append (code).append (Code.msg(code)).append ("\r\n");
if (text != null && text.length() != 0) {
builder.append ("Content-Length: ")
.append (text.length()).append ("\r\n")
.append ("Content-Type: text/html\r\n");
} else {
builder.append ("Content-Length: 0\r\n");
text = "";
}
if (closeNow) {
builder.append ("Connection: close\r\n");
}
builder.append ("\r\n").append (text);
String s = builder.toString();
byte[] b = s.getBytes("ISO8859_1");
rawout.write (b);
rawout.flush();
if (closeNow) {
closeConnection(connection);
}
} catch (IOException e) {
logger.log (Level.FINER, "ServerImpl.sendReply", e);
closeConnection(connection);
}
}
}
void logReply (int code, String requestStr, String text) {
if (!logger.isLoggable(Level.FINE)) {
return;
}
if (text == null) {
text = "";
}
String r;
if (requestStr.length() > 80) {
r = requestStr.substring (0, 80) + "<TRUNCATED>";
} else {
r = requestStr;
}
String message = r + " [" + code + " " +
Code.msg(code) + "] ("+text+")";
logger.fine (message);
}
long getTicks() {
return ticks;
}
public long getTime() {
return time;
}
void delay () {
Thread.yield();
try {
Thread.sleep (200);
} catch (InterruptedException e) {}
}
private int exchangeCount = 0;
synchronized void startExchange () {
exchangeCount ++;
}
synchronized int endExchange () {
exchangeCount --;
assert exchangeCount >= 0;
return exchangeCount;
}
HttpServer getWrapper () {
return wrapper;
}
void requestStarted (HttpConnection c) {
c.creationTime = getTime();
c.setState (State.REQUEST);
reqConnections.add (c);
}
// called after a request has been completely read
// by the server. This stops the timer which would
// close the connection if the request doesn't arrive
// quickly enough. It then starts the timer
// that ensures the client reads the response in a timely
// fashion.
void requestCompleted (HttpConnection c) {
assert c.getState() == State.REQUEST;
reqConnections.remove (c);
c.rspStartedTime = getTime();
rspConnections.add (c);
c.setState (State.RESPONSE);
}
// called after response has been sent
void responseCompleted (HttpConnection c) {
assert c.getState() == State.RESPONSE;
rspConnections.remove (c);
c.setState (State.IDLE);
}
/**
* TimerTask run every CLOCK_TICK ms
*/
class ServerTimerTask extends TimerTask {
public void run () {
LinkedList<HttpConnection> toClose = new LinkedList<HttpConnection>();
time = System.currentTimeMillis();
ticks ++;
synchronized (idleConnections) {
for (HttpConnection c : idleConnections) {
if (c.time <= time) {
toClose.add (c);
}
}
for (HttpConnection c : toClose) {
idleConnections.remove (c);
allConnections.remove (c);
c.close();
}
}
}
}
class ServerTimerTask1 extends TimerTask {
// runs every TIMER_MILLIS
public void run () {
LinkedList<HttpConnection> toClose = new LinkedList<HttpConnection>();
time = System.currentTimeMillis();
synchronized (reqConnections) {
if (MAX_REQ_TIME != -1) {
for (HttpConnection c : reqConnections) {
if (c.creationTime + TIMER_MILLIS + MAX_REQ_TIME <= time) {
toClose.add (c);
}
}
for (HttpConnection c : toClose) {
logger.log (Level.FINE, "closing: no request: " + c);
reqConnections.remove (c);
allConnections.remove (c);
c.close();
}
}
}
toClose = new LinkedList<HttpConnection>();
synchronized (rspConnections) {
if (MAX_RSP_TIME != -1) {
for (HttpConnection c : rspConnections) {
if (c.rspStartedTime + TIMER_MILLIS +MAX_RSP_TIME <= time) {
toClose.add (c);
}
}
for (HttpConnection c : toClose) {
logger.log (Level.FINE, "closing: no response: " + c);
rspConnections.remove (c);
allConnections.remove (c);
c.close();
}
}
}
}
}
void logStackTrace (String s) {
logger.finest (s);
StringBuilder b = new StringBuilder ();
StackTraceElement[] e = Thread.currentThread().getStackTrace();
for (int i=0; i<e.length; i++) {
b.append (e[i].toString()).append("\n");
}
logger.finest (b.toString());
}
static long getTimeMillis(long secs) {
if (secs == -1) {
return -1;
} else {
return secs * 1000;
}
}
}