Example #1
0
        /// <summary>
        /// Checks if a provided email is valid
        /// </summary>
        /// <param name="stream">The stream that sended the data</param>
        /// <param name="dict">The request that the stream sended</param>
        private void IsEmailValid(TCPStream stream, Dictionary <string, string> dict)
        {
            if (!dict.ContainsKey("email"))
            {
                SendErrorAndFreeStream(stream, 1, "There was an error parsing an incoming request.");
                return;
            }

            try
            {
                if (databaseDriver.Query("SELECT userid FROM users WHERE LOWER(email)=@P0", dict["email"].ToLowerInvariant()).Count != 0)
                {
                    stream.SendAsync(@"\vr\1\final\");
                }
                else
                {
                    stream.SendAsync(@"\vr\0\final\");
                }
            }
            catch (Exception ex)
            {
                LogWriter.Log.WriteException(ex);
                SendErrorAndFreeStream(stream, 4, "This request cannot be processed because of a database error.");
            }
        }
Example #2
0
        protected override void ProcessAccept(TCPStream Stream)
        {
            // Get our connection id
            long       connId = Interlocked.Increment(ref ConnectionCounter);
            GPCMClient client;

            try
            {
                // Create a new GpcmClient, passing the IO object for the TcpClientStream
                client = new GPCMClient(Stream, connId, databaseDriver);
                Processing.TryAdd(connId, client);

                // Begin the asynchronous login process
                client.SendServerChallenge(1);
            }
            catch (Exception e)
            {
                // Log the error
                LogWriter.Log.WriteException(e);

                // Remove pending connection
                Processing.TryRemove(connId, out client);

                // Release this stream so it can be used again
                Release(Stream);
            }
        }
Example #3
0
        private void ReverseBuddies(TCPStream stream, Dictionary <string, string> dict)
        {
            //            PrintReceivedDictToLogger("others", dict);
            //            SendErrorAndFreeStream(stream, 0, "This request is not supported yet.");

            stream.SendAsync(@"\others\\odone\final\");
        }
Example #4
0
        /// <summary>
        /// Creates an account
        /// </summary>
        /// <param name="stream">The stream that sended the data</param>
        /// <param name="dict">The request that the stream sended</param>
        private void CreateUser(TCPStream stream, Dictionary <string, string> dict)
        {
            //string UniqueNick;

            PrintReceivedDictToLogger("newuser", dict);
            SendErrorAndFreeStream(stream, 0, "This request is not supported yet.");
        }
Example #5
0
        /// <summary>
        /// 发送报文至指定的客户端
        /// </summary>
        /// <param name="tcpClient">客户端</param>
        /// <param name="datagram">报文</param>
        public bool Send(TcpClient tcpClient, byte[] datagram)
        {
            bool result = false;

            if (!IsRunning)
            {
                LogHelper.WriteLog(DateTime.Now.ToString("HH-mm-ss:") + tcpClient.Client.RemoteEndPoint.ToString() + "This TCP server has not been started.");
                //throw new InvalidProgramException("This TCP server has not been started.");
                return(false);
            }


            if (tcpClient == null)
            {
                LogHelper.WriteLog(DateTime.Now.ToString("HH-mm-ss:") + tcpClient.Client.RemoteEndPoint.ToString() + "参数tcpClient空值异常");
                //throw new ArgumentNullException("tcpClient");
                return(false);
            }


            if (datagram == null)
            {
                LogHelper.WriteLog(DateTime.Now.ToString("HH-mm-ss:") + tcpClient.Client.RemoteEndPoint.ToString() + "参数datagram空值异常");
                //throw new ArgumentNullException("datagram");
                return(false);
            }

            try
            {
                NetworkStream TCPStream;// = tcpClient.GetStream();
                //boxes.Common.LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "发送报文失败;" + ee.Message + "位置:" + ee.StackTrace);
                if (tcpClient != null && tcpClient.Connected)
                {
                    TCPStream = tcpClient.GetStream();
                    LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + ";TCPStream:" + TCPStream.ToString());
                    if (TCPStream.CanWrite)
                    {
                        TCPStream.BeginWrite(datagram, 0, datagram.Length, HandleDatagramWritten, tcpClient);
                        result = true;
                    }
                }
                else
                {
                    result = false;
                }
                //tcpClient.GetStream().BeginWrite(datagram, 0, datagram.Length, HandleDatagramWritten, tcpClient);原代码
                result = true;
            }
            catch (Exception ee)
            {
                LogHelper.WriteLog("异常的客户端:" + Converts.GetTPandMac(datagram));
                LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "发送报文失败;" + ee.Message + "位置:" + ee.StackTrace);
                //if (tcpClient != null && tcpClient.Client != null && tcpClient.Client.RemoteEndPoint != null)
                //{
                //    boxes.Common.LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "发送报文至" + tcpClient.Client.RemoteEndPoint.ToString() + "失败:" + ee.Message + "位置:" + ee.StackTrace);
                //}
            }
            return(result);
        }
Example #6
0
        /// <summary>
        /// Event fired when the stream disconnects unexpectedly
        /// </summary>
        private void OnStreamDisconnects(TCPStream stream)
        {
            if (stream != Stream)
            {
                return;
            }

            Disconnect(DisconnectReason.Disconnected);
        }
Example #7
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="client"></param>
 public SBClient(TCPStream stream, long connectionid) : base(stream, connectionid)
 {
     // Generate a unique name for this connection
     ConnectionID = connectionid;
     // Init a new client stream class
     Stream = stream;
     Stream.OnDisconnected += ClientDisconnected;
     Stream.OnDataReceived += ProcessData;
 }
Example #8
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="ReadArgs">The Tcp Client connection</param>
        public GPCMClient(TCPStream stream, long connectionid) : base(stream, connectionid)
        {
            PlayerInfo = new GPCMPlayerInfo();

            Stream.OnDataReceived    += ProcessData;
            Stream.IsMessageFinished += IsMessageFinished;
            Stream.OnDisconnected    += ClientDisconnected;
            Stream.BeginReceive();
        }
        private async Task <HttpResponseMessage> GetResponseAsync(TCPStream tcpStream)
        {
            var response = new HttpResponseMessage()
            {
                StatusCode = (HttpStatusCode)await tcpStream.ReadVarIntAsync().ConfigureAwait(false)
            };

            List <Tuple <string, string> > headers = new List <Tuple <string, string> >();

            if (Options.IncludeHeaders)
            {
                var headersCount = await tcpStream.ReadVarIntAsync().ConfigureAwait(false);

                for (int i = 0; i < (int)headersCount; i++)
                {
                    var key = await tcpStream.ReadStringAync().ConfigureAwait(false);

                    var value = await tcpStream.ReadStringAync().ConfigureAwait(false);

                    headers.Add(Tuple.Create(key, value));
                }
            }

            var headersByKey = headers.GroupBy(h => h.Item1, h => h.Item2);
            var length       = await tcpStream.ReadVarIntAsync().ConfigureAwait(false);

            if ((int)length > tcpStream.MaxArrayLength)
            {
                throw new IOException("Server's response is too long");
            }
            var bodyArray = new byte[(int)length];

            if (length != 0)
            {
                int readen = 0;
                while (readen != bodyArray.Length)
                {
                    readen += await tcpStream.Inner.ReadAsync(bodyArray, readen, bodyArray.Length - readen, tcpStream.Cancellation).ConfigureAwait(false);
                }
            }
            response.Content = new StreamContent(new MemoryStream(bodyArray));
            response.Content.Headers.ContentLength = (int)length;
            if (Options.IncludeHeaders)
            {
                foreach (var g in headersByKey)
                {
                    if (response.Content.Headers.Contains(g.Key))
                    {
                        response.Content.Headers.Remove(g.Key);
                    }
                    response.Content.Headers.TryAddWithoutValidation(g.Key, g);
                }
            }

            return(response);
        }
Example #10
0
 public TCPPmlChannel(TCPStream socket)
 {
     if (socket == null)
     {
         throw new ArgumentNullException("socket");
     }
     _socket = socket;
     _rw     = new PmlBinaryRW(_socket);
     _open   = true;
 }
        private async Task <HttpResponseMessage> SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            using (var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _DisposedToken.Token))
            {
                cancellationToken = linked.Token;
                var socket = await EnsureConnectedAsync(request.RequestUri, cancellationToken).ConfigureAwait(false);

                var networkStream = new NetworkStream(socket, false);
                using (TCPStream tcpStream = new TCPStream(networkStream)
                {
                    MaxArrayLength = Options.MaxArrayLength,
                    MaxMessageSize = Options.MaxMessageSize,
                    Cancellation = cancellationToken,
                    ArrayPool = Options.ArrayPool
                })
                {
                    await tcpStream.WriteStringAsync(request.Method.Method).ConfigureAwait(false);

                    await tcpStream.WriteStringAsync(request.RequestUri.AbsoluteUri).ConfigureAwait(false);

                    if (Options.IncludeHeaders)
                    {
                        var requestHeaders = request.Headers.ToList();
                        var contentHeaders = request.Content?.Headers.ToList() ?? new List <KeyValuePair <string, IEnumerable <string> > >();

                        var headers = requestHeaders.Concat(contentHeaders).SelectMany(h => h.Value.Select(v => new
                        {
                            Key   = h.Key,
                            Value = v
                        })).ToList();

                        await tcpStream.WriteVarIntAsync((ulong)headers.Count()).ConfigureAwait(false);

                        foreach (var header in headers)
                        {
                            await tcpStream.WriteStringAsync(header.Key).ConfigureAwait(false);

                            await tcpStream.WriteStringAsync(header.Value).ConfigureAwait(false);
                        }
                    }

                    await tcpStream.WriteVarIntAsync(request.Content == null? 0UL : 1).ConfigureAwait(false);

                    if (request.Content != null)
                    {
                        await tcpStream.WriteVarIntAsync((ulong)request.Content.Headers.ContentLength).ConfigureAwait(false);

                        await(await request.Content.ReadAsStreamAsync().ConfigureAwait(false)).CopyToAsync(networkStream, 81920, cancellationToken).ConfigureAwait(false);
                    }
                    await networkStream.FlushAsync(cancellationToken).ConfigureAwait(false);

                    return(await GetResponseAsync(tcpStream).ConfigureAwait(false));
                }
            }
        }
