io.undertow.util.HeaderValues Java Examples

The following examples show how to use io.undertow.util.HeaderValues. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JsonContentHandler.java    From divolte-collector with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final HeaderValues contentType = exchange.getRequestHeaders().get(Headers.CONTENT_TYPE);
    if (null != contentType
            && contentType.size() == 1
            && contentType.getFirst().toLowerCase(Locale.ROOT).equals("application/json")) {
        next.handleRequest(exchange);
    } else {
        exchange.setStatusCode(StatusCodes.UNSUPPORTED_MEDIA_TYPE);
        exchange.getResponseHeaders()
                .put(Headers.CONTENT_TYPE, "text/plain; charset=utf-8");
        exchange.getResponseSender()
                .send("Content type must be application/json.", StandardCharsets.UTF_8);
        exchange.endExchange();
    }
}
 
Example #2
Source File: OpenApiHandler.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
public static Map<String, ?> getHeaderParameters(final HttpServerExchange exchange, final boolean deserializedValueOnly){
	Map<String, Object> deserializedHeaderParamters = exchange.getAttachment(DESERIALIZED_HEADER_PARAMETERS);
	
	if (!deserializedValueOnly) {
		HeaderMap headers = exchange.getRequestHeaders();
		
		if (null==headers) {
			return Collections.emptyMap();
		}
		
		Map<String, HeaderValues> headerMap = new HashMap<>();
		
		for (HttpString headerName: headers.getHeaderNames()) {
			headerMap.put(headerName.toString(), headers.get(headerName));
		}
		
		return mergeMaps(deserializedHeaderParamters, headerMap);
	}
	
	return nonNullMap(deserializedHeaderParamters);
}
 
Example #3
Source File: RequestValidator.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
private Status validateHeader(final HttpServerExchange exchange,
                              final SwaggerOperation swaggerOperation,
                              final Parameter headerParameter) {

    final HeaderValues headerValues = exchange.getRequestHeaders().get(headerParameter.getName());
    if ((headerValues == null || headerValues.isEmpty())) {
        if(headerParameter.getRequired()) {
            return new Status(VALIDATOR_REQUEST_PARAMETER_HEADER_MISSING, headerParameter.getName(), swaggerOperation.getPathString().original());
        }
    } else {

        Optional<Status> optional = headerValues
                .stream()
                .map((v) -> parameterValidators.validate(v, headerParameter))
                .filter(s -> s != null)
                .findFirst();
        if(optional.isPresent()) {
            return optional.get();
        }
    }
    return null;
}
 
Example #4
Source File: RequestValidator.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
private Status validateHeader(final HttpServerExchange exchange,
                              final OpenApiOperation openApiOperation,
                              final Parameter headerParameter) {
    final HeaderValues headerValues = exchange.getRequestHeaders().get(new HttpString(headerParameter.getName()));
    if ((headerValues == null || headerValues.isEmpty())) {
        if(headerParameter.getRequired()) {
            return new Status(VALIDATOR_REQUEST_PARAMETER_HEADER_MISSING, headerParameter.getName(), openApiOperation.getPathString().original());
        }
    } else {
        Optional<Status> optional = headerValues
                .stream()
                .map((v) -> schemaValidator.validate(v, Overlay.toJson((SchemaImpl)headerParameter.getSchema()), headerParameter.getName()))
                .filter(s -> s != null)
                .findFirst();
        return optional.orElse(null);
    }
    return null;
}
 
Example #5
Source File: ResponseValidator.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
private Status validateHeader(HttpServerExchange exchange, String headerName, Header operationHeader) {
    final HeaderValues headerValues = exchange.getResponseHeaders().get(headerName);
    SchemaValidatorsConfig config = new SchemaValidatorsConfig();
    //header won't tell if it's a real string or not. needs trying to convert.
    config.setTypeLoose(true);
    config.setHandleNullableField(ValidatorHandler.config.isHandleNullableField());
    if ((headerValues == null || headerValues.isEmpty())) {
        if(Boolean.TRUE.equals(operationHeader.getRequired())) {
            return new Status(REQUIRED_RESPONSE_HEADER_MISSING, headerName);
        }
    } else {
        Optional<Status> optional = headerValues
                .stream()
                .map((v) -> schemaValidator.validate(v, Overlay.toJson((SchemaImpl)operationHeader.getSchema()),  config))
                .filter(s -> s != null)
                .findFirst();
        if(optional.isPresent()) {
            return optional.get();
        }
    }
    return null;
}
 
