Search in sources :

Example 11 with Extension

use of javax.websocket.Extension in project undertow by undertow-io.

the class ServerWebSocketContainer method connectToServerInternal.

private Session connectToServerInternal(final Endpoint endpointInstance, final ConfiguredClientEndpoint cec, WebSocketClient.ConnectionBuilder connectionBuilder) throws DeploymentException, IOException {
    IoFuture<WebSocketChannel> session = connectionBuilder.connect();
    Number timeout = (Number) cec.getConfig().getUserProperties().get(TIMEOUT);
    IoFuture.Status result = session.await(timeout == null ? DEFAULT_WEB_SOCKET_TIMEOUT_SECONDS : timeout.intValue(), TimeUnit.SECONDS);
    if (result == IoFuture.Status.WAITING) {
        //add a notifier to close the channel if the connection actually completes
        session.cancel();
        session.addNotifier(new IoFuture.HandlingNotifier<WebSocketChannel, Object>() {

            @Override
            public void handleDone(WebSocketChannel data, Object attachment) {
                IoUtils.safeClose(data);
            }
        }, null);
        throw JsrWebSocketMessages.MESSAGES.connectionTimedOut();
    }
    WebSocketChannel channel;
    try {
        channel = session.get();
    } catch (UpgradeFailedException e) {
        throw new DeploymentException(e.getMessage(), e);
    }
    EndpointSessionHandler sessionHandler = new EndpointSessionHandler(this);
    final List<Extension> extensions = new ArrayList<>();
    final Map<String, Extension> extMap = new HashMap<>();
    for (Extension ext : cec.getConfig().getExtensions()) {
        extMap.put(ext.getName(), ext);
    }
    String subProtocol = null;
    if (connectionBuilder.getClientNegotiation() != null) {
        for (WebSocketExtension e : connectionBuilder.getClientNegotiation().getSelectedExtensions()) {
            Extension ext = extMap.get(e.getName());
            if (ext == null) {
                throw JsrWebSocketMessages.MESSAGES.extensionWasNotPresentInClientHandshake(e.getName(), connectionBuilder.getClientNegotiation().getSupportedExtensions());
            }
            extensions.add(ExtensionImpl.create(e));
        }
        subProtocol = connectionBuilder.getClientNegotiation().getSelectedSubProtocol();
    }
    UndertowSession undertowSession = new UndertowSession(channel, connectionBuilder.getUri(), Collections.<String, String>emptyMap(), Collections.<String, List<String>>emptyMap(), sessionHandler, null, new ImmediateInstanceHandle<>(endpointInstance), cec.getConfig(), connectionBuilder.getUri().getQuery(), cec.getEncodingFactory().createEncoding(cec.getConfig()), cec, subProtocol, extensions, connectionBuilder);
    endpointInstance.onOpen(undertowSession, cec.getConfig());
    channel.resumeReceives();
    return undertowSession;
}
Also used : WebSocketExtension(io.undertow.websockets.WebSocketExtension) HashMap(java.util.HashMap) WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) ArrayList(java.util.ArrayList) IoFuture(org.xnio.IoFuture) WebSocketExtension(io.undertow.websockets.WebSocketExtension) Extension(javax.websocket.Extension) UpgradeFailedException(org.xnio.http.UpgradeFailedException) DeploymentException(javax.websocket.DeploymentException)

Example 12 with Extension

use of javax.websocket.Extension in project undertow by undertow-io.

the class JsrHybi13Handshake method selectedExtension.

@Override
protected List<WebSocketExtension> selectedExtension(List<WebSocketExtension> extensionList) {
    List<Extension> ext = new ArrayList<>();
    for (WebSocketExtension i : extensionList) {
        ext.add(ExtensionImpl.create(i));
    }
    List<Extension> selected = HandshakeUtil.selectExtensions(config, ext);
    if (selected == null) {
        return Collections.emptyList();
    }
    Map<String, ExtensionHandshake> extensionMap = new HashMap<>();
    for (ExtensionHandshake availible : availableExtensions) {
        extensionMap.put(availible.getName(), availible);
    }
    List<WebSocketExtension> ret = new ArrayList<>();
    List<ExtensionHandshake> accepted = new ArrayList<>();
    for (Extension i : selected) {
        ExtensionHandshake handshake = extensionMap.get(i.getName());
        if (handshake == null) {
            //should not happen
            continue;
        }
        List<WebSocketExtension.Parameter> parameters = new ArrayList<>();
        for (Extension.Parameter p : i.getParameters()) {
            parameters.add(new WebSocketExtension.Parameter(p.getName(), p.getValue()));
        }
        if (!handshake.isIncompatible(accepted)) {
            WebSocketExtension accept = handshake.accept(new WebSocketExtension(i.getName(), parameters));
            if (accept != null) {
                ret.add(accept);
                accepted.add(handshake);
            }
        }
    }
    return ret;
}
Also used : WebSocketExtension(io.undertow.websockets.WebSocketExtension) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) WebSocketExtension(io.undertow.websockets.WebSocketExtension) Extension(javax.websocket.Extension) ExtensionHandshake(io.undertow.websockets.extensions.ExtensionHandshake)