Example #12
0
        /// <summary>
        /// This function is fired when data is received from a stream
        /// </summary>
        /// <param name="stream">The stream that sended the data</param>
        /// <param name="message">The message the stream sended</param>
        protected void ProcessDataReceived(TCPStream stream, string message)
        {
            string[] recieved = message.TrimStart('\\').Split('\\');
            Dictionary <string, string> dict = ConvertToKeyValue(recieved);

            switch (recieved[0])
            {
            case "valid":
                IsEmailValid(stream, dict);
                break;

            case "nicks":
                RetriveNicknames(stream, dict);
                break;

            case "check":
                CheckAccount(stream, dict);
                break;

            case "search":
                SearchUser(stream, dict);
                break;

            case "others":
                ReverseBuddies(stream, dict);
                break;

            case "otherslist":
                OnOthersList(stream, dict);
                break;

            case "uniquesearch":
                SuggestUniqueNickname(stream, dict);
                break;

            case "profilelist":
                OnProfileList(stream, dict);
                break;

            case "pmatch":
                MatchProduct(stream, dict);
                break;

            case "newuser":
                CreateUser(stream, dict);
                break;

            default:
                LogWriter.Log.Write("Received unknown request " + recieved[0], LogLevel.Debug);
                SendErrorAndFreeStream(stream, 0, "An invalid request was sended.");
                break;
            }
        }