Example #6
Source File: CorsHttpHandler.java    From light-4j with Apache License 2.0 6 votes vote down vote up
private void setCorsResponseHeaders(HttpServerExchange exchange) throws Exception {
    HeaderMap headers = exchange.getRequestHeaders();
    if (headers.contains(Headers.ORIGIN)) {
        if(matchOrigin(exchange, allowedOrigins) != null) {
            exchange.getResponseHeaders().addAll(ACCESS_CONTROL_ALLOW_ORIGIN, headers.get(Headers.ORIGIN));
            exchange.getResponseHeaders().add(Headers.VARY, Headers.ORIGIN_STRING);
        }
    }
    exchange.getResponseHeaders().addAll(ACCESS_CONTROL_ALLOW_METHODS, allowedMethods);
    HeaderValues requestedHeaders = headers.get(ACCESS_CONTROL_REQUEST_HEADERS);
    if (requestedHeaders != null && !requestedHeaders.isEmpty()) {
        exchange.getResponseHeaders().addAll(ACCESS_CONTROL_ALLOW_HEADERS, requestedHeaders);
    } else {
        exchange.getResponseHeaders().add(ACCESS_CONTROL_ALLOW_HEADERS, Headers.CONTENT_TYPE_STRING);
        exchange.getResponseHeaders().add(ACCESS_CONTROL_ALLOW_HEADERS, Headers.WWW_AUTHENTICATE_STRING);
        exchange.getResponseHeaders().add(ACCESS_CONTROL_ALLOW_HEADERS, Headers.AUTHORIZATION_STRING);
    }
    exchange.getResponseHeaders().add(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
    exchange.getResponseHeaders().add(ACCESS_CONTROL_MAX_AGE, ONE_HOUR_IN_SECONDS);
}
 
Example #7
Source File: HttpResponseConduit.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private boolean flushHeaderBuffer(ByteBuffer buffer, String string, HeaderValues headerValues, int charIndex, long fiCookie, int valueIdx) throws IOException {
    int res;
    buffer.flip();
    do {
        res = next.write(buffer);
        if (res == 0) {
            this.string = string;
            this.headerValues = headerValues;
            this.charIndex = charIndex;
            this.fiCookie = fiCookie;
            this.valueIdx = valueIdx;
            return true;
        }
    } while (buffer.hasRemaining());
    buffer.clear();
    return false;
}
 
Example #8
Source File: LocaleHandler.java    From mangooio with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    Locale locale = Locale.forLanguageTag(this.config.getApplicationLanguage());
    Attachment attachment = exchange.getAttachment(RequestUtils.getAttachmentKey());

    Cookie i18nCookie = exchange.getRequestCookies().get(this.config.getI18nCookieName());
    if (i18nCookie == null) {
        final HeaderValues headerValues = exchange.getRequestHeaders().get(Header.ACCEPT_LANGUAGE.toHttpString());
        if (headerValues != null) {
            String acceptLanguage = headerValues.element();
            if (StringUtils.isNotBlank(acceptLanguage)) {
                locale = LocaleUtils.getLocaleFromString(acceptLanguage);
            }
        }
    } else {
        locale = LocaleUtils.getLocaleFromString(i18nCookie.getValue());
    }

    attachment.getMessages().reload(locale);
    attachment.withLocale(locale);
    
    exchange.putAttachment(RequestUtils.getAttachmentKey(), attachment);
    nextHandler(exchange);
}
 
Example #9
Source File: ServerSentEventHandler.java    From mangooio with Apache License 2.0 6 votes vote down vote up
@Override
public void connected(ServerSentEventConnection connection, String lastEventId) {
    if (this.hasAuthentication) {
        String header = null;
        HeaderValues headerValues = connection.getRequestHeaders().get(Header.COOKIE.toHttpString());
        if (headerValues != null) {
            header = headerValues.element();
        }

        if (RequestUtils.hasValidAuthentication(header)) {
            Application.getInstance(ServerSentEventService.class).addConnection(connection);
            connection.addCloseTask(Application.getInstance(ServerSentEventCloseListener.class));
        } else {
            MangooUtils.closeQuietly(connection);
        }
    } else {
        Application.getInstance(ServerSentEventService.class).addConnection(connection);
        connection.addCloseTask(Application.getInstance(ServerSentEventCloseListener.class));
    }
}
 
