Initial Commit

This commit is contained in:
Sebastian Cabrera 2021-08-02 05:44:37 -04:00
parent 53eb92e9af
commit 270ab7d11f
15341 changed files with 700234 additions and 0 deletions

View file

@ -0,0 +1,37 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using System.IO;
using System.Text;
namespace Microsoft.Unity.VisualStudio.Editor.Messaging
{
internal class Deserializer
{
private readonly BinaryReader _reader;
public Deserializer(byte[] buffer)
{
_reader = new BinaryReader(new MemoryStream(buffer));
}
public int ReadInt32()
{
return _reader.ReadInt32();
}
public string ReadString()
{
var length = ReadInt32();
return length > 0
? Encoding.UTF8.GetString(_reader.ReadBytes(length))
: "";
}
public bool CanReadMore()
{
return _reader.BaseStream.Position < _reader.BaseStream.Length;
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 3eda7a83649158546826efb3ffe6c1e3
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,18 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using System;
namespace Microsoft.Unity.VisualStudio.Editor.Messaging
{
internal class ExceptionEventArgs
{
public Exception Exception { get; }
public ExceptionEventArgs(Exception exception)
{
Exception = exception;
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 917a51fff055ce547b4ad1215321f3da
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,23 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using System.Globalization;
using System.Net;
namespace Microsoft.Unity.VisualStudio.Editor.Messaging
{
internal class Message
{
public MessageType Type { get; set; }
public string Value { get; set; }
public IPEndPoint Origin { get; set; }
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "<Message type:{0} value:{1}>", Type, Value);
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: de1c9ea7b82c9904d9e5fba2ee70a998
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,19 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
namespace Microsoft.Unity.VisualStudio.Editor.Messaging
{
internal class MessageEventArgs
{
public Message Message
{
get;
}
public MessageEventArgs(Message message)
{
Message = message;
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 275143c81d816ef4286fdc67aabc20c8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,48 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
namespace Microsoft.Unity.VisualStudio.Editor.Messaging
{
internal enum MessageType
{
None = 0,
Ping,
Pong,
Play,
Stop,
Pause,
Unpause,
Build,
Refresh,
Info,
Error,
Warning,
Open,
Opened,
Version,
UpdatePackage,
ProjectPath,
// This message is a technical one for big messages, not intended to be used directly
Tcp,
RunStarted,
RunFinished,
TestStarted,
TestFinished,
TestListRetrieved,
RetrieveTestList,
ExecuteTests,
ShowUsage
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f3edbdc86577af648a23263aa75161e1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,220 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using System;
using System.Net;
using System.Net.Sockets;
namespace Microsoft.Unity.VisualStudio.Editor.Messaging
{
internal class Messager : IDisposable
{
public event EventHandler<MessageEventArgs> ReceiveMessage;
public event EventHandler<ExceptionEventArgs> MessagerException;
private readonly UdpSocket _socket;
private readonly object _disposeLock = new object();
private bool _disposed;
protected Messager(int port)
{
_socket = new UdpSocket();
_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, false);
_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
_socket.Bind(IPAddress.Any, port);
BeginReceiveMessage();
}
private void BeginReceiveMessage()
{
var buffer = new byte[UdpSocket.BufferSize];
var any = UdpSocket.Any();
try
{
lock (_disposeLock)
{
if (_disposed)
return;
_socket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref any, ReceiveMessageCallback, buffer);
}
}
catch (SocketException se)
{
MessagerException?.Invoke(this, new ExceptionEventArgs(se));
BeginReceiveMessage();
}
catch (ObjectDisposedException)
{
}
}
private void ReceiveMessageCallback(IAsyncResult result)
{
try
{
var endPoint = UdpSocket.Any();
lock (_disposeLock)
{
if (_disposed)
return;
_socket.EndReceiveFrom(result, ref endPoint);
}
var message = DeserializeMessage(UdpSocket.BufferFor(result));
if (message != null)
{
message.Origin = (IPEndPoint)endPoint;
int port;
int bufferSize;
if (IsValidTcpMessage(message, out port, out bufferSize))
{
// switch to TCP mode to handle big messages
TcpClient.Queue(message.Origin.Address, port, bufferSize, buffer =>
{
var originalMessage = DeserializeMessage(buffer);
originalMessage.Origin = message.Origin;
ReceiveMessage?.Invoke(this, new MessageEventArgs(originalMessage));
});
}
else
{
ReceiveMessage?.Invoke(this, new MessageEventArgs(message));
}
}
}
catch (ObjectDisposedException)
{
return;
}
catch (Exception e)
{
RaiseMessagerException(e);
}
BeginReceiveMessage();
}
private static bool IsValidTcpMessage(Message message, out int port, out int bufferSize)
{
port = 0;
bufferSize = 0;
if (message.Value == null)
return false;
if (message.Type != MessageType.Tcp)
return false;
var parts = message.Value.Split(':');
if (parts.Length != 2)
return false;
if (!int.TryParse(parts[0], out port))
return false;
return int.TryParse(parts[1], out bufferSize);
}
private void RaiseMessagerException(Exception e)
{
MessagerException?.Invoke(this, new ExceptionEventArgs(e));
}
private static Message MessageFor(MessageType type, string value)
{
return new Message { Type = type, Value = value };
}
public void SendMessage(IPEndPoint target, MessageType type, string value = "")
{
var message = MessageFor(type, value);
var buffer = SerializeMessage(message);
try
{
lock (_disposeLock)
{
if (_disposed)
return;
if (buffer.Length >= UdpSocket.BufferSize)
{
// switch to TCP mode to handle big messages
var port = TcpListener.Queue(buffer);
if (port > 0)
{
// success, replace original message with "switch to tcp" marker + port information + buffer length
message = MessageFor(MessageType.Tcp, string.Concat(port, ':', buffer.Length));
buffer = SerializeMessage(message);
}
}
_socket.BeginSendTo(buffer, 0, Math.Min(buffer.Length, UdpSocket.BufferSize), SocketFlags.None, target, SendMessageCallback, null);
}
}
catch (SocketException se)
{
MessagerException?.Invoke(this, new ExceptionEventArgs(se));
}
}
private void SendMessageCallback(IAsyncResult result)
{
try
{
lock (_disposeLock)
{
if (_disposed)
return;
_socket.EndSendTo(result);
}
}
catch (SocketException se)
{
MessagerException?.Invoke(this, new ExceptionEventArgs(se));
}
catch (ObjectDisposedException)
{
}
}
private static byte[] SerializeMessage(Message message)
{
var serializer = new Serializer();
serializer.WriteInt32((int)message.Type);
serializer.WriteString(message.Value);
return serializer.Buffer();
}
private static Message DeserializeMessage(byte[] buffer)
{
if (buffer.Length < 4)
return null;
var deserializer = new Deserializer(buffer);
var type = (MessageType)deserializer.ReadInt32();
var value = deserializer.ReadString();
return new Message { Type = type, Value = value };
}
public static Messager BindTo(int port)
{
return new Messager(port);
}
public void Dispose()
{
lock (_disposeLock)
{
_disposed = true;
_socket.Close();
}
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5e249ae353801f043a6e4173410c6152
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,43 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using System.IO;
using System.Text;
namespace Microsoft.Unity.VisualStudio.Editor.Messaging
{
internal class Serializer
{
private readonly MemoryStream _stream;
private readonly BinaryWriter _writer;
public Serializer()
{
_stream = new MemoryStream();
_writer = new BinaryWriter(_stream);
}
public void WriteInt32(int i)
{
_writer.Write(i);
}
public void WriteString(string s)
{
var bytes = Encoding.UTF8.GetBytes(s ?? "");
if (bytes.Length > 0)
{
_writer.Write(bytes.Length);
_writer.Write(bytes);
}
else
_writer.Write(0);
}
public byte[] Buffer()
{
return _stream.ToArray();
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 369c09afe05d2c346af49faef943c773
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,93 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace Microsoft.Unity.VisualStudio.Editor.Messaging
{
internal class TcpClient
{
private const int ConnectOrReadTimeoutMilliseconds = 5000;
private class State
{
public System.Net.Sockets.TcpClient TcpClient;
public NetworkStream NetworkStream;
public byte[] Buffer;
public Action<byte[]> OnBufferAvailable;
}
public static void Queue(IPAddress address, int port, int bufferSize, Action<byte[]> onBufferAvailable)
{
var client = new System.Net.Sockets.TcpClient();
var state = new State {OnBufferAvailable = onBufferAvailable, TcpClient = client, Buffer = new byte[bufferSize]};
try
{
ThreadPool.QueueUserWorkItem(_ =>
{
var handle = client.BeginConnect(address, port, OnClientConnected, state);
if (!handle.AsyncWaitHandle.WaitOne(ConnectOrReadTimeoutMilliseconds))
Cleanup(state);
});
}
catch (Exception)
{
Cleanup(state);
}
}
private static void OnClientConnected(IAsyncResult result)
{
var state = (State)result.AsyncState;
try
{
state.TcpClient.EndConnect(result);
state.NetworkStream = state.TcpClient.GetStream();
var handle = state.NetworkStream.BeginRead(state.Buffer, 0, state.Buffer.Length, OnEndRead, state);
if (!handle.AsyncWaitHandle.WaitOne(ConnectOrReadTimeoutMilliseconds))
Cleanup(state);
}
catch (Exception)
{
Cleanup(state);
}
}
private static void OnEndRead(IAsyncResult result)
{
var state = (State)result.AsyncState;
try
{
var count = state.NetworkStream.EndRead(result);
if (count == state.Buffer.Length)
state.OnBufferAvailable?.Invoke(state.Buffer);
}
catch (Exception)
{
// Ignore and cleanup
}
finally
{
Cleanup(state);
}
}
private static void Cleanup(State state)
{
state.NetworkStream?.Dispose();
state.TcpClient?.Close();
state.NetworkStream = null;
state.TcpClient = null;
state.Buffer = null;
state.OnBufferAvailable = null;
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f6674c38820d12a49ac116d416521d85
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,82 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using System;
using System.Net;
using System.Threading;
namespace Microsoft.Unity.VisualStudio.Editor.Messaging
{
internal class TcpListener
{
private const int ListenTimeoutMilliseconds = 5000;
private class State
{
public System.Net.Sockets.TcpListener TcpListener;
public byte[] Buffer;
}
public static int Queue(byte[] buffer)
{
var tcpListener = new System.Net.Sockets.TcpListener(IPAddress.Any, 0);
var state = new State {Buffer = buffer, TcpListener = tcpListener};
try
{
tcpListener.Start();
int port = ((IPEndPoint)tcpListener.LocalEndpoint).Port;
ThreadPool.QueueUserWorkItem(_ =>
{
bool listening = true;
while (listening)
{
var handle = tcpListener.BeginAcceptTcpClient(OnIncomingConnection, state);
listening = handle.AsyncWaitHandle.WaitOne(ListenTimeoutMilliseconds);
}
Cleanup(state);
});
return port;
}
catch (Exception)
{
Cleanup(state);
return -1;
}
}
private static void OnIncomingConnection(IAsyncResult result)
{
var state = (State)result.AsyncState;
try
{
using (var client = state.TcpListener.EndAcceptTcpClient(result))
{
using (var stream = client.GetStream())
{
stream.Write(state.Buffer, 0, state.Buffer.Length);
}
}
}
catch (Exception)
{
// Ignore and cleanup
}
}
private static void Cleanup(State state)
{
state.TcpListener?.Stop();
state.TcpListener = null;
state.Buffer = null;
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ded625cf0d03fa94c9f939fd13ced18d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,55 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using System;
using System.Net;
using System.Net.Sockets;
namespace Microsoft.Unity.VisualStudio.Editor.Messaging
{
internal class UdpSocket : Socket
{
// Maximum UDP payload is 65507 bytes.
// TCP mode will be used when the payload is bigger than this BufferSize
public const int BufferSize = 1024 * 8;
internal UdpSocket()
: base(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
{
SetIOControl();
}
public void Bind(IPAddress address, int port = 0)
{
Bind(new IPEndPoint(address ?? IPAddress.Any, port));
}
private void SetIOControl()
{
if (!VisualStudioEditor.IsWindows)
return;
try
{
const int SIO_UDP_CONNRESET = -1744830452;
IOControl(SIO_UDP_CONNRESET, new byte[] { 0 }, new byte[0]);
}
catch
{
// fallback
}
}
public static byte[] BufferFor(IAsyncResult result)
{
return (byte[])result.AsyncState;
}
public static EndPoint Any()
{
return new IPEndPoint(IPAddress.Any, 0);
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 38cb3a4a17d2cfd41926da95ce675934
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: