Search in sources :

Example 96 with HttpString

use of io.undertow.util.HttpString in project undertow by undertow-io.

the class PushBuilderImpl method push.

@Override
public void push() {
    if (path == null) {
        throw UndertowServletMessages.MESSAGES.pathWasNotSet();
    }
    ServerConnection con = servletRequest.getExchange().getConnection();
    if (con.isPushSupported()) {
        HeaderMap newHeaders = new HeaderMap();
        for (HeaderValues entry : headers) {
            newHeaders.addAll(entry.getHeaderName(), entry);
        }
        if (sessionId != null) {
            // TODO: do this properly, may be a different tracking method or a different cookie name
            newHeaders.put(Headers.COOKIE, "JSESSIONID=" + sessionId);
        }
        String path = this.path;
        if (!path.startsWith("/")) {
            path = servletRequest.getContextPath() + "/" + path;
        }
        if (queryString != null && !queryString.isEmpty()) {
            if (path.contains("?")) {
                path += "&" + queryString;
            } else {
                path += "?" + queryString;
            }
        }
        con.pushResource(path, new HttpString(method), newHeaders);
    }
    path = null;
    for (HttpString h : CONDITIONAL) {
        headers.remove(h);
    }
}
Also used : HeaderMap(io.undertow.util.HeaderMap) HeaderValues(io.undertow.util.HeaderValues) ServerConnection(io.undertow.server.ServerConnection) HttpString(io.undertow.util.HttpString) HttpString(io.undertow.util.HttpString)

Example 97 with HttpString

use of io.undertow.util.HttpString in project indy by Commonjava.

the class BasicAuthenticationOAuthTranslator method authenticate.

@Override
public AuthenticationMechanismOutcome authenticate(final HttpServerExchange exchange, final SecurityContext securityContext) {
    if (!enabled) {
        return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
    }
    logger.debug("BASIC authenticate injector checking for " + AUTHORIZATION_HEADER + " header.");
    final HeaderMap headers = exchange.getRequestHeaders();
    final Collection<String> vals = headers.remove(AUTHORIZATION_HEADER);
    String basicAuth = null;
    String bearerAuth = null;
    final List<String> resultValues = new ArrayList<>();
    if (vals != null) {
        for (final String value : vals) {
            logger.debug("Found Authorization header: '{}'", value);
            if (value.toLowerCase().startsWith(BASIC_AUTH_PREFIX)) {
                logger.debug("detected basic auth");
                basicAuth = value;
            } else if (value.toLowerCase().startsWith(BEARER_AUTH_PREFIX)) {
                bearerAuth = value;
                resultValues.add(value);
            } else {
                resultValues.add(value);
            }
        }
    }
    if (bearerAuth == null && basicAuth != null) {
        final UserPass userPass = UserPass.parse(basicAuth);
        logger.debug("Parsed BASIC authorization: {}", userPass);
        if (userPass != null) {
            final AccessTokenResponse token = lookupToken(userPass);
            if (token != null) {
                final String encodedToken = token.getToken();
                logger.debug("Raw token: {}", encodedToken);
                final String value = BEARER_AUTH_PREFIX + " " + encodedToken;
                logger.debug("Adding {} value: {}", AUTHORIZATION_HEADER, value);
                logger.info("BASIC authentication translated into OAuth 2.0 bearer token. Handing off to Keycloak.");
                resultValues.add(value);
                // KeycloakBearerTokenDebug.debugToken( encodedToken );
                exchange.getResponseHeaders().add(new HttpString(INDY_BEARER_TOKEN), encodedToken);
            }
        }
    }
    logger.debug("Re-adding {} values: {}", AUTHORIZATION_HEADER, resultValues);
    headers.addAll(new HttpString(AUTHORIZATION_HEADER), resultValues);
    // The best we can do is lookup the token for the given basic auth fields, and inject it for keycloak to use.
    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
Also used : HeaderMap(io.undertow.util.HeaderMap) ArrayList(java.util.ArrayList) UserPass(org.commonjava.indy.subsys.http.util.UserPass) HttpString(io.undertow.util.HttpString) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) HttpString(io.undertow.util.HttpString)

Example 98 with HttpString

use of io.undertow.util.HttpString in project oap by oaplatform.

the class HttpServerExchangeStub method createHttpExchange.

