<commit_before>/*
 * JBoss, Home of Professional Open Source
 *
 * Copyright 2008, Red Hat Middleware LLC, and individual contributors
 * by the @author tags. See the COPYRIGHT.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.netty.channel.socket.http;

import static org.jboss.netty.channel.Channels.*;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.URI;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.AbstractChannel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineCoverage;
import org.jboss.netty.channel.ChannelSink;
import org.jboss.netty.channel.DefaultChannelPipeline;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.socket.ClientSocketChannelFactory;
import org.jboss.netty.channel.socket.SocketChannel;
import org.jboss.netty.channel.socket.SocketChannelConfig;
import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder;
import org.jboss.netty.util.internal.LinkedTransferQueue;

/**
 * @author The Netty Project (<EMAIL>)
 * @author <NAME> (<EMAIL>)
 * @version $Rev$, $Date$
 */
class HttpTunnelingClientSocketChannel extends AbstractChannel
        implements org.jboss.netty.channel.socket.SocketChannel {

    private final Lock reconnectLock = new ReentrantLock();

    volatile boolean awaitingInitialResponse = true;

    private final Object writeLock = new Object();

    volatile Thread workerThread;

    String sessionId;

    boolean closed = false;

    LinkedTransferQueue<byte[]> messages = new LinkedTransferQueue<byte[]>();

    private final ClientSocketChannelFactory clientSocketChannelFactory;

    SocketChannel channel;

    private final DelimiterBasedFrameDecoder handler = new DelimiterBasedFrameDecoder(8092, ChannelBuffers.wrappedBuffer(new byte[] { '\r', '\n' }));

    private final HttpTunnelingClientSocketChannel.ServletChannelHandler servletHandler = new ServletChannelHandler();

    private HttpTunnelAddress remoteAddress;

    HttpTunnelingClientSocketChannel(
            ChannelFactory factory,
            ChannelPipeline pipeline,
            ChannelSink sink, ClientSocketChannelFactory clientSocketChannelFactory) {

        super(null, factory, pipeline, sink);
        this.clientSocketChannelFactory = clientSocketChannelFactory;

        DefaultChannelPipeline channelPipeline = new DefaultChannelPipeline();
        channelPipeline.addLast("DelimiterBasedFrameDecoder", handler);
        channelPipeline.addLast("servletHandler", servletHandler);
        channel = clientSocketChannelFactory.newChannel(channelPipeline);

        fireChannelOpen(this);
    }

    public SocketChannelConfig getConfig() {
        return channel.getConfig();
    }

    public InetSocketAddress getLocalAddress() {
        return channel.getLocalAddress();
    }

    public InetSocketAddress getRemoteAddress() {
        return channel.getRemoteAddress();
    }

    public boolean isBound() {
        return channel.isOpen();
    }

    public boolean isConnected() {
        return channel.isConnected();
    }

    @Override
    protected boolean setClosed() {
        return super.setClosed();
    }

    @Override
    protected void setInterestOpsNow(int interestOps) {
        super.setInterestOpsNow(interestOps);
    }

    @Override
    public ChannelFuture write(Object message, SocketAddress remoteAddress) {
        if (remoteAddress == null || remoteAddress.equals(getRemoteAddress())) {
            return super.write(message, null);
        }
        else {
            return getUnsupportedOperationFuture();
        }
    }

    void connectAndSendHeaders(boolean reconnect, HttpTunnelAddress remoteAddress) {
        this.remoteAddress = remoteAddress;
        URI url = remoteAddress.getUri();
        if (reconnect) {
            DefaultChannelPipeline channelPipeline = new DefaultChannelPipeline();
            channelPipeline.addLast("DelimiterBasedFrameDecoder", handler);
            channelPipeline.addLast("servletHandler", servletHandler);
            channel = clientSocketChannelFactory.newChannel(channelPipeline);
        }
        SocketAddress connectAddress = new InetSocketAddress(url.getHost(), url.getPort());
        channel.connect(connectAddress);
        StringBuilder builder = new StringBuilder();
        builder.append("POST ").append(url.getRawPath()).append(" HTTP/1.1").append(HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR).
                append("Host: ").append(url.getHost()).append(":").append(url.getPort()).append(HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR).
                append("Content-Type: application/octet-stream").append(HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR).append("Transfer-Encoding: chunked").
                append(HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR).append("Content-Transfer-Encoding: Binary").append(HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR).append("Connection: Keep-Alive").
                append(HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR);
        if (reconnect) {
            builder.append("Cookie: JSESSIONID=").append(sessionId).append(HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR);
        }
        builder.append(HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR);
        String msg = builder.toString();
        channel.write(ChannelBuffers.copiedBuffer(msg, "ASCII"));
    }

    public void sendChunk(ChannelBuffer a) {
        int size = a.readableBytes();
        String hex = Integer.toHexString(size) + HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR;

        // try {
        synchronized (writeLock) {
            a.writeBytes(HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR.getBytes());
            channel.write(ChannelBuffers.wrappedBuffer(hex.getBytes()));
            channel.write(a).awaitUninterruptibly();
            //channel.write(ChannelBuffers.wrappedBuffer(LINE_TERMINATOR.getBytes()));
        }
    }

    public byte[] receiveChunk() {
        byte[] buf = null;
        try {
            buf = messages.take();
        }
        catch (InterruptedException e) {
            // Ignore<commit_msg>Fixed broken chunked encoding in HttpTunnelingClientSocketChannel<commit_after>/*
 * JBoss, Home of Professional Open Source
 *
 * Copyright 2008, Red Hat Middleware LLC, and individual contributors
 * by the @author tags. See the COPYRIGHT.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.netty.channel.socket.http;

import static org.jboss.netty.channel.Channels.*;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.URI;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.AbstractChannel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineCoverage;
import org.jboss.netty.channel.ChannelSink;
import org.jboss.netty.channel.DefaultChannelPipeline;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.socket.ClientSocketChannelFactory;
import org.jboss.netty.channel.socket.SocketChannel;
import org.jboss.netty.channel.socket.SocketChannelConfig;
import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder;
import org.jboss.netty.util.internal.LinkedTransferQueue;

/**
 * @author The Netty Project (<EMAIL>)
 * @author <NAME> (<EMAIL>)
 * @version $Rev$, $Date$
 */
class HttpTunnelingClientSocketChannel extends AbstractChannel
        implements org.jboss.netty.channel.socket.SocketChannel {

    private final Lock reconnectLock = new ReentrantLock();

    volatile boolean awaitingInitialResponse = true;

    private final Object writeLock = new Object();

    volatile Thread workerThread;

    String sessionId;

    boolean closed = false;

    LinkedTransferQueue<byte[]> messages = new LinkedTransferQueue<byte[]>();

    private final ClientSocketChannelFactory clientSocketChannelFactory;

    SocketChannel channel;

    private final DelimiterBasedFrameDecoder handler = new DelimiterBasedFrameDecoder(8092, ChannelBuffers.wrappedBuffer(new byte[] { '\r', '\n' }));

    private final HttpTunnelingClientSocketChannel.ServletChannelHandler servletHandler = new ServletChannelHandler();

    private HttpTunnelAddress remoteAddress;

    HttpTunnelingClientSocketChannel(
            ChannelFactory factory,
            ChannelPipeline pipeline,
            ChannelSink sink, ClientSocketChannelFactory clientSocketChannelFactory) {

        super(null, factory, pipeline, sink);
        this.clientSocketChannelFactory = clientSocketChannelFactory;

        DefaultChannelPipeline channelPipeline = new DefaultChannelPipeline();
        channelPipeline.addLast("DelimiterBasedFrameDecoder", handler);
        channelPipeline.addLast("servletHandler", servletHandler);
        channel = clientSocketChannelFactory.newChannel(channelPipeline);

        fireChannelOpen(this);
    }

    public SocketChannelConfig getConfig() {
        return channel.getConfig();
    }

    public InetSocketAddress getLocalAddress() {
        return channel.getLocalAddress();
    }

    public InetSocketAddress getRemoteAddress() {
        return channel.getRemoteAddress();
    }

    public boolean isBound() {
        return channel.isOpen();
    }

    public boolean isConnected() {
        return channel.isConnected();
    }

    @Override
    protected boolean setClosed() {
        return super.setClosed();
    }

    @Override
    protected void setInterestOpsNow(int interestOps) {
        super.setInterestOpsNow(interestOps);
    }

    @Override
    public ChannelFuture write(Object message, SocketAddress remoteAddress) {
        if (remoteAddress == null || remoteAddress.equals(getRemoteAddress())) {
            return super.write(message, null);
        }
        else {
            return getUnsupportedOperationFuture();
        }
    }

    void connectAndSendHeaders(boolean reconnect, HttpTunnelAddress remoteAddress) {
        this.remoteAddress = remoteAddress;
        URI url = remoteAddress.getUri();
        if (reconnect) {
            DefaultChannelPipeline channelPipeline = new DefaultChannelPipeline();
            channelPipeline.addLast("DelimiterBasedFrameDecoder", handler);
            channelPipeline.addLast("servletHandler", servletHandler);
            channel = clientSocketChannelFactory.newChannel(channelPipeline);
        }
        SocketAddress connectAddress = new InetSocketAddress(url.getHost(), url.getPort());
        channel.connect(connectAddress);
        StringBuilder builder = new StringBuilder();
        builder.append("POST ").append(url.getRawPath()).append(" HTTP/1.1").append(HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR).
                append("Host: ").append(url.getHost()).append(":").append(url.getPort()).append(HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR).
                append("Content-Type: application/octet-stream").append(HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR).append("Transfer-Encoding: chunked").
                append(HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR).append("Content-Transfer-Encoding: Binary").append(HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR).append("Connection: Keep-Alive").
                append(HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR);
        if (reconnect) {
            builder.append("Cookie: JSESSIONID=").append(sessionId).append(HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR);
        }
        builder.append(HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR);
        String msg = builder.toString();
        channel.write(ChannelBuffers.copiedBuffer(msg, "ASCII"));
    }

    public void sendChunk(ChannelBuffer a) {
        int size = a.readableBytes();
        String hex = Integer.toHexString(size) + HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR;

        synchronized (writeLock) {
            ChannelFuture future = channel.write(ChannelBuffers.wrappedBuffer(
                    ChannelBuffers.copiedBuffer(hex, "ASCII"),
                    a,
                    ChannelBuffers.copiedBuffer(HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR, "ASCII")));
            future.awaitUninterruptibly();
        }
    }

    public byte[] receiveChunk() {
        byte[] buf = null;
        try {
            buf = messages.take();
        }
        catch (InterruptedException e) {
            // Ignore
{'fraction_non_alphanumeric': 0.09070157771064115, 'fraction_numerical': 0.003088284659281638, 'mean_word_length': 3.7927927927927927, 'pattern_counts': {'":': 2, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, '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': '6350349', 'n_tokens_mistral': 3962, 'n_tokens_neox': 3843, 'n_words': 888}