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
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.tomcat.websocket.server;
import java.io.EOFException;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import javax.websocket.CloseReason;
import javax.websocket.CloseReason.CloseCodes;
import javax.websocket.DeploymentException;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.Extension;
import org.apache.coyote.http11.upgrade.AbstractServletInputStream;
import org.apache.coyote.http11.upgrade.AbstractServletOutputStream;
import org.apache.coyote.http11.upgrade.servlet31.HttpUpgradeHandler;
import org.apache.coyote.http11.upgrade.servlet31.ReadListener;
import org.apache.coyote.http11.upgrade.servlet31.WebConnection;
import org.apache.coyote.http11.upgrade.servlet31.WriteListener;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.res.StringManager;
import org.apache.tomcat.websocket.Transformation;
import org.apache.tomcat.websocket.WsIOException;
import org.apache.tomcat.websocket.WsSession;
/**
* Servlet 3.1 HTTP upgrade handler for WebSocket connections.
*/
public class WsHttpUpgradeHandler implements HttpUpgradeHandler {
private static final Log log =
LogFactory.getLog(WsHttpUpgradeHandler.class);
private static final StringManager sm =
StringManager.getManager(Constants.PACKAGE_NAME);
private final ClassLoader applicationClassLoader;
private Endpoint ep;
private EndpointConfig endpointConfig;
private WsServerContainer webSocketContainer;
private WsHandshakeRequest handshakeRequest;
private List<Extension> negotiatedExtensions;
private String subProtocol;
private Transformation transformation;
private Map<String,String> pathParameters;
private boolean secure;
private WebConnection connection;
private WsSession wsSession;
public WsHttpUpgradeHandler() {
applicationClassLoader = Thread.currentThread().getContextClassLoader();
}
public void preInit(Endpoint ep, EndpointConfig endpointConfig,
WsServerContainer wsc, WsHandshakeRequest handshakeRequest,
List<Extension> negotiatedExtensionsPhase2, String subProtocol,
Transformation transformation, Map<String,String> pathParameters,
boolean secure) {
this.ep = ep;
this.endpointConfig = endpointConfig;
this.webSocketContainer = wsc;
this.handshakeRequest = handshakeRequest;
this.negotiatedExtensions = negotiatedExtensionsPhase2;
this.subProtocol = subProtocol;
this.transformation = transformation;
this.pathParameters = pathParameters;
this.secure = secure;
}
@Override
public void init(WebConnection connection) {
if (ep == null) {
throw new IllegalStateException(
sm.getString("wsHttpUpgradeHandler.noPreInit"));
}
this.connection = connection;
AbstractServletInputStream sis;
AbstractServletOutputStream sos;
try {
sis = connection.getInputStream();
sos = connection.getOutputStream();
} catch (IOException e) {
throw new IllegalStateException(e);
}
String httpSessionId = null;
Object session = handshakeRequest.getHttpSession();
if (session != null ) {
httpSessionId = ((HttpSession) session).getId();
}
// Need to call onOpen using the web application's class loader
// Create the frame using the application's class loader so it can pick
// up application specific config from the ServerContainerImpl
Thread t = Thread.currentThread();
ClassLoader cl = t.getContextClassLoader();
t.setContextClassLoader(applicationClassLoader);
try {
WsRemoteEndpointImplServer wsRemoteEndpointServer =
new WsRemoteEndpointImplServer(sos, webSocketContainer);
wsSession = new WsSession(ep, wsRemoteEndpointServer,
webSocketContainer, handshakeRequest.getRequestURI(),
handshakeRequest.getParameterMap(),
handshakeRequest.getQueryString(),
handshakeRequest.getUserPrincipal(), httpSessionId,
negotiatedExtensions, subProtocol, pathParameters, secure,
endpointConfig);
WsFrameServer wsFrame = new WsFrameServer(sis, wsSession, transformation);
sos.setWriteListener(new WsWriteListener(this, wsRemoteEndpointServer));
// WsFrame adds the necessary final transformations. Copy the
// completed transformation chain to the remote end point.
wsRemoteEndpointServer.setTransformation(wsFrame.getTransformation());
ep.onOpen(wsSession, endpointConfig);
webSocketContainer.registerSession(ep, wsSession);
sis.setReadListener(new WsReadListener(this, wsFrame));
} catch (DeploymentException e) {
throw new IllegalArgumentException(e);
} finally {
t.setContextClassLoader(cl);
}
}
@Override
public void destroy() {
if (connection != null) {
try {
connection.close();
} catch (Exception e) {
log.error(sm.getString("wsHttpUpgradeHandler.destroyFailed"), e);
}
}
}
private void onError(Throwable throwable) {
// Need to call onError using the web application's class loader
Thread t = Thread.currentThread();
ClassLoader cl = t.getContextClassLoader();
t.setContextClassLoader(applicationClassLoader);
try {
ep.onError(wsSession, throwable);
} finally {
t.setContextClassLoader(cl);
}
}
private void close(CloseReason cr) {
/*
* Any call to this method is a result of a problem reading from the
* client. At this point that state of the connection is unknown.
* Attempt to send a close frame to the client and then close the socket
* immediately. There is no point in waiting for a close frame from the
* client because there is no guarantee that we can recover from
* whatever messed up state the client put the connection into.
*/
wsSession.onClose(cr);
}
private static class WsReadListener implements ReadListener {
private final WsHttpUpgradeHandler wsProtocolHandler;
private final WsFrameServer wsFrame;
private WsReadListener(WsHttpUpgradeHandler wsProtocolHandler,
WsFrameServer wsFrame) {
this.wsProtocolHandler = wsProtocolHandler;
this.wsFrame = wsFrame;
}
@Override
public void onDataAvailable() {
try {
wsFrame.onDataAvailable();
} catch (WsIOException ws) {
wsProtocolHandler.close(ws.getCloseReason());
} catch (EOFException eof) {
CloseReason cr = new CloseReason(
CloseCodes.CLOSED_ABNORMALLY, eof.getMessage());
wsProtocolHandler.close(cr);
} catch (IOException ioe) {
onError(ioe);
CloseReason cr = new CloseReason(
CloseCodes.CLOSED_ABNORMALLY, ioe.getMessage());
wsProtocolHandler.close(cr);
}
}
@Override
public void onAllDataRead() {
// Will never happen with WebSocket
throw new IllegalStateException();
}
@Override
public void onError(Throwable throwable) {
wsProtocolHandler.onError(throwable);
}
}
private static class WsWriteListener implements WriteListener {
private final WsHttpUpgradeHandler wsProtocolHandler;
private final WsRemoteEndpointImplServer wsRemoteEndpointServer;
private WsWriteListener(WsHttpUpgradeHandler wsProtocolHandler,
WsRemoteEndpointImplServer wsRemoteEndpointServer) {
this.wsProtocolHandler = wsProtocolHandler;
this.wsRemoteEndpointServer = wsRemoteEndpointServer;
}
@Override
public void onWritePossible() {
// Triggered by the poller so this isn't the same thread that
// triggered the write so no need for a dispatch
wsRemoteEndpointServer.onWritePossible(false);
}
@Override
public void onError(Throwable throwable) {
wsProtocolHandler.onError(throwable);
wsRemoteEndpointServer.close();
}
}
}
|