<commit_before>﻿using System;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Threading.Tasks;
using System.Collections.Generic;

using Eavesdrop.Network;

namespace Eavesdrop
{
    public static class Eavesdropper
    {
        private static TcpListener _listener;
        private static readonly object _stateLock;
        private static TaskCompletionSource<bool> _terminationSource;

        public delegate Task AsyncEventHandler<TEventArgs>(object sender, TEventArgs e);

        public static event AsyncEventHandler<RequestInterceptedEventArgs> RequestInterceptedAsync;
        private static async Task OnRequestInterceptedAsync(RequestInterceptedEventArgs e)
        {
            Task interceptedTask = RequestInterceptedAsync?.Invoke(null, e);
            if (interceptedTask != null)
            {
                await interceptedTask;
            }
        }

        public static event AsyncEventHandler<ResponseInterceptedEventArgs> ResponseInterceptedAsync;
        private static async Task OnResponseInterceptedAsync(ResponseInterceptedEventArgs e)
        {
            Task interceptedTask = ResponseInterceptedAsync?.Invoke(null, e);
            if (interceptedTask != null)
            {
                await interceptedTask;
            }
        }

        public static List<string> Overrides { get; }
        public static bool IsRunning { get; private set; }
        public static CertificateManager Certifier { get; set; }

        static Eavesdropper()
        {
            _stateLock = new object();

            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            Overrides = new List<string>();
            Certifier = new CertificateManager("Eavesdrop", "Eavesdrop Root Certificate Authority");
        }

        public static void Terminate()
        {
            lock (_stateLock)
            {
                ResetMachineProxy();
                IsRunning = false;

                if (_listener != null)
                {
                    _terminationSource = new TaskCompletionSource<bool>();

                    _listener.Stop();
                    _listener = null;

                    _terminationSource.Task.Wait();
                }
            }
        }
        public static void Initiate(int port)
        {
            Initiate(port, Interceptors.Default);
        }
        public static void Initiate(int port, Interceptors interceptors)
        {
            lock (_stateLock)
            {
                Terminate();

                _listener = new TcpListener(IPAddress.Any, port);
                _listener.Start();

                IsRunning = true;

                Task.Factory.StartNew(InterceptRequestAsnync, TaskCreationOptions.LongRunning);
                SetMachineProxy(port, interceptors);
            }
        }

        private static async Task InterceptRequestAsnync()
        {
            while (IsRunning && _listener != null)
            {
                try
                {
                    TcpClient client = await _listener.AcceptTcpClientAsync().ConfigureAwait(false);
                    Task handleClientAsync = HandleClientAsync(client);
                }
                catch (ObjectDisposedException) { }
            }
            _terminationSource?.SetResult(true);
        }
        private static async Task HandleClientAsync(TcpClient client)
        {
            using (var local = new EavesNode(Certifier, client))
            {
                WebRequest request = await local.ReadRequestAsync().ConfigureAwait(false);
                if (request == null) return;

                HttpContent requestContent = null;
                var requestArgs = new RequestInterceptedEventArgs(request);
                try
                {
                    requestArgs.Content = requestContent = await local.ReadRequestContentAsync(request).ConfigureAwait(false);
                    await OnRequestInterceptedAsync(requestArgs).ConfigureAwait(false);
                    if (requestArgs.Cancel) return;

                    request = requestArgs.Request;
                    if (requestArgs.Content != null)
                    {
                        await local.WriteRequestContentAsync(request, requestArgs.Content).ConfigureAwait(false);
                    }<commit_msg>Not sure what this was doing, I removed it but I'll probably regret it later<commit_after>﻿using System;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Threading.Tasks;
using System.Collections.Generic;

using Eavesdrop.Network;

namespace Eavesdrop
{
    public static class Eavesdropper
    {
        private static TcpListener _listener;
        private static readonly object _stateLock;

        public delegate Task AsyncEventHandler<TEventArgs>(object sender, TEventArgs e);

        public static event AsyncEventHandler<RequestInterceptedEventArgs> RequestInterceptedAsync;
        private static async Task OnRequestInterceptedAsync(RequestInterceptedEventArgs e)
        {
            Task interceptedTask = RequestInterceptedAsync?.Invoke(null, e);
            if (interceptedTask != null)
            {
                await interceptedTask;
            }
        }

        public static event AsyncEventHandler<ResponseInterceptedEventArgs> ResponseInterceptedAsync;
        private static async Task OnResponseInterceptedAsync(ResponseInterceptedEventArgs e)
        {
            Task interceptedTask = ResponseInterceptedAsync?.Invoke(null, e);
            if (interceptedTask != null)
            {
                await interceptedTask;
            }
        }

        public static List<string> Overrides { get; }
        public static bool IsRunning { get; private set; }
        public static CertificateManager Certifier { get; set; }

        static Eavesdropper()
        {
            _stateLock = new object();

            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            Overrides = new List<string>();
            Certifier = new CertificateManager("Eavesdrop", "Eavesdrop Root Certificate Authority");
        }

        public static void Terminate()
        {
            lock (_stateLock)
            {
                ResetMachineProxy();
                IsRunning = false;

                if (_listener != null)
                {
                    _listener.Stop();
                    _listener = null;
                }
            }
        }
        public static void Initiate(int port)
        {
            Initiate(port, Interceptors.Default);
        }
        public static void Initiate(int port, Interceptors interceptors)
        {
            lock (_stateLock)
            {
                Terminate();

                _listener = new TcpListener(IPAddress.Any, port);
                _listener.Start();

                IsRunning = true;

                Task.Factory.StartNew(InterceptRequestAsnync, TaskCreationOptions.LongRunning);
                SetMachineProxy(port, interceptors);
            }
        }

        private static async Task InterceptRequestAsnync()
        {
            while (IsRunning && _listener != null)
            {
                try
                {
                    TcpClient client = await _listener.AcceptTcpClientAsync().ConfigureAwait(false);
                    Task handleClientAsync = HandleClientAsync(client);
                }
                catch (ObjectDisposedException) { }
            }
        }
        private static async Task HandleClientAsync(TcpClient client)
        {
            using (var local = new EavesNode(Certifier, client))
            {
                WebRequest request = await local.ReadRequestAsync().ConfigureAwait(false);
                if (request == null) return;

                HttpContent requestContent = null;
                var requestArgs = new RequestInterceptedEventArgs(request);
                try
                {
                    requestArgs.Content = requestContent = await local.ReadRequestContentAsync(request).ConfigureAwait(false);
                    await OnRequestInterceptedAsync(requestArgs).ConfigureAwait(false);
                    if (requestArgs.Cancel) return;

                    request = requestArgs.Request;
                    if (requestArgs.Content != null)
                    {
                        await local.WriteRequestContentAsync(request, requestArgs.Content).ConfigureAwait(false);
                    }
{'fraction_non_alphanumeric': 0.06829882164512069, 'fraction_numerical': 0.0016016474087632993, 'mean_word_length': 1.8001281229980781, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '739813', 'n_tokens_mistral': 2082, 'n_tokens_neox': 1953, 'n_words': 467}