Example #13
0
        /// <summary>
        /// Main listner loop. Keeps an open stream between the client and server while
        /// the client is logged in / playing
        /// </summary>
        private void OnDataReceived(TCPStream stream, string message)
        {
            if (stream != Stream)
            {
                return;
            }

            // Read client message, and parse it into key value pairs
            string[] recieved = message.TrimStart('\\').Split('\\');
            switch (recieved[0])
            {
            case "inviteto":
                AddProducts(PresenceServer.ConvertToKeyValue(recieved));
                break;

            case "newuser":
                CreateNewUser(PresenceServer.ConvertToKeyValue(recieved));
                break;

            case "login":
                ProcessLogin(PresenceServer.ConvertToKeyValue(recieved));
                break;

            case "getprofile":
                SendProfile(PresenceServer.ConvertToKeyValue(recieved));
                break;

            case "updatepro":
                UpdateUser(PresenceServer.ConvertToKeyValue(recieved));
                break;

            case "logout":
                Disconnect(DisconnectReason.NormalLogout);
                break;

            case "status":
                UpdateStatus(PresenceServer.ConvertToKeyValue(recieved));
                break;

            case "ka":
                SendKeepAlive();
                break;

            default:
                LogWriter.Log.Write("Received unknown request " + recieved[0], LogLevel.Debug);
                PresenceServer.SendError(stream, 0, "An invalid request was sended.");
                stream.Close();
                break;
            }
        }