Example #10
Source File: RequestHeaderAttribute.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public String readAttribute(final HttpServerExchange exchange) {
    HeaderValues header = exchange.getRequestHeaders().get(requestHeader);
    if (header == null) {
        return null;
    } else if(header.size() == 1) {
        return header.getFirst();
    }
    StringBuilder sb = new StringBuilder();
    sb.append("[");
    for (int i = 0; i < header.size(); ++i) {
        if (i != 0) {
            sb.append(", ");
        }
        sb.append(header.get(i));
    }
    sb.append("]");
    return sb.toString();
}
 
Example #11
Source File: ResponseHeaderAttribute.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public String readAttribute(final HttpServerExchange exchange) {
    HeaderValues header = exchange.getResponseHeaders().get(responseHeader);
    if (header == null) {
        return null;
    } else if(header.size() == 1) {
        return header.getFirst();
    }
    StringBuilder sb = new StringBuilder();
    sb.append("[");
    for (int i = 0; i < header.size(); ++i) {
        if (i != 0) {
            sb.append(", ");
        }
        sb.append(header.get(i));
    }
    sb.append("]");
    return sb.toString();
}
 
Example #12
Source File: DomainUtil.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static String determineMimeType(OperationResponse.StreamEntry entry, HttpServerExchange exchange) {
    // We see if the type provided by the response "matches" the ACCEPT header; if yes, use it
    // If not, use application/octet-stream to trigger the browser to treat it as a download
    String entryType = entry.getMimeType();
    HeaderValues headerValues = exchange.getRequestHeaders().get(Headers.ACCEPT);
    if (headerValues == null || headerValues.size() == 0) {
        // The browser doesn't care
        return entryType;
    }
    String wildCard = null;
    int slash = entryType.indexOf('/');
    if (slash > 0) {
        wildCard = entryType.substring(0, slash) + "/*";
    }
    for (String acceptable : headerValues) {
        if ("*/*".equals(acceptable) || acceptable.contains(entryType) || (wildCard != null && acceptable.contains(wildCard))) {
            return entryType;
        }
    }

    return "application/octet-stream";
}
 