@SuppressWarnings("checkstyle:OverloadMethodsDeclarationOrder")
private static HttpServerExchange createHttpExchange(ServerConnection connection, HeaderMap headerMap) {
    HttpServerExchange httpServerExchange = new HttpServerExchange(connection, new HeaderMap(), headerMap, 200);
    httpServerExchange.setRequestMethod(new HttpString("GET"));
    httpServerExchange.setProtocol(Protocols.HTTP_1_1);
    httpServerExchange.setDestinationAddress(new InetSocketAddress(8081));
    return httpServerExchange;
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) HeaderMap(io.undertow.util.HeaderMap) InetSocketAddress(java.net.InetSocketAddress) HttpString(io.undertow.util.HttpString)

Example 99 with HttpString

use of io.undertow.util.HttpString in project undertow by undertow-io.

the class HttpClientConnection method prepareResponseChannel.

private void prepareResponseChannel(ClientResponse response, ClientExchange exchange) {
    String encoding = response.getResponseHeaders().getLast(Headers.TRANSFER_ENCODING);
    boolean chunked = encoding != null && Headers.CHUNKED.equals(new HttpString(encoding));
    String length = response.getResponseHeaders().getFirst(Headers.CONTENT_LENGTH);
    if (exchange.getRequest().getMethod().equals(Methods.HEAD)) {
        connection.getSourceChannel().setConduit(new FixedLengthStreamSourceConduit(connection.getSourceChannel().getConduit(), 0, responseFinishedListener));
    } else if (chunked) {
        connection.getSourceChannel().setConduit(new ChunkedStreamSourceConduit(connection.getSourceChannel().getConduit(), pushBackStreamSourceConduit, bufferPool, responseFinishedListener, exchange, connection));
    } else if (length != null) {
        try {
            long contentLength = Long.parseLong(length);
            connection.getSourceChannel().setConduit(new FixedLengthStreamSourceConduit(connection.getSourceChannel().getConduit(), contentLength, responseFinishedListener));
        } catch (NumberFormatException e) {
            handleError(e);
            throw e;
        }
    } else if (response.getProtocol().equals(Protocols.HTTP_1_1) && !Connectors.isEntityBodyAllowed(response.getResponseCode())) {
        connection.getSourceChannel().setConduit(new FixedLengthStreamSourceConduit(connection.getSourceChannel().getConduit(), 0, responseFinishedListener));
    } else {
        connection.getSourceChannel().setConduit(new FinishableStreamSourceConduit(connection.getSourceChannel().getConduit(), responseFinishedListener));
        state |= CLOSE_REQ;
    }
}
Also used : HttpString(io.undertow.util.HttpString) FinishableStreamSourceConduit(io.undertow.conduits.FinishableStreamSourceConduit) FixedLengthStreamSourceConduit(io.undertow.conduits.FixedLengthStreamSourceConduit) ChunkedStreamSourceConduit(io.undertow.conduits.ChunkedStreamSourceConduit) HttpString(io.undertow.util.HttpString)

Example 100 with HttpString

use of io.undertow.util.HttpString in project undertow by undertow-io.

the class AjpClientRequestClientStreamSinkChannel method createFrameHeaderImpl.

