Search in sources :

Example 1 with QuotedStringTokenizer

use of org.eclipse.jetty.util.QuotedStringTokenizer in project jetty.project by eclipse.

the class WebSocketUpgradeRequest method upgrade.

@Override
public void upgrade(HttpResponse response, HttpConnectionOverHTTP oldConn) {
    if (!this.getHeaders().get(HttpHeader.UPGRADE).equalsIgnoreCase("websocket")) {
        // Not my upgrade
        throw new HttpResponseException("Not WebSocket Upgrade", response);
    }
    // Check the Accept hash
    String reqKey = this.getHeaders().get(HttpHeader.SEC_WEBSOCKET_KEY);
    String expectedHash = AcceptHash.hashKey(reqKey);
    String respHash = response.getHeaders().get(HttpHeader.SEC_WEBSOCKET_ACCEPT);
    if (expectedHash.equalsIgnoreCase(respHash) == false) {
        throw new HttpResponseException("Invalid Sec-WebSocket-Accept hash", response);
    }
    // We can upgrade
    EndPoint endp = oldConn.getEndPoint();
    WebSocketClientConnection connection = new WebSocketClientConnection(endp, wsClient.getExecutor(), wsClient.getScheduler(), localEndpoint.getPolicy(), wsClient.getBufferPool());
    URI requestURI = this.getURI();
    WebSocketSession session = getSessionFactory().createSession(requestURI, localEndpoint, connection);
    session.setUpgradeRequest(new ClientUpgradeRequest(this));
    session.setUpgradeResponse(new ClientUpgradeResponse(response));
    connection.addListener(session);
    ExtensionStack extensionStack = new ExtensionStack(getExtensionFactory());
    List<ExtensionConfig> extensions = new ArrayList<>();
    HttpField extField = response.getHeaders().getField(HttpHeader.SEC_WEBSOCKET_EXTENSIONS);
    if (extField != null) {
        String[] extValues = extField.getValues();
        if (extValues != null) {
            for (String extVal : extValues) {
                QuotedStringTokenizer tok = new QuotedStringTokenizer(extVal, ",");
                while (tok.hasMoreTokens()) {
                    extensions.add(ExtensionConfig.parse(tok.nextToken()));
                }
            }
        }
    }
    extensionStack.negotiate(extensions);
    extensionStack.configure(connection.getParser());
    extensionStack.configure(connection.getGenerator());
    // Setup Incoming Routing
    connection.setNextIncomingFrames(extensionStack);
    extensionStack.setNextIncoming(session);
    // Setup Outgoing Routing
    session.setOutgoingHandler(extensionStack);
    extensionStack.setNextOutgoing(connection);
    session.addManaged(extensionStack);
    session.setFuture(fut);
    wsClient.addManaged(session);
    if (upgradeListener != null) {
        upgradeListener.onHandshakeResponse(new ClientUpgradeResponse(response));
    }
    // Now swap out the connection
    endp.upgrade(connection);
}
Also used : ArrayList(java.util.ArrayList) WebSocketClientConnection(org.eclipse.jetty.websocket.client.io.WebSocketClientConnection) HttpResponseException(org.eclipse.jetty.client.HttpResponseException) EndPoint(org.eclipse.jetty.io.EndPoint) URI(java.net.URI) ExtensionStack(org.eclipse.jetty.websocket.common.extensions.ExtensionStack) WebSocketSession(org.eclipse.jetty.websocket.common.WebSocketSession) QuotedStringTokenizer(org.eclipse.jetty.util.QuotedStringTokenizer) ExtensionConfig(org.eclipse.jetty.websocket.api.extensions.ExtensionConfig) HttpField(org.eclipse.jetty.http.HttpField)

Example 2 with QuotedStringTokenizer

use of org.eclipse.jetty.util.QuotedStringTokenizer in project jetty.project by eclipse.

the class QuickStartDescriptorProcessor method visitContextParam.

/**
     * Process a context-param element
     * @param context  the webapp 
     * @param descriptor the xml file to process
     * @param node the context-param node in the xml file
     * @throws Exception
     */
