Beispiel #1
0
        protected override void OnReceived(string message)
        {
            message = RequstFormatConversion(message);

            if (message[0] != '\\')
            {
                GameSpyUtils.SendGPError(this, GPErrorCode.Parse, "An invalid request was sended.");
                return;
            }

            string[] commands = message.Split("\\final\\");

            foreach (string command in commands)
            {
                if (command.Length < 1)
                {
                    continue;
                }

                // Read client message, and parse it into key value pairs
                string[] recieved = command.TrimStart('\\').Split('\\');
                Dictionary <string, string> dict = GameSpyUtils.ConvertGPResponseToKeyValue(recieved);

                CommandSwitcher.Switch(this, dict);
            }
        }
Beispiel #2
0
        /// <summary>
        /// check if a email is exist in database
        /// </summary>
        /// <param name="client"></param>
        /// <param name="dict"></param>
        public static void IsEmailValid(GPSPClient client, Dictionary <string, string> dict)
        {
            if (!dict.ContainsKey("email"))
            {
                GameSpyUtils.SendGPError(client, GPErrorCode.Parse, "There was an error parsing an incoming request.");
                return;
            }

            try
            {
                if (GameSpyUtils.IsEmailFormatCorrect(dict["email"]))
                {
                    if (ValidQuery.IsEmailValid(dict))
                    {
                        client.Send(@"\vr\1\final\");
                    }
                    else
                    {
                        client.Send(@"\vr\0\final\");
                    }

                    //client.Stream.Dispose();
                }
                else
                {
                    client.Send(@"\vr\0\final\");
                    //client.Stream.Dispose();
                }
            }
            catch (Exception ex)
            {
                LogWriter.Log.WriteException(ex);
                GameSpyUtils.SendGPError(client, GPErrorCode.DatabaseError, "This request cannot be processed because of a database error.");
            }
        }
        public static void PlayerMatch(GPSPClient client, Dictionary <string, string> dict)
        { //pmath\\sesskey\\profileid\\productid\\
            string sendingBuffer;

            if (IsContainAllKey(dict))
            {
                List <Dictionary <string, object> > temp = PmatchQuery.PlayerMatch(dict);
                if (temp.Count == 1)
                {
                    sendingBuffer = string.Format(@"\psr\status\{0}\nick\{1}\statuscode\{2}\final\",
                                                  temp[0]["status"], temp[0]["nick"], temp[0]["statuscode"]);
                    client.Send(sendingBuffer);
                }
                else
                {
                    GameSpyUtils.SendGPError(client, GPErrorCode.DatabaseError, "No match found!");
                }
            }

            //there are two ways to send information back.

            //First way: \psr\<profileid>\status\<status>\statuscode\<statuscode>\psrdone\final\

            //this is a multiple command. you can contain mutiple \psr\........... in the Steam
            //Second way:\psr\<profileid>\nick\<nick>\***multiple \psr\ command***\psrdone\final\
            //<status> is like the introduction in a player homepage
            //<statuscode> mean the status information is support or not the value should be as follows
            //GP_NEW_STATUS_INFO_SUPPORTED = 0xC00,
            //GP_NEW_STATUS_INFO_NOT_SUPPORTED = 0xC01
        }
Beispiel #4
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 override void ProcessData(string message)
        {
            //message= @"\search\sesskey\0\profileid\0\namespaceid\1\email\[email protected]\gamename\conflictsopc\final\";
            message = RequstFormatConversion(message);
            if (message[0] != '\\')
            {
                GameSpyUtils.SendGPError(this, GPErrorCode.Parse, "An invalid request was sended.");
                return;
            }

            string[] commands = message.Split("\\final\\");

            foreach (string command in commands)
            {
                if (command.Length < 1)
                {
                    continue;
                }

                // Read client message, and parse it into key value pairs
                string[] recieved = command.TrimStart('\\').Split('\\');
                Dictionary <string, string> dict = GameSpyUtils.ConvertGPResponseToKeyValue(recieved);

                CommandSwitcher.Switch(this, dict);
            }
        }
        /// <summary>
        /// Main listner loop. Keeps an open stream between the client and server while
        /// the client is logged in / playing
        /// </summary>
        protected override void ProcessData(string message)
        {
            //message = @"\login\\challenge\l73Iv120dsOnQIA5hCBIqQSkojR191hy\user\retrospy@[email protected]\response\05d45e1b1bf6fbe6b6590785ec8dbe70\port\-9805\productid\10469\gamename\conflictsopc\namespaceid\1\id\1\final\";
            message = RequstFormatConversion(message);

            if (message[0] != '\\')
            {
                GameSpyUtils.SendGPError(this, GPErrorCode.General, "An invalid request was sended.");
                return;
            }

            string[] commands = message.Split("\\final\\");

            foreach (string command in commands)
            {
                if (command.Length < 1)
                {
                    continue;
                }
                // Read client message, and parse it into key value pairs
                string[] recieved = command.TrimStart('\\').Split('\\');

                Dictionary <string, string> dict = GameSpyUtils.ConvertGPResponseToKeyValue(recieved);

                CommandSwitcher.Switch(this, dict, OnSuccessfulLogin, OnStatusChanged);
            }
        }
        /// <summary>
        /// Get profiles that have you on their buddy(friend) list.
        /// </summary>
        /// <param name="client"></param>
        /// <param name="dict"></param>
        public static void SearchOtherBuddy(GPSPClient client, Dictionary <string, string> dict)
        {
            // TODO: Please finis this function
            //others\sesskey\profileid\namespace\
            string sendingbuffer; //= @"\others\o\nick\<>\uniquenick\<>\first\<>\last\<>\email\<>\odone\";
            var    temp = OthersQuery.GetOtherBuddy(dict);

            if (temp == null)
            {
                GameSpyUtils.SendGPError(client, GPErrorCode.DatabaseError, "No Math Found");
                return;
            }
            if (temp.Count == 1)
            {
                sendingbuffer = string.Format(@"\others\o\nick\{0}\uniquenick\{1}\first\{2}\last\{3}\email\{4}\odone\final\", temp[0]["nick"], temp[0]["uniquenick"], temp[0]["firstname"], temp[0]["lastname"], temp[0]["email"]);
                client.Stream.SendAsync(sendingbuffer);
                return;
            }
            if (temp.Count > 1)
            {
                sendingbuffer = @"\others\";
                foreach (Dictionary <string, object> info in temp)
                {
                    sendingbuffer += string.Format(@"o\nick\{0}\uniquenick\{1}\first\{1}\last\{2}\email\{3}\", info["nick"], info["uniquenick"], info["firstname"], info["lastname"], info["email"]);
                }
                client.Stream.SendAsync(sendingbuffer);
                return;
            }

            GameSpyUtils.PrintReceivedGPDictToLogger("others", dict);
            GameSpyUtils.SendGPError(client, GPErrorCode.General, "This request is not supported yet.");
        }
Beispiel #7
0
        public static void Switch(GPSPClient client, Dictionary <string, string> recv)
        {
            string command = recv.Keys.First();

            try
            {
                switch (command)
                {
                case "search":
                    SearchHandler.SearchUsers(client, recv);
                    break;

                case "valid":
                    ValidHandler.IsEmailValid(client, recv);
                    break;

                case "nicks":
                    NickHandler.SearchNicks(client, recv);
                    break;

                case "pmatch":
                    PmatchHandler.PlayerMatch(client, recv);
                    break;

                case "check":
                    CheckHandler.CheckProfileid(client, recv);
                    break;

                case "newuser":
                    NewUserHandler.NewUser(client, recv);
                    break;

                case "searchunique":
                    SearchUniqueHandler.SearchProfileWithUniquenick(client, recv);
                    break;

                case "others":
                    OthersHandler.SearchOtherBuddy(client, recv);
                    break;

                case "otherslist":
                    OthersListHandler.SearchOtherBuddyList(client, recv);
                    break;

                case "uniquesearch":
                    UniqueSearchHandler.SuggestUniqueNickname(client, recv);
                    break;

                default:
                    LogWriter.Log.Write("[GPSP] received unknown data " + command, LogLevel.Debug);
                    GameSpyUtils.PrintReceivedGPDictToLogger(command, recv);
                    GameSpyUtils.SendGPError(client, GPErrorCode.Parse, "An invalid request was sended.");
                    break;
                }
            }
            catch (Exception e)
            {
                LogWriter.Log.WriteException(e);
            }
        }
        /// <summary>
        /// Get nickname through email and password
        /// </summary>
        /// <param name="client"></param>
        /// <param name="dict"></param>
        public static void SearchNicks(GPSPClient client, Dictionary <string, string> dict)
        {
            //Format the password for our database storage
            //if not recieved correct request we terminate
            GPErrorCode error = IsSearchNicksContianAllKeys(dict);

            if (error != GPErrorCode.NoError)
            {
                GameSpyUtils.SendGPError(client, (int)error, "Error recieving SearchNicks request.");
                return;
            }

            List <Dictionary <string, object> > queryResult;

            try
            {
                //get nicknames from GPSPDBQuery class
                queryResult = NickQuery.RetriveNicknames(dict);
            }
            catch (Exception ex)
            {
                LogWriter.Log.Write(ex.Message, LogLevel.Error);
                GameSpyUtils.SendGPError(client, GPErrorCode.DatabaseError, "This request cannot be processed because of a database error.");
                return;
            }

            if (queryResult.Count < 1)
            {
                GameSpyUtils.SendGPError(client, GPErrorCode.DatabaseError, "No match found !");
                return;
            }

            string sendingBuffer;

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

            sendingBuffer += @"\ndone\final\";
            client.Stream.SendAsync(sendingBuffer);
        }
        /// <summary>
        /// update the uniquenick
        /// </summary>
        /// <param name="session"></param>
        /// <param name="dict"></param>
        public static void RegisterNick(GPCMSession session, Dictionary <string, string> dict)
        {
            GPErrorCode error = IsContainAllKeys(dict);

            if (error != GPErrorCode.NoError)
            {
                GameSpyUtils.SendGPError(session, error, "Parsing error");
                return;
            }
            string sendingBuffer;

            try
            {
                RegisterNickQuery.UpdateUniquenick(dict["uniquenick"], session.PlayerInfo.SessionKey, Convert.ToUInt16(dict["patnerid"]));
                sendingBuffer = @"\rn\final\";
                session.Send(sendingBuffer);
            }
            catch (Exception e)
            {
                LogWriter.Log.WriteException(e);
            }
        }
        /// <summary>
        /// Creates an account and use new account to login
        /// </summary>
        /// <param name="client">The client that sended the data</param>
        /// <param name="dict">The request that the stream sended</param>
        public static void NewUser(GPCMClient client, Dictionary <string, string> dict)
        {
            //Format the password for our database storage
            GPErrorCode error = IsRequestContainAllKeys(dict);

            //if there do not recieved right <key,value> pairs we send error
            if (error != GPErrorCode.NoError)
            {
                GameSpyUtils.SendGPError(client, error, "Error recieving request. Please check the input!");
                return;
            }

            //Check the nick and uniquenick is formated correct and uniquenick is existed in database
            string sendingBuffer;

            error = IsEmailNickUniquenickValied(dict);
            if (error != GPErrorCode.NoError)
            {
                sendingBuffer = string.Format(@"\nur\{0}\final\", (int)error);
                client.Send(sendingBuffer);
                return;
            }

            //if the request did not contain uniquenick and namespaceid we use our way to create it.
            PreProcessRequest(dict);
            //we get the userid in database. If no userid found according to email we create one
            //and store the new account into database.
            int profileid = CreateAccount(dict);

            if (profileid == -1)
            {
                GameSpyUtils.SendGPError(client, GPErrorCode.DatabaseError, "Account is existed, please use another one.");
            }
            else
            {
                sendingBuffer = string.Format(@"\nur\0\pid\{0}\final\", profileid);
                client.Send(sendingBuffer);
            }
        }
Beispiel #11
0
        /// <summary>
        /// update the uniquenick
        /// </summary>
        /// <param name="client"></param>
        /// <param name="dict"></param>
        public static void RegisterNick(GPCMClient client, Dictionary <string, string> dict)
        {
            GPErrorCode error = IsContainAllKeys(dict);

            if (error != GPErrorCode.NoError)
            {
                GameSpyUtils.SendGPError(client, error, "Parsing error");
                return;
            }
            string sendingBuffer;

            try
            {
                RegisterNickQuery.UpdateUniquenick(dict);
                sendingBuffer = @"\rn\final\";
                client.Send(sendingBuffer);
            }
            catch (Exception e)
            {
                LogWriter.Log.WriteException(e);
            }
        }
Beispiel #12
0
        /// <summary>
        /// we just simply check the existance of the unique nickname in the database and suggest some numbered postfix nickname
        /// </summary>
        /// <param name="client"></param>
        /// <param name="dict"></param>
        public static void SuggestUniqueNickname(GPSPClient client, Dictionary <string, string> dict)
        {
            //The multiple nick suggest correct response is like
            //@"\us\<number of suggested nick>\nick\<nick1>\nick\<nick2>\usdone\final\";
            string      sendingBuffer;
            GPErrorCode error = IsContainAllKeys(dict);

            if (error != GPErrorCode.NoError)
            {
                GameSpyUtils.SendGPError(client, GPErrorCode.Parse, "There was an error parsing an incoming request.");
                return;
            }

            if (UniqueSearchQuery.IsUniqueNickExist(dict))
            {
                GameSpyUtils.SendGPError(client, GPErrorCode.General, "The Nick is existed, please choose another name");
            }
            else
            {
                sendingBuffer = @"\us\1\nick\" + dict["preferrednick"] + @"\usdone\final\";
                client.Send(sendingBuffer);
            }
        }
        /// <summary>
        /// Validates a user's info, without logging into the account.
        /// </summary>
        /// <param name="client"></param>
        /// <param name="dict"></param>
        public static void CheckProfileid(GPSPClient client, Dictionary <string, string> dict)
        {
            // \check\\nick\<nick>\email\<email>\partnerid\0\passenc\<passenc>\gamename\gmtest\final\
            //\cur\pid\<pid>\final
            //check is request recieved correct and convert password into our MD5 type
            bool isContiansAllKey = dict.ContainsKey("nick") && dict.ContainsKey("email") && (dict.ContainsKey("passenc") || dict.ContainsKey("pass"));

            if (!isContiansAllKey)
            {
                GameSpyUtils.SendGPError(client, GPErrorCode.Parse, "Parsing error, please check input.");
                return;
            }
            bool isEmailCorrect = GameSpyUtils.IsEmailFormatCorrect(dict["email"]);

            if (!isEmailCorrect)
            {
                GameSpyUtils.SendGPError(client, GPErrorCode.Parse, "Email format not correct.");
                return;
            }


            //Search pid in our database and return whether exist
            string sendingBuffer;
            int    profileid = CheckQuery.GetProfileidFromNickEmailPassword(dict);

            if (profileid != -1)
            {
                sendingBuffer = string.Format(@"\cur\0\pid\{0}\final\", profileid);
                client.Stream.SendAsync(sendingBuffer);
            }
            else
            {
                sendingBuffer = "No math found";
                GameSpyUtils.SendGPError(client, GPErrorCode.DatabaseError, sendingBuffer);
            }
        }
Beispiel #14
0
        /// <summary>
        /// This method is called when the client requests for the Account profile
        /// </summary>
        public static void SendProfile(GPCMClient client, Dictionary <string, string> recv)
        {
            //TODO

            // \getprofile\\sesskey\19150\profileid\2\id\2\final\
            //profileid is

            if (!recv.ContainsKey("profileid"))
            {
                GameSpyUtils.SendGPError(client, GPErrorCode.Parse, "There was an error parsing an incoming request.");
                return;
            }

            uint targetPID, messID, sesskey;

            if (!uint.TryParse(recv["profileid"], out targetPID))
            {
                GameSpyUtils.SendGPError(client, GPErrorCode.Parse, "There was an error parsing an incoming request.");
                return;
            }

            if (!uint.TryParse(recv["id"], out messID))
            {
                GameSpyUtils.SendGPError(client, GPErrorCode.Parse, "There was an error parsing an incoming request.");
                return;
            }
            if (!uint.TryParse(recv["sesskey"], out sesskey))
            {
                GameSpyUtils.SendGPError(client, GPErrorCode.Parse, "There was an error parsing an incoming request.");
                return;
            }

            string datatoSend = @"\pi\profileid\" + targetPID + @"\mp\4";

            // If the client want to access the public information
            // of another client
            if (targetPID != client.PlayerInfo.PlayerId)
            {
                GPCMPlayerInfo playerInfo = GetProfileQuery.GetProfileInfo(targetPID);
                if (playerInfo == null)
                {
                    GameSpyUtils.SendGPError(client, 4, "Unable to get profile information.");
                    return;
                }

                datatoSend = string.Format(datatoSend + @"\nick\{0}\uniquenick\{1}\id\{2}", playerInfo.PlayerNick, playerInfo.PlayerUniqueNick, messID);

                if (playerInfo.PlayerEmail.Length > 0)
                {
                    datatoSend += @"\email\" + playerInfo.PlayerEmail;
                }

                if (playerInfo.PlayerLastName.Length > 0)
                {
                    datatoSend += @"\lastname\" + playerInfo.PlayerLastName;
                }

                if (playerInfo.PlayerFirstName.Length > 0)
                {
                    datatoSend += @"\firstname\" + playerInfo.PlayerFirstName;
                }

                if (playerInfo.PlayerICQ != 0)
                {
                    datatoSend += @"\icquin\" + playerInfo.PlayerICQ;
                }

                if (playerInfo.PlayerHomepage.Length > 0)
                {
                    datatoSend += @"\homepage\" + playerInfo.PlayerHomepage;
                }

                if (playerInfo.PlayerPicture != 0)
                {
                    datatoSend += @"\pic\" + playerInfo.PlayerPicture;
                }

                if (playerInfo.PlayerAim.Length > 0)
                {
                    datatoSend += @"\aim\" + playerInfo.PlayerAim;
                }

                if (playerInfo.PlayerOccupation != 0)
                {
                    datatoSend += @"\occ\" + playerInfo.PlayerOccupation;
                }

                if (playerInfo.PlayerZIPCode.Length > 0)
                {
                    datatoSend += @"\zipcode\" + playerInfo.PlayerZIPCode;
                }

                if (playerInfo.PlayerCountryCode.Length > 0)
                {
                    datatoSend += @"\countrycode\" + playerInfo.PlayerCountryCode;
                }

                if (playerInfo.PlayerBirthday > 0 && playerInfo.PlayerBirthmonth > 0 && playerInfo.PlayerBirthyear > 0)
                {
                    datatoSend += @"\birthday\" + (uint)((playerInfo.PlayerBirthday << 24) | (playerInfo.PlayerBirthmonth << 16) | playerInfo.PlayerBirthyear);
                }

                if (playerInfo.PlayerLocation.Length > 0)
                {
                    datatoSend += @"\loc\" + playerInfo.PlayerLocation;
                }

                if (playerInfo.PlayerSex != PlayerSexType.PAT)
                {
                    if (playerInfo.PlayerSex == PlayerSexType.FEMALE)
                    {
                        datatoSend += @"\sex\1";
                    }
                    else if (playerInfo.PlayerSex == PlayerSexType.MALE)
                    {
                        datatoSend += @"\sex\0";
                    }
                }

                if (playerInfo.PlayerLatitude != 0.0f)
                {
                    datatoSend += @"\lat\" + playerInfo.PlayerLatitude;
                }

                if (playerInfo.PlayerLongitude != 0.0f)
                {
                    datatoSend += @"\lon\" + playerInfo.PlayerLongitude;
                }

                if (playerInfo.PlayerIncomeID != 0)
                {
                    datatoSend += @"\inc\" + playerInfo.PlayerIncomeID;
                }

                if (playerInfo.PlayerIndustryID != 0)
                {
                    datatoSend += @"\ind\" + playerInfo.PlayerIndustryID;
                }

                if (playerInfo.PlayerMarried != 0)
                {
                    datatoSend += @"\mar\" + playerInfo.PlayerMarried;
                }

                if (playerInfo.PlayerChildCount != 0)
                {
                    datatoSend += @"\chc\" + playerInfo.PlayerChildCount;
                }

                if (playerInfo.PlayerInterests != 0)
                {
                    datatoSend += @"\i1\" + playerInfo.PlayerInterests;
                }

                if (playerInfo.PlayerOwnership != 0)
                {
                    datatoSend += @"\o1\" + playerInfo.PlayerOwnership;
                }

                if (playerInfo.PlayerConnectionType != 0)
                {
                    datatoSend += @"\conn\" + playerInfo.PlayerConnectionType;
                }

                // SUPER NOTE: Please check the Signature of the PID, otherwise when it will be compared with other peers, it will break everything (See gpiPeer.c @ peerSig)
                datatoSend += @"\sig\" + GameSpyLib.Common.Random.GenerateRandomString(33, GameSpyLib.Common.Random.StringType.Hex) + @"\final\";
            }
            else
            {
                // Since this is our profile, we have to see ALL informations that we can edit. This means that we don't need to check the public masks for sending
                // the data

                datatoSend = string.Format(datatoSend + @"\nick\{0}\uniquenick\{1}\email\{2}\id\{3}\pmask\{4}",
                                           client.PlayerInfo.PlayerNick,
                                           client.PlayerInfo.PlayerUniqueNick,
                                           client.PlayerInfo.PlayerEmail,
                                           /*(ProfileSent ? "5" : "2")*/ messID,
                                           client.PlayerInfo.PlayerPublicMask
                                           );

                if (client.PlayerInfo.PlayerLastName.Length > 0)
                {
                    datatoSend += @"\lastname\" + client.PlayerInfo.PlayerLastName;
                }

                if (client.PlayerInfo.PlayerFirstName.Length > 0)
                {
                    datatoSend += @"\firstname\" + client.PlayerInfo.PlayerFirstName;
                }

                if (client.PlayerInfo.PlayerICQ != 0)
                {
                    datatoSend += @"\icquin\" + client.PlayerInfo.PlayerICQ;
                }

                if (client.PlayerInfo.PlayerHomepage.Length > 0)
                {
                    datatoSend += @"\homepage\" + client.PlayerInfo.PlayerHomepage;
                }

                if (client.PlayerInfo.PlayerPicture != 0)
                {
                    datatoSend += @"\pic\" + client.PlayerInfo.PlayerPicture;
                }

                if (client.PlayerInfo.PlayerAim.Length > 0)
                {
                    datatoSend += @"\aim\" + client.PlayerInfo.PlayerAim;
                }

                if (client.PlayerInfo.PlayerOccupation != 0)
                {
                    datatoSend += @"\occ\" + client.PlayerInfo.PlayerOccupation;
                }

                if (client.PlayerInfo.PlayerZIPCode.Length > 0)
                {
                    datatoSend += @"\zipcode\" + client.PlayerInfo.PlayerZIPCode;
                }

                if (client.PlayerInfo.PlayerCountryCode.Length > 0)
                {
                    datatoSend += @"\countrycode\" + client.PlayerInfo.PlayerCountryCode;
                }

                if (client.PlayerInfo.PlayerBirthday > 0 && client.PlayerInfo.PlayerBirthmonth > 0 && client.PlayerInfo.PlayerBirthyear > 0)
                {
                    datatoSend += @"\birthday\" + (uint)((client.PlayerInfo.PlayerBirthday << 24) | (client.PlayerInfo.PlayerBirthmonth << 16) | client.PlayerInfo.PlayerBirthyear);
                }

                if (client.PlayerInfo.PlayerLocation.Length > 0)
                {
                    datatoSend += @"\loc\" + client.PlayerInfo.PlayerLocation;
                }

                if (client.PlayerInfo.PlayerSex == PlayerSexType.FEMALE)
                {
                    datatoSend += @"\sex\1";
                }
                else if (client.PlayerInfo.PlayerSex == PlayerSexType.MALE)
                {
                    datatoSend += @"\sex\0";
                }

                if (client.PlayerInfo.PlayerLatitude != 0.0f)
                {
                    datatoSend += @"\lat\" + client.PlayerInfo.PlayerLatitude;
                }

                if (client.PlayerInfo.PlayerLongitude != 0.0f)
                {
                    datatoSend += @"\lon\" + client.PlayerInfo.PlayerLongitude;
                }

                if (client.PlayerInfo.PlayerIncomeID != 0)
                {
                    datatoSend += @"\inc\" + client.PlayerInfo.PlayerIncomeID;
                }

                if (client.PlayerInfo.PlayerIndustryID != 0)
                {
                    datatoSend += @"\ind\" + client.PlayerInfo.PlayerIndustryID;
                }

                if (client.PlayerInfo.PlayerMarried != 0)
                {
                    datatoSend += @"\mar\" + client.PlayerInfo.PlayerMarried;
                }

                if (client.PlayerInfo.PlayerChildCount != 0)
                {
                    datatoSend += @"\chc\" + client.PlayerInfo.PlayerChildCount;
                }

                if (client.PlayerInfo.PlayerInterests != 0)
                {
                    datatoSend += @"\i1\" + client.PlayerInfo.PlayerInterests;
                }

                if (client.PlayerInfo.PlayerOwnership != 0)
                {
                    datatoSend += @"\o1\" + client.PlayerInfo.PlayerOwnership;
                }

                if (client.PlayerInfo.PlayerConnectionType != 0)
                {
                    datatoSend += @"\conn\" + client.PlayerInfo.PlayerConnectionType;
                }

                // SUPER NOTE: Please check the Signature of the PID, otherwise when it will be compared with other peers, it will break everything (See gpiPeer.c @ peerSig)
                datatoSend += @"\sig\" + GameSpyLib.Common.Random.GenerateRandomString(33, GameSpyLib.Common.Random.StringType.Hex) + @"\final\";

                // Set that we send the profile initially
                if (!client.ProfileSent)
                {
                    client.ProfileSent = true;
                }
            }

            client.Send(datatoSend);
        }
Beispiel #15
0
        /// <summary>
        /// This method verifies the login information sent by
        /// the client, and returns encrypted data for the client
        /// to verify as well
        /// </summary>
        public static void ProcessLogin(GPCMClient client, Dictionary <string, string> recv, GPCMConnectionUpdate OnSuccessfulLogin, GPCMStatusChanged OnStatusChanged)
        {
            uint partnerID = 0;

            // Make sure we have all the required data to process this login
            //if (!recv.ContainsKey("challenge") || !recv.ContainsKey("response"))
            //{
            //    GameSpyUtils.SendGPError(client, GPErrorCode.General, "Invalid response received from the client!");
            //    client.DisconnectByReason(DisconnectReason.InvalidLoginQuery);
            //    return;
            //}
            if (IsContainAllKeys(recv) != GPErrorCode.NoError)
            {
                GameSpyUtils.SendGPError(client, GPErrorCode.General, "Invalid response received from the client!");
                client.DisconnectByReason(DisconnectReason.InvalidLoginQuery);
                return;
            }


            // Parse the partnerid, required since it changes the challenge for Unique nick and User login
            ParseRequestToPlayerInfo(client, recv, ref partnerID);


            // Dispose connection after use
            try
            {
                // Try and fetch the user from the database

                Dictionary <string, object> queryResult;

                try
                {
                    if (client.PlayerInfo.PlayerUniqueNick.Length > 0)
                    {
                        queryResult = LoginQuery.GetUserFromUniqueNick(recv);
                    }
                    else if (client.PlayerInfo.PlayerAuthToken.Length > 0)
                    {
                        //TODO! Add the database entry
                        GameSpyUtils.SendGPError(client, GPErrorCode.General, "AuthToken is not supported yet");
                        return;
                    }
                    else
                    {
                        queryResult = LoginQuery.GetUserFromNickAndEmail(recv);
                    }
                }
                catch (Exception ex)
                {
                    LogWriter.Log.WriteException(ex);
                    GameSpyUtils.SendGPError(client, GPErrorCode.DatabaseError, "This request cannot be processed because of a database error.");
                    return;
                }

                //if no match found we disconnect the game
                if (queryResult == null)
                {
                    if (client.PlayerInfo.PlayerUniqueNick.Length > 0)
                    {
                        GameSpyUtils.SendGPError(client, GPErrorCode.LoginBadUniquenick, "The uniquenick provided is incorrect!");
                    }
                    else
                    {
                        GameSpyUtils.SendGPError(client, GPErrorCode.LoginBadUniquenick, "The information provided is incorrect!");
                    }
                    client.DisconnectByReason(DisconnectReason.InvalidUsername);
                    return;
                }

                // Check if user is banned
                string           msg;
                DisconnectReason reason;
                GPErrorCode      error = CheckUsersAccountAvailability(queryResult, out msg, out reason);
                if (error != GPErrorCode.NoError)
                {
                    GameSpyUtils.SendGPError(client, error, msg);
                    client.DisconnectByReason(reason);
                    return;
                }

                // we finally set the player variables and return challengeData
                string challengeData = SetPlayerInfo(client, queryResult, recv);
                string sendingBuffer;
                // Use the GenerateProof method to compare with the "response" value. This validates the given password
                if (recv["response"] == GenerateProof(recv["challenge"], client.ServerChallengeKey, challengeData, client.PlayerInfo.PlayerAuthToken.Length > 0 ? 0 : partnerID, client.PlayerInfo))
                {
                    // Create session key
                    client.SessionKey = Crc.ComputeChecksum(client.PlayerInfo.PlayerUniqueNick);

                    //actually we should store sesskey in database at namespace table, when we want someone's profile we just
                    //access to the sesskey to find the uniquenick for particular game
                    LoginQuery.UpdateSessionKey(recv, client.SessionKey, client.PlayerInfo);

                    // Password is correct
                    sendingBuffer = string.Format(@"\lc\2\sesskey\{0}\proof\{1}\userid\{2}\profileid\{2}\uniquenick\{3}\lt\{4}__\id\1\final\",
                                                  client.SessionKey,
                                                  GenerateProof(client.ServerChallengeKey, recv["challenge"], challengeData, client.PlayerInfo.PlayerAuthToken.Length > 0 ? 0 : partnerID, client.PlayerInfo), // Do this again, Params are reversed!
                                                  client.PlayerInfo.PlayerId,
                                                  client.PlayerInfo.PlayerUniqueNick,
                                                  // Generate LT whatever that is (some sort of random string, 22 chars long)
                                                  GameSpyLib.Common.Random.GenerateRandomString(22, GameSpyLib.Common.Random.StringType.Hex)
                                                  );
                    //Send response to client
                    client.Send(sendingBuffer);
                    // Log Incoming Connections
                    //LogWriter.Log.Write(LogLevel.Info, "{0,-8} [Login] {1} - {2} - {3}", client.ServerName, client.PlayerInfo.PlayerNick, client.PlayerInfo.PlayerId, RemoteEndPoint);
                    //string statusString = string.Format(" [Login Success!] Nick:{0} - Profileid:{1} - IP:{2}", client.PlayerInfo.PlayerNick, client.PlayerInfo.PlayerId, client.RemoteEndPoint);
                    client.StatusToLog("Login Success", client.PlayerInfo.PlayerNick, client.PlayerInfo.PlayerId, client.RemoteEndPoint, null);
                    // Update status last, and call success login
                    client.PlayerInfo.LoginStatus          = LoginStatus.Completed;
                    client.PlayerInfo.PlayerStatus         = PlayerStatus.Online;
                    client.PlayerInfo.PlayerStatusString   = "Online";
                    client.PlayerInfo.PlayerStatusLocation = "";
                    client.CompletedLoginProcess           = true;

                    OnSuccessfulLogin?.Invoke(client);
                    OnStatusChanged?.Invoke(client);
                    SendBuddiesHandler.HandleSendBuddies(client, recv);
                }
                else
                {
                    // Log Incoming Connection
                    string statusString = string.Format(@"[Login Failed!] Nick:{0} - Profileid:{1} - IP:{2}", client.PlayerInfo.PlayerNick, client.PlayerInfo.PlayerId, client.RemoteEndPoint);
                    client.ToLog(LogLevel.Info, statusString);
                    // Password is incorrect with database value.
                    client.Send(@"\error\\err\260\fatal\\errmsg\The password provided is incorrect.\id\1\final\");
                    client.DisconnectByReason(DisconnectReason.InvalidPassword);
                }
            }
            catch (Exception ex)
            {
                LogWriter.Log.Write(ex.ToString(), LogLevel.Error);
                client.DisconnectByReason(DisconnectReason.GeneralError);
                return;
            }
        }
 public static void Addfriends(GPCMClient client, Dictionary <string, string> recv)
 {
     GameSpyUtils.PrintReceivedGPDictToLogger("profilelist", recv);
     GameSpyUtils.SendGPError(client, GPErrorCode.General, "This request is not supported yet.");
 }
        public static void SearchUsers(GPSPClient client, Dictionary <string, string> dict)
        {
            //string sendingbuffer = "\\bsr\\1\\nick\\mycrysis\\uniquenick\\1\\namespaceid\\0\\firstname\\jiangheng\\lastname\\kou\\email\\[email protected]\\bsrdone\\0\\final\\";
            //client.Stream.SendAsync(sendingbuffer);

            string      sendingBuffer;
            GPErrorCode error;

            error = IsLogIn(dict);
            //if (error != GPErrorCode.NoError)
            //{
            //    GameSpyUtils.SendGPError(client.Stream, error, "You must login to use search functions");
            //    return;
            //}

            //we only need uniquenick to search a profile
            if (dict.ContainsKey("uniquenick"))
            {
                error = SearchWithUniquenick(dict, out sendingBuffer);
                if (error != GPErrorCode.NoError)
                {
                    GameSpyUtils.SendGPError(client, error, sendingBuffer);
                }
                else
                {
                    client.Send(sendingBuffer);
                }
                return;
            }

            if (dict.ContainsKey("nick") && dict.ContainsKey("email"))
            {
                //exist nick and email which can identify multiple profiles
                //you have to add \more\bsr\******\final\
                error = SearchWithNickEmail(dict, out sendingBuffer);
                if (error != GPErrorCode.NoError)
                {
                    GameSpyUtils.SendGPError(client, error, sendingBuffer);
                }
                else
                {
                    client.Send(sendingBuffer);
                }
                return;
            }

            if (dict.ContainsKey("email"))
            {
                error = SearchWithEmail(dict, out sendingBuffer);
                if (error != GPErrorCode.NoError)
                {
                    GameSpyUtils.SendGPError(client, error, sendingBuffer);
                }
                else
                {
                    client.Send(sendingBuffer);
                }
                return;
            }
            //if above 3 functions not excuted then it must be parsing error
            GameSpyUtils.SendGPError(client, GPErrorCode.Parse, "There is a parse error in request!");

            //last one we search with email this may get few profile so we can not return GPErrorCode
            //SearchWithEmail(client,dict );
            //client.Stream.SendAsync(@"\bsr\1\nick\1\uniquenick\1\namespaceid\1\firstname\1\lastname\1\email\1\bsrdone\\more\bsr\2\nick\2\uniquenick\2\namespaceid\2\firstname\2\lastname\2\email\2\bsrdone\\final\");
            //we need full information to find a player.
            //if recieved data contians nick, uniquenick, email,
            //a player must need to login to use the search function. sessionkey is 0 or else and profileid also.
            //case1:  uniquenick  email . check uniquenick email is exist or not
            //case4:  uniquenick
            //case2:  nick uniquenick email
            //case3:  nick uniquenick
            //case5:  nick   email gamename
            //case6:  nick
            //if not contain email, we need to
            //\search\\sesskey\0\profileid\0\namespaceid\1\partnerid\0\nick\mycrysis\uniquenick\xiaojiuwo\email\[email protected]\gamename\gmtest\final\
            //\bsrdone\more\<more>\final\
            //\bsr\
        }
Beispiel #18
0
        public void Switch(GPSPSession session, string message)
        {
            try
            {
                if (message[0] != '\\')
                {
                    GameSpyUtils.SendGPError(session, GPErrorCode.Parse, "An invalid request was sended.");
                    return;
                }

                string[] commands = message.Split("\\final\\", System.StringSplitOptions.RemoveEmptyEntries);

                foreach (string command in commands)
                {
                    if (command.Length < 1)
                    {
                        continue;
                    }

                    // Read client message, and parse it into key value pairs
                    string[] recieved = command.TrimStart('\\').Split('\\');
                    Dictionary <string, string> recv = GameSpyUtils.ConvertRequestToKeyValue(recieved);

                    switch (recv.Keys.First())
                    {
                    case "search":
                        new SearchHandler(session, recv).Handle();
                        break;

                    case "valid":    //is email format valid
                        new ValidHandler(session, recv).Handle();
                        break;

                    case "nicks":    // search an user with nick name
                        new NickHandler(session, recv).Handle();
                        break;

                    //case "pmatch":
                    //    PmatchHandler pmatch = new PmatchHandler(recv);
                    //    pmatch.Handle(session);
                    //    break;

                    case "check":
                        new CheckHandler(session, recv).Handle();
                        break;

                    case "newuser":    //create an new user
                        new NewUserHandler(session, recv).Handle();
                        break;

                    case "searchunique":    //search an user with uniquenick
                        new SearchUniqueHandler(session, recv).Handle();
                        break;

                    case "others":    //search
                        new OthersHandler(session, recv).Handle();
                        break;

                    case "otherslist":    //search other players friend list to see who is in his list?
                        new OthersListHandler(session, recv).Handle();
                        break;

                    case "uniquesearch":    //search a user with uniquenick and namespaceid
                        new UniqueSearchHandler(session, recv).Handle();
                        break;

                    default:
                        LogWriter.UnknownDataRecieved(message);
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                LogWriter.ToLog(e);
            }
        }
Beispiel #19
0
        public static void Switch(GPCMClient client, Dictionary <string, string> recv, GPCMConnectionUpdate OnSuccessfulLogin, GPCMStatusChanged OnStatusChanged)
        {
            string command = recv.Keys.First();

            try
            {
                switch (command)
                {
                case "inviteto":
                    InviteToHandler.AddFriends(client, recv);
                    break;

                case "login":
                    LoginHandler.ProcessLogin(client, recv, OnSuccessfulLogin, OnStatusChanged);
                    break;

                case "getprofile":
                    GetProfileHandler.SendProfile(client, recv);
                    break;

                case "addbuddy":
                    AddBuddyHandler.Addfriends(client, recv);
                    break;

                case "delbuddy":
                    DelBuddyHandler.Handle(client, recv);
                    break;

                case "updateui":
                    UpdateUiHandler.UpdateUi(client, recv);
                    break;

                case "updatepro":
                    UpdateProHandler.UpdateUser(client, recv);
                    break;

                case "registernick":
                    RegisterNickHandler.RegisterNick(client, recv);
                    break;

                case "logout":
                    client.DisconnectByReason(DisconnectReason.NormalLogout);
                    break;

                case "status":
                    StatusHandler.UpdateStatus(client, recv, OnStatusChanged);
                    break;

                case "newuser":
                    NewUserHandler.NewUser(client, recv);
                    break;

                case "ka":
                    KAHandler.SendKeepAlive(client);
                    break;

                default:
                    LogWriter.Log.Write("[GPCM] received unknown data " + command, LogLevel.Debug);
                    GameSpyUtils.SendGPError(client, GPErrorCode.General, "An invalid request was sended.");
                    break;
                }
            }
            catch (Exception e)
            {
                LogWriter.Log.WriteException(e);
            }
        }
 public static void UpdateUI(GPCMSession client, Dictionary <string, string> recv)
 {
     GameSpyUtils.PrintReceivedGPDictToLogger(recv);
     GameSpyUtils.SendGPError(client, GPErrorCode.General, "This request is not supported yet.");
 }
 public static void SearchProfileWithUniquenick(GPSPClient client, Dictionary <string, string> dict)
 {
     GameSpyUtils.PrintReceivedGPDictToLogger("searchunique", dict);
     GameSpyUtils.SendGPError(client, GPErrorCode.General, "This request is not supported yet.");
 }
        /// <summary>
        /// Send others profile.
        /// </summary>
        public static void SendProfile(GPCMSession session, Dictionary <string, string> recv)
        {
            //TODO
            _recv = recv;
            // \getprofile\\sesskey\19150\profileid\2\id\2\final\
            //profileid is

            IsContainAllKey();

            if (_error != GPErrorCode.NoError)
            {
                GameSpyUtils.SendGPError(session, _error, "Parsing error.");
                return;
            }

            var result = GetProfileQuery.GetProfileInfo(Convert.ToUInt32(_recv["profileid"]), Convert.ToUInt32(_recv["sesskey"]));

            if (result == null)
            {
                GameSpyUtils.SendGPError(session, GPErrorCode.GetProfileBadProfile, "Unable to get profile information.");
                return;
            }

            string sendingBuffer = @"\pi\\profileid\" + _recv["profileid"];

            if (result["nick"].ToString().Length > 0)
            {
                sendingBuffer += @"\nick\" + result["nick"].ToString();
            }

            if (result["uniquenick"].ToString().Length > 0)
            {
                sendingBuffer += @"\uniquenick\" + result["uniquenick"].ToString();
            }

            if (result["email"].ToString().Length > 0)
            {
                sendingBuffer += @"\email\" + result["email"].ToString();
            }

            if (result["firstname"].ToString().Length > 0)
            {
                sendingBuffer += @"\firstname\" + result["firstname"].ToString();
            }

            if (result["lastname"].ToString().Length > 0)
            {
                sendingBuffer += @"\firstname\" + result["lastname"].ToString();
            }

            //if (result["icquin"].ToString().Length > 0)
            //    sendingBuffer += @"\icquin\" + Convert.ToUInt32(result["icquin"]);

            //if (result["homepage"].ToString().Length > 0)
            //    sendingBuffer += @"\homepage\" + result["homepage"].ToString();

            //if (result["zipcode"].ToString().Length > 0)
            //    sendingBuffer += @"\zipcode\" + result["zipcode"].ToString();

            //if (result["countrycode"].ToString().Length > 0)
            //    sendingBuffer += @"\countrycode\" + result["countrycode"].ToString();


            //float longtitude;
            //if (result["longitude"].ToString().Length > 0)
            //{
            //    float.TryParse(result["longitude"].ToString(), out longtitude);
            //    sendingBuffer += @"\lon\" + longtitude;
            //}


            //float latitude;
            //if (result["latitude"].ToString().Length > 0)
            //{
            //    float.TryParse(result["latitude"].ToString(), out latitude);
            //    sendingBuffer += @"\lat\" + latitude;
            //}

            //if (result["location"].ToString().Length > 0)
            //    sendingBuffer += @"\loc\" + result["location"].ToString();

            //if (result["birthday"].ToString().Length > 0 && result["birthmonth"].ToString().Length > 0 && result["birthyear"].ToString().Length > 0)
            //{
            //    uint birthday = (Convert.ToUInt32(result["birthday"]) << 24) | (Convert.ToUInt32(result["birthmonth"]) << 16) | Convert.ToUInt32(result["birthyear"]);
            //    sendingBuffer += @"\birthday\" + birthday;
            //}

            //PlayerSexType playerSexType;
            //if (!Enum.TryParse(result["sex"].ToString().ToUpper(), out playerSexType))
            //    if (playerSexType == PlayerSexType.PAT)
            //        sendingBuffer += @"\sex\2";
            //if (playerSexType == PlayerSexType.FEMALE)
            //    sendingBuffer += @"\sex\1";
            //if (playerSexType == PlayerSexType.MALE)
            //    sendingBuffer += @"\sex\0";


            //PublicMasks mask;
            //if (result["publicmask"].ToString().Length > 0)
            //    if (!Enum.TryParse(result["publicmask"].ToString(), out mask))
            //        sendingBuffer += @"\publicmask\" + mask;

            //if (result["aim"].ToString().Length > 0)
            //    sendingBuffer += @"\aim\" + result["aim"].ToString();

            //if (result["picture"].ToString().Length > 0)
            //    sendingBuffer += @"\picture\" + Convert.ToUInt16(result["picture"]);

            //if (result["occupationid"].ToString().Length > 0)
            //    sendingBuffer += @"\occ\" + Convert.ToUInt16(result["occupationid"]);
            //if (result["industryid"].ToString().Length > 0)
            //    sendingBuffer += @"\ind\" + Convert.ToUInt16(result["industryid"]);
            //if (result["incomeid"].ToString().Length > 0)
            //    sendingBuffer += @"\inc\" + Convert.ToUInt16(result["incomeid"]);


            //if (result["marriedid"].ToString().Length > 0)
            //    sendingBuffer += @"\mar\" + Convert.ToUInt16(result["marriedid"]);
            //if (result["childcount"].ToString().Length > 0)
            //    sendingBuffer += @"\chc\" + Convert.ToUInt16(result["childcount"]);

            //if (result["interests1"].ToString().Length > 0)
            //    sendingBuffer += @"\i1\" + result["interests1"].ToString();
            //if (result["ownership1"].ToString().Length > 0)
            //    sendingBuffer += @"\o1\" + result["ownership1"].ToString();
            //if (result["connectiontype"].ToString().Length > 0)
            //    sendingBuffer += @"\conn\" + Convert.ToUInt16(result["connectiontype"]);

            // SUPER NOTE: Please check the Signature of the PID, otherwise when it will be compared with other peers, it will break everything (See gpiPeer.c @ peerSig)
            string signature = GameSpyLib.Common.GameSpyRandom.GenerateRandomString(10, GameSpyLib.Common.GameSpyRandom.StringType.Hex);

            sendingBuffer += @"\sig\" + signature + @"\id\" + recv["id"] + @"\final\";


            session.SendAsync(sendingBuffer);
            session.PlayerInfo.BuddiesSent = true;
        }
Beispiel #23
0
        public void Switch(GPCMSession session, string message)
        {
            try
            {
                message = session.RequstFormatConversion(message);
                if (message[0] != '\\')
                {
                    GameSpyUtils.SendGPError(session, GPErrorCode.General, "An invalid request was sended.");
                    return;
                }
                string[] commands = message.Split("\\final\\", StringSplitOptions.RemoveEmptyEntries);

                foreach (string command in commands)
                {
                    if (command.Length < 1)
                    {
                        continue;
                    }

                    // Read client message, and parse it into key value pairs
                    string[] recieved = command.TrimStart('\\').Split('\\');

                    Dictionary <string, string> recv = GameSpyUtils.ConvertRequestToKeyValue(recieved);

                    switch (recv.Keys.First())
                    {
                    //case "inviteto":
                    //    InviteToHandler.InvitePlayer();
                    //    break;

                    case "login":    //login to retrospy
                        new LoginHandler(session, recv).Handle();
                        break;

                    case "getprofile":    //get profile of a player
                        new GetProfileHandler(session, recv).Handle();
                        break;

                    case "addbuddy":    //Send a request which adds an user to our friend list
                        new AddBuddyHandler(session, recv).Handle();
                        break;

                    case "delbuddy":    //delete a user from our friend list
                        new DelBuddyHandler(session, recv).Handle();
                        break;

                    case "updateui":    //update a user's email
                        new UpdateUIHandler(session, recv).Handle();
                        break;

                    case "updatepro":    //update a user's profile
                        new UpdateProHandler(session, recv).Handle();
                        break;

                    case "registernick":    //update user's uniquenick
                        new RegisterNickHandler(session, recv).Handle();
                        break;

                    case "logout":    //logout from retrospy
                        session.Disconnect();
                        GPCMServer.LoggedInSession.TryRemove(session.Id, out _);
                        break;

                    case "status":    //update current logged in user's status info
                        new StatusHandler(session, recv).Handle();
                        break;

                    case "newuser":    //create an new user
                        new NewUserHandler(session, recv).Handle();
                        break;

                    case "addblock":    //add an user to our block list
                        new AddBlockHandler(session, recv).Handle();
                        break;

                    case "ka":
                        //KAHandler.SendKeepAlive(_session);
                        break;

                    case "newprofile":    //create an new profile
                        new NewProfileHandler(session, recv).Handle();
                        break;

                    default:
                        LogWriter.UnknownDataRecieved(message);
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                LogWriter.ToLog(Serilog.Events.LogEventLevel.Error, e.ToString());
            }
        }