<commit_before>/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2015 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * Licensed 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.wildfly.elytron.web.undertow.server;

import static org.wildfly.common.Assert.checkNotNullParam;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import javax.net.ssl.SSLSession;

import org.wildfly.security.auth.server.SecurityIdentity;
import org.wildfly.security.http.HttpAuthenticationException;
import org.wildfly.security.http.HttpExchangeSpi;
import org.wildfly.security.http.HttpScope;
import org.wildfly.security.http.HttpScopeNotification;
import org.wildfly.security.http.HttpServerCookie;
import org.wildfly.security.http.Scope;

import io.undertow.security.api.SecurityContext;
import io.undertow.server.HttpServerExchange;
import io.undertow.server.ServerConnection;
import io.undertow.server.handlers.Cookie;
import io.undertow.server.handlers.CookieImpl;
import io.undertow.server.handlers.form.FormData;
import io.undertow.server.handlers.form.FormData.FormValue;
import io.undertow.server.handlers.form.FormDataParser;
import io.undertow.server.handlers.form.FormParserFactory;
import io.undertow.server.protocol.http.HttpServerConnection;
import io.undertow.server.session.Session;
import io.undertow.server.session.SessionConfig;
import io.undertow.server.session.SessionManager;
import io.undertow.util.AbstractAttachable;
import io.undertow.util.AttachmentKey;
import io.undertow.util.HttpString;

/**
 * Implementation of {@link HttpExchangeSpi} to wrap access to the Undertow specific {@link HttpServerExchange}.
 *
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 */
public class ElytronHttpExchange implements HttpExchangeSpi {

    private static final AttachmentKey<HttpScope> HTTP_SCOPE_ATTACHMENT_KEY = AttachmentKey.create(HttpScope.class);

    private final HttpServerExchange httpServerExchange;
    private final Map<Scope, Function<HttpServerExchange, HttpScope>> scopeResolvers;
    private final ScopeSessionListener scopeSessionListener;
    private final FormParserFactory formParserFactory = FormParserFactory.builder().build();

    private Map<String, List<String>> requestParameters;

    protected ElytronHttpExchange(final HttpServerExchange httpServerExchange,
            final Map<Scope, Function<HttpServerExchange, HttpScope>> scopeResolvers,
            final ScopeSessionListener scopeSessionListener) {
        this.httpServerExchange = checkNotNullParam("httpServerExchange", httpServerExchange);
        this.scopeResolvers = scopeResolvers;
        this.scopeSessionListener = scopeSessionListener;
    }

    protected ElytronHttpExchange(final HttpServerExchange httpServerExchange) {
        this(httpServerExchange, Collections.emptyMap(), null);
    }

    /**
     * @see org.wildfly.security.http.HttpExchangeSpi#getRequestHeaderValues(java.lang.String)
     */
    @Override
    public List<String> getRequestHeaderValues(String headerName) {
        return httpServerExchange.getRequestHeaders().get(headerName);
    }

    /**
     * @see org.wildfly.security.http.HttpExchangeSpi#addResponseHeader(java.lang.String, java.lang.String)
     */
    @Override
    public void addResponseHeader(String headerName, String headerValue) {
        httpServerExchange.getResponseHeaders().add(new HttpString(headerName), headerValue);
    }

    /**
     * @see org.wildfly.security.http.HttpExchangeSpi#getSSLSession()
     */
    @Override
    public SSLSession getSSLSession() {
        ServerConnection connection = httpServerExchange.getConnection();
        if (connection instanceof HttpServerConnection) {
            return ((HttpServerConnection) connection).getSslSession();
        }
        return null;
    }

    /**
     * @see org.wildfly.security.http.HttpExchangeSpi#authenticationComplete(org.wildfly.security.auth.spi.AuthenticatedRealmIdentity, java.lang.String)
     */
    @Override
    public void authenticationComplete(SecurityIdentity securityIdentity, String mechanismName) {
        SecurityContext securityContext = httpServerExchange.getSecurityContext();
        if (securityContext != null) {
            securityContext.authenticationComplete(new ElytronAccount(securityIdentity), mechanismName, false);
        }
    }

    /**
     * @see org.wildfly.security.http.HttpExchangeSpi#authenticationFailed(java.lang.String, java.lang.String)
     */
    @Override
    public void authenticationFailed(String message, String mechanismName) {
        SecurityContext securityContext = httpServerExchange.getSecurityContext();
        if (securityContext != null) {
            securityContext.authenticationFailed(message, mechanismName);
        }
    }

    @Override
    public void badRequest(HttpAuthenticationException error, String mechanismName) {
    }

    @Override
    public String getRequestMethod() {
        return httpServerExchange.getRequestMethod().toString();
    }