Example #14
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="client"></param>
        public ChatClient(TCPStream stream, long connectionid) : base(stream, connectionid)
        {
            // Generate a unique name for this connection
            ConnectionID = connectionid;

            // Init a new client stream class
            Stream = stream;
            //determine whether gamespy request is finished
            Stream.IsMessageFinished += IsMessageFinished;

            // Read client message, and parse it into key value pairs
            Stream.OnDataReceived += ProcessData;

            //Dispose stream when a client is disconnected
            Stream.OnDisconnected += Dispose;
        }
Example #15
0
        /// <summary>
        /// When a new connection is established, we the parent class are responsible
        /// for handling the processing
        /// </summary>
        /// <param name="Stream">A GamespyTcpStream object that wraps the I/O AsyncEventArgs and socket</param>
        protected override void ProcessAccept(TCPStream stream)
        {
            // Get our connection id
            long         conid = Interlocked.Increment(ref ConnectionCounter);
            GStatsClient client;

            try
            {
                // Convert the TcpClient to a MasterClient
                client = new GStatsClient(stream, conid);
                Clients.TryAdd(conid, client);
                client.SendServerChallenge();
                // Start receiving data
                stream.BeginReceive();
            }
            catch
            {
                // Remove pending connection
                Clients.TryRemove(conid, out client);
            }
        }
Example #16
0
        /// <summary>
        /// When a new connection is established, we the parent class are responsible
        /// for handling the processing
        /// </summary>
        /// <param name="Stream">A GamespyTcpStream object that wraps the I/O AsyncEventArgs and socket</param>
        protected override void ProcessAccept(TCPStream stream)
        {
            // Get our connection id
            long       ConID = Interlocked.Increment(ref ConnectionCounter);
            ChatClient client;

            try
            {
                // Convert the TcpClient to a MasterClient
                client = new ChatClient(stream, ConID);
                Clients.TryAdd(ConID, client);

                // Start receiving data
                stream.BeginReceive();
            }
            catch
            {
                // Remove pending connection
                Clients.TryRemove(ConID, out client);
            }
        }
Example #17
0
        /// <summary>
        /// Accepts a TcpClient, and begin the serverlist fetching process for the client.
        /// This method is executed when the user updates his server browser ingame
        /// </summary>
        protected override void ProcessAccept(TCPStream Stream)
        {
            // Get our connection id
            long     ConID = Interlocked.Increment(ref ConnectionCounter);
            SBClient client;

            // End the operation and display the received data on
            // the console.
            try
            {
                // Convert the TcpClient to a MasterClient
                client = new SBClient(Stream, ConID);
                Clients.TryAdd(client.ConnectionID, client);

                // Start receiving data
                Stream.BeginReceive();
            }
            catch (ObjectDisposedException) // Ignore
            {
                // Remove client
                Clients.TryRemove(ConID, out client);
            }
            catch (IOException) // Connection closed before a TcpClientStream could be made
            {
                // Remove client
                Clients.TryRemove(ConID, out client);
            }
            catch (Exception e)
            {
                // Remove client
                Clients.TryRemove(ConID, out client);

                // Report error

                LogWriter.Log.Write(LogLevel.Error, "[SB] : An Error occured at : {0}", e.ToString());

                //ExceptionHandler.GenerateExceptionLog(e);
            }
        }
