Example #1
0
        /// <summary>
        /// Callback when one client successfully connected to the server.
        /// </summary>
        private void AcceptCallback(IAsyncResult ar)
        {
            try
            {
                // Signal the connect thread to continue.
                connectDone.Set();

                // Dont accept connection if the server is not running and the listener is null
                if (!IsServerRunning || _listener == null)
                {
                    log.Error("Server is not running");
                    return;
                }

                // Get the socket that handles the client request.
                Socket listener = (Socket)ar.AsyncState;
                Socket handler  = listener.EndAccept(ar);

                IPEndPoint ipEndPoint = handler.RemoteEndPoint as IPEndPoint;

                // Try to get the Hostname of the client which will connect to the server
                IPHostEntry entry = ServerFunctions.GetIPHostEntryOfClient(ipEndPoint);

                // Check if the client which wants to connect is already connected.
                // If Client is not connected then try to connect to the server
                if (!ServerFunctions.CheckClientStatus(this.ConnectedClients, handler, false) && ipEndPoint != null)
                {
                    // Add connected Client to the listbox
                    ServerWindow.Dispatcher.Invoke(new AddClientHandler(ServerWindow.AddClient), ipEndPoint, entry);

                    // Add connected client to the connected client list
                    this.ConnectedClients.Add(handler);

                    log.Info("Client " + entry.HostName + " successfully connected to the server.");
                    log.Info("");
                }
                else
                {
                    // Check if the already connected client is still connected.
                    // If the already connected client is connected then close the same client which tries to connect again
                    if (ServerFunctions.CheckClientStatus(this.ConnectedClients, handler, true))
                    {
                        log.Info("Client " + entry.HostName + " already connected. Dont connect to server.");

                        // Close socket because this socket is already connected
                        handler.Shutdown(SocketShutdown.Both);
                        handler.Close();
                    }
                    else
                    {
                        // Delete the already connected client and connect the new client which tries to connect
                        this.DeleteAndAddConnectedClient(this.ConnectedClients, handler);
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
            }
        }
Example #2
0
        /// <summary>
        /// Delete Socket if its closed and reset the UI
        /// </summary>
        public void ResetUIAfterSocketException(Socket clientSocket)
        {
            IPEndPoint ipEndPoint = clientSocket.RemoteEndPoint as IPEndPoint;
            string     address    = ipEndPoint.Address.ToString();

            log.Warn("Request problem from client: " + address);
            this.UpdateLogStatus(ServerFunctions.GetCurrentDateTime() + ServerFunctions.LogTextWarning + "Request problem from client: " + address);

            bool clientConnected = ServerFunctions.CheckClientConnected(clientSocket);

            if (!clientConnected)
            {
                log.Warn("Selected client :" + address + " is not connected. Remove client from list.");
                this.UpdateLogStatus(ServerFunctions.GetCurrentDateTime() + ServerFunctions.LogTextWarning + "Selected client :" + address + " is not connected. Remove client from list.");
                this.UpdateLogStatus("\n");

                this.RemoveClient(address, false);
                this.RemoveClientSocket(address, false);

                try
                {
                    clientSocket.Shutdown(SocketShutdown.Both);
                    clientSocket.Close();
                }
                catch (ObjectDisposedException)
                {
                    // Socket is already closed. Do nothing
                }
            }

            progressBar.Visibility    = Visibility.Hidden;
            tbProgressText.Visibility = Visibility.Hidden;
            btnRequestLogs.IsEnabled  = true;
            lbxServer.IsEnabled       = true;
        }
Example #3
0
        /// <summary>
        /// Method to check if the client which wants to connect again already connected.
        /// We can avoid clients to connected several times
        /// Iterate through already connected clients list and check if this client is in the list
        /// </summary>
        public static bool CheckClientStatus(IList <Socket> socketList, Socket socket, bool checkConnection)
        {
            IPEndPoint socket1 = socket.RemoteEndPoint as IPEndPoint;

            for (int i = 0; i < socketList.Count; i++)
            {
                IPEndPoint socket2 = socketList[i].RemoteEndPoint as IPEndPoint;

                if (socket1.Address.Equals(socket2.Address))
                {
                    // Check if socket is connected
                    if (checkConnection)
                    {
                        if (ServerFunctions.CheckClientConnected(socketList[i]))
                        {
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
Example #4
0
 public UserInstance(TcpClient user, ServerFunctions server)
 {
     userID         = nextID;
     this.user      = user;
     serverFunction = server;
     SetNickPassRegister();
     nextID++;
 }
Example #5
0
        /// <summary>
        /// Creates a <see cref="ServiceManager"/>.
        /// </summary>
        /// <param name="moduleRepository">A <see cref="IModuleRepository"/> implementation.</param>
        /// <param name="accountManager">The <see cref="AccountManager"/>.</param>
        public ServiceManager(IModuleRepository moduleRepository, AccountManager accountManager)
        {
            this.logManager           = new LogManager();
            this.services             = new Dictionary <long, ModuleInstance>();
            this.packetManager        = new PacketManager();
            this.pluginNetworking     = new PluginNetworking(packetManager, accountManager);
            this.moduleRepository     = moduleRepository;
            this.customPacketDatabase = new CustomPacketDatabase(RepositoryFactory.CustomRepository());
            this.serverFunctions      = new ServerFunctions(accountManager);

            // Start services from database
            LoadServices();
        }
Example #6
0
        public ServerWindow()
        {
            InitializeComponent();

            // Starts method to read the server configuration from the xml file.
            // Creates a xml configuration file when it doesnt exist.
            ServerFunctions.ServerStartPreparation();

            server           = new AsynchronousServer();
            this.DataContext = server;

            // Starts listening to client connections asynchronously in a new thread
            this.StartListeningToClients();
        }
Example #7
0
        private void Button_RestartServer(object sender, RoutedEventArgs e)
        {
            log.Info("Server has been restarted by user");

            // Starts method to read the server configuration from the xml file.
            // Creates a xml configuration file when it doesnt exist.
            ServerFunctions.ServerStartPreparation();

            Thread listener = new Thread(() => server.RestartServer())
            {
                IsBackground = true
            };

            listener.Start();
        }
Example #8
0
 static void Main(string[] args)
 {
     try
     {
         server       = new ServerFunctions();
         listenThread = new Thread(new ThreadStart(server.ListenConnections));
         listenThread.Start();
         showStatusThread = new Thread(new ThreadStart(server.ShowInfo));
         showStatusThread.Start();
     }
     catch (Exception exception)
     {
         server.DisconnectServer();
         Console.WriteLine(exception.Message);
     }
 }
Example #9
0
        /// <summary>
        /// Method which which deletes the disconnected client and connect the new client which tries to connect
        /// </summary>
        private void DeleteAndAddConnectedClient(IList <Socket> socketList, Socket socket)
        {
            IPEndPoint s1 = socket.RemoteEndPoint as IPEndPoint;

            for (int i = 0; i < socketList.Count; i++)
            {
                try
                {
                    IPEndPoint s2 = socketList[i].RemoteEndPoint as IPEndPoint;

                    if (s1.Address.Equals(s2.Address))
                    {
                        ServerWindow.Dispatcher.Invoke(new RemoveClientSocketHandler(ServerWindow.RemoveClient), s1.Address.ToString(), false);

                        ServerWindow.Dispatcher.Invoke(new RemoveClientHandler(ServerWindow.RemoveClientSocket), s1.Address.ToString(), false);

                        // Add connected Client to the listbox
                        // Try to get the Hostname of the client which will connect to the server
                        IPEndPoint  ipEndPoint = socket.RemoteEndPoint as IPEndPoint;
                        IPHostEntry entry      = ServerFunctions.GetIPHostEntryOfClient(ipEndPoint);

                        // Add connected Client to the listbox
                        ServerWindow.Dispatcher.Invoke(new AddClientHandler(ServerWindow.AddClient), ipEndPoint, entry);

                        // Add connected client to the connected client list
                        this.ConnectedClients.Add(socket);

                        log.Info("Client " + entry.HostName + " successfully reconnected to the server.");
                        log.Info("");

                        return;
                    }
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message, ex);
                }
            }
        }
Example #10
0
        private void Button_RequestLogs(object sender, RoutedEventArgs e)
        {
            try
            {
                if (lbxServer.SelectedItems.Count != 0)
                {
                    // Check selected clients before log request if there are connected
                    for (int i = 0; i < lbxServer.SelectedItems.Count; i++)
                    {
                        for (int j = 0; j < server.ConnectedClients.Count; j++)
                        {
                            string iPAddress = "";

                            IPEndPoint ipEndPoint = server.ConnectedClients[j].RemoteEndPoint as IPEndPoint;
                            string     address    = ipEndPoint.Address.ToString();

                            int index = lbxServer.SelectedItems[i].ToString().IndexOf(" ");

                            if (index > 0)
                            {
                                iPAddress = lbxServer.SelectedItems[i].ToString().Substring(0, index);
                            }

                            if (string.Equals(iPAddress, address, StringComparison.OrdinalIgnoreCase))
                            {
                                // Check if selected clients are still connected
                                bool isClientConnected = ServerFunctions.CheckClientConnected(server.ConnectedClients[j]);

                                if (!isClientConnected)
                                {
                                    log.Warn("Selected client :" + lbxServer.SelectedItems[i].ToString() + " is not connected. Remove client from list.");
                                    this.UpdateLogStatus(ServerFunctions.GetCurrentDateTime() + ServerFunctions.LogTextWarning + "Selected client :" + lbxServer.SelectedItems[i].ToString() + " is not connected. Remove client from list.");
                                    this.UpdateLogStatus("\n");

                                    this.RemoveClientSocket(lbxServer.SelectedItems[i].ToString(), true);

                                    this.RemoveClient(lbxServer.SelectedItems[i].ToString(), true);
                                }
                            }
                        }
                    }

                    // Check selected clients for log request
                    foreach (object item in lbxServer.SelectedItems)
                    {
                        // Iterate through the list with connected clients and check if its selected by the user.
                        // If yes: Add the client to the list for log request
                        foreach (Socket handler in server.ConnectedClients)
                        {
                            IPEndPoint ipEndPoint = handler.RemoteEndPoint as IPEndPoint;
                            string     address    = ipEndPoint.Address.ToString();

                            string selectedItem = item.ToString();
                            int    index        = selectedItem.IndexOf(" ");

                            if (index > 0)
                            {
                                selectedItem = selectedItem.Substring(0, index);
                            }

                            if (string.Equals(selectedItem, address, StringComparison.OrdinalIgnoreCase))
                            {
                                server.SelectedClientsForCollectingLogs.Add(handler);
                            }
                        }
                    }

                    foreach (Socket handler in server.SelectedClientsForCollectingLogs)
                    {
                        Thread logsRequester = new Thread(() => this.RequestLogsOneByOne(handler))
                        {
                            IsBackground = true
                        };
                        logsRequester.Start();
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
            }
        }
Example #11
0
        /// <summary>
        /// Receive the file send by the client.
        /// </summary>
        private void Receive()
        {
            // Data buffer for incoming data.
            byte[] buffer = new byte[BUFFER_SIZE];

            BinaryWriter writer = null;

            long bytesLeftToReceive = _fileLength;

            // Stop progress bar indeterminate mode after copying and zipping progress is finished.
            AsynchronousServer.ServerWindow.Dispatcher.BeginInvoke(new ProgressBarIndeterminateSetHandler(AsynchronousServer.ServerWindow.ProgressBarIndeterminateMode), false);

            // Prepare progress bar. Set the file length for the progress bar.
            AsynchronousServer.ServerWindow.Dispatcher.BeginInvoke(new SetProgressLengthHandler(AsynchronousServer.ServerWindow.SetProgressLength), _fileLength);

            // Check and delete log file from this client if its already exists for the current date.
            try
            {
                DateTime date     = DateTime.Now;
                DateTime dateOnly = date.Date;

                // Check if log zip folder already exists. If yes delete log zip folder, create new file
                if (File.Exists(_fileSavePath + dateOnly.ToString("yyyy/MM/dd") + "_" + _clientName + ".zip"))
                {
                    try
                    {
                        File.Delete(_fileSavePath + dateOnly.ToString("yyyy/MM/dd") + "_" + _clientName + ".zip");
                    }
                    catch (Exception ex)
                    {
                        log.Error(ex.Message, ex);
                    }
                }

                _fileSavePath += dateOnly.ToString("yyyy/MM/dd") + "_" + _clientName + ".zip";

                writer = new BinaryWriter(File.Open(_fileSavePath, FileMode.Create));

                do
                {
                    // Receive log file from client
                    int bytesRead = _clientSocket.Receive(buffer);

                    if (bytesRead == 0)
                    {
                        log.Warn("Logs from Client " + _clientName + " could not be received. Remote endpoint disconnected");
                    }

                    // Write to file
                    writer.Write(buffer, 0, bytesRead);
                    writer.Flush();

                    AsynchronousServer.ServerWindow.Dispatcher.BeginInvoke(new ProgressChangeHandler(AsynchronousServer.ServerWindow.ProgressChanged), bytesRead);

                    bytesLeftToReceive -= bytesRead;
                } while (bytesLeftToReceive > 0);

                writer.Close();

                log.Info("Logs from Client " + _clientName + " successfully received.");
                log.Info("Logs for Client " + _clientName + " can be found under: " + _fileSavePath);
                log.Info("");

                AsynchronousServer.ServerWindow.Dispatcher.BeginInvoke(new SetStatusLogHandler(AsynchronousServer.ServerWindow.UpdateLogStatus), ServerFunctions.GetCurrentDateTime() + ServerFunctions.LogTextInfo + " Logs from Client " + _clientName + " successfully received.");
                AsynchronousServer.ServerWindow.Dispatcher.BeginInvoke(new SetStatusLogHandler(AsynchronousServer.ServerWindow.UpdateLogStatus), ServerFunctions.GetCurrentDateTime() + ServerFunctions.LogTextInfo + " Logs for Client " + _clientName + " can be found under: " + _fileSavePath);
                AsynchronousServer.ServerWindow.Dispatcher.BeginInvoke(new SetStatusLogHandler(AsynchronousServer.ServerWindow.UpdateLogStatus), "\n");

                // Signal that all bytes have been received. Ready for request logs from client.
                receiveDone.Set();
            }
            catch (SocketException)
            {
                throw;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
            }
        }
Example #12
0
 public SychronousServerFunctions(Socket clientSocket)
 {
     _clientSocket = clientSocket;
     _clientName   = ServerFunctions.GetHostNameOfClient(_clientSocket);
     _fileSavePath = Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\AppData\Local\SeeTec\Templogs\");
 }
Example #13
0
        public void SendLogsRequest()
        {
            AsynchronousServer.ServerWindow.Dispatcher.BeginInvoke(new ListBoxEnabledHandler(AsynchronousServer.ServerWindow.ListBoxEnabled), false);

            byte[] msg = Encoding.UTF8.GetBytes("RequestLogs");

            try
            {
                // Send client a request trigger
                _clientSocket.Send(msg);

                AsynchronousServer.ServerWindow.Dispatcher.BeginInvoke(new ProgressBarIndeterminateSetHandler(AsynchronousServer.ServerWindow.ProgressBarIndeterminateMode), true);

                log.Info("Logs from Client " + _clientName + " requested.");
                AsynchronousServer.ServerWindow.Dispatcher.BeginInvoke(new SetStatusLogHandler(AsynchronousServer.ServerWindow.UpdateLogStatus), ServerFunctions.GetCurrentDateTime() + ServerFunctions.LogTextInfo + " Logs from Client " + _clientName + " requested.");

                // Receive the length information of the log zip folder from the client
                ReceiveFileInfo();

                // Receive the zip folder.
                Receive();
                receiveDone.WaitOne();

                // Notify the user whether receive the file completely.
                AsynchronousServer.ServerWindow.Dispatcher.BeginInvoke(new FileReceiveDoneHandler(AsynchronousServer.ServerWindow.FileReceiveDone));
            }
            catch (SocketException)
            {
                AsynchronousServer.ServerWindow.Dispatcher.BeginInvoke(new ResetUIAfterSocketExceptionHandler(AsynchronousServer.ServerWindow.ResetUIAfterSocketException), _clientSocket);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
            }
        }
Example #14
0
        /// <summary>
        /// Receive the file information send by the server.
        /// </summary>
        private void ReceiveFileInfo()
        {
            try
            {
                // Get the file length from the server.
                byte[] fileLenByte = new byte[8];

                _clientSocket.Receive(fileLenByte);

                _fileLength = BitConverter.ToInt64(fileLenByte, 0);

                AsynchronousServer.ServerWindow.Dispatcher.BeginInvoke(new SetStatusLogHandler(AsynchronousServer.ServerWindow.UpdateLogStatus), ServerFunctions.GetCurrentDateTime() + ServerFunctions.LogTextInfo + " Log zip file size for Client " + _clientName + " is " + ServerFunctions.CheckZipSize(_fileLength) + " MB");
            }
            catch (SocketException)
            {
                throw;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
            }
        }