Skip to content

Commit

Permalink
feat: Added logging manager
Browse files Browse the repository at this point in the history
  • Loading branch information
TwoTenPvP committed Aug 6, 2019
1 parent 2e5dd30 commit fd4a9fd
Show file tree
Hide file tree
Showing 2 changed files with 154 additions and 25 deletions.
132 changes: 107 additions & 25 deletions Ruffles/Core/RuffleSocket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
using Ruffles.Messaging;
using Ruffles.Random;
using Ruffles.Simulation;
using Ruffles.Utils;

// TODO: Make sure only connection receiver send hails to prevent a hacked client sending messed up channel configs and the receiver applying them.
// Might actually already be enforced via the state? Verify
Expand Down Expand Up @@ -56,7 +57,16 @@ public RuffleSocket(SocketConfig config)
Connections = new Connection[config.MaxConnections];
challengeInitializationVectors = new SlidingSet<ulong>((int)config.ConnectionChallengeHistory, true);

bool bindSuccess = Bind(config.IPv4ListenAddress, config.IPv6ListenAddress, config.DualListenPort, config.UseIPv6Dual);
bool bindSuccess = Bind(config.IPv4ListenAddress, config.IPv6ListenAddress, config.DualListenPort, config.UseIPv6Dual);

if (!bindSuccess)
{
Logging.Error("Failed to bind socket");
}
else
{
Logging.Info("Socket was bound");
}
}

private bool Bind(IPAddress addressIPv4, IPAddress addressIPv6, int port, bool ipv6Dual)
Expand Down Expand Up @@ -125,8 +135,9 @@ private bool SetupAndBind(Socket socket, IPEndPoint endpoint)
socket.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, true);
socket.Bind(endpoint);
}
catch (SocketException)
catch (SocketException e)
{
Logging.Error("Socket bind failed after setting dual mode with exception: " + e);
// TODO: Handle
return false;
}
Expand All @@ -140,8 +151,9 @@ private bool SetupAndBind(Socket socket, IPEndPoint endpoint)
{
return true;
}
}

}

Logging.Error("Socket bind with exception: " + bindException);
return false;
}

Expand Down Expand Up @@ -192,7 +204,9 @@ public void Send(ArraySegment<byte> payload, ulong connectionId, byte channelId,
/// <returns>The pending connection.</returns>
/// <param name="endpoint">The endpoint to connect to.</param>
public Connection Connect(EndPoint endpoint)
{
{
Logging.Info("Starting connect to " + endpoint);

Connection connection = AddNewConnection(endpoint, ConnectionState.RequestingConnection);

if (connection != null)
Expand Down Expand Up @@ -246,9 +260,15 @@ public Connection Connect(EndPoint endpoint)
}

int minSize = 1 + (config.TimeBasedConnectionChallenge ? sizeof(ulong) * 3 : 0);

Logging.Info("Sending connection request to " + endpoint);

connection.SendRaw(new ArraySegment<byte>(outgoingInternalBuffer, 0, Math.Max(minSize, (int)config.AmplificationPreventionHandshakePadding)), true);
}
else
{
Logging.Error("Failed to allocate connection to " + endpoint);
}

return connection;
}
Expand Down Expand Up @@ -585,12 +605,15 @@ internal void HandlePacket(ArraySegment<byte> payload, EndPoint endpoint)
{
if (payload.Count < 1)
{
// Invalid size
// Invalid size
Logging.Error("Got packet of size " + payload.Count + " from " + endpoint + ". Packet is too small");
return;
}

// Unpack header, dont cast to MessageType enum for safety
HeaderPacker.Unpack(payload.Array[payload.Offset], out byte messageType, out bool fragmented);
HeaderPacker.Unpack(payload.Array[payload.Offset], out byte messageType, out bool fragmented);

Logging.Info("Unpacked packet. [MessageType=" + (MessageType)messageType + "] [Fragmented=" + fragmented + "]");

switch (messageType)
{
Expand Down Expand Up @@ -649,7 +672,8 @@ internal void HandlePacket(ArraySegment<byte> payload, EndPoint endpoint)

if (secondsDiff > (long)config.ConnectionChallengeTimeWindow || secondsDiff < -(long)config.ConnectionChallengeTimeWindow)
{
// Outside the allowed window
// Outside the allowed window
Logging.Error("Client " + endpoint + " failed the connection request. They were outside of their allowed window. The diff was " + Math.Abs(secondsDiff) + " seconds");
return;
}

Expand Down Expand Up @@ -677,6 +701,7 @@ internal void HandlePacket(ArraySegment<byte> payload, EndPoint endpoint)
if (challengeInitializationVectors[userIv])
{
// This IV is being reused.
Logging.Error("Client " + endpoint + " failed the connection request. They were trying to reuse an IV");
return;
}

Expand All @@ -689,12 +714,15 @@ internal void HandlePacket(ArraySegment<byte> payload, EndPoint endpoint)
if (!isCollided)
{
// They failed the challenge
Logging.Error("Client " + endpoint + " failed the connection request. They submitted an invalid answer");
return;
}

// Save the IV to the sliding window
challengeInitializationVectors[userIv] = true;
}
}

