<commit_before>﻿/*
Copyright (C) 2012 Andrew 'the vk' Maraev

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using log4net;

namespace WebTyphoon
{
	public enum WebSocketConnectionStatus
	{
		Open,
		Closing,
		Closed
	}

	public class WebSocketConnection
	{
		private static readonly ILog Log = LogManager.GetLogger("WebTyphoon");

		private readonly NetworkStream _stream;

		private int _currentFragmentLength;
		private MemoryStream _dataBuffer;
		private readonly List<WebSocketFragment> _fragmentsList;
		private readonly Queue<WebSocketFragment> _sendFragmentQueue;

		private const int InputBufferLength = 102400;

		public WebSocketConnectionStatus Status { get; set; }

		public string Uri { get; internal set; }
		public IEnumerable<string> Protocols { get; internal set; }
		public string Origin { get; internal set; }


		internal bool HasWork
		{
			get { return _stream.DataAvailable || _sendFragmentQueue.Count != 0; }
		}

		public WebSocketConnection(NetworkStream stream)
		{
			Status = WebSocketConnectionStatus.Open;

			_stream = stream;
			_dataBuffer = new MemoryStream();
			_fragmentsList = new List<WebSocketFragment>();
			_sendFragmentQueue = new Queue<WebSocketFragment>();
		}

		public void SendText(string message)
		{
			var fragment = new WebSocketFragment(true, OpCode.TextFrame, message);
			SendFragment(fragment);
		}

		public void SendFragment(WebSocketFragment fragment)
		{
			if(Status != WebSocketConnectionStatus.Open) throw new InvalidOperationException("Connection is not open");

			WriteData(fragment);
		}

		internal void StartRead()
		{
			var state = new AsyncReadData {Stream = _stream, Buffer = new byte[InputBufferLength]};

			_stream.BeginRead(state.Buffer, 0, InputBufferLength, AsyncReadHandler, state);
		}

		private void AsyncReadHandler(IAsyncResult ar)
		{
			var s = (AsyncReadData) ar.AsyncState;
			try
			{
				var readBytes = s.Stream.EndRead(ar);
				ReadData(s.Buffer, readBytes);

				StartRead();
			}
			catch (Exception ex)
			{
				Log.Error("Error during read from socket", ex);
				FailConnection("Read error", false);
			}
			
		}

		private void ReadData(byte[] buffer, int readBytes)
		{
			_dataBuffer.Write(buffer, 0, readBytes);

			CheckForFrame();
		}

		private void CheckForFrame()
		{
			if (_dataBuffer.Length == 0) return;

			byte[] buffer = _dataBuffer.GetBuffer();
			long dataLength = _dataBuffer.Length;
			var fragmentStart = 0;
			while (fragmentStart < dataLength)
			{
				if (_currentFragmentLength == 0)
				{
					if (dataLength >= 2)
					{
						_currentFragmentLength = 2;

						var payloadLength = buffer[fragmentStart + 1] & 0x7F;
						if (payloadLength <= 125)
						{
							_currentFragmentLength += payloadLength;
						}
						if (payloadLength == 126 && dataLength >= 4)
						{
							_currentFragmentLength += buffer[fragmentStart + 2] << 8 | buffer[fragmentStart + 3];
							_currentFragmentLength += 2;
						}
						if (payloadLength == 127 && dataLength >= 10)
						{
							_currentFragmentLength +=
								(buffer[fragmentStart + 2] << 56 |
								 buffer[fragmentStart + 3] << 48 |
								 buffer[fragmentStart + 4] << 40 |
								 buffer[fragmentStart + 5] << 32 |
								 buffer[fragmentStart + 6] << 24 |
								 buffer[fragmentStart + 7] << 16 |
								 buffer[fragmentStart + 8] << 8 |
								 buffer[fragmentStart + 9]);
							_currentFragmentLength += 8;
						}

						if ((buffer[fragmentStart + 1] & 0x80) != 0) _currentFragmentLength += 4;
					}
					else
					{
						return;
					}
				}

				if ((dataLength - fragmentStart) < _currentFragmentLength)
				{
					_dataBuffer = new MemoryStream();
					_dataBuffer.Write(buffer, fragmentStart, (int)(dataLength - fragmentStart));
					return;
				}

				var fragmentBuffer = new byte[_currentFragmentLength];
				Array.Copy(buffer, fragmentStart, fragmentBuffer, 0, _currentFragmentLength);

				var fragment = new WebSocketFragment(fragmentBuffer);
				OnWebSocketFragmentRecieved(this, new WebSocketFragmentRecievedEventArgs(fragment));

				fragmentStart += _currentFragmentLength;

				_currentFragmentLength = 0;
			}
		}

		private void WriteData(WebSocketFragment fragment)
		{
			var fragmentData = fragment.GetBuffer();

			_stream.BeginWrite(fragmentData, 0, fragmentData.Length, AsyncWriteHandler, _stream);
		}

		private void AsyncWriteHandler(IAsyncResult ar)
		{
			try
			{
				var str = (NetworkStream)ar.AsyncState;
				str.EndWrite(ar);
			}
			catch (Exception ex)
			{
				Log.Error("Error during write to socket", ex);
				FailConnection(true);
			}
			
		}

		private void StopWriterThread()
		{
			Status = WebSocketConnectionStatus.Closed;
		}

		public event EventHandler<WebSocketMessageRecievedEventArgs> TextMessageRecieved;
		protected void OnTextMessageRecieved(object sender, WebSocketMessageRecievedEventArgs e)
		{
			if (TextMessageRecieved != null)
			{<commit_msg>Updated class WebSocketConnection: * Enclosed code for working with network stream in try-catch statements.<commit_after>﻿/*
Copyright (C) 2012 Andrew 'the vk' Maraev

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using log4net;

namespace WebTyphoon
{
	public enum WebSocketConnectionStatus
	{
		Open,
		Closing,
		Closed
	}

	public class WebSocketConnection
	{
		private static readonly ILog Log = LogManager.GetLogger("WebTyphoon");

		private readonly NetworkStream _stream;

		private int _currentFragmentLength;
		private MemoryStream _dataBuffer;
		private readonly List<WebSocketFragment> _fragmentsList;
		private readonly Queue<WebSocketFragment> _sendFragmentQueue;

		private const int InputBufferLength = 102400;

		public WebSocketConnectionStatus Status { get; set; }

		public string Uri { get; internal set; }
		public IEnumerable<string> Protocols { get; internal set; }
		public string Origin { get; internal set; }


		internal bool HasWork
		{
			get { return _stream.DataAvailable || _sendFragmentQueue.Count != 0; }
		}

		public WebSocketConnection(NetworkStream stream)
		{
			Status = WebSocketConnectionStatus.Open;

			_stream = stream;
			_dataBuffer = new MemoryStream();
			_fragmentsList = new List<WebSocketFragment>();
			_sendFragmentQueue = new Queue<WebSocketFragment>();
		}

		public void SendText(string message)
		{
			var fragment = new WebSocketFragment(true, OpCode.TextFrame, message);
			SendFragment(fragment);
		}

		public void SendFragment(WebSocketFragment fragment)
		{
			if(Status != WebSocketConnectionStatus.Open) throw new InvalidOperationException("Connection is not open");

			WriteData(fragment);
		}

		internal void StartRead()
		{
			var state = new AsyncReadData {Stream = _stream, Buffer = new byte[InputBufferLength]};

			try
			{
				_stream.BeginRead(state.Buffer, 0, InputBufferLength, AsyncReadHandler, state);
			}
			catch (Exception ex)
			{
				Log.Error("Error while starting read fron network stream.", ex);
				FailConnection(false);
			}
		}

		private void AsyncReadHandler(IAsyncResult ar)
		{
			var s = (AsyncReadData) ar.AsyncState;
			try
			{
				var readBytes = s.Stream.EndRead(ar);
				ReadData(s.Buffer, readBytes);

				StartRead();
			}
			catch (Exception ex)
			{
				Log.Error("Error during read from socket", ex);
				FailConnection("Read error", false);
			}
			
		}

		private void ReadData(byte[] buffer, int readBytes)
		{
			_dataBuffer.Write(buffer, 0, readBytes);

			CheckForFrame();
		}

		private void CheckForFrame()
		{
			if (_dataBuffer.Length == 0) return;

			byte[] buffer = _dataBuffer.GetBuffer();
			long dataLength = _dataBuffer.Length;
			var fragmentStart = 0;
			while (fragmentStart < dataLength)
			{
				if (_currentFragmentLength == 0)
				{
					if (dataLength >= 2)
					{
						_currentFragmentLength = 2;

						var payloadLength = buffer[fragmentStart + 1] & 0x7F;
						if (payloadLength <= 125)
						{
							_currentFragmentLength += payloadLength;
						}
						if (payloadLength == 126 && dataLength >= 4)
						{
							_currentFragmentLength += buffer[fragmentStart + 2] << 8 | buffer[fragmentStart + 3];
							_currentFragmentLength += 2;
						}
						if (payloadLength == 127 && dataLength >= 10)
						{
							_currentFragmentLength +=
								(buffer[fragmentStart + 2] << 56 |
								 buffer[fragmentStart + 3] << 48 |
								 buffer[fragmentStart + 4] << 40 |
								 buffer[fragmentStart + 5] << 32 |
								 buffer[fragmentStart + 6] << 24 |
								 buffer[fragmentStart + 7] << 16 |
								 buffer[fragmentStart + 8] << 8 |
								 buffer[fragmentStart + 9]);
							_currentFragmentLength += 8;
						}

						if ((buffer[fragmentStart + 1] & 0x80) != 0) _currentFragmentLength += 4;
					}
					else
					{
						return;
					}
				}

				if ((dataLength - fragmentStart) < _currentFragmentLength)
				{
					_dataBuffer = new MemoryStream();
					_dataBuffer.Write(buffer, fragmentStart, (int)(dataLength - fragmentStart));
					return;
				}

				var fragmentBuffer = new byte[_currentFragmentLength];
				Array.Copy(buffer, fragmentStart, fragmentBuffer, 0, _currentFragmentLength);

				var fragment = new WebSocketFragment(fragmentBuffer);
				OnWebSocketFragmentRecieved(this, new WebSocketFragmentRecievedEventArgs(fragment));

				fragmentStart += _currentFragmentLength;

				_currentFragmentLength = 0;
			}
		}

		private void WriteData(WebSocketFragment fragment)
		{
			var fragmentData = fragment.GetBuffer();

			try
			{
				_stream.BeginWrite(fragmentData, 0, fragmentData.Length, AsyncWriteHandler, _stream);
			}
			catch (Exception ex)
			{
				Log.Error("Error while starting write to network stream.", ex);
			}
		}

		private void AsyncWriteHandler(IAsyncResult ar)
		{
			try
			{
				var str = (NetworkStream)ar.AsyncState;
				str.EndWrite(ar);
			}
			catch (Exception ex)
			{
				Log.Error("Error during write to socket", ex);
				FailConnection(true);
			}
			
		}

		private void StopWriterThread()
		{
			Status = WebSocketConnectionStatus.Closed;
		}

		public event EventHandler<WebSocketMessageRecievedEventArgs> TextMessageRecieved;
		protected void OnTextMessageRecieved(object sender, WebSocketMessageRecievedEventArgs e)
		{
			if (TextMessageRecieved != null)
			{
{'fraction_non_alphanumeric': 0.08747370124615633, 'fraction_numerical': 0.011166855478232724, 'mean_word_length': 3.634045744281965, 'pattern_counts': {'":': 0, '<': 53, '<?xml version=': 0, '>': 21, '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': '343134', 'n_tokens_mistral': 4447, 'n_tokens_neox': 3405, 'n_words': 1073}