Example #13
Source File: CorsHttpHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void setCorsResponseHeaders(HttpServerExchange exchange) throws Exception {
    HeaderMap headers = exchange.getRequestHeaders();
    if (headers.contains(Headers.ORIGIN)) {
        if(matchOrigin(exchange, allowedOrigins) != null) {
            exchange.getResponseHeaders().addAll(ACCESS_CONTROL_ALLOW_ORIGIN, headers.get(Headers.ORIGIN));
            exchange.getResponseHeaders().add(Headers.VARY, Headers.ORIGIN_STRING);
        }
    }
    HeaderValues requestedMethods = headers.get(ACCESS_CONTROL_REQUEST_METHOD);
    if (requestedMethods != null && !requestedMethods.isEmpty()) {
        exchange.getResponseHeaders().addAll(ACCESS_CONTROL_ALLOW_METHODS, requestedMethods);
    } else {
        exchange.getResponseHeaders().addAll(ACCESS_CONTROL_ALLOW_METHODS, Arrays.asList(new String[]{Methods.GET_STRING, Methods.POST_STRING}));
    }
    HeaderValues requestedHeaders = headers.get(ACCESS_CONTROL_REQUEST_HEADERS);
    if (requestedHeaders != null && !requestedHeaders.isEmpty()) {
        exchange.getResponseHeaders().addAll(ACCESS_CONTROL_ALLOW_HEADERS, requestedHeaders);
    } else {
        exchange.getResponseHeaders().add(ACCESS_CONTROL_ALLOW_HEADERS, Headers.CONTENT_TYPE_STRING);
        exchange.getResponseHeaders().add(ACCESS_CONTROL_ALLOW_HEADERS, Headers.WWW_AUTHENTICATE_STRING);
        exchange.getResponseHeaders().add(ACCESS_CONTROL_ALLOW_HEADERS, Headers.AUTHORIZATION_STRING);
    }
    exchange.getResponseHeaders().add(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
    exchange.getResponseHeaders().add(ACCESS_CONTROL_MAX_AGE, ONE_HOUR_IN_SECONDS);
}
 
Example #14
Source File: ClientTest.java    From pnc with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRetryFailedConnection() throws RemoteResourceException {

    AtomicInteger requestsReceived = new AtomicInteger(0);
    AtomicReference<String> headerReceived = new AtomicReference<>();

    Undertow server = Undertow.builder().addHttpListener(8080, "localhost").setHandler(new HttpHandler() {
        @Override
        public void handleRequest(final HttpServerExchange exchange) throws Exception {
            requestsReceived.incrementAndGet();
            String headerName = MDCUtils.getMDCToHeaderMappings().get(MDCKeys.REQUEST_CONTEXT_KEY);
            HeaderValues strings = exchange.getRequestHeaders().get(headerName);
            if (strings != null) {
                headerReceived.set(strings.getFirst());
            }
            exchange.getConnection().close();
        }
    }).build();
    server.start();

    Configuration configuration = getBasicConfiguration(8080).addDefaultMdcToHeadersMappings().build();

    ProjectClient projectClient = new ProjectClient(configuration);

    String requestContext = "12345";
    MDC.put(MDCKeys.REQUEST_CONTEXT_KEY, requestContext);
    try {
        projectClient.getSpecific("1");
    } catch (javax.ws.rs.ProcessingException | ClientException e) {
        // expected
    }

    Assert.assertTrue(requestsReceived.intValue() > 2);
    Assert.assertEquals(requestContext, headerReceived.get());
    System.out.println("Done!");
}
 
Example #15
Source File: LimitHandler.java    From mangooio with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a key for used for limit an request containing the
 * requested url and the source host
 * 
 * @param exchange The HttpServerExchange
 * @return The key url + host
 */
private String getCacheKey(HttpServerExchange exchange) {
    String host = "";

    HeaderMap headerMap = exchange.getRequestHeaders();
    if (headerMap != null) {
        HeaderValues headerValues = headerMap.get(Header.X_FORWARDED_FOR.toHttpString());
        if (headerValues != null) {
            host = headerValues.element();
        }
    }
    
    if (StringUtils.isBlank(host)) {
        InetSocketAddress inetSocketAddress = exchange.getSourceAddress();
        if (inetSocketAddress != null) {
            host = inetSocketAddress.getHostString();
        }
    }
    
    if (StringUtils.isNotBlank(host)) {
        host = host.toLowerCase(Locale.ENGLISH);
    }
    
    String url = exchange.getRequestURL();
    if (StringUtils.isNotBlank(url)) {
        url = url.toLowerCase(Locale.ENGLISH);
    }
    
    return url + host;
}
 
Example #16
Source File: UndertowLogbackAccessEvent.java    From logback-access-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public Map<String, String> buildResponseHeaderMap() {
    Map<String, String> result = new HashMap<>();
    HeaderMap headers = exchange.getResponseHeaders();
    for (HeaderValues header : headers) {
        result.put(header.getHeaderName().toString(), header.getFirst());
    }
    return result;
}
 
Example #17
Source File: RequestParser.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
private void logHeaders(HeaderMap headers) {
    for (HeaderValues header : headers) {
        HttpString name = header.getHeaderName();
        if (!Headers.COOKIE.equals(name)) {
            logger.debug("[request:header] {}={}", name, new HeaderLogParam(name, header));
        }
    }
}
 
Example #18
Source File: RequestParser.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
void parseCookies(RequestImpl request, HttpServerExchange exchange) {
    HeaderValues cookieHeaders = exchange.getRequestHeaders().get(Headers.COOKIE);
    if (cookieHeaders != null) {
        try {
            request.cookies = decodeCookies(exchange.getRequestCookies());
        } catch (IllegalArgumentException e) {
            logger.debug("[request:header] {}={}", Headers.COOKIE, new HeaderLogParam(Headers.COOKIE, cookieHeaders));
            // entire cookie will be failed to parse if there is poison cookie value, undertow doesn't provide API to parse cookie individually
            // since it's rare case, here is to use simplified solution to block entire request, rather than hide which may cause potential issues, e.g. never get SESSION_ID to login
            // so this force client to clear all cookies and refresh
            throw new BadRequestException("invalid cookie", "INVALID_COOKIE", e);
        }
    }
}
 
Example #19
Source File: MetricsHttpHandler.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {

    String requestPath = exchange.getRequestPath();

    if (dispatched.get() != null && dispatched.get().getCount() == 1) {
        next.handleRequest(exchange);
        dispatched.set(null);
        return;
    }

    if (!requestPath.startsWith("/metrics")) {
        next.handleRequest(exchange);
        return;
    }

    String method = exchange.getRequestMethod().toString();
    HeaderValues acceptHeaders = exchange.getRequestHeaders().get(Headers.ACCEPT);
    metricsHandler.handleRequest(requestPath, method, acceptHeaders == null ? null : acceptHeaders.stream(), (status, message, headers) -> {
        exchange.setStatusCode(status);
        headers.forEach(
                (key, value) -> exchange.getResponseHeaders().put(new HttpString(key), value)
        );
        exchange.getResponseSender().send(message);
    });

}
 
Example #20
Source File: TokenManager.java    From light-4j with Apache License 2.0 5 votes vote down vote up
/**
 * get a Jwt with a provided clientRequest,
 * it will get token based on Jwt.Key (either scope or service_id)
 * if the user declared both scope and service_id in header, it will get jwt based on scope
 * @param clientRequest client request
 * @return Result
 */
public Result<Jwt> getJwt(ClientRequest clientRequest) {
    HeaderValues scope = clientRequest.getRequestHeaders().get(ClientConfig.SCOPE);
    if(scope != null) {
        String scopeStr = scope.getFirst();
        Set<String> scopeSet = new HashSet<>();
        scopeSet.addAll(Arrays.asList(scopeStr.split(" ")));
        return getJwt(new Jwt.Key(scopeSet));
    }
    HeaderValues serviceId = clientRequest.getRequestHeaders().get(ClientConfig.SERVICE_ID);
    if(serviceId != null) {
        return getJwt(new Jwt.Key(serviceId.getFirst()));
    }
    return getJwt(new Jwt.Key());
}
 
Example #21
Source File: SanitizerHandler.java    From light-4j with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    String method = exchange.getRequestMethod().toString();
    if (config.isSanitizeHeader()) {
        HeaderMap headerMap = exchange.getRequestHeaders();
        if (headerMap != null) {
            for (HeaderValues values : headerMap) {
                if (values != null) {
                    ListIterator<String> itValues = values.listIterator();
                    while (itValues.hasNext()) {
                        itValues.set(encoding.applyEncoding(itValues.next()));
                    }
                }
            }
        }
    }

    if (config.isSanitizeBody() && ("POST".equalsIgnoreCase(method) || "PUT".equalsIgnoreCase(method) || "PATCH".equalsIgnoreCase(method))) {
        // assume that body parser is installed before this middleware and body is parsed as a map.
        // we are talking about JSON api now.
        Object body = exchange.getAttachment(BodyHandler.REQUEST_BODY);
        if (body != null) {
            if(body instanceof List) {
                encoding.encodeList((List<Map<String, Object>>)body);
            } else {
                // assume it is a map here.
                encoding.encodeNode((Map<String, Object>)body);
            }
        }
    }
    Handler.next(exchange, next);
}
 