public void visitContextParam(WebAppContext context, Descriptor descriptor, XmlParser.Node node) throws Exception {
    String name = node.getString("param-name", false, true);
    String value = node.getString("param-value", false, true);
    List<String> values = new ArrayList<>();
    // extract values
    switch(name) {
        case QuickStartDescriptorGenerator.ORIGIN:
            {
                //value already contains what we need
                break;
            }
        case ServletContext.ORDERED_LIBS:
        case AnnotationConfiguration.CONTAINER_INITIALIZERS:
        case MetaInfConfiguration.METAINF_TLDS:
        case MetaInfConfiguration.METAINF_RESOURCES:
            {
                context.removeAttribute(name);
                QuotedStringTokenizer tok = new QuotedStringTokenizer(value, ",");
                while (tok.hasMoreElements()) values.add(tok.nextToken().trim());
                break;
            }
        default:
            values.add(value);
    }
    AttributeNormalizer normalizer = new AttributeNormalizer(context.getBaseResource());
    // handle values
    switch(name) {
        case QuickStartDescriptorGenerator.ORIGIN:
            {
                context.setAttribute(QuickStartDescriptorGenerator.ORIGIN, value);
                break;
            }
        case ServletContext.ORDERED_LIBS:
            {
                List<Object> libs = new ArrayList<>();
                Object o = context.getAttribute(ServletContext.ORDERED_LIBS);
                if (o instanceof Collection<?>)
                    libs.addAll((Collection<?>) o);
                libs.addAll(values);
                if (libs.size() > 0)
                    context.setAttribute(ServletContext.ORDERED_LIBS, libs);
                break;
            }
        case AnnotationConfiguration.CONTAINER_INITIALIZERS:
            {
                for (String i : values) visitContainerInitializer(context, new ContainerInitializer(Thread.currentThread().getContextClassLoader(), i));
                break;
            }
        case MetaInfConfiguration.METAINF_TLDS:
            {
                List<Object> tlds = new ArrayList<>();
                Object o = context.getAttribute(MetaInfConfiguration.METAINF_TLDS);
                if (o instanceof Collection<?>)
                    tlds.addAll((Collection<?>) o);
                for (String i : values) {
                    Resource r = Resource.newResource(normalizer.expand(i));
                    if (r.exists())
                        tlds.add(r.getURI().toURL());
                    else
                        throw new IllegalArgumentException("TLD not found: " + r);
                }
                //empty list signals that tlds were prescanned but none found.
                //a missing METAINF_TLDS attribute means that prescanning was not done.
                context.setAttribute(MetaInfConfiguration.METAINF_TLDS, tlds);
                break;
            }
        case MetaInfConfiguration.METAINF_RESOURCES:
            {
                for (String i : values) {
                    Resource r = Resource.newResource(normalizer.expand(i));
                    if (r.exists())
                        visitMetaInfResource(context, r);
                    else
                        throw new IllegalArgumentException("Resource not found: " + r);
                }
                break;
            }
        default:
    }
}
Also used : QuotedStringTokenizer(org.eclipse.jetty.util.QuotedStringTokenizer) ArrayList(java.util.ArrayList) Resource(org.eclipse.jetty.util.resource.Resource) ContainerInitializer(org.eclipse.jetty.plus.annotation.ContainerInitializer) ArrayList(java.util.ArrayList) List(java.util.List)

Example 3 with QuotedStringTokenizer

use of org.eclipse.jetty.util.QuotedStringTokenizer in project jetty.project by eclipse.

the class HttpFields method valueParameters.

/**
     * Get field value parameters. Some field values can have parameters. This method separates the
     * value from the parameters and optionally populates a map with the parameters. For example:
     *
     * <PRE>
     *
     * FieldName : Value ; param1=val1 ; param2=val2
     *
     * </PRE>
     *
     * @param value The Field value, possibly with parameters.
     * @param parameters A map to populate with the parameters, or null
     * @return The value.
     */
