<commit_before>/*
 * Licensed to Elasticsearch under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch 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.elasticsearch.http.netty4.cors;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import org.elasticsearch.common.Strings;

import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * Handles <a href="http://www.w3.org/TR/cors/">Cross Origin Resource Sharing</a> (CORS) requests.
 * <p>
 * This handler can be configured using a {@link Netty4CorsConfig}, please
 * refer to this class for details about the configuration options available.
 *
 * This code was borrowed from Netty 4 and refactored to work for Elasticsearch's Netty 3 setup.
 */
public class Netty4CorsHandler extends ChannelDuplexHandler {

    public static final String ANY_ORIGIN = "*";
    private static Pattern SCHEME_PATTERN = Pattern.compile("^https?://");

    private final Netty4CorsConfig config;
    private HttpRequest request;

    /**
     * Creates a new instance with the specified {@link Netty4CorsConfig}.
     */
    public Netty4CorsHandler(final Netty4CorsConfig config) {
        if (config == null) {
            throw new NullPointerException();
        }
        this.config = config;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (config.isCorsSupportEnabled() && msg instanceof HttpRequest) {
            request = (HttpRequest) msg;
            if (isPreflightRequest(request)) {
                handlePreflight(ctx, request);
                return;
            }
            if (config.isShortCircuit() && !validateOrigin()) {
                forbidden(ctx, request);
                return;
            }
        }
        ctx.fireChannelRead(msg);
    }

    public static void setCorsResponseHeaders(HttpRequest request, HttpResponse resp, Netty4CorsConfig config) {
        if (!config.isCorsSupportEnabled()) {
            return;
        }
        String originHeader = request.headers().get(HttpHeaderNames.ORIGIN);
        if (!Strings.isNullOrEmpty(originHeader)) {
            final String originHeaderVal;
            if (config.isAnyOriginSupported()) {
                originHeaderVal = ANY_ORIGIN;
            } else if (config.isOriginAllowed(originHeader) || isSameOrigin(originHeader, request.headers().get(HttpHeaderNames.HOST))) {
                originHeaderVal = originHeader;
            } else {
                originHeaderVal = null;
            }
            if (originHeaderVal != null) {
                resp.headers().add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, originHeaderVal);
            }
        }
        if (config.isCredentialsAllowed()) {
            resp.headers().add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
        }
    }

    private void handlePreflight(final ChannelHandlerContext ctx, final HttpRequest request) {
        final HttpResponse response = new DefaultFullHttpResponse(request.protocolVersion(), HttpResponseStatus.OK, true, true);
        if (setOrigin(response)) {
            setAllowMethods(response);
            setAllowHeaders(response);
            setAllowCredentials(response);
            setMaxAge(response);
            setPreflightHeaders(response);
            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            forbidden(ctx, request);
        }
    }

    private static void forbidden(final ChannelHandlerContext ctx, final HttpRequest request) {
        ctx.writeAndFlush(new DefaultFullHttpResponse(request.protocolVersion(), HttpResponseStatus.FORBIDDEN))
            .addListener(ChannelFutureListener.CLOSE);
    }<commit_msg>Release requests in cors handle (#32410)<commit_after>/*
 * Licensed to Elasticsearch under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch 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.elasticsearch.http.netty4.cors;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import org.elasticsearch.common.Strings;

import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * Handles <a href="http://www.w3.org/TR/cors/">Cross Origin Resource Sharing</a> (CORS) requests.
 * <p>
 * This handler can be configured using a {@link Netty4CorsConfig}, please
 * refer to this class for details about the configuration options available.
 *
 * This code was borrowed from Netty 4 and refactored to work for Elasticsearch's Netty 3 setup.
 */
public class Netty4CorsHandler extends ChannelDuplexHandler {

    public static final String ANY_ORIGIN = "*";
    private static Pattern SCHEME_PATTERN = Pattern.compile("^https?://");

    private final Netty4CorsConfig config;
    private FullHttpRequest request;

    /**
     * Creates a new instance with the specified {@link Netty4CorsConfig}.
     */
    public Netty4CorsHandler(final Netty4CorsConfig config) {
        if (config == null) {
            throw new NullPointerException();
        }
        this.config = config;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        assert msg instanceof FullHttpRequest : "Invalid message type: " + msg.getClass();
        if (config.isCorsSupportEnabled()) {
            request = (FullHttpRequest) msg;
            if (isPreflightRequest(request)) {
                try {
                    handlePreflight(ctx, request);
                    return;
                } finally {
                    releaseRequest();
                }
            }
            if (config.isShortCircuit() && !validateOrigin()) {
                try {
                    forbidden(ctx, request);
                    return;
                } finally {
                    releaseRequest();
                }
            }
        }
        ctx.fireChannelRead(msg);
    }

    public static void setCorsResponseHeaders(HttpRequest request, HttpResponse resp, Netty4CorsConfig config) {
        if (!config.isCorsSupportEnabled()) {
            return;
        }
        String originHeader = request.headers().get(HttpHeaderNames.ORIGIN);
        if (!Strings.isNullOrEmpty(originHeader)) {
            final String originHeaderVal;
            if (config.isAnyOriginSupported()) {
                originHeaderVal = ANY_ORIGIN;
            } else if (config.isOriginAllowed(originHeader) || isSameOrigin(originHeader, request.headers().get(HttpHeaderNames.HOST))) {
                originHeaderVal = originHeader;
            } else {
                originHeaderVal = null;
            }
            if (originHeaderVal != null) {
                resp.headers().add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, originHeaderVal);
            }
        }
        if (config.isCredentialsAllowed()) {
            resp.headers().add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
        }
    }

    private void handlePreflight(final ChannelHandlerContext ctx, final HttpRequest request) {
        final HttpResponse response = new DefaultFullHttpResponse(request.protocolVersion(), HttpResponseStatus.OK, true, true);
        if (setOrigin(response)) {
            setAllowMethods(response);
            setAllowHeaders(response);
            setAllowCredentials(response);
            setMaxAge(response);
            setPreflightHeaders(response);
            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            forbidden(ctx, request);
        }
    }

    private void releaseRequest() {
        request.release();
        request = null;
    }

    private static void forbidden(final ChannelHandlerContext ctx, final HttpRequest request) {
        ctx.writeAndFlush(new DefaultFullHttpResponse(request.protocolVersion(), HttpResponseStatus.FORBIDDEN))
            .addListener(ChannelFutureListener.CLOSE);
    }
{'fraction_non_alphanumeric': 0.08821788040260509, 'fraction_numerical': 0.0034537201499901323, 'mean_word_length': 2.8536121673003803, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4828793', 'n_tokens_mistral': 2643, 'n_tokens_neox': 2598, 'n_words': 698}