/// <summary> /// Constructor /// </summary> /// <param name="Pid">The player account ID</param> public AccountEditForm(int Pid) { InitializeComponent(); this.AccountId = Pid; // Register for Events GpcmClient.OnSuccessfulLogin += GpcmClient_OnSuccessfulLogin; GpcmClient.OnDisconnect += GpcmClient_OnDisconnect; // Fill the account information boxes using (GamespyDatabase Database = new GamespyDatabase()) { Dictionary <string, object> User = Database.GetUser(AccountId); PlayerID.Value = AccountId = Int32.Parse(User["id"].ToString()); AccountNick.Text = User["name"].ToString(); AccountEmail.Text = User["email"].ToString(); // Disable options if user is online if (GamespyEmulator.IsPlayerConnected(AccountId)) { SatusLabel.Text = "Online (IP: " + User["lastip"].ToString() + ")"; UpdateBtn.Enabled = false; DeleteBtn.Enabled = false; DisconnectBtn.Enabled = true; } else { SatusLabel.Text = "Offline"; } } }
/// <summary> /// This method verifies the login information sent by /// the client, and returns encrypted data for the client /// to verify as well /// </summary> public void ProcessLogin(Dictionary <string, string> Recv) { // Make sure we have all the required data to process this login if (!Recv.ContainsKey("uniquenick") || !Recv.ContainsKey("challenge") || !Recv.ContainsKey("response")) { Stream.SendAsync(@"\error\\err\0\fatal\\errmsg\Invalid Query!\id\1\final\"); Disconnect(DisconnectReason.InvalidLoginQuery); return; } // Dispose connection after use try { using (GamespyDatabase Conn = new GamespyDatabase()) { // Try and fetch the user from the database Dictionary <string, object> User = Conn.GetUser(Recv["uniquenick"]); if (User == null) { Stream.SendAsync(@"\error\\err\265\fatal\\errmsg\The uniquenick provided is incorrect!\id\1\final\"); Disconnect(DisconnectReason.InvalidUsername); return; } // Check if user is banned bool banned = Int32.Parse(User["permban"].ToString()) > 0; if (banned) { Stream.SendAsync(@"\error\\err\265\fatal\\errmsg\You account has been permanently suspended.\id\1\final\"); Disconnect(DisconnectReason.PlayerIsBanned); return; } // Set player variables PlayerId = Int32.Parse(User["id"].ToString()); PlayerNick = Recv["uniquenick"]; PlayerEmail = User["email"].ToString(); PlayerCountryCode = User["country"].ToString(); PasswordHash = User["password"].ToString().ToLowerInvariant(); // Use the GenerateProof method to compare with the "response" value. This validates the given password if (Recv["response"] == GenerateProof(Recv["challenge"], ServerChallengeKey)) { // Create session key SessionKey = Crc.ComputeChecksum(PlayerNick); // Password is correct Stream.SendAsync( @"\lc\2\sesskey\{0}\proof\{1}\userid\{2}\profileid\{2}\uniquenick\{3}\lt\{4}__\id\1\final\", SessionKey, GenerateProof(ServerChallengeKey, Recv["challenge"]), // Do this again, Params are reversed! PlayerId, PlayerNick, GenerateRandomString(22) // Generate LT whatever that is (some sort of random string, 22 chars long) ); // Log Incoming Connections ServerManager.Log("Client Login: {0} - {1} - {2}", PlayerNick, PlayerId, RemoteEndPoint); // Update status last, and call success login Status = LoginStatus.Completed; CompletedLoginProcess = true; OnSuccessfulLogin?.Invoke(this); } else { // Log Incoming Connections ServerManager.Log("Failed Login Attempt: {0} - {1} - {2}", PlayerNick, PlayerId, RemoteEndPoint); // Password is incorrect with database value Stream.SendAsync(@"\error\\err\260\fatal\\errmsg\The password provided is incorrect.\id\1\final\"); Disconnect(DisconnectReason.InvalidPassword); } } } catch (Exception ex) { ExceptionHandler.GenerateExceptionLog(ex); Disconnect(DisconnectReason.GeneralError); return; } }
/// <summary> /// This method verifies the login information sent by /// the client, and returns encrypted data for the client /// to verify as well /// </summary> public void ProcessLogin(Dictionary <string, string> Recv) { // Make sure we have all the required data to process this login if (!Recv.ContainsKey("uniquenick") || !Recv.ContainsKey("challenge") || !Recv.ContainsKey("response")) { Stream.SendAsync(@"\error\\err\0\fatal\\errmsg\Invalid Query!\id\1\final\"); Disconnect(2); return; } // Dispose connection after use try { using (GamespyDatabase Conn = new GamespyDatabase()) { // Try and fetch the user from the database Dictionary <string, object> User = Conn.GetUser(Recv["uniquenick"]); if (User == null) { Stream.SendAsync(@"\error\\err\265\fatal\\errmsg\The uniquenick provided is incorrect!\id\1\final\"); Disconnect(2); return; } // Set player variables PlayerId = Int32.Parse(User["pid"].ToString()); PlayerNick = Recv["uniquenick"]; PlayerEmail = User["email"].ToString(); PlayerCountryCode = User["game_country"].ToString(); PasswordHash = User["password"].ToString().ToLowerInvariant(); // Use the GenerateProof method to compare with the "response" value. This validates the given password if (Recv["response"] == GenerateProof(Recv["challenge"], ServerChallengeKey)) { // Create session key SessionKey = Crc.ComputeChecksum(PlayerNick); // Password is correct Stream.SendAsync( @"\lc\2\sesskey\{0}\proof\{1}\userid\{2}\profileid\{2}\uniquenick\{3}\lt\{4}__\id\1\final\", SessionKey, GenerateProof(ServerChallengeKey, Recv["challenge"]), // Do this again, Params are reversed! PlayerId, PlayerNick, GenerateRandomString(22) // Generate LT whatever that is (some sort of random string, 22 chars long) ); // Log Incoming Connections ServerManager.Log("Client Login: {0} - {1} - {2}", PlayerNick, PlayerId, RemoteEndPoint); Conn.Execute( "UPDATE web_users SET last_game_ip=@P0, game_session=1, game_tstamp=@P1 WHERE pid=@P2", RemoteEndPoint.Address, DateTime.UtcNow.ToUnixTimestamp(), PlayerId ); // Update status last, and call success login Status = LoginStatus.Completed; if (OnSuccessfulLogin != null) { OnSuccessfulLogin(this); } } else { // Log Incoming Connections ServerManager.Log("Failed Login Attempt: {0} - {1} - {2}", PlayerNick, PlayerId, RemoteEndPoint); // Password is incorrect with database value Stream.SendAsync(@"\error\\err\260\fatal\\errmsg\The password provided is incorrect.\id\1\final\"); Disconnect(3); } } } catch (Exception ex) { ExceptionHandler.GenerateExceptionLog(ex); Disconnect(4); return; } }
public void CheckInput() { // Get user input Console.Write("cmd > "); string Line = Console.ReadLine(); // Make sure input is not empty if (string.IsNullOrWhiteSpace(Line)) { return; } // Define some base vars Dictionary <string, object> user = new Dictionary <string, object>(); string command = Line.Trim(); string[] parts = command.Split(' '); try { switch (parts[0]) { case "stop": case "quit": case "exit": isRunning = false; break; case "connections": Console.WriteLine(" - Total Connections: {0}" + Environment.NewLine, CmServer.NumClients()); break; case "accounts": Console.WriteLine(" - Total Accounts: {0}" + Environment.NewLine, Database.GetNumAccounts()); break; case "fetch": // Prevent an out of range exception if (parts.Length < 2) { Console.WriteLine(" - Incorrect command format. Please type 'help' to see list of available commands."); Console.WriteLine(""); return; } // Make sure we have a nick if (String.IsNullOrEmpty(parts[1])) { Console.WriteLine(" - No account named provided. Please make sure you are providing an account name, and not a space"); Console.WriteLine(""); return; } // Fetch user account info user = Database.GetUser(parts[1]); if (user == null) { Console.WriteLine( " - Account '{0}' does not exist in the gamespy database." + Environment.NewLine, parts[1]); return; } // Get BF2 PID Console.Write( " - Account ID: " + user["id"].ToString() + Environment.NewLine + " - Email: " + user["email"].ToString() + Environment.NewLine + " - Country: " + user["country"].ToString() + Environment.NewLine + Environment.NewLine ); break; case "create": // Prevent an out of range exception if (parts.Length < 4) { Console.WriteLine(" - Incorrect command format. Please type 'help' to see list of available commands."); Console.WriteLine(""); return; } // Make sure our strings are not empty! if (String.IsNullOrEmpty(parts[1]) || String.IsNullOrEmpty(parts[2]) || String.IsNullOrEmpty(parts[3])) { Console.WriteLine(" - Account name, password, or email was not provided. Please try again with the correct format."); Console.WriteLine(""); return; } // Make sure the account exists! if (Database.UserExists(parts[1])) { Console.WriteLine(" - Account '{0}' already exists in the gamespy database.", parts[1]); return; } bool r = Database.CreateUser(parts[1], parts[2], parts[3], "00"); string m = (r == true) ? " - Account created successfully" : " - Error creating account!"; Console.WriteLine(m + Environment.NewLine); break; case "delete": // Prevent an out of range exception if (parts.Length < 2) { Console.WriteLine(" - Incorrect command format. Please type 'help' to see list of available commands."); Console.WriteLine(""); return; } // Make sure our strings are not empty! if (String.IsNullOrEmpty(parts[1])) { Console.WriteLine(" - Account name was not provided. Please try again with the correct format."); Console.WriteLine(""); return; } // Make sure the account exists! if (!Database.UserExists(parts[1])) { Console.WriteLine(" - Account '{0}' doesnt exist in the gamespy database.", parts[1]); Console.WriteLine(""); return; } // Do a confimration Console.Write(" - Are you sure you want to delete account '{0}'? <y/n>: ", parts[1]); string v = Console.ReadLine().ToLower(); // If no, stop here if (v == "n" || v == "no") { Console.WriteLine(" - Command cancelled." + Environment.NewLine); return; } // Process any command other then no if (v == "y" || v == "yes") { string output = ""; if (Database.DeleteUser(parts[1]) == 1) { output = " - Account deleted successfully"; } else { output = " - Failed to remove account from database."; } Console.WriteLine(output + Environment.NewLine); } else { Console.WriteLine(" - Incorrect repsonse. Aborting command" + Environment.NewLine); } break; case "setpid": // Prevent an out of range exception if (parts.Length < 3) { Console.WriteLine(" - Incorrect command format. Please type 'help' to see list of available commands."); Console.WriteLine(""); return; } // Make sure our strings are not empty! if (String.IsNullOrEmpty(parts[1]) || String.IsNullOrEmpty(parts[2])) { Console.WriteLine(" - Account name or PID not provided. Please try again with the correct format."); Console.WriteLine(""); return; } // Make sure the account exists! user = Database.GetUser(parts[1]); if (user == null) { Console.WriteLine(" - Account '{0}' does not exist in the gamespy database.", parts[1]); return; } // Try to make a PID out of parts 2 int newpid; if (!Int32.TryParse(parts[2], out newpid)) { Console.WriteLine(" - Player ID must be an numeric only!"); Console.WriteLine(""); return; } // try and set the PID int result = Database.SetPID(parts[1], newpid); string message = ""; switch (result) { case 1: message = "New PID is set!"; break; case 0: message = "Error setting PID"; break; case -1: message = String.Format("Account '{0}' does not exist in the gamespy database.", parts[1]); break; case -2: message = String.Format("PID {0} is already in use.", newpid); break; } Console.WriteLine(" - " + message); Console.WriteLine(""); break; case "help": Console.Write(Environment.NewLine + "stop/quit/exit - Stops the server" + Environment.NewLine + "connections - Displays the current number of connected clients" + Environment.NewLine + "accounts - Displays the current number accounts in the DB." + Environment.NewLine + "create {nick} {password} {email} - Create a new Gamespy account." + Environment.NewLine + "delete {nick} - Deletes a user account." + Environment.NewLine + "fetch {nick} - Displays the account information" + Environment.NewLine + "setpid {nick} {newpid} - Sets the BF2 Player ID of the givin account name" + Environment.NewLine + Environment.NewLine ); break; default: lock (Console.Out) { Console.WriteLine("Unrecognized input '{0}'", Line); } break; } } catch {} Thread.Sleep(100); }
/// <summary> /// Reads the next input in the console (Blocking Method) /// </summary> private static void CheckInput() { // Get user input [Blocking] string Input = Console.ReadLine(); // Make sure input is not empty if (String.IsNullOrWhiteSpace(Input)) { Console.WriteLine("Please enter a command"); Console.WriteLine(); Console.Write("Cmd > "); return; } // Split input into an array by whitespace, empty entries are removed string[] InParts = Input.Split((char[])null, StringSplitOptions.RemoveEmptyEntries); Dictionary <string, object> user = new Dictionary <string, object>(); // Process Task try { switch (InParts[0].ToLowerInvariant()) { case "stop": case "quit": case "exit": IsRunning = false; // Setting to false will stop program loop break; case "connections": Console.WriteLine("Total Connections: {0}", ServerManager.NumConnections()); break; case "accounts": using (GamespyDatabase Db = new GamespyDatabase()) Console.WriteLine("Total Accounts: {0}", Db.GetNumAccounts()); break; case "fetch": // Prevent an out of range exception if (InParts.Length < 2) { Console.WriteLine("Incorrect command format. Please type 'help' to see list of available commands."); break; } // Make sure we have a nick if (String.IsNullOrEmpty(InParts[1])) { Console.WriteLine("No account named provided. Please make sure you are providing an account name, and not a space"); break; } // Fetch user account info using (GamespyDatabase Db = new GamespyDatabase()) user = Db.GetUser(InParts[1]); if (user == null) { Console.WriteLine("Account '{0}' does not exist in the gamespy database.", InParts[1]); break; } // Get BF2 PID Console.WriteLine(" - PlayerID: " + user["id"].ToString()); Console.WriteLine(" - Email: " + user["email"].ToString()); Console.WriteLine(" - Country: " + user["country"].ToString()); break; case "create": // Prevent an out of range exception if (InParts.Length < 4) { Console.WriteLine("Incorrect command format. Please type 'help' to see list of available commands."); break; } // Make sure our strings are not empty! if (String.IsNullOrEmpty(InParts[1]) || String.IsNullOrEmpty(InParts[2]) || String.IsNullOrEmpty(InParts[3])) { Console.WriteLine("Account name, password, or email was not provided. Please try again with the correct format."); break; } // Disposible connection using (GamespyDatabase Db = new GamespyDatabase()) { // Make sure the account exists! if (Db.UserExists(InParts[1])) { Console.WriteLine("Account '{0}' already exists in the gamespy database.", InParts[1]); break; } bool r = Db.CreateUser(InParts[1], InParts[2], InParts[3], "00") > 0; Console.WriteLine((r == true) ? "Account created successfully" : "Error creating account!"); } break; case "delete": // Prevent an out of range exception if (InParts.Length < 2) { Console.WriteLine("Incorrect command format. Please type 'help' to see list of available commands."); break; } // Make sure our strings are not empty! if (String.IsNullOrEmpty(InParts[1])) { Console.WriteLine("Account name was not provided. Please try again with the correct format."); break; } // Disposible connection using (GamespyDatabase Db = new GamespyDatabase()) { // Make sure the account exists! if (!Db.UserExists(InParts[1])) { break; } // Do a confimration Console.Write("Are you sure you want to delete account '{0}'? <y/n>: ", InParts[1]); string v = Console.ReadLine().ToLower().Trim(); // If no, stop here if (v == "n" || v == "no" || v == "na" || v == "nope") { Console.WriteLine("Command cancelled."); break; } // Process any command other then no if (v == "y" || v == "yes" || v == "ya" || v == "yep") { if (Db.DeleteUser(InParts[1]) == 1) { Console.WriteLine("Account deleted successfully"); } else { Console.WriteLine("Failed to remove account from database."); } } else { Console.WriteLine("Incorrect repsonse. Aborting command"); } } break; case "setpid": // Prevent an out of range exception if (InParts.Length < 3) { Console.WriteLine("Incorrect command format. Please type 'help' to see list of available commands."); break; } // Make sure our strings are not empty! if (String.IsNullOrEmpty(InParts[1]) || String.IsNullOrEmpty(InParts[2])) { Console.WriteLine("Account name or PID not provided. Please try again with the correct format."); break; } // Disposible connection using (GamespyDatabase Db = new GamespyDatabase()) { // Make sure the account exists! user = Db.GetUser(InParts[1]); if (user == null) { Console.WriteLine("Account '{0}' does not exist in the gamespy database.", InParts[1]); break; } // Try to make a PID out of parts 2 int newpid; if (!Int32.TryParse(InParts[2], out newpid)) { Console.WriteLine("Player ID must be an numeric only!"); break; } // try and set the PID int result = Db.SetPID(InParts[1], newpid); string message = ""; switch (result) { case 1: message = "New PID is set!"; break; case 0: message = "Error setting PID"; break; case -1: message = String.Format("Account '{0}' does not exist in the gamespy database.", InParts[1]); break; case -2: message = String.Format("PID {0} is already in use.", newpid); break; } Console.WriteLine(" - " + message); } break; case "?": case "help": Console.Write(Environment.NewLine + "stop/quit/exit - Stops the server" + Environment.NewLine + "connections - Displays the current number of connected clients" + Environment.NewLine + "accounts - Displays the current number accounts in the DB." + Environment.NewLine + "create {nick} {password} {email} - Create a new Gamespy account." + Environment.NewLine + "delete {nick} - Deletes a user account." + Environment.NewLine + "fetch {nick} - Displays the account information" + Environment.NewLine + "setpid {nick} {newpid} - Sets the BF2 Player ID of the givin account name" + Environment.NewLine ); break; case "enter": // Insert a break point here in Visual Studio to and enter this command to "Enter" the program during debugging IsRunning = true; break; default: Console.WriteLine("Unrecognized input '{0}'", Input); break; } } catch (Exception e) { Console.Write(e.Message); } // Await a new command if (IsRunning) { Console.WriteLine(); Console.Write("Cmd > "); } }