Example #18
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="ReadArgs">The Tcp Client connection</param>
        public GPCMClient(TCPStream ConnectionStream, long ConnectionId, DatabaseDriver databaseDriver)
        {
            // Set default variable values
            PlayerNick         = "Connecting...";
            PlayerStatusString = "Offline";
            PlayerLocation     = "";
            PlayerId           = 0;
            RemoteEndPoint     = (IPEndPoint)ConnectionStream.RemoteEndPoint;
            Disposed           = false;
            LoginStatus        = LoginStatus.Connected;
            PlayerStatus       = PlayerStatus.Offline;

            // Set the connection ID
            this.ConnectionId   = ConnectionId;
            this.databaseDriver = databaseDriver;

            // Create our Client Stream
            Stream = ConnectionStream;
            Stream.OnDisconnect += OnStreamDisconnects;
            Stream.DataReceived += OnDataReceived;
            Stream.BeginReceive();
        }
Example #19
0
        public bool Accept(TCPStream Stream)
        {
            XmlSocket XSocket = new XmlSocket(Stream);

            Stream.ReadTimeout = 5000;
            XmlDocument FirstMessage = XSocket.ReadDocument();

            if (FirstMessage == null)
            {
                return(true);
            }
            IModule module;

            if (Modules.TryGetValue(FirstMessage.FirstChild.Name, out module))
            {
                module.Accept(XSocket, FirstMessage);
            }
            else
            {
                Console.WriteLine("XMLServer.Accept: Module not found: " + FirstMessage.FirstChild.Name);
            }
            return(true);
        }
Example #20
0
 /// <summary>
 /// This function sended the error to a stream and release it
 /// </summary>
 /// <param name="stream">The stream that will receive the error</param>
 /// <param name="code">The error code</param>
 /// <param name="error">A string containing the error</param>
 protected void SendErrorAndFreeStream(TCPStream stream, int code, string error)
 {
     SendError(stream, code, error);
     stream.Close();
     Release(stream);
 }
Example #21
0
 private void OnOthersList(TCPStream stream, Dictionary <string, string> dict)
 {
     PrintReceivedDictToLogger("otherslist", dict);
     SendErrorAndFreeStream(stream, 0, "This request is not supported yet.");
 }