public static String valueParameters(String value, Map<String, String> parameters) {
    if (value == null)
        return null;
    int i = value.indexOf(';');
    if (i < 0)
        return value;
    if (parameters == null)
        return value.substring(0, i).trim();
    StringTokenizer tok1 = new QuotedStringTokenizer(value.substring(i), ";", false, true);
    while (tok1.hasMoreTokens()) {
        String token = tok1.nextToken();
        StringTokenizer tok2 = new QuotedStringTokenizer(token, "= ");
        if (tok2.hasMoreTokens()) {
            String paramName = tok2.nextToken();
            String paramVal = null;
            if (tok2.hasMoreTokens())
                paramVal = tok2.nextToken();
            parameters.put(paramName, paramVal);
        }
    }
    return value.substring(0, i).trim();
}
Also used : QuotedStringTokenizer(org.eclipse.jetty.util.QuotedStringTokenizer) StringTokenizer(java.util.StringTokenizer) QuotedStringTokenizer(org.eclipse.jetty.util.QuotedStringTokenizer)

Example 4 with QuotedStringTokenizer

use of org.eclipse.jetty.util.QuotedStringTokenizer in project blade by biezhi.

the class DigestAuthenticator method validateRequest.

@Override
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException {
    if (!mandatory)
        return new DeferredAuthentication(this);
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    String credentials = request.getHeader(HttpHeader.AUTHORIZATION.asString());
    try {
        boolean stale = false;
        if (credentials != null) {
            if (LOG.isDebugEnabled())
                LOG.debug("Credentials: " + credentials);
            QuotedStringTokenizer tokenizer = new QuotedStringTokenizer(credentials, "=, ", true, false);
            final Digest digest = new Digest(request.getMethod());
            String last = null;
            String name = null;
            while (tokenizer.hasMoreTokens()) {
                String tok = tokenizer.nextToken();
                char c = (tok.length() == 1) ? tok.charAt(0) : '\0';
                switch(c) {
                    case '=':
                        name = last;
                        last = tok;
                        break;
                    case ',':
                        name = null;
                        break;
                    case ' ':
                        break;
                    default:
                        last = tok;
                        if (name != null) {
                            if ("username".equalsIgnoreCase(name))
                                digest.username = tok;
                            else if ("realm".equalsIgnoreCase(name))
                                digest.realm = tok;
                            else if ("nonce".equalsIgnoreCase(name))
                                digest.nonce = tok;
                            else if ("nc".equalsIgnoreCase(name))
                                digest.nc = tok;
                            else if ("cnonce".equalsIgnoreCase(name))
                                digest.cnonce = tok;
                            else if ("qop".equalsIgnoreCase(name))
                                digest.qop = tok;
                            else if ("uri".equalsIgnoreCase(name))
                                digest.uri = tok;
                            else if ("response".equalsIgnoreCase(name))
                                digest.response = tok;
                            name = null;
                        }
                }
            }
            int n = checkNonce(digest, (Request) request);
            if (n > 0) {
                //UserIdentity user = _loginService.login(digest.username,digest);
                UserIdentity user = login(digest.username, digest, req);
                if (user != null) {
                    return new UserAuthentication(getAuthMethod(), user);
                }
            } else if (n == 0)
                stale = true;
        }
        if (!DeferredAuthentication.isDeferred(response)) {
            String domain = request.getContextPath();
            if (domain == null)
                domain = "/";
            response.setHeader(HttpHeader.WWW_AUTHENTICATE.asString(), "Digest realm=\"" + _loginService.getName() + "\", domain=\"" + domain + "\", nonce=\"" + newNonce((Request) request) + "\", algorithm=MD5, qop=\"auth\"," + " stale=" + stale);
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return Authentication.SEND_CONTINUE;
        }
        return Authentication.UNAUTHENTICATED;
    } catch (IOException e) {
        throw new ServerAuthException(e);
    }
}
Also used : MessageDigest(java.security.MessageDigest) UserIdentity(org.eclipse.jetty.server.UserIdentity) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ServerAuthException(org.eclipse.jetty.security.ServerAuthException) UserAuthentication(org.eclipse.jetty.security.UserAuthentication) Constraint(org.eclipse.jetty.util.security.Constraint) HttpServletRequest(javax.servlet.http.HttpServletRequest) QuotedStringTokenizer(org.eclipse.jetty.util.QuotedStringTokenizer)

Example 5 with QuotedStringTokenizer

use of org.eclipse.jetty.util.QuotedStringTokenizer in project jetty.project by eclipse.

the class DigestAuthModule method validateRequest.