Example #22
Source File: HttpServerExchangeAdaptor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
public String getHeader(HttpServerExchange request, String name) {
    final HeaderValues values = request.getRequestHeaders().get(name);
    if (values != null) {
        return values.peekFirst();
    }
    return null;
}
 
Example #23
Source File: UndertowHeadersAdapter.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@Nullable
public List<String> put(String key, List<String> value) {
	HeaderValues previousValues = this.headers.get(key);
	this.headers.putAll(HttpString.tryFromString(key), value);
	return previousValues;
}
 
Example #24
Source File: HttpTraceHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    if(exchange.getRequestMethod().equals(Methods.TRACE)) {
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "message/http");
        StringBuilder body = new StringBuilder("TRACE ");
        body.append(exchange.getRequestURI());
        if(!exchange.getQueryString().isEmpty()) {
            body.append('?');
            body.append(exchange.getQueryString());
        }
        body.append(' ');
        body.append(exchange.getProtocol().toString());
        body.append("\r\n");
        for(HeaderValues header : exchange.getRequestHeaders()) {
            for(String value : header) {
                body.append(header.getHeaderName());
                body.append(": ");
                body.append(value);
                body.append("\r\n");
            }
        }
        body.append("\r\n");
        exchange.getResponseSender().send(body.toString());
    } else {
        handler.handleRequest(exchange);
    }
}
 
Example #25
Source File: ProxyHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
static void copyHeaders(final HeaderMap to, final HeaderMap from) {
    long f = from.fastIterateNonEmpty();
    HeaderValues values;
    while (f != -1L) {
        values = from.fiCurrent(f);
        if(!to.contains(values.getHeaderName())) {
            //don't over write existing headers, normally the map will be empty, if it is not we assume it is not for a reason
            to.putAll(values.getHeaderName(), values);
        }
        f = from.fiNextNonEmpty(f);
    }
}
 