Example #22
0
        private async Task ListenClient <TContext>(ConnectedSocket connectedSocket, IHttpApplication <TContext> application)
        {
            bool exceptionHandled = false;
            CancellationTokenSource idleTimeout = null;
            CancellationTokenSource sendTimeout = null;

            try
            {
                var client        = connectedSocket.Socket;
                var networkStream = new NetworkStream(client, false);
                while (true)
                {
                    using (var disposables = new CompositeDisposable())
                    {
                        var stream = new TCPStream(networkStream)
                        {
                            ArrayPool      = Options.ArrayPool,
                            Cancellation   = _Stopped.Token,
                            MaxArrayLength = Options.MaxBytesArrayLength,
                            MaxMessageSize = Options.MaxMessageSize
                        };
                        disposables.Children.Add(stream);
                        idleTimeout = new CancellationTokenSource();
                        idleTimeout.CancelAfter(Options.IdleTimeout);
                        disposables.Children.Add(idleTimeout);
                        var linked = CancellationTokenSource.CreateLinkedTokenSource(stream.Cancellation, idleTimeout.Token);
                        disposables.Children.Add(linked);
                        stream.Cancellation = linked.Token;
                        TCPRequest request = null;
                        try
                        {
                            request = await TCPRequest.Parse(stream, Options.IncludeHeaders).ConfigureAwait(false);
                        }
                        catch (Exception ex)
                        {
                            _Logger.LogWarning(new EventId(), ex, $"Error while parsing the request of {EndpointString(connectedSocket)}");
                            exceptionHandled = true;
                            throw;
                        }

                        disposables.Children.Add(connectedSocket.MarkProcessingRequest());

                        var context = (HostingApplication.Context)(object) application.CreateContext(Features);

                        context.HttpContext = new TCPContext(request, Features, new TCPConnectionInfo(client, _ListeningEndPoint));
                        try
                        {
                            await application.ProcessRequestAsync((TContext)(object)context);
                        }
                        catch (Exception ex)
                        {
                            _Logger.LogError(new EventId(), ex, "Error during request processing");
                            exceptionHandled = true;
                            throw;
                        }

                        sendTimeout = new CancellationTokenSource();
                        sendTimeout.CancelAfter(Options.SendTimeout);
                        disposables.Children.Add(sendTimeout);
                        linked = CancellationTokenSource.CreateLinkedTokenSource(stream.Cancellation, sendTimeout.Token);
                        disposables.Children.Add(linked);
                        stream.Cancellation = linked.Token;
                        var response = (TCPResponse)context.HttpContext.Response;
                        try
                        {
                            response.OnStarting();
                            await stream.WriteVarIntAsync((ulong)response.StatusCode).ConfigureAwait(false);

                            if (Options.IncludeHeaders)
                            {
                                await stream.WriteVarIntAsync((ulong)response.Headers.Count).ConfigureAwait(false);

                                foreach (var header in response.Headers)
                                {
                                    await stream.WriteStringAsync(header.Key).ConfigureAwait(false);

                                    await stream.WriteStringAsync(header.Value).ConfigureAwait(false);
                                }
                            }

                            await stream.WriteVarIntAsync((ulong)response.Body.Length);

                            response.Body.Position = 0;
                            await response.Body.CopyToAsync(networkStream, 81920, stream.Cancellation).ConfigureAwait(false);

                            await networkStream.FlushAsync(stream.Cancellation).ConfigureAwait(false);
                        }
                        finally
                        {
                            response.OnCompleted();
                            connectedSocket.LastReceivedMessage = DateTimeOffset.UtcNow;
                        }
                    }
                }
            }
            catch (OperationCanceledException)
            {
                if (connectedSocket.Socket.Connected)
                {
                    if (_Stopped.Token.IsCancellationRequested)
                    {
                        _Logger.LogInformation($"Connection to {EndpointString(connectedSocket)} stopped");
                    }
                    else if (idleTimeout != null && idleTimeout.IsCancellationRequested)
                    {
                        _Logger.LogWarning($"Connection idle detected, kicking {EndpointString(connectedSocket)}");
                    }
                    else if (sendTimeout != null && sendTimeout.IsCancellationRequested)
                    {
                        _Logger.LogWarning($"Send timeout detected, kicking {EndpointString(connectedSocket)}");
                    }
                }
            }
            catch (Exception ex)
            {
                if (connectedSocket.Socket.Connected && !exceptionHandled)
                {
                    _Logger.LogCritical(new EventId(), ex, "TCPServer internal error");
                }
            }
            finally
            {
                if (!connectedSocket.Socket.Connected)
                {
                    _Logger.LogInformation($"{EndpointString(connectedSocket)} dropped connection");
                }
                DisconnectClient(connectedSocket);
            }
        }