    @Override
    public URI getRequestURI() {
        final String scheme;
        final String host;
        final int port;
        final String path;
        final String query = httpServerExchange.getQueryString();
        try {
            if (httpServerExchange.isHostIncludedInRequestURI()) {
                URI tempUri = new URI(httpServerExchange.getRequestURI());
                scheme = tempUri.getScheme();
                host = tempUri.getHost();
                port = tempUri.getPort();
                path = tempUri.getPath();
            } else {
                scheme = httpServerExchange.getRequestScheme();
                host = httpServerExchange.getHostName();
                port = httpServerExchange.getHostPort();
                path = httpServerExchange.getRequestURI();
            }
            return new URI(scheme, null, host,
                    ("http".equals(scheme) && port == 80) || ("https".equals(scheme) && port == 443) ? -1 : port, path,
                    query == null || "".equals(query) ? null : query, null);
        } catch (URISyntaxException e) {
            return null;
        }
    }

    @Override
    public String getRequestPath() {
        return httpServerExchange.getRelativePath();
    }

    @Override
    public Map<String, List<String>> getRequestParameters() {
        if (requestParameters == null) {
            synchronized(this) {
                if (requestParameters == null) {
                    HashMap<String, List<String>> parameters = new HashMap<>();

                    Map<String, Deque<String>> queryParameters = httpServerExchange.getQueryParameters();

                    FormDataParser parser = formParserFactory.createParser(httpServerExchange);

                    if (parser != null) {
                        try {
                            FormData data = parser.parseBlocking();

                            for (String name : queryParameters.keySet()) {
                                List<String> values = new ArrayList<>(queryParameters.get(name));
                                if (data.contains(name)) {
                                    Deque<FormValue> formValues = data.get(name);
                                    formValues.stream().filter((FormValue fv) -> fv.isFile() == false)
                                            .forEach((FormValue fv) -> values.add(fv.getValue()));
                                }
                                parameters.put(name, Collections.unmodifiableList(values));
                            }

                            StreamSupport
                                    .stream(data.spliterator(), true)
                                    .filter((String s) -> parameters.containsKey(s) == false)
                                    .forEach(
                                            (String s) -> parameters.put(s,
                                                    Collections.unmodifiableList(data.get(s).stream()
                                                            .filter((FormValue v) -> v.isFile() == false)
                                                            .map((FormValue fv) -> fv.getValue()).collect(Collectors.toList()))));
                        } catch (IOException e) {}
                    } else {
                        queryParameters.forEach((name, values) -> parameters.put(name, Collections.unmodifiableList(new ArrayList<String>(values))));
                    }<commit_msg>[ELY-981] Coverity static analysis: Performace optimalization in map iterating<commit_after>/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2015 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * Licensed 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.wildfly.elytron.web.undertow.server;

import static org.wildfly.common.Assert.checkNotNullParam;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import javax.net.ssl.SSLSession;

import org.wildfly.security.auth.server.SecurityIdentity;
import org.wildfly.security.http.HttpAuthenticationException;
import org.wildfly.security.http.HttpExchangeSpi;
import org.wildfly.security.http.HttpScope;
import org.wildfly.security.http.HttpScopeNotification;
import org.wildfly.security.http.HttpServerCookie;
import org.wildfly.security.http.Scope;

import io.undertow.security.api.SecurityContext;
import io.undertow.server.HttpServerExchange;
import io.undertow.server.ServerConnection;
import io.undertow.server.handlers.Cookie;
import io.undertow.server.handlers.CookieImpl;
import io.undertow.server.handlers.form.FormData;
import io.undertow.server.handlers.form.FormData.FormValue;
import io.undertow.server.handlers.form.FormDataParser;
import io.undertow.server.handlers.form.FormParserFactory;
import io.undertow.server.protocol.http.HttpServerConnection;
import io.undertow.server.session.Session;
import io.undertow.server.session.SessionConfig;
import io.undertow.server.session.SessionManager;
import io.undertow.util.AbstractAttachable;
import io.undertow.util.AttachmentKey;
import io.undertow.util.HttpString;

/**
 * Implementation of {@link HttpExchangeSpi} to wrap access to the Undertow specific {@link HttpServerExchange}.
 *
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 */
public class ElytronHttpExchange implements HttpExchangeSpi {

    private static final AttachmentKey<HttpScope> HTTP_SCOPE_ATTACHMENT_KEY = AttachmentKey.create(HttpScope.class);

    private final HttpServerExchange httpServerExchange;
    private final Map<Scope, Function<HttpServerExchange, HttpScope>> scopeResolvers;
    private final ScopeSessionListener scopeSessionListener;
    private final FormParserFactory formParserFactory = FormParserFactory.builder().build();

    private Map<String, List<String>> requestParameters;

    protected ElytronHttpExchange(final HttpServerExchange httpServerExchange,
            final Map<Scope, Function<HttpServerExchange, HttpScope>> scopeResolvers,
            final ScopeSessionListener scopeSessionListener) {
        this.httpServerExchange = checkNotNullParam("httpServerExchange", httpServerExchange);
        this.scopeResolvers = scopeResolvers;
        this.scopeSessionListener = scopeSessionListener;
    }

    protected ElytronHttpExchange(final HttpServerExchange httpServerExchange) {
        this(httpServerExchange, Collections.emptyMap(), null);
    }

    /**
     * @see org.wildfly.security.http.HttpExchangeSpi#getRequestHeaderValues(java.lang.String)
     */
    @Override
    public List<String> getRequestHeaderValues(String headerName) {
        return httpServerExchange.getRequestHeaders().get(headerName);
    }

    /**
     * @see org.wildfly.security.http.HttpExchangeSpi#addResponseHeader(java.lang.String, java.lang.String)
     */
    @Override
    public void addResponseHeader(String headerName, String headerValue) {
        httpServerExchange.getResponseHeaders().add(new HttpString(headerName), headerValue);
    }

    /**
     * @see org.wildfly.security.http.HttpExchangeSpi#getSSLSession()
     */
    @Override
    public SSLSession getSSLSession() {
        ServerConnection connection = httpServerExchange.getConnection();
        if (connection instanceof HttpServerConnection) {
            return ((HttpServerConnection) connection).getSslSession();
        }
        return null;
    }

    /**
     * @see org.wildfly.security.http.HttpExchangeSpi#authenticationComplete(org.wildfly.security.auth.spi.AuthenticatedRealmIdentity, java.lang.String)
     */
    @Override
    public void authenticationComplete(SecurityIdentity securityIdentity, String mechanismName) {
        SecurityContext securityContext = httpServerExchange.getSecurityContext();
        if (securityContext != null) {
            securityContext.authenticationComplete(new ElytronAccount(securityIdentity), mechanismName, false);
        }
    }

    /**
     * @see org.wildfly.security.http.HttpExchangeSpi#authenticationFailed(java.lang.String, java.lang.String)
     */
    @Override
    public void authenticationFailed(String message, String mechanismName) {
        SecurityContext securityContext = httpServerExchange.getSecurityContext();
        if (securityContext != null) {
            securityContext.authenticationFailed(message, mechanismName);
        }
    }

    @Override
    public void badRequest(HttpAuthenticationException error, String mechanismName) {
    }

    @Override
    public String getRequestMethod() {
        return httpServerExchange.getRequestMethod().toString();
    }

    @Override
    public URI getRequestURI() {
        final String scheme;
        final String host;
        final int port;
        final String path;
        final String query = httpServerExchange.getQueryString();
        try {
            if (httpServerExchange.isHostIncludedInRequestURI()) {
                URI tempUri = new URI(httpServerExchange.getRequestURI());
                scheme = tempUri.getScheme();
                host = tempUri.getHost();
                port = tempUri.getPort();
                path = tempUri.getPath();
            } else {
                scheme = httpServerExchange.getRequestScheme();
                host = httpServerExchange.getHostName();
                port = httpServerExchange.getHostPort();
                path = httpServerExchange.getRequestURI();
            }
            return new URI(scheme, null, host,
                    ("http".equals(scheme) && port == 80) || ("https".equals(scheme) && port == 443) ? -1 : port, path,
                    query == null || "".equals(query) ? null : query, null);
        } catch (URISyntaxException e) {
            return null;
        }
    }

    @Override
    public String getRequestPath() {
        return httpServerExchange.getRelativePath();
    }

    @Override
    public Map<String, List<String>> getRequestParameters() {
        if (requestParameters == null) {
            synchronized(this) {
                if (requestParameters == null) {
                    HashMap<String, List<String>> parameters = new HashMap<>();

                    Map<String, Deque<String>> queryParameters = httpServerExchange.getQueryParameters();

                    FormDataParser parser = formParserFactory.createParser(httpServerExchange);

                    if (parser != null) {
                        try {
                            FormData data = parser.parseBlocking();

                            for (Map.Entry<String, Deque<String>> queryParametersEntry : queryParameters.entrySet()) {
                                List<String> values = new ArrayList<>(queryParametersEntry.getValue());
                                if (data.contains(queryParametersEntry.getKey())) {
                                    Deque<FormValue> formValues = data.get(queryParametersEntry.getKey());
                                    formValues.stream().filter((FormValue fv) -> fv.isFile() == false)
                                            .forEach((FormValue fv) -> values.add(fv.getValue()));
                                }
                                parameters.put(queryParametersEntry.getKey(), Collections.unmodifiableList(values));
                            }

                            StreamSupport
                                    .stream(data.spliterator(), true)
                                    .filter((String s) -> parameters.containsKey(s) == false)
                                    .forEach(
                                            (String s) -> parameters.put(s,
                                                    Collections.unmodifiableList(data.get(s).stream()
                                                            .filter((FormValue v) -> v.isFile() == false)
                                                            .map((FormValue fv) -> fv.getValue()).collect(Collectors.toList()))));
                        } catch (IOException e) {}
                    } else {
                        queryParameters.forEach((name, values) -> parameters.put(name, Collections.unmodifiableList(new ArrayList<String>(values))));
                    }
{'fraction_non_alphanumeric': 0.09575916230366492, 'fraction_numerical': 0.0016230366492146597, 'mean_word_length': 2.619670267197271, 'pattern_counts': {'":': 0, '<': 51, '<?xml version=': 0, '>': 65, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 32, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3961054', 'n_tokens_mistral': 4938, 'n_tokens_neox': 4663, 'n_words': 1027}