Example 13 with Extension

use of javax.websocket.Extension in project tomcat by apache.

the class WsWebSocketContainer method connectToServer.

// socketChannel is closed
@SuppressWarnings("resource")
@Override
public Session connectToServer(Endpoint endpoint, ClientEndpointConfig clientEndpointConfiguration, URI path) throws DeploymentException {
    boolean secure = false;
    ByteBuffer proxyConnect = null;
    URI proxyPath;
    // Validate scheme (and build proxyPath)
    String scheme = path.getScheme();
    if ("ws".equalsIgnoreCase(scheme)) {
        proxyPath = URI.create("http" + path.toString().substring(2));
    } else if ("wss".equalsIgnoreCase(scheme)) {
        proxyPath = URI.create("https" + path.toString().substring(3));
        secure = true;
    } else {
        throw new DeploymentException(sm.getString("wsWebSocketContainer.pathWrongScheme", scheme));
    }
    // Validate host
    String host = path.getHost();
    if (host == null) {
        throw new DeploymentException(sm.getString("wsWebSocketContainer.pathNoHost"));
    }
    int port = path.getPort();
    SocketAddress sa = null;
    // Check to see if a proxy is configured. Javadoc indicates return value
    // will never be null
    List<Proxy> proxies = ProxySelector.getDefault().select(proxyPath);
    Proxy selectedProxy = null;
    for (Proxy proxy : proxies) {
        if (proxy.type().equals(Proxy.Type.HTTP)) {
            sa = proxy.address();
            if (sa instanceof InetSocketAddress) {
                InetSocketAddress inet = (InetSocketAddress) sa;
                if (inet.isUnresolved()) {
                    sa = new InetSocketAddress(inet.getHostName(), inet.getPort());
                }
            }
            selectedProxy = proxy;
            break;
        }
    }
    // scheme
    if (port == -1) {
        if ("ws".equalsIgnoreCase(scheme)) {
            port = 80;
        } else {
            // Must be wss due to scheme validation above
            port = 443;
        }
    }
    // If sa is null, no proxy is configured so need to create sa
    if (sa == null) {
        sa = new InetSocketAddress(host, port);
    } else {
        proxyConnect = createProxyRequest(host, port);
    }
    // Create the initial HTTP request to open the WebSocket connection
    Map<String, List<String>> reqHeaders = createRequestHeaders(host, port, clientEndpointConfiguration.getPreferredSubprotocols(), clientEndpointConfiguration.getExtensions());
    clientEndpointConfiguration.getConfigurator().beforeRequest(reqHeaders);
    if (Constants.DEFAULT_ORIGIN_HEADER_VALUE != null && !reqHeaders.containsKey(Constants.ORIGIN_HEADER_NAME)) {
        List<String> originValues = new ArrayList<>(1);
        originValues.add(Constants.DEFAULT_ORIGIN_HEADER_VALUE);
        reqHeaders.put(Constants.ORIGIN_HEADER_NAME, originValues);
    }
    ByteBuffer request = createRequest(path, reqHeaders);
    AsynchronousSocketChannel socketChannel;
    try {
        socketChannel = AsynchronousSocketChannel.open(getAsynchronousChannelGroup());
    } catch (IOException ioe) {
        throw new DeploymentException(sm.getString("wsWebSocketContainer.asynchronousSocketChannelFail"), ioe);
    }
    // Get the connection timeout
    long timeout = Constants.IO_TIMEOUT_MS_DEFAULT;
    String timeoutValue = (String) clientEndpointConfiguration.getUserProperties().get(Constants.IO_TIMEOUT_MS_PROPERTY);
    if (timeoutValue != null) {
        timeout = Long.valueOf(timeoutValue).intValue();
    }
    // Set-up
    // Same size as the WsFrame input buffer
    ByteBuffer response = ByteBuffer.allocate(maxBinaryMessageBufferSize);
    String subProtocol;
    boolean success = false;
    List<Extension> extensionsAgreed = new ArrayList<>();
    Transformation transformation = null;
    // Open the connection
    Future<Void> fConnect = socketChannel.connect(sa);
    AsyncChannelWrapper channel = null;
    if (proxyConnect != null) {
        try {
            fConnect.get(timeout, TimeUnit.MILLISECONDS);
            // Proxy CONNECT is clear text
            channel = new AsyncChannelWrapperNonSecure(socketChannel);
            writeRequest(channel, proxyConnect, timeout);
            HttpResponse httpResponse = processResponse(response, channel, timeout);
            if (httpResponse.getStatus() != 200) {
                throw new DeploymentException(sm.getString("wsWebSocketContainer.proxyConnectFail", selectedProxy, Integer.toString(httpResponse.getStatus())));
            }
        } catch (TimeoutException | InterruptedException | ExecutionException | EOFException e) {
            if (channel != null) {
                channel.close();
            }
            throw new DeploymentException(sm.getString("wsWebSocketContainer.httpRequestFailed"), e);
        }
    }
    if (secure) {
        // Regardless of whether a non-secure wrapper was created for a
        // proxy CONNECT, need to use TLS from this point on so wrap the
        // original AsynchronousSocketChannel
        SSLEngine sslEngine = createSSLEngine(clientEndpointConfiguration.getUserProperties());
        channel = new AsyncChannelWrapperSecure(socketChannel, sslEngine);
    } else if (channel == null) {
        // Only need to wrap as this point if it wasn't wrapped to process a
        // proxy CONNECT
        channel = new AsyncChannelWrapperNonSecure(socketChannel);
    }
    try {
        fConnect.get(timeout, TimeUnit.MILLISECONDS);
        Future<Void> fHandshake = channel.handshake();
        fHandshake.get(timeout, TimeUnit.MILLISECONDS);
        writeRequest(channel, request, timeout);
        HttpResponse httpResponse = processResponse(response, channel, timeout);
        // TODO: Handle redirects
        if (httpResponse.status != 101) {
            throw new DeploymentException(sm.getString("wsWebSocketContainer.invalidStatus", Integer.toString(httpResponse.status)));
        }
        HandshakeResponse handshakeResponse = httpResponse.getHandshakeResponse();
        clientEndpointConfiguration.getConfigurator().afterResponse(handshakeResponse);
        // Sub-protocol
        List<String> protocolHeaders = handshakeResponse.getHeaders().get(Constants.WS_PROTOCOL_HEADER_NAME);
        if (protocolHeaders == null || protocolHeaders.size() == 0) {
            subProtocol = null;
        } else if (protocolHeaders.size() == 1) {
            subProtocol = protocolHeaders.get(0);
        } else {
            throw new DeploymentException(sm.getString("wsWebSocketContainer.invalidSubProtocol"));
        }
        // Extensions
        // Should normally only be one header but handle the case of
        // multiple headers
        List<String> extHeaders = handshakeResponse.getHeaders().get(Constants.WS_EXTENSIONS_HEADER_NAME);
        if (extHeaders != null) {
            for (String extHeader : extHeaders) {
                Util.parseExtensionHeader(extensionsAgreed, extHeader);
            }
        }
        // Build the transformations
        TransformationFactory factory = TransformationFactory.getInstance();
        for (Extension extension : extensionsAgreed) {
            List<List<Extension.Parameter>> wrapper = new ArrayList<>(1);
            wrapper.add(extension.getParameters());
            Transformation t = factory.create(extension.getName(), wrapper, false);
            if (t == null) {
                throw new DeploymentException(sm.getString("wsWebSocketContainer.invalidExtensionParameters"));
            }
            if (transformation == null) {
                transformation = t;
            } else {
                transformation.setNext(t);
            }
        }
        success = true;
    } catch (ExecutionException | InterruptedException | SSLException | EOFException | TimeoutException e) {
        throw new DeploymentException(sm.getString("wsWebSocketContainer.httpRequestFailed"), e);
    } finally {
        if (!success) {
            channel.close();
        }
    }
    // Switch to WebSocket
    WsRemoteEndpointImplClient wsRemoteEndpointClient = new WsRemoteEndpointImplClient(channel);
    WsSession wsSession = new WsSession(endpoint, wsRemoteEndpointClient, this, null, null, null, null, null, extensionsAgreed, subProtocol, Collections.<String, String>emptyMap(), secure, clientEndpointConfiguration);
    WsFrameClient wsFrameClient = new WsFrameClient(response, channel, wsSession, transformation);
    // WsFrame adds the necessary final transformations. Copy the
    // completed transformation chain to the remote end point.
    wsRemoteEndpointClient.setTransformation(wsFrameClient.getTransformation());
    endpoint.onOpen(wsSession, clientEndpointConfiguration);
    registerSession(endpoint, wsSession);
    /* It is possible that the server sent one or more messages as soon as
         * the WebSocket connection was established. Depending on the exact
         * timing of when those messages were sent they could be sat in the
         * input buffer waiting to be read and will not trigger a "data
         * available to read" event. Therefore, it is necessary to process the
         * input buffer here. Note that this happens on the current thread which
         * means that this thread will be used for any onMessage notifications.
         * This is a special case. Subsequent "data available to read" events
         * will be handled by threads from the AsyncChannelGroup's executor.
         */
    wsFrameClient.startInputProcessing();
    return wsSession;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) SSLEngine(javax.net.ssl.SSLEngine) ArrayList(java.util.ArrayList) URI(java.net.URI) SSLException(javax.net.ssl.SSLException) HandshakeResponse(javax.websocket.HandshakeResponse) Proxy(java.net.Proxy) EOFException(java.io.EOFException) List(java.util.List) ArrayList(java.util.ArrayList) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) Endpoint(javax.websocket.Endpoint) ClientEndpoint(javax.websocket.ClientEndpoint) Extension(javax.websocket.Extension) AsynchronousSocketChannel(java.nio.channels.AsynchronousSocketChannel) DeploymentException(javax.websocket.DeploymentException)