Example #26
Source File: RequestDumpingHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void dumpRequestBody(HttpServerExchange exchange, StringBuilder sb) {
    try {
        FormData formData = exchange.getAttachment(FormDataParser.FORM_DATA);
        if (formData != null) {
            sb.append("body=\n");

            for (String formField : formData) {
                Deque<FormData.FormValue> formValues = formData.get(formField);

                sb.append(formField)
                        .append("=");
                for (FormData.FormValue formValue : formValues) {
                    sb.append(formValue.isFile() ? "[file-content]" : formValue.getValue());
                    sb.append("\n");

                    if (formValue.getHeaders() != null) {
                        sb.append("headers=\n");
                        for (HeaderValues header : formValue.getHeaders()) {
                            sb.append("\t")
                                    .append(header.getHeaderName()).append("=").append(header.getFirst()).append("\n");

                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #27
Source File: ForwardedHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    HeaderValues forwarded = exchange.getRequestHeaders().get(Headers.FORWARDED);
    if (forwarded != null) {
        Map<Token, String> values = new HashMap<>();
        for (String val : forwarded) {
            parseHeader(val, values);
        }
        String host = values.get(Token.HOST);
        String proto = values.get(Token.PROTO);
        String by = values.get(Token.BY);
        String forVal = values.get(Token.FOR);

        if (host != null) {
            exchange.getRequestHeaders().put(Headers.HOST, host);
            exchange.setDestinationAddress(InetSocketAddress.createUnresolved(exchange.getHostName(), exchange.getHostPort()));
        } else if (by != null) {
            //we only use 'by' if the host is null
            InetSocketAddress destAddress = parseAddress(by);
            if (destAddress != null) {
                exchange.setDestinationAddress(destAddress);
            }
        }
        if (proto != null) {
            exchange.setRequestScheme(proto);
        }
        if (forVal != null) {
            InetSocketAddress sourceAddress = parseAddress(forVal);
            if (sourceAddress != null) {
                exchange.setSourceAddress(sourceAddress);
            }
        }
    }


    next.handleRequest(exchange);
}
 
Example #28
Source File: Connectors.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Verifies that the provided request headers are valid according to rfc7230. In particular:
 * - At most one content-length or transfer encoding
 */
public static boolean areRequestHeadersValid(HeaderMap headers) {
    HeaderValues te = headers.get(Headers.TRANSFER_ENCODING);
    HeaderValues cl = headers.get(Headers.CONTENT_LENGTH);
    if(te != null && cl != null) {
        return false;
    } else if(te != null && te.size() > 1) {
        return false;
    } else if(cl != null && cl.size() > 1) {
        return false;
    }
    return true;
}
 
Example #29
Source File: UndertowHeadersAdapter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@Nullable
public List<String> put(String key, List<String> value) {
	HeaderValues previousValues = this.headers.get(key);
	this.headers.putAll(HttpString.tryFromString(key), value);
	return previousValues;
}
 
Example #30
Source File: SavedRequest.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public static void trySaveRequest(final HttpServerExchange exchange, final byte[] buffer, int length) {
    int maxSize = exchange.getConnection().getUndertowOptions().get(UndertowOptions.MAX_BUFFERED_REQUEST_SIZE, UndertowOptions.DEFAULT_MAX_BUFFERED_REQUEST_SIZE);
    if (maxSize > 0) {
        if (length > maxSize) {
            UndertowLogger.REQUEST_LOGGER.debugf("Request to %s was to large to save", exchange.getRequestURI());
            return;//failed to save the request, we just return
        }
        //TODO: we should really be used pooled buffers
        //TODO: we should probably limit the number of saved requests at any given time
        HeaderMap headers = new HeaderMap();
        for (HeaderValues entry : exchange.getRequestHeaders()) {
            if (entry.getHeaderName().equals(Headers.CONTENT_LENGTH) ||
                    entry.getHeaderName().equals(Headers.TRANSFER_ENCODING) ||
                    entry.getHeaderName().equals(Headers.CONNECTION)) {
                continue;
            }
            headers.putAll(entry.getHeaderName(), entry);
        }
        SavedRequest request = new SavedRequest(buffer, length, exchange.getRequestMethod(), exchange.getRelativePath(), exchange.getRequestHeaders());
        final ServletRequestContext sc = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
        HttpSessionImpl session = sc.getCurrentServletContext().getSession(exchange, true);
        Session underlyingSession;
        if (System.getSecurityManager() == null) {
            underlyingSession = session.getSession();
        } else {
            underlyingSession = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(session));
        }
        underlyingSession.setAttribute(SESSION_KEY, request);
    }
}