Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * 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 static org.jboss.web.WebsocketsMessages.MESSAGES;
 
 import  java.nio.charset.StandardCharsets;
 import java.util.List;
 import java.util.Map;
 
 
 
 public class UpgradeUtil {
 
     private static final byte[] WS_ACCEPT =
             "258EAFA5-E914-47DA-95CA-C5AB0DC85B11".getBytes(
                     StandardCharsets.ISO_8859_1);
     private static final Queue<MessageDigestsha1Helpers =
             new ConcurrentLinkedQueue<MessageDigest>();
 
     private UpgradeUtil() {
         // Utility class. Hide default constructor.
     }

    
Checks to see if this is an HTTP request that includes a valid upgrade request to web socket.

Note: RFC 2616 does not limit HTTP upgrade to GET requests but the Java WebSocket spec 1.0, section 8.2 implies such a limitation and RFC 6455 section 4.1 requires that a WebSocket Upgrade uses GET.

 
     public static boolean isWebSocketUpgradeRequest(ServletRequest request,
             ServletResponse response) {
 
         return ((request instanceof HttpServletRequest) &&
                 (response instanceof HttpServletResponse) &&
                 headerContainsToken((HttpServletRequestrequest,
                         .,
                         .) &&
                 "GET".equals(((HttpServletRequestrequest).getMethod()));
     }
 
 
     public static void doUpgrade(WsServerContainer scHttpServletRequest req,
             HttpServletResponse respServerEndpointConfig sec,
             Map<String,StringpathParams)
             throws ServletExceptionIOException {
 
         // Validate the rest of the headers and reject the request if that
         // validation fails
         String key;
         String subProtocol = null;
         List<Extensionextensions = Collections.emptyList();
                 .)) {
             resp.sendError(.);
             return;
         }
                .)) {
            resp.setStatus(426);
            resp.setHeader(.,
                    .);
            return;
        }
        key = req.getHeader(.);
        if (key == null) {
            resp.sendError(.);
            return;
        }
        // Origin check
        String origin = req.getHeader("Origin");
        if (!sec.getConfigurator().checkOrigin(origin)) {
            resp.sendError(.);
            return;
        }
        // Sub-protocols
        List<StringsubProtocols = getTokensFromHeader(req,
                "Sec-WebSocket-Protocol");
        subProtocol = sec.getConfigurator().getNegotiatedSubprotocol(
                sec.getSubprotocols(), subProtocols);
        // Extensions
        // Currently no extensions are supported by this implementation
        // If we got this far, all is good. Accept the connection.
                .);
                .);
                getWebSocketAccept(key));
        if (subProtocol != null && subProtocol.length() > 0) {
            // RFC6455 4.2.2 explicitly states "" is not valid here
            resp.setHeader("Sec-WebSocket-Protocol"subProtocol);
        }
        if (!extensions.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            Iterator<Extensioniter = extensions.iterator();
            // There must be at least one
            sb.append(iter.next());
            while (iter.hasNext()) {
                sb.append(',');
                sb.append(iter.next().getName());
            }
            resp.setHeader("Sec-WebSocket-Extensions"sb.toString());
        }
        WsHandshakeRequest wsRequest = new WsHandshakeRequest(req);
        WsHandshakeResponse wsResponse = new WsHandshakeResponse();
        WsPerSessionServerEndpointConfig perSessionServerEndpointConfig =
                new WsPerSessionServerEndpointConfig(sec);
        sec.getConfigurator().modifyHandshake(perSessionServerEndpointConfig,
                wsRequestwsResponse);
        wsRequest.finished();
        // Add any additional headers
        for (Entry<String,List<String>> entry :
                wsResponse.getHeaders().entrySet()) {
            for (String headerValueentry.getValue()) {
                resp.addHeader(entry.getKey(), headerValue);
            }
        }
        Endpoint ep;
        try {
            Class<?> clazz = sec.getEndpointClass();
            if (Endpoint.class.isAssignableFrom(clazz)) {
                ep = (Endpointsec.getConfigurator().getEndpointInstance(
                        clazz);
            } else {
                ep = new PojoEndpointServer();
            }
        } catch (InstantiationException e) {
            throw new ServletException(e);
        }
        // Small hack until the Servlet API provides a way to do this.
        ServletRequest inner = req;
        // Unwrap the request
        while (inner instanceof ServletRequestWrapper) {
            inner = ((ServletRequestWrapperinner).getRequest();
        }
        if (inner instanceof RequestFacade) {
            WsHttpUpgradeHandler wsHandler =
                    ((RequestFacadeinner).upgrade(WsHttpUpgradeHandler.class);
            wsHandler.preInit(epperSessionServerEndpointConfigscwsRequest,
                    subProtocolpathParamsreq.isSecure());
        } else {
            throw new ServletException(.upgradeFailed());
        }
    }
    /*
     * This only works for tokens. Quoted strings need more sophisticated
     * parsing.
     */
    private static boolean headerContainsToken(HttpServletRequest req,
            String headerNameString target) {
        Enumeration<Stringheaders = req.getHeaders(headerName);
        while (headers.hasMoreElements()) {
            String header = headers.nextElement();
            String[] tokens = header.split(",");
            for (String token : tokens) {
                if (target.equalsIgnoreCase(token.trim())) {
                    return true;
                }
            }
        }
        return false;
    }
    /*
     * This only works for tokens. Quoted strings need more sophisticated
     * parsing.
     */
    private static List<StringgetTokensFromHeader(HttpServletRequest req,
            String headerName) {
        List<Stringresult = new ArrayList<String>();
        Enumeration<Stringheaders = req.getHeaders(headerName);
        while (headers.hasMoreElements()) {
            String header = headers.nextElement();
            String[] tokens = header.split(",");
            for (String token : tokens) {
                result.add(token.trim());
            }
        }
        return result;
    }
    private static String getWebSocketAccept(String keythrows ServletException {
        MessageDigest sha1Helper = .poll();
        if (sha1Helper == null) {
            try {
                sha1Helper = MessageDigest.getInstance("SHA1");
            } catch (NoSuchAlgorithmException e) {
                throw new ServletException(e);
            }
        }
        sha1Helper.reset();
        sha1Helper.update(key.getBytes(StandardCharsets.ISO_8859_1));
        String result = Base64.encodeBase64String(sha1Helper.digest());
        .add(sha1Helper);
        return result;
    }
New to GrepCode? Check out our FAQ X