Example 14 with Extension

use of javax.websocket.Extension in project tomcat by apache.

the class WsWebSocketContainer method generateExtensionHeaders.

private static List<String> generateExtensionHeaders(List<Extension> extensions) {
    List<String> result = new ArrayList<>(extensions.size());
    for (Extension extension : extensions) {
        StringBuilder header = new StringBuilder();
        header.append(extension.getName());
        for (Extension.Parameter param : extension.getParameters()) {
            header.append(';');
            header.append(param.getName());
            String value = param.getValue();
            if (value != null && value.length() > 0) {
                header.append('=');
                header.append(value);
            }
        }
        result.add(header.toString());
    }
    return result;
}
Also used : Extension(javax.websocket.Extension) ArrayList(java.util.ArrayList)

Example 15 with Extension

use of javax.websocket.Extension in project tomcat by apache.

the class PerMessageDeflate method getExtensionResponse.

@Override
public Extension getExtensionResponse() {
    Extension result = new WsExtension(NAME);
    List<Extension.Parameter> params = result.getParameters();
    if (!serverContextTakeover) {
        params.add(new WsExtensionParameter(SERVER_NO_CONTEXT_TAKEOVER, null));
    }
    if (serverMaxWindowBits != -1) {
        params.add(new WsExtensionParameter(SERVER_MAX_WINDOW_BITS, Integer.toString(serverMaxWindowBits)));
    }
    if (!clientContextTakeover) {
        params.add(new WsExtensionParameter(CLIENT_NO_CONTEXT_TAKEOVER, null));
    }
    if (clientMaxWindowBits != -1) {
        params.add(new WsExtensionParameter(CLIENT_MAX_WINDOW_BITS, Integer.toString(clientMaxWindowBits)));
    }
    return result;
}
Also used : Extension(javax.websocket.Extension) Parameter(javax.websocket.Extension.Parameter)

Aggregations

Extension (javax.websocket.Extension)22 ArrayList (java.util.ArrayList)16 ClientEndpointConfig (javax.websocket.ClientEndpointConfig)6 URI (java.net.URI)5 WebSocketExtension (io.undertow.websockets.WebSocketExtension)4 DeploymentException (javax.websocket.DeploymentException)4 Endpoint (javax.websocket.Endpoint)4 Parameter (javax.websocket.Extension.Parameter)4 Session (javax.websocket.Session)4 IOException (java.io.IOException)3 InetSocketAddress (java.net.InetSocketAddress)3 HashMap (java.util.HashMap)3 List (java.util.List)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 ServerEndpointConfig (javax.websocket.server.ServerEndpointConfig)3 JsrExtension (org.eclipse.jetty.websocket.jsr356.JsrExtension)3 WebSocketChannel (io.undertow.websockets.core.WebSocketChannel)2 ExtensionHandshake (io.undertow.websockets.extensions.ExtensionHandshake)2 HashSet (java.util.HashSet)2 ExecutionException (java.util.concurrent.ExecutionException)2