@Override
public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException {
    HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage();
    HttpServletResponse response = (HttpServletResponse) messageInfo.getResponseMessage();
    String credentials = request.getHeader(HttpHeader.AUTHORIZATION.asString());
    try {
        boolean stale = false;
        // TODO extract from request
        long timestamp = System.currentTimeMillis();
        if (credentials != null) {
            if (LOG.isDebugEnabled())
                LOG.debug("Credentials: " + credentials);
            QuotedStringTokenizer tokenizer = new QuotedStringTokenizer(credentials, "=, ", true, false);
            final Digest digest = new Digest(request.getMethod());
            String last = null;
            String name = null;
            while (tokenizer.hasMoreTokens()) {
                String tok = tokenizer.nextToken();
                char c = (tok.length() == 1) ? tok.charAt(0) : '\0';
                switch(c) {
                    case '=':
                        name = last;
                        last = tok;
                        break;
                    case ',':
                        name = null;
                    case ' ':
                        break;
                    default:
                        last = tok;
                        if (name != null) {
                            if ("username".equalsIgnoreCase(name))
                                digest.username = tok;
                            else if ("realm".equalsIgnoreCase(name))
                                digest.realm = tok;
                            else if ("nonce".equalsIgnoreCase(name))
                                digest.nonce = tok;
                            else if ("nc".equalsIgnoreCase(name))
                                digest.nc = tok;
                            else if ("cnonce".equalsIgnoreCase(name))
                                digest.cnonce = tok;
                            else if ("qop".equalsIgnoreCase(name))
                                digest.qop = tok;
                            else if ("uri".equalsIgnoreCase(name))
                                digest.uri = tok;
                            else if ("response".equalsIgnoreCase(name))
                                digest.response = tok;
                            break;
                        }
                }
            }
            int n = checkNonce(digest.nonce, timestamp);
            if (n > 0) {
                if (login(clientSubject, digest.username, digest, Constraint.__DIGEST_AUTH, messageInfo)) {
                    return AuthStatus.SUCCESS;
                }
            } else if (n == 0)
                stale = true;
        }
        if (!isMandatory(messageInfo)) {
            return AuthStatus.SUCCESS;
        }
        String domain = request.getContextPath();
        if (domain == null)
            domain = "/";
        response.setHeader(HttpHeader.WWW_AUTHENTICATE.asString(), "Digest realm=\"" + realmName + "\", domain=\"" + domain + "\", nonce=\"" + newNonce(timestamp) + "\", algorithm=MD5, qop=\"auth\"" + (useStale ? (" stale=" + stale) : ""));
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return AuthStatus.SEND_CONTINUE;
    } catch (IOException e) {
        throw new AuthException(e.getMessage());
    } catch (UnsupportedCallbackException e) {
        throw new AuthException(e.getMessage());
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) QuotedStringTokenizer(org.eclipse.jetty.util.QuotedStringTokenizer) MessageDigest(java.security.MessageDigest) HttpServletResponse(javax.servlet.http.HttpServletResponse) AuthException(javax.security.auth.message.AuthException) IOException(java.io.IOException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) Constraint(org.eclipse.jetty.util.security.Constraint)

Aggregations

QuotedStringTokenizer (org.eclipse.jetty.util.QuotedStringTokenizer)6 IOException (java.io.IOException)3 MessageDigest (java.security.MessageDigest)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)3 HttpServletResponse (javax.servlet.http.HttpServletResponse)3 Constraint (org.eclipse.jetty.util.security.Constraint)3 ArrayList (java.util.ArrayList)2 ServletRequest (javax.servlet.ServletRequest)2 ServerAuthException (org.eclipse.jetty.security.ServerAuthException)2 UserAuthentication (org.eclipse.jetty.security.UserAuthentication)2 Request (org.eclipse.jetty.server.Request)2 UserIdentity (org.eclipse.jetty.server.UserIdentity)2 URI (java.net.URI)1 List (java.util.List)1 StringTokenizer (java.util.StringTokenizer)1 UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)1 AuthException (javax.security.auth.message.AuthException)1 HttpResponseException (org.eclipse.jetty.client.HttpResponseException)1 HttpField (org.eclipse.jetty.http.HttpField)1 EndPoint (org.eclipse.jetty.io.EndPoint)1