Example #23
0
        private async Task ListenClient <TContext>(ConnectedSocket connectedSocket, IHttpApplication <TContext> application)
        {
            try
            {
                var client        = connectedSocket.Socket;
                var networkStream = new NetworkStream(client, false);
                while (true)
                {
                    using (var disposables = new     CompositeDisposable())
                    {
                        var stream = new TCPStream(networkStream)
                        {
                            ArrayPool      = Options.ArrayPool,
                            Cancellation   = _Stopped.Token,
                            MaxArrayLength = Options.MaxBytesArrayLength,
                            MaxMessageSize = Options.MaxMessageSize
                        };
                        disposables.Children.Add(stream);
                        var idleTimeout = new CancellationTokenSource();
                        idleTimeout.CancelAfter(Options.IdleTimeout);
                        disposables.Children.Add(idleTimeout);
                        var linked = CancellationTokenSource.CreateLinkedTokenSource(stream.Cancellation, idleTimeout.Token);
                        disposables.Children.Add(linked);
                        stream.Cancellation = linked.Token;
                        var request = await TCPRequest.Parse(stream, Options.IncludeHeaders).ConfigureAwait(false);

                        disposables.Children.Add(connectedSocket.MarkProcessingRequest());

                        var context = (HostingApplication.Context)(object) application.CreateContext(Features);

                        context.HttpContext = new TCPContext(request, Features, new TCPConnectionInfo(client, _ListeningEndPoint));
                        await application.ProcessRequestAsync((TContext)(object)context);

                        CancellationTokenSource sendTimeout = new CancellationTokenSource();
                        sendTimeout.CancelAfter(Options.SendTimeout);
                        disposables.Children.Add(sendTimeout);
                        linked = CancellationTokenSource.CreateLinkedTokenSource(stream.Cancellation, sendTimeout.Token);
                        disposables.Children.Add(linked);
                        stream.Cancellation = linked.Token;
                        var response = (TCPResponse)context.HttpContext.Response;
                        try
                        {
                            response.OnStarting();
                            await stream.WriteVarIntAsync((ulong)response.StatusCode).ConfigureAwait(false);

                            if (Options.IncludeHeaders)
                            {
                                await stream.WriteVarIntAsync((ulong)response.Headers.Count).ConfigureAwait(false);

                                foreach (var header in response.Headers)
                                {
                                    await stream.WriteStringAsync(header.Key).ConfigureAwait(false);

                                    await stream.WriteStringAsync(header.Value).ConfigureAwait(false);
                                }
                            }

                            await stream.WriteVarIntAsync((ulong)response.Body.Length);

                            response.Body.Position = 0;
                            await response.Body.CopyToAsync(networkStream, 81920, stream.Cancellation).ConfigureAwait(false);

                            await networkStream.FlushAsync(stream.Cancellation).ConfigureAwait(false);
                        }
                        finally
                        {
                            response.OnCompleted();
                            connectedSocket.LastReceivedMessage = DateTimeOffset.UtcNow;
                        }
                    }
                }
            }
            catch (OperationCanceledException)
            {
                if (!_Stopped.IsCancellationRequested)
                {
                    throw;
                }
            }
            finally
            {
                DisconnectClient(connectedSocket);
            }
        }
Example #24
0
 private void SearchUser(TCPStream stream, Dictionary <string, string> dict)
 {
     PrintReceivedDictToLogger("search", dict);
     SendErrorAndFreeStream(stream, 0, "This request is not supported yet.");
 }
Example #25
0
 private void CheckAccount(TCPStream stream, Dictionary <string, string> dict)
 {
     PrintReceivedDictToLogger("check", dict);
     SendErrorAndFreeStream(stream, 0, "This request is not supported yet.");
 }
