/// <summary>
        /// Connects to the server specified by the address and port, sends the request and waits for a response.
        /// </summary>
        /// <param name="address">The address of the server, either an IPv4 address or Dns hostname</param>
        /// <param name="port">The port of the server</param>
        /// <param name="request">The request to send</param>
        /// <param name="exception">Any exception that is throw or encountered during the request/response session with the server</param>
        /// <param name="verbose">A flag that indicates the connection's verbosity level, true for more messages</param>
        /// <returns></returns>
        public static HttpResponse GetResponse(
            string address,
            int port,
            HttpRequest request,
            out Exception exception,
            bool verbose,
            EventHandler <AddressResolutionEventArgs> onResolvingAddress,
            EventHandler <HttpMessageProgressEventArgs> onSendProgress,
            EventHandler <HttpMessageProgressEventArgs> onRecvProgress,
            object stateObject)
        {
            exception = null;

            try
            {
                // parse the address using either IPv4 or Dns for hostnames into an end point with the port specified
                IPEndPoint ep = SocketUtilities.Resolve(address, port, null, onResolvingAddress, stateObject);

                // return a response from the server
                return(HttpRequest.GetResponse(ep, request, out exception, verbose, onSendProgress, onRecvProgress, stateObject));
            }
            catch (ThreadAbortException)
            {
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            return(null);
        }
        public static void ManageAnonymous(object socket)
        {
            AnonymousThread client = (AnonymousThread)socket;

            try
            {
                var clientStream = client.Client.GetStream();
                if (Program.ServerState == 0)
                {
                    SocketUtilities.SendShutdown(clientStream, "The server is shutting down", "0");
                    clientStream.Close();
                    return;
                }
                string smessage = SocketUtilities.RecieveMessage(clientStream, SocketUtilities.RecieveMessageLength(clientStream));
                if (smessage == null)
                {
                    Program.Disconnect(ThreadType.AnonymousThread, client.Guid);
                    return;
                }
                CommandParameterPair message = MessageUtilites.DecodeMessage(smessage);
                var builder = new StringBuilder();
                foreach (string i in message.Parameters)
                {
                    builder.Append(String.Format("{0} with", i));
                }
                ConsoleUtilities.PrintCommand(String.Format("{0} has sent command {1} with parameters {2}", client.Guid, message.Command, builder));
                InitializeCommand execute;
                if (Program.InitializeCommands.TryGetValue(message.Command, out execute))
                {
                    execute(client.Client, message.Parameters);
                }
                else
                {
                    SocketUtilities.SendError(clientStream, "Unable to find command (Concurrency Issues)");
                    clientStream.Close();
                }
            }
            catch (SocketException e)
            {
                if (client.Client.Client.RemoteEndPoint == null)
                {
                    Console.WriteLine("A severe error has occurred with the clientStream. Data: {0}", e.Data);
                    return;
                }
                Console.WriteLine("Error: A clientStream has disconnected from {0}. ", (client.Client.Client.RemoteEndPoint as IPEndPoint).Address);
            }
            catch (IOException e)
            {
                if (client.Client.Client.RemoteEndPoint == null)
                {
                    Console.WriteLine("A severe error has occurred with the clientStream. Data: {0}", e.Data);
                    return;
                }
                Console.WriteLine("Error: A clientStream has disconnected from {0}. ", (client.Client.Client.RemoteEndPoint as IPEndPoint).Address);
            }
        }
Example #3
0
        public static void SecureConnect(TcpClient tcpclient, params string[] value)
        {
            var stream = tcpclient.GetStream();

            if (Program.ServerProperties["SSLENABLED"] == "false")
            {
                SocketUtilities.SendInvalid(stream, "SSL isn't enabled on this server");
                tcpclient.Close();
                return;
            }
            if (value.Length != 2)
            {
                SocketUtilities.SendInvalid(stream, "Incorrect number of parameters");
                tcpclient.Close();
                return;
            }
            string username = value[0];
            string client   = value[1];

            if (Program.Clients.ContainsKey(username))
            {
                SocketUtilities.SendCommand(stream, new CommandParameterPair("INVALIDUN {0}", username));
                tcpclient.Close();
                return;
            }
            string certFile;

            if (!Program.ServerDependencies.TryGetValue("SSLCERT", out certFile))
            {
                SocketUtilities.SendInvalid(stream, "SSL isn't properly supported on this server");
                tcpclient.Close();
                return;
            }
            string password;

            if (!Program.ServerDependencies.TryGetValue("SSLPASS", out password))
            {
                SocketUtilities.SendInvalid(stream, "SSL isn't properyly supported on this serverserver");
                tcpclient.Close();
                return;
            }
            var service = new UserClientService(new SecureClient(stream, certFile, username, client, new ConcurrentDictionary <string, string>(), new ConcurrentDictionary <string, string>(), DateTime.UtcNow, password), true);

            service.SendCommand(new CommandParameterPair("CONNECTED"));
            Program.Clients.TryAdd(username, service);
            var thread = new Thread(ClientManagement.ManageClient);

            thread.Start(service);
            Program.ClientThreads.TryAdd(username, thread);
        }
        public static void GetIdShouldReturnCorrectIds()
        {
            //Arrange
            SocketManager    socketManager    = MockData.GetSocketManager();
            SocketRepository socketRepository = new SocketRepository(socketManager);

            string test =
                "42[\"msg\",{\"id\":15,\"type\":\"System/getTime\",\"headers\":{\"traveltimes\":[[\"browser_send\",1574343907381]]}}]";

            //Act
            int?result = SocketUtilities.GetId(test);


            // Assert
            Assert.NotNull(result);
        }
Example #5
0
        public static void RequestInfo(TcpClient tcpClient, params string[] value)
        {
            var stream = tcpClient.GetStream();

            if (value.Length != 0)
            {
                SocketUtilities.SendInvalid(stream, "INFOREQ should not send parameters");
                tcpClient.Close();
                return;
            }
            SocketUtilities.SendCommand(stream, new CommandParameterPair("INFORESP",
                                                                         JsonConvert.SerializeObject(Program.ServerProperties.ToDictionary(kvp => kvp.Key, kvp => kvp.Value))));
            Thread          thread  = new Thread(AcceptClientManagement.ManageAnonymous);
            AnonymousThread athread = new AnonymousThread(tcpClient.Client.RemoteEndPoint.ToString(), tcpClient);

            thread.Start(athread);
            Program.AnonymousThreads.TryAdd(tcpClient.Client.RemoteEndPoint.ToString(), thread);
        }
Example #6
0
        public static void Connect(TcpClient tcpClient, params string[] parameters)
        {
            if (!tcpClient.Connected)
            {
                tcpClient.Close();
                return;
            }
            NetworkStream stream = tcpClient.GetStream();

            if (parameters.Length != 2)
            {
                SocketUtilities.SendInvalid(stream, "Parameters not formatted correctly");
                stream.Close();
                tcpClient.Close();
                return;
            }
            string username = parameters[0];
            string client   = parameters[1];

            if (Program.Clients.ContainsKey(username) | username.Trim().ToLower() == "system" | username.Length > 15)
            {
                SocketUtilities.SendCommand(stream, new CommandParameterPair("INVALIDUN"));
                stream.Close();
                tcpClient.Close();
                return;
            }

            var service = new UserClientService(new UserClient(username, client, tcpClient, new ConcurrentDictionary <string, string>(), new ConcurrentDictionary <string, string>(), DateTime.UtcNow));

            SocketUtilities.SendCommand(stream, new CommandParameterPair("CONNECTED"));

            ConsoleUtilities.PrintWarning("Got here!");
            foreach (IMessagingClient sclient in Program.Clients.Values)
            {
                sclient.Alert(String.Format("{0} has connected", username), 3);
            }
            ConsoleUtilities.PrintInformation("Connected {0}", username);
            Program.Clients.TryAdd(username, service);
            Thread thread = new Thread(ClientManagement.ManageClient);

            thread.Start(service);
            Program.ClientThreads.TryAdd(username, thread);
        }
Example #7
0
        public static WebHeaderCollection GetWebBrowserRequestHeaders(IWebBrowserInfo webBrowserInfo, TimeSpan timeout, string responseBody)
        {
            WebHeaderCollection requestHeaders = new WebHeaderCollection();

            if (webBrowserInfo is null)
            {
                throw new ArgumentNullException(nameof(webBrowserInfo));
            }

            if (!File.Exists(webBrowserInfo?.ExecutablePath))
            {
                throw new FileNotFoundException();
            }

            // Start an HTTP server on a random port.

            Uri  requestUri        = new Uri($"http://localhost:{SocketUtilities.GetUnusedPort()}/");
            bool listenForRequests = true;

            using (HttpListener listener = new HttpListener()) {
                listener.Prefixes.Add(requestUri.AbsoluteUri);

                listener.Start();

                // Open the HTTP server in the user's web browser.

                Process.Start(webBrowserInfo.ExecutablePath, requestUri.AbsoluteUri);

                // Wait for an incoming request.

                while (listenForRequests)
                {
                    listenForRequests = false;

                    HttpListenerContext context = listener.GetContext(timeout);

                    if (!(context is null))
                    {
                        HttpListenerRequest request = context.Request;

                        if (request.HttpMethod.Equals("get", StringComparison.OrdinalIgnoreCase))
                        {
                            // The web browser requested our webpage, so copy the request headers.

                            context.Request.Headers.CopyTo(requestHeaders);

                            // Respond to the request.

                            HttpListenerResponse response = context.Response;

                            StringBuilder responseBuilder = new StringBuilder();

                            responseBuilder.AppendLine("<!DOCTYPE html>");
                            responseBuilder.Append("<html>");
                            responseBuilder.Append("<body>");
                            responseBuilder.Append("<script>fetch(\"" + requestUri.AbsoluteUri + "\", {method: \"POST\"});</script>");
                            responseBuilder.Append(responseBody ?? "This window may now be closed.");
                            responseBuilder.Append("</body>");
                            responseBuilder.Append("</html>");

                            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(responseBuilder.ToString())))
                                ms.CopyTo(response.OutputStream);

                            response.Close();

                            // Wait for the web browser to POST back let us know it got our response.

                            listenForRequests = true;
                        }
                        else
                        {
                            // The web browser has POSTed back to let us know it got our response.
                        }
                    }
                }
            }

            return(requestHeaders);
        }
        public static void AcceptNewClients()
        {
            Console.WriteLine("Thread started");
            while (true)
            {
                try
                {
                    TcpClient tcpClient = Program.ServerSocket.AcceptTcpClient();
                    if (Program.ServerState == 0)
                    {
                        ConsoleUtilities.PrintCritical("Thread has been ended {0}", DateTime.UtcNow);
                        return;
                    }
                    if (Program.ServerState == 2)
                    {
                        Thread.Sleep(Timeout.Infinite);
                    }
                    NetworkStream clientStream = tcpClient.GetStream();
                    ConsoleUtilities.PrintCommand("Connection has been accepted from {0}", tcpClient.Client.RemoteEndPoint);

                    if (Program.AnonymousThreads.ContainsKey(tcpClient.Client.RemoteEndPoint.ToString()))
                    {
                        SocketUtilities.SendInvalid(clientStream, "Your network is already connected. Try again later.");
                        tcpClient.Close();
                        continue;
                    }

                    int messageLength = SocketUtilities.RecieveMessageLength(clientStream);
                    if (messageLength == -1)
                    {
                        ConsoleUtilities.PrintCommand("Connection has been closed for {0}", tcpClient.Client.RemoteEndPoint);
                        tcpClient.Close();
                        continue;
                    }
                    string stringmessage = SocketUtilities.RecieveMessage(clientStream, messageLength);
                    if (stringmessage == null)
                    {
                        tcpClient.Close();
                        continue;
                    }

                    CommandParameterPair message = MessageUtilites.DecodeMessage(stringmessage);
                    if (message == null)
                    {
                        SocketUtilities.SendInvalid(clientStream, "The message was formatted incorrectly.");
                        tcpClient.Close();
                        continue;
                    }

                    if (!Program.InitializeCommands.ContainsKey(message.Command))
                    {
                        SocketUtilities.SendInvalid(clientStream, "The command was not found");
                        tcpClient.Close();
                        continue;
                    }

                    InitializeCommand execute;
                    if (Program.InitializeCommands.TryGetValue(message.Command, out execute))
                    {
                        execute(tcpClient, message.Parameters);
                        continue;
                    }
                    SocketUtilities.SendError(clientStream, "Unable to find command (Concurrency Issues)");
                    if (Program.ServerState == 0)
                    {
                        Console.WriteLine("Thread has been ended");
                        return;
                    }
                    if (Program.ServerState == 2)
                    {
                        Thread.Sleep(Timeout.Infinite);
                    }
                }
                catch (ThreadAbortException e)
                {
                    Console.WriteLine("Thread has been stopped {0}", e.Data.Values);
                    return;
                }
                catch (InvalidOperationException e)
                {
                    ConsoleUtilities.PrintCritical("Accept thread has been terminated {0}", e.Message);
                    return;
                }
                catch (ThreadInterruptedException)
                {
                    Console.WriteLine("Resuming accepting threads");
                }
                catch (IOException e)
                {
                    ConsoleUtilities.PrintWarning("Impropert disconnect. {1}", e.Message);
                }
                catch (SocketException e)
                {
                    ConsoleUtilities.PrintWarning("Improper disconnect. Data: {0}", e.Data);
                }
            }
        }