private SendFrameHeader createFrameHeaderImpl() {
    if (discardMode) {
        getBuffer().clear();
        getBuffer().flip();
        return new SendFrameHeader(new ImmediatePooledByteBuffer(ByteBuffer.wrap(new byte[0])));
    }
    PooledByteBuffer pooledHeaderBuffer = getChannel().getBufferPool().allocate();
    try {
        final ByteBuffer buffer = pooledHeaderBuffer.getBuffer();
        ByteBuffer dataBuffer = getBuffer();
        int dataInBuffer = dataBuffer.remaining();
        if (!firstFrameWritten && requestedChunkSize == 0) {
            // we are waiting on a read body chunk
            return new SendFrameHeader(dataInBuffer, null);
        }
        int maxData = getChannel().getSettings().get(UndertowOptions.MAX_AJP_PACKET_SIZE, DEFAULT_MAX_DATA_SIZE) - 6;
        if (!firstFrameWritten) {
            String contentLength = headers.getFirst(Headers.CONTENT_LENGTH);
            if (contentLength != null) {
                dataSize = Long.parseLong(contentLength);
                requestedChunkSize = maxData;
                if (dataInBuffer > dataSize) {
                    throw UndertowMessages.MESSAGES.fixedLengthOverflow();
                }
            } else if (isWritesShutdown() && !headers.contains(Headers.TRANSFER_ENCODING)) {
                // writes are shut down, go to fixed length
                headers.put(Headers.CONTENT_LENGTH, dataInBuffer);
                dataSize = dataInBuffer;
                requestedChunkSize = maxData;
            } else {
                headers.put(Headers.TRANSFER_ENCODING, Headers.CHUNKED.toString());
                dataSize = -1;
                requestedChunkSize = 0;
            }
            firstFrameWritten = true;
            final String path;
            final String queryString;
            int qsIndex = this.path.indexOf('?');
            if (qsIndex == -1) {
                path = this.path;
                queryString = null;
            } else {
                path = this.path.substring(0, qsIndex);
                queryString = this.path.substring(qsIndex + 1);
            }
            buffer.put((byte) 0x12);
            buffer.put((byte) 0x34);
            // we fill the size in later
            buffer.put((byte) 0);
            buffer.put((byte) 0);
            buffer.put((byte) 2);
            boolean storeMethod = false;
            Integer methodNp = AjpConstants.HTTP_METHODS_MAP.get(method);
            if (methodNp == null) {
                methodNp = 0xFF;
                storeMethod = true;
            }
            buffer.put((byte) (int) methodNp);
            AjpUtils.putHttpString(buffer, protocol);
            putString(buffer, path);
            putString(buffer, notNull(attachable.getAttachment(ProxiedRequestAttachments.REMOTE_ADDRESS)));
            putString(buffer, notNull(attachable.getAttachment(ProxiedRequestAttachments.REMOTE_HOST)));
            putString(buffer, notNull(attachable.getAttachment(ProxiedRequestAttachments.SERVER_NAME)));
            AjpUtils.putInt(buffer, notNull(attachable.getAttachment(ProxiedRequestAttachments.SERVER_PORT)));
            buffer.put((byte) (notNull(attachable.getAttachment(ProxiedRequestAttachments.IS_SSL)) ? 1 : 0));
            int headers = 0;
            // we need to count the headers
            final HeaderMap responseHeaders = this.headers;
            for (HttpString name : responseHeaders.getHeaderNames()) {
                headers += responseHeaders.get(name).size();
            }
            AjpUtils.putInt(buffer, headers);
            for (final HttpString header : responseHeaders.getHeaderNames()) {
                for (String headerValue : responseHeaders.get(header)) {
                    Integer headerCode = AjpConstants.HEADER_MAP.get(header);
                    if (headerCode != null) {
                        AjpUtils.putInt(buffer, headerCode);
                    } else {
                        AjpUtils.putHttpString(buffer, header);
                    }
                    putString(buffer, headerValue);
                }
            }
            if (queryString != null) {
                // query_string
                buffer.put((byte) ATTR_QUERY_STRING);
                putString(buffer, queryString);
            }
            String remoteUser = attachable.getAttachment(ProxiedRequestAttachments.REMOTE_USER);
            if (remoteUser != null) {
                buffer.put((byte) ATTR_REMOTE_USER);
                putString(buffer, remoteUser);
            }
            String authType = attachable.getAttachment(ProxiedRequestAttachments.AUTH_TYPE);
            if (authType != null) {
                buffer.put((byte) ATTR_AUTH_TYPE);
                putString(buffer, authType);
            }
            String route = attachable.getAttachment(ProxiedRequestAttachments.ROUTE);
            if (route != null) {
                buffer.put((byte) ATTR_ROUTE);
                putString(buffer, route);
            }
            String sslCert = attachable.getAttachment(ProxiedRequestAttachments.SSL_CERT);
            if (sslCert != null) {
                buffer.put((byte) ATTR_SSL_CERT);
                putString(buffer, sslCert);
            }
            String sslCypher = attachable.getAttachment(ProxiedRequestAttachments.SSL_CYPHER);
            if (sslCypher != null) {
                buffer.put((byte) ATTR_SSL_CIPHER);
                putString(buffer, sslCypher);
            }
            byte[] sslSession = attachable.getAttachment(ProxiedRequestAttachments.SSL_SESSION_ID);
            if (sslSession != null) {
                buffer.put((byte) ATTR_SSL_SESSION);
                putString(buffer, HexConverter.convertToHexString(sslSession));
            }
            Integer sslKeySize = attachable.getAttachment(ProxiedRequestAttachments.SSL_KEY_SIZE);
            if (sslKeySize != null) {
                buffer.put((byte) ATTR_SSL_KEY_SIZE);
                putString(buffer, sslKeySize.toString());
            }
            String secret = attachable.getAttachment(ProxiedRequestAttachments.SECRET);
            if (secret != null) {
                buffer.put((byte) ATTR_SECRET);
                putString(buffer, secret);
            }
            if (storeMethod) {
                buffer.put((byte) ATTR_STORED_METHOD);
                putString(buffer, method.toString());
            }
            buffer.put((byte) 0xFF);
            int dataLength = buffer.position() - 4;
            buffer.put(2, (byte) ((dataLength >> 8) & 0xFF));
            buffer.put(3, (byte) (dataLength & 0xFF));
        }
        if (dataSize == 0) {
            // no data, just write out this frame and we are done
            buffer.flip();
            return new SendFrameHeader(pooledHeaderBuffer);
        } else if (requestedChunkSize > 0) {
            if (isWritesShutdown() && dataInBuffer == 0) {
                buffer.put((byte) 0x12);
                buffer.put((byte) 0x34);
                buffer.put((byte) 0x00);
                buffer.put((byte) 0x02);
                buffer.put((byte) 0x00);
                buffer.put((byte) 0x00);
                buffer.flip();
                return new SendFrameHeader(pooledHeaderBuffer);
            }
            int remaining = dataInBuffer;
            remaining = Math.min(remaining, maxData);
            remaining = Math.min(remaining, requestedChunkSize);
            int bodySize = remaining + 2;
            buffer.put((byte) 0x12);
            buffer.put((byte) 0x34);
            buffer.put((byte) ((bodySize >> 8) & 0xFF));
            buffer.put((byte) (bodySize & 0xFF));
            buffer.put((byte) ((remaining >> 8) & 0xFF));
            buffer.put((byte) (remaining & 0xFF));
            requestedChunkSize = 0;
            if (remaining < dataInBuffer) {
                dataBuffer.limit(getBuffer().position() + remaining);
                buffer.flip();
                return new SendFrameHeader(dataInBuffer - remaining, pooledHeaderBuffer, dataSize < 0);
            } else {
                buffer.flip();
                return new SendFrameHeader(0, pooledHeaderBuffer, dataSize < 0);
            }
        } else {
            // chunked. We just write the headers, and leave all the data in the buffer
            // they need to send us a read body chunk in order to get any data
            buffer.flip();
            if (buffer.remaining() == 0) {
                pooledHeaderBuffer.close();
                return new SendFrameHeader(dataInBuffer, null, true);
            }
            dataBuffer.limit(dataBuffer.position());
            return new SendFrameHeader(dataInBuffer, pooledHeaderBuffer, true);
        }
    } catch (BufferOverflowException e) {
        // TODO: UNDERTOW-901
        pooledHeaderBuffer.close();
        markBroken();
        throw e;
    }
}
Also used : HeaderMap(io.undertow.util.HeaderMap) ImmediatePooledByteBuffer(io.undertow.util.ImmediatePooledByteBuffer) PooledByteBuffer(io.undertow.connector.PooledByteBuffer) AjpUtils.putString(io.undertow.protocols.ajp.AjpUtils.putString) HttpString(io.undertow.util.HttpString) BufferOverflowException(java.nio.BufferOverflowException) SendFrameHeader(io.undertow.server.protocol.framed.SendFrameHeader) ByteBuffer(java.nio.ByteBuffer) ImmediatePooledByteBuffer(io.undertow.util.ImmediatePooledByteBuffer) PooledByteBuffer(io.undertow.connector.PooledByteBuffer) ImmediatePooledByteBuffer(io.undertow.util.ImmediatePooledByteBuffer) HttpString(io.undertow.util.HttpString)

Aggregations

HttpString (io.undertow.util.HttpString)147 HeaderMap (io.undertow.util.HeaderMap)31 HttpServerExchange (io.undertow.server.HttpServerExchange)27 Test (org.junit.Test)25 ClientRequest (io.undertow.client.ClientRequest)23 Map (java.util.Map)23 ClientResponse (io.undertow.client.ClientResponse)21 IOException (java.io.IOException)21 HashMap (java.util.HashMap)21 URI (java.net.URI)19 ClientConnection (io.undertow.client.ClientConnection)17 HttpHandler (io.undertow.server.HttpHandler)17 Http2Client (com.networknt.client.Http2Client)14 ClientException (com.networknt.exception.ClientException)14 AtomicReference (java.util.concurrent.atomic.AtomicReference)14 User (com.networknt.portal.usermanagement.model.common.model.user.User)13 URISyntaxException (java.net.URISyntaxException)13 ArrayList (java.util.ArrayList)13 List (java.util.List)13 CountDownLatch (java.util.concurrent.CountDownLatch)11