Example #26
0
        private void RetriveNicknames(TCPStream stream, Dictionary <string, string> dict)
        {
            string password       = "";
            bool   sendUniqueNick = false;

            if (!dict.ContainsKey("email"))
            {
                SendErrorAndFreeStream(stream, 1, "There was an error parsing an incoming request.");
                return;
            }

            // First, we try to receive an encoded password
            if (!dict.ContainsKey("passenc"))
            {
                // If the encoded password is not sended, we try receving the password in plain text
                if (!dict.ContainsKey("pass"))
                {
                    // No password is specified, we cannot continue
                    SendErrorAndFreeStream(stream, 1, "There was an error parsing an incoming request.");
                    return;
                }
                else
                {
                    // Store the plain text password
                    password = dict["pass"];
                }
            }
            else
            {
                // Store the decrypted password
                password = GamespyUtils.DecodePassword(dict["passenc"]);
            }

            password = StringExtensions.GetMD5Hash(password);

            sendUniqueNick = dict.ContainsKey("gamename");

            List <Dictionary <string, object> > queryResult = null;

            try
            {
                queryResult = databaseDriver.Query("SELECT profiles.nick, profiles.uniquenick FROM profiles INNER JOIN users ON profiles.userid=users.userid WHERE LOWER(users.email)=@P0 AND LOWER(users.password)=@P1", dict["email"].ToLowerInvariant(), password.ToLowerInvariant());
            }
            catch (Exception ex)
            {
                LogWriter.Log.Write(ex.Message, LogLevel.Error);
                SendErrorAndFreeStream(stream, 4, "This request cannot be processed because of a database error.");
                return;
            }

            if (queryResult.Count < 1)
            {
                stream.SendAsync(@"\nr\ndone\final\");
                return;
            }

            // We will recycle the "password" variable by storing the response
            // that we have to send to the stream. This is done for save memory space
            // so we don't have to declare a new variable.
            password = @"\nr\";

            foreach (Dictionary <string, object> row in queryResult)
            {
                password += @"\nick\";
                password += row["nick"];

                if (sendUniqueNick)
                {
                    password += @"\uniquenick\";
                    password += row["uniquenick"];
                }
            }

            password += @"\ndone\final\";
            stream.SendAsync(password);

            /* Legacy C++ code to reimpliment
             * bool PSServer::OnSendNicks(mdk_socket stream, const char *buf, int)
             * {
             *  std::string email = "", pass = "", gamename = "", str = "";
             *  bool bSendUnique = false;
             *  size_t i = 0;
             *  CResultSet *result = NULL;
             *
             *  // Get data from buffer
             *
             *  if (!get_gs_data(buf, email, "email"))
             *      return false;
             *
             *  if (get_gs_data(buf, pass, "passenc"))
             *  {
             *      // Uncrypt the password
             *      gs_pass_decode(pass);
             *  }
             *  else
             *  {
             *      if (!get_gs_data(buf, pass, "pass"))
             *          return false;
             *  }
             *
             *  if (get_gs_data(buf, gamename, "gamename"))
             *      bSendUnique = true;
             *
             *  // Create the query and execute it
             *  str = "SELECT profiles.nick, profiles.uniquenick FROM profiles INNER "
             *      "JOIN users ON profiles.userid=users.userid WHERE users.email='";
             *  if (!mdk_escape_query_string(m_lpDatabase, email))
             *      return false;
             *
             *  str += email;
             *  str += "' AND password='******'";
             *
             *  result = new CResultSet();
             *
             *  if (!result->ExecuteQuery(m_lpDatabase, str))
             *  {
             *      delete result;
             *
             *      WriteTCP(stream, "\\nr\\\\ndone\\final\\");
             *      return false;
             *  }
             *
             *  if (!result->GotoFirstRow())
             *  {
             *      delete result;
             *
             *      WriteTCP(stream, "\\nr\\\\ndone\\final\\");
             *      return false;
             *
             *  }
             *
             *  str = "\\nr\\" + std::to_string(result->GetTotalRows());
             *
             *  // Get all the nicks and store them
             *  do
             *  {
             *      str += "\\nick\\";
             *      str += result->GetStringFromRow(0);
             *
             *      if (bSendUnique)
             *      {
             *          str += "\\uniquenick\\";
             *          str += result->GetStringFromRow(1);
             *      }
             *  } while(result->GotoNextRow());
             *
             *  str += "\\ndone\\final\\";
             *
             *  // Send to the socket
             *  WriteTCP(stream, str);
             *
             *  delete result;
             *
             *  return true;
             * }*/
        }
Example #27
0
 /// <summary>
 /// This function is fired when a client is being accepted
 /// </summary>
 /// <param name="Stream">The stream of the client to be accepted</param>
 protected override void ProcessAccept(TCPStream Stream)
 {
     Stream.DataReceived += ProcessDataReceived;
     Stream.OnDisconnect += (stream) => stream.Dispose();
     Stream.BeginReceive();
 }
Example #28
0
 /// <summary>
 /// Send a presence error
 /// </summary>
 /// <param name="stream">The stream that will receive the error</param>
 /// <param name="code">The error code</param>
 /// <param name="error">A string containing the error</param>
 public static void SendError(TCPStream stream, int code, string error)
 {
     stream.SendAsync(Encoding.UTF8.GetBytes(String.Format(@"\error\\err\{0}\fatal\\errmsg\{1}\id\1\final\", code, error)));
 }