Logging.Info("Client " + endpoint + " is being challenged");

Connection connection = AddNewConnection(endpoint, ConnectionState.RequestingChallenge);

Expand All @@ -713,6 +741,12 @@ internal void HandlePacket(ArraySegment<byte> payload, EndPoint endpoint)

// Send the challenge
connection.SendRaw(new ArraySegment<byte>(outgoingInternalBuffer, 0, 1 + sizeof(ulong) + 1), true);

Logging.Info("Client " + endpoint + " was sent a challenge of difficulty " + connection.ChallengeDifficulty);
}
else
{
Logging.Error("Client " + endpoint + " could not be challenged. Allocation failed");
}
}
break;
Expand All @@ -724,7 +758,8 @@ internal void HandlePacket(ArraySegment<byte> payload, EndPoint endpoint)
{
if (payload.Count < 10)
{
// The message is not large enough to contain all the data neccecary. Wierd server?
// The message is not large enough to contain all the data neccecary. Wierd server?
Logging.Error("Server " + endpoint + " sent us a payload that was too small. Disconnecting");
DisconnectConnection(connection, false, false);
return;
}
Expand Down Expand Up @@ -761,11 +796,12 @@ internal void HandlePacket(ArraySegment<byte> payload, EndPoint endpoint)

// Write the challenge response
outgoingInternalBuffer[0] = HeaderPacker.Pack((byte)MessageType.ChallengeResponse, false);
for (byte i = 0; i < sizeof(ulong); i++) outgoingInternalBuffer[1 + i] = ((byte)(additionsRequired >> (i * 8)));


for (byte i = 0; i < sizeof(ulong); i++) outgoingInternalBuffer[1 + i] = ((byte)(additionsRequired >> (i * 8)));

// Send the challenge response
connection.SendRaw(new ArraySegment<byte>(outgoingInternalBuffer, 0, Math.Max(1 + sizeof(ulong), (int)config.AmplificationPreventionHandshakePadding)), true);
connection.SendRaw(new ArraySegment<byte>(outgoingInternalBuffer, 0, Math.Max(1 + sizeof(ulong), (int)config.AmplificationPreventionHandshakePadding)), true);

Logging.Info("Server " + endpoint + " challenge of difficulty " + connection.ChallengeDifficulty + " was solved. Answer was sent");
}
}
break;
Expand All @@ -774,6 +810,7 @@ internal void HandlePacket(ArraySegment<byte> payload, EndPoint endpoint)
if (payload.Count < config.AmplificationPreventionHandshakePadding)
{
// This message is too small. They might be trying to use us for amplification
Logging.Error("Client " + endpoint + " sent a challenge response that was smaller than the amplification padding");
return;
}

Expand Down Expand Up @@ -804,10 +841,14 @@ internal void HandlePacket(ArraySegment<byte> payload, EndPoint endpoint)
bool isCollided = connection.ChallengeDifficulty == 0 || ((HashProvider.GetStableHash64(claimedCollision) << ((sizeof(ulong) * 8) - connection.ChallengeDifficulty)) >> ((sizeof(ulong) * 8) - connection.ChallengeDifficulty)) == 0;

if (isCollided)
{
{
// Success, they completed the hashcash challenge

Logging.Info("Client " + endpoint + " successfully completed challenge of difficulty " + connection.ChallengeDifficulty);

ConnectPendingConnection(connection);

Logging.Info("Client " + endpoint + " state changed to connected");

connection.HailStatus.Attempts = 1;
connection.HailStatus.HasAcked = false;
Expand All @@ -827,6 +868,8 @@ internal void HandlePacket(ArraySegment<byte> payload, EndPoint endpoint)

connection.SendRaw(new ArraySegment<byte>(outgoingInternalBuffer, 0, 2 + (byte)config.ChannelTypes.Length), true);

Logging.Info("Client " + endpoint + " was sent a hail");

// Send to userspace
UserEventQueue.Enqueue(new NetworkEvent()
{
Expand All @@ -843,8 +886,14 @@ internal void HandlePacket(ArraySegment<byte> payload, EndPoint endpoint)
else
{
// Failed, disconnect them
Logging.Error("Client " + endpoint + " failed the challenge. Disconnecting");

DisconnectConnection(connection, false, false);
}
}
else
{
Logging.Warning("Client " + endpoint + " sent a challenge response but they were either not connected or were not in a RequestingChallenge state. Delayed packets?");
}
}
break;
Expand All @@ -859,13 +908,17 @@ internal void HandlePacket(ArraySegment<byte> payload, EndPoint endpoint)
outgoingInternalBuffer[0] = HeaderPacker.Pack((byte)MessageType.HailConfirmed, false);

// Send confirmation
connectedConnection.SendRaw(new ArraySegment<byte>(outgoingInternalBuffer, 0, 1), true);
connectedConnection.SendRaw(new ArraySegment<byte>(outgoingInternalBuffer, 0, 1), true);

Logging.Info("Hail confirmation sent to " + endpoint);
}
else if (pendingConnection != null && pendingConnection.State == ConnectionState.SolvingChallenge)
{
if (payload.Count < 2)
{
// Invalid size.
Logging.Error("Client " + endpoint + " sent a payload that was too small. Disconnecting");

DisconnectConnection(pendingConnection, false, false);
return;
}
Expand All @@ -878,6 +931,7 @@ internal void HandlePacket(ArraySegment<byte> payload, EndPoint endpoint)
if (payload.Count < channelCount + 2)
{
// Invalid size.
Logging.Error("Client " + endpoint + " sent a payload that was too small. Disconnecting");
DisconnectConnection(pendingConnection, false, false);
return;
}
Expand Down Expand Up @@ -919,10 +973,11 @@ internal void HandlePacket(ArraySegment<byte> payload, EndPoint endpoint)
break;
default:
{
// Unknown channel type. Disconnect.
DisconnectConnection(pendingConnection, false, false);
// Unknown channel type. Disconnect.
Logging.Error("Client " + endpoint + " sent an invalid ChannelType. Disconnecting");
DisconnectConnection(pendingConnection, false, false);
return;
}
break;
}
}

Expand Down Expand Up @@ -974,14 +1029,17 @@ internal void HandlePacket(ArraySegment<byte> payload, EndPoint endpoint)
default:
{
// Unknown channel type. Disconnect.
DisconnectConnection(pendingConnection, false, false);
}
break;
Logging.Error("Client " + endpoint + " sent an invalid ChannelType. Disconnecting");
DisconnectConnection(pendingConnection, false, false);
return;
}
}
}

// Set state to connected
ConnectPendingConnection(pendingConnection);
ConnectPendingConnection(pendingConnection);

Logging.Info("Client " + endpoint + " state changed to connected");

// Send to userspace
UserEventQueue.Enqueue(new NetworkEvent()
Expand All @@ -1001,6 +1059,8 @@ internal void HandlePacket(ArraySegment<byte> payload, EndPoint endpoint)

// Send confirmation
pendingConnection.SendRaw(new ArraySegment<byte>(outgoingInternalBuffer, 0, 1), true);

Logging.Info("Client " + endpoint + " was sent hail confimrations");
}
}
break;
Expand All @@ -1014,6 +1074,10 @@ internal void HandlePacket(ArraySegment<byte> payload, EndPoint endpoint)
{
connection.HailStatus.HasAcked = true;
}
}
else
{
Logging.Error("Client " + endpoint + " connection could not be found");
}
}
break;
Expand All @@ -1022,7 +1086,8 @@ internal void HandlePacket(ArraySegment<byte> payload, EndPoint endpoint)
if (!config.EnableHeartbeats)
{
// TODO: Handle
// This is a missmatch.
// This is a missmatch.
Logging.Error("Heartbeat received from " + endpoint + " but the we do not have heartbeats enabled. Configuration missmatch?");
return;
}

Expand All @@ -1036,6 +1101,10 @@ internal void HandlePacket(ArraySegment<byte> payload, EndPoint endpoint)
{
connection.LastMessageIn = DateTime.Now;
}
}
else
{
Logging.Error("Client " + endpoint + " connection could not be found");
}
}
break;
Expand All @@ -1048,6 +1117,10 @@ internal void HandlePacket(ArraySegment<byte> payload, EndPoint endpoint)
connection.LastMessageIn = DateTime.Now;

PacketHandler.HandleIncomingMessage(new ArraySegment<byte>(payload.Array, payload.Offset + 1, payload.Count - 1), connection, config);
}
else
{
Logging.Error("Client " + endpoint + " connection could not be found");
}
}
break;
Expand All @@ -1071,6 +1144,10 @@ internal void HandlePacket(ArraySegment<byte> payload, EndPoint endpoint)

// Handle ack
channel.HandleAck(new ArraySegment<byte>(payload.Array, payload.Offset + 2, payload.Count - 2));
}
else
{
Logging.Error("Client " + endpoint + " connection could not be found");
}
}
break;
Expand All @@ -1081,6 +1158,10 @@ internal void HandlePacket(ArraySegment<byte> payload, EndPoint endpoint)
if (connection != null)
{
connection.Disconnect(false);
}
else
{
Logging.Error("Client " + endpoint + " connection could not be found");
}
}
break;
Expand Down Expand Up @@ -1269,8 +1350,9 @@ internal Connection AddNewConnection(EndPoint endpoint, ConnectionState state)
break;
default:
{
// Unknown channel type. Disconnect.
// Unknown channel type. Disconnect.
// TODO: Fix
Logging.Error("Client " + endpoint + " sent an invalid ChannelType. Disconnecting");
DisconnectConnection(connection, false, false);
}
break;
Expand Down
Loading

0 comments on commit fd4a9fd

Please sign in to comment.