4 Commits

Author SHA1 Message Date
Norman Lansing
23bcff131a New Shooter Game Mode Complete - Lesson 44 done. 2026-03-12 21:31:36 -04:00
Norman Lansing
51e89e8613 Parsing and error logging complete 2026-03-12 07:13:47 -04:00
Norman Lansing
bf2ead5f97 SHA256 Hashing for AuthToken Complete 2026-03-11 07:40:45 -04:00
Norman Lansing
04f5cb37dc New Parser Completed. Verification next. 2026-03-10 22:38:12 -04:00
8 changed files with 548 additions and 363 deletions

View File

@@ -179,6 +179,10 @@ DefaultBroadphaseSettings=(bUseMBPOnClient=False,bUseMBPOnServer=False,bUseMBPOu
MinDeltaVelocityForHitEvents=0.000000
ChaosSettings=(DefaultThreadingModel=TaskGraph,DedicatedThreadTickMode=VariableCappedWithTarget,DedicatedThreadBufferMode=Double)
[URL]
DefaultPort=7777
[CoreRedirects]
+PropertyRedirects=(OldName="/Script/FPSTemplate.CommandLineArgs.Arguments",NewName="/Script/FPSTemplate.CommandLineArgs.CmdArguments")
+EnumRedirects=(OldName="/Script/FPSTemplate.EvalidationError",NewName="/Script/FPSTemplate.EValidationError")
+FunctionRedirects=(OldName="/Script/FPSTemplate.GameLiftValidators.LogValidataErrorMessage",NewName="/Script/FPSTemplate.GameLiftValidators.LogValidationErrorMessage")
;+PropertyRedirects=(OldName="/Script/FPSTemplate.CommandLineArgs.Arguments",NewName="/Script/FPSTemplate.CommandLineArgs.CmdArguments")

View File

@@ -1,6 +1,8 @@
// Copyright Epic Games, Inc. All Rights Reserved.
using System.IO;
using UnrealBuildTool;
using System.Linq;
public class FPSTemplate : ModuleRules
{
@@ -8,9 +10,24 @@ public class FPSTemplate : ModuleRules
{
PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "EnhancedInput", "PhysicsCore" });
PublicDependencyModuleNames.AddRange(new string[]
{
"Core",
"CoreUObject",
"Engine",
"InputCore",
"EnhancedInput",
"PhysicsCore",
"OpenSSL"
});
PrivateDependencyModuleNames.AddRange(new string[] { "GameplayTags", "Slate", "SlateCore" });
PrivateDependencyModuleNames.AddRange(new string[]
{
"GameplayTags",
"Slate",
"SlateCore",
"OpenSSL",
});
// Adds in the plugin for GameLiftServerSDK if it is the server build.
@@ -26,7 +43,7 @@ public class FPSTemplate : ModuleRules
// Uncomment if you are using Slate UI
// PrivateDependencyModuleNames.AddRange(new string[] { "Slate", "SlateCore" });
// Uncomment if you are using online features
// PrivateDependencyModuleNames.Add("OnlineSubsystem");

View File

@@ -1,68 +1,28 @@
// Fill out your copyright notice in the Description page of Project Settings.
#include "Game/ShooterGameMode.h"
#include "Logging/LogMacros.h"
#include "Logging/StructuredLog.h"
#if WITH_GAMELIFT
#include "GenericPlatform/GenericPlatformMisc.h"
#include "Containers/UnrealString.h"
#include "GameLiftClpTypes.h"
#include "GameLift/GameLiftClp.h"
#include "openssl/sha.h"
#include "GameLiftServerSDK.h"
#endif
#include "GameLiftServerSDKModels.h"
#include "DSP/BufferDiagnostics.h"
#include "Misc/TypeContainer.h"
DEFINE_LOG_CATEGORY(LogShooterGameMode)
namespace GameLiftValidators {
const FRegexPattern FleetIdPattern(TEXT("^[a-z]*fleet-[a-zA-Z0-9\\-]+$"));
const int32 FleetIdLengthMin = 1;
const int32 FleetIdLengthMax = 128;
const FString ServerRegionPattern(TEXT("^[a-z]{2}-[a-z]+-[0-9]$"));
const int32 ServerRegionLengthMin = 3;
const int32 ServerRegionLengthMax = 16;
const FString WebSocketUrlPattern(TEXT("^(ws|wss):\\/\\/([0-9a-zA-Z.-]+)(:([1-9][0-9]{0,4}))?(\\/.*)?$"));
const int32 WebSocketUrlLengthMin = 1;
const int32 WebSocketUrlLengthMax = 128;
const FString AuthTokenPattern(TEXT("^[A-Za-z0-9+/=]+$"));
const int32 AuthTokenLengthMin = 20;
const int32 AuthTokenLengthMax = 2048;
const FString HostIdPattern(TEXT("^[a-z]*host-[a-zA-Z0-9\\-]+$"));
const int32 HostIdLengthMin = 1;
const int32 HostIdLengthMax = 128;
const int32 ServerPortMin = 1026;
const int32 ServerPortMax = 60000;
const int32 WebSocketPortMin = 1;
const int32 WebSocketPortMax = 60000;
bool IsStringValid(const FString& Value, const FRegexPattern* OptionalPattern, const int32 Min, const int32 Max)
{
if (Value.IsEmpty()) return false;
if (OptionalPattern)
{
return FRegexMatcher(*OptionalPattern, Value).FindNext() &&
Value.Len() >= Min &&
Value.Len() <= Max;
}
else
{
return Value.Len() >= Min && Value.Len() <= Max;
}
}
bool IsNumberValid(const int32 Value, const int32 Min, const int32 Max)
{
return Value >= Min && Value <= Max;
}
}
DEFINE_LOG_CATEGORY(LogShooterGameMode);
// Function implementations.
AShooterGameMode::AShooterGameMode()
{
UE_LOG(LogShooterGameMode, Log, TEXT("Initializing ShooterGameMode..."));
}
void AShooterGameMode::BeginPlay()
{
Super::BeginPlay();
#if WITH_GAMELIFT
InitGameLift();
#endif
@@ -71,248 +31,324 @@ void AShooterGameMode::BeginPlay()
void AShooterGameMode::InitGame(const FString& MapName, const FString& Options, FString& ErrorMessage)
{
Super::InitGame(MapName, Options, ErrorMessage);
UE_LOG(LogShooterGameMode, Log, TEXT("[%s] Parsing CLI"), *FDateTime::UtcNow().ToString(TEXT("%Y%m%d-%H%M%S")));
CachedCommandLine = FCommandLine::Get();
// Parsing of Command Line
GameLiftConfig.bDebugMode = FParse::Param(*CachedCommandLine, TEXT("Debug"));
if (GameLiftConfig.bDebugMode)
GameLiftConfig.ServerPort = cmdlineparser::details::GetConfiguredOrDefaultPort(CachedCommandLine, TEXT("port"));
if (FParse::Param(*CachedCommandLine, TEXT("glAnywhereFleet")))
{
UE_LOG(LogShooterGameMode, Log, TEXT("Debug mode: ENABLED"));
#if UE_BUILD_DEBUG
UE_LOG(LogShooterGameMode, Log, TEXT("Command Line Arguments: %s"), *CachedCommandLine);
#endif
}
GameLiftConfig.ServerPort = GetConfiguredOrDefaultPort();
GameLiftConfig.bIsAnywhereFleet = FParse::Param(*CachedCommandLine, TEXT("glAnywhere"));
if (GameLiftConfig.bIsAnywhereFleet)
{
UE_LOGFMT(LogShooterGameMode, Log, "GameLift Anywhere Fleet Command Line Parsing");
UE_LOGFMT(LogShooterGameMode, Log, "======Command Line Parameters======");
UE_LOGFMT(LogShooterGameMode, Log, "===================================");
UE_LOGFMT(LogShooterGameMode, Log, "Fleet type: Anywhere");
GameLiftConfig.bIsAnywhereFleet = true;
GameLiftConfig.bAllOptionsFound = GetAnywhereFleetParameters(CachedCommandLine);
LogAnywhereFleetParameters();
}
else
{
UE_LOGFMT(LogShooterGameMode, Log, "Fleet type: EC2");
// TODO: EC2 configuration
}
}
void AShooterGameMode::InitGame_original(const FString& MapName, const FString& Options, FString& ErrorMessage)
FString AShooterGameMode::GetSHA256Hash(const FString& InString)
{
Super::InitGame(MapName, Options, ErrorMessage);
UE_LOG(LogShooterGameMode, Log, TEXT("[%s] Parsing CLI"), *FDateTime::UtcNow().ToString(TEXT("%Y%m%d-%H%M%S")));
CachedCommandLine = FCommandLine::Get();
bool bIsCriticalError = false;
if (bDebugMode)
{
UE_LOG(LogShooterGameMode, Log, TEXT("Debug mode: ENABLED"));
#if UE_BUILD_DEBUG
UE_LOG(LogShooterGameMode, Log, TEXT("Command Line Arguments: %s"), *CachedCommandLine);
#endif
}
ServerPort = GetConfiguredOrDefaultPort();
bIsAnywhereFleet = FParse::Param(*CachedCommandLine, TEXT("glAnywhere"));
if (bIsAnywhereFleet)
{
UE_LOG(LogShooterGameMode, Log, TEXT("GameLift Anywhere Fleet Command Line Parsing"));
UE_LOG(LogShooterGameMode, Log, TEXT("======Command Line Parameters======"));
if (!FParse::Value(*CachedCommandLine, TEXT("fleetID="), FleetId))
{
UE_LOG(LogShooterGameMode, Error, TEXT("FleetId Missing in Command Line"));
bIsCriticalError = true;
}
else
{
UE_LOG(LogShooterGameMode, Log, TEXT("Fleet ID: %s"), *FleetId);
}
if (!FParse::Value(*CachedCommandLine, TEXT("authtoken="), AuthToken))
{
UE_LOG(LogShooterGameMode, Error, TEXT("AuthToken Missing in Command Line"));
bIsCriticalError = true;
}
else
{
if (bDebugMode)
{
FString TokenHash = GetSHA256Hash(AuthToken);
UE_LOG(LogShooterGameMode, Log, TEXT("AuthToken: %s"), *TokenHash);
}
else
{
UE_LOG(LogShooterGameMode, Log, TEXT("AuthToken Length: %d"), AuthToken.Len());
}
}
if (!FParse::Value(*CachedCommandLine, TEXT("hostId="), HostId))
{
UE_LOG(LogShooterGameMode, Error, TEXT("HostId Missing in Command Line"));
bIsCriticalError = true;
}
else
{
UE_LOG(LogShooterGameMode, Log, TEXT("Host ID: %s"), *HostId);
}
if (!FParse::Value(*CachedCommandLine, TEXT("websocketUrl="), WebSocketUrl))
{
UE_LOG(LogShooterGameMode, Error, TEXT("WebSocketUrl Missing in Command Line"));
bIsCriticalError = true;
}
else
{
UE_LOG(LogShooterGameMode, Log, TEXT("Websocket URL: %s"), *WebSocketUrl);
bool bValidWebSocket = WebSocketUrl.StartsWith(TEXT("wss://")) || WebSocketUrl.StartsWith(TEXT("ws://"));
if (InString.IsEmpty())
return TEXT("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
if (bValidWebSocket)
{
int32 ColonPos = WebSocketUrl.Find(TEXT(":"), ESearchCase::CaseSensitive);
int32 SlashPos = WebSocketUrl.Find(TEXT("/"), ESearchCase::CaseSensitive, ESearchDir::FromStart, ColonPos + 1);
int32 ParsedPort = 443; // Default wss
if (WebSocketUrl.StartsWith(TEXT("ws://"))) ParsedPort = 80;
if (ColonPos != INDEX_NONE && SlashPos != INDEX_NONE)
{
FString PortStr = WebSocketUrl.Mid(ColonPos + 1, SlashPos - ColonPos - 1);
int32 ExplicitPort = FCString::Atoi(*PortStr);
if (ExplicitPort > 1024 && ExplicitPort <= 65535) // Privileged ports OK for servers
{
ParsedPort = ExplicitPort;
}
else
{
bValidWebSocket = false; // Invalid explicit port
}
}
UE_LOG(LogShooterGameMode, Log, TEXT("WebSocket Parsed Port: %d"), ParsedPort);
}
if (!bValidWebSocket)
{
UE_LOG(LogShooterGameMode, Error, TEXT("Invalid WebSocketUrl: %s"), *WebSocketUrl);
bIsCriticalError = true;
}
}
if (ServerPort == 0)
{
UE_LOG(LogShooterGameMode, Error, TEXT("Invalid or Missing Server Port Number. Shutting Down."));
bIsCriticalError = true;
}
else
{
UE_LOG(LogShooterGameMode, Log, TEXT("Port: %d"), ServerPort);
}
if (!FParse::Value(*CachedCommandLine, TEXT("serverRegion="), ServerRegion))
{
UE_LOG(LogShooterGameMode, Warning, TEXT("ServerRegion Missing in Command Line"));
}
else
{
UE_LOG(LogShooterGameMode, Log, TEXT(">>>Server Region: %s"), *ServerRegion);
}
UE_LOG(LogShooterGameMode, Log, TEXT("==================================="));
}
else
{
UE_LOG(LogShooterGameMode, Log, TEXT("GameLift EC2 Fleet"));
if (ServerPort == 0)
{
UE_LOG(LogShooterGameMode, Error, TEXT("Invalid or Missing Server Port Number. Shutting Down."));
bIsCriticalError = true;
}
else
{
UE_LOG(LogShooterGameMode, Log, TEXT("Port: %d"), ServerPort);
}
}
if (bIsCriticalError)
{
UE_LOG(LogShooterGameMode, Error, TEXT("Critical Missing or Invalid Arguments in Command Line. Shutting Down."));
FPlatformMisc::RequestExit(true);
}
else
{
UE_LOG(LogShooterGameMode, Log, TEXT("Command Line Parsed Successfully."));
}
}
int32 AShooterGameMode::GetConfiguredOrDefaultPort() const
{
// Default Unreal Engine listen/dedicated server port
constexpr int32 DefaultPort = 7777;
int32 CmdPort = DefaultPort;
// Check if a port was passed via command line: -port=xxxx
if (FParse::Value(*CachedCommandLine, TEXT("port="), CmdPort) &&
GameLiftValidators::IsNumberValid(CmdPort, GameLiftValidators::ServerPortMin, GameLiftValidators::ServerPortMax))
{
return CmdPort;
}
UE_LOGFMT(LogShooterGameMode, Warning, "Invalid/Missing port in command line - using {0}", DefaultPort);
return DefaultPort;
}
FString AShooterGameMode::GetSHA256Hash(const FString& Input)
{
FTCHARToUTF8 Utf8Input(Input);
FSHA256Signature Hash;
if (FPlatformMisc::GetSHA256Signature(reinterpret_cast<const uint8*>(Utf8Input.Get()), Utf8Input.Length(), Hash))
{
return Hash.ToString();
}
return FString::Printf(TEXT("Fail_%dbytes"), Input.Len());
}
bool AShooterGameMode::ParseAndOutputResult(const FString& InString, FString& OutValue, bool bRequired)
{
// Returns True if it is a critical error, returns false
if (!FParse::Value(*InString, TEXT("hostId="), HostId))
{
UE_LOG(LogShooterGameMode, Error, TEXT("HostId Missing in Command Line"));
return bRequired;
}
else
{
UE_LOG(LogShooterGameMode, Log, TEXT("Host ID: %s"), *HostId);
return false;
}
}
bool AShooterGameMode::ValidateFleetId(const FString& InFleetId)
{
// FRegexMatcher Matcher(FleetIdPattern, InFleetId);
// return Matcher.IsMatch() &&
// InFleetId.Len() >= 10 &&
// InFleetId.Len() < 128;
return false;
// Use OpenSSL to compute the SHA-256 hash
FTCHARToUTF8 Utf8(InString);
const uint8* Bytes = reinterpret_cast<const uint8*>(Utf8.Get());
uint32 Length = Utf8.Length() * sizeof(UTF8CHAR);
SHA256_CTX Sha256Context;
SHA256_Init(&Sha256Context);
SHA256_Update(&Sha256Context, Bytes,Length);
SHA256_Final(Hash.Signature, &Sha256Context);
return Hash.ToString();
}
void AShooterGameMode::InitGameLift()
{
#if WITH_GAMELIFT
//TODO: Need to write later, working on parser first.
#else
UE_LOGFMT(LogShooterGameMode, Warning, "GameLift disabled");
UE_LOGFMT(LogShooterGameMode, Log, "Calling InitGameLift...");
// Get the module first
FGameLiftServerSDKModule* GameLiftSdkModule = &FModuleManager::LoadModuleChecked<FGameLiftServerSDKModule>("GameLiftServerSDK");
// Define the server parameters for an Anywhere fleet. These are not needed for a GameLift managed EC2 fleet.
FServerParameters ServerParametersForAnywhere;
uint32 PID = FPlatformProcess::GetCurrentProcessId();
FString PIDString = FString::FromInt(static_cast<int32>(PID));
if (GameLiftConfig.bIsAnywhereFleet)
{
UE_LOGFMT(LogShooterGameMode, Log, "Configuring server parameters for Anywhere...");
// If AnywhereFleets are being used load the command line arguments parsed earlier.
ServerParametersForAnywhere.m_webSocketUrl = TCHAR_TO_UTF8(*GameLiftConfig.WebSocketUrlResult.Value);
ServerParametersForAnywhere.m_fleetId = TCHAR_TO_UTF8((*GameLiftConfig.FleetIdResult.Value));
ServerParametersForAnywhere.m_hostId = TCHAR_TO_UTF8(*GameLiftConfig.HostIdResult.Value);
ServerParametersForAnywhere.m_processId = PIDString;
ServerParametersForAnywhere.m_authToken = TCHAR_TO_UTF8(*GameLiftConfig.AuthTokenResult.Value);
LogServerParameters(ServerParametersForAnywhere);
UE_LOGFMT(LogShooterGameMode, Log, "Initializing the GameLift Server...");
// InitSDK will establish a local connection with GameLfit's agent to enable further communication.
FGameLiftGenericOutcome InitSdkOutcome = GameLiftSdkModule->InitSDK(ServerParametersForAnywhere);
if (InitSdkOutcome.IsSuccess())
{
UE_LOG(LogShooterGameMode, SetColor, TEXT("%s"), COLOR_GREEN);
UE_LOG(LogShooterGameMode, Log, TEXT("GameLift InitSDK succeeded!"));
UE_LOG(LogShooterGameMode, SetColor, TEXT("%s"), COLOR_NONE);
}
else
{
UE_LOG(LogShooterGameMode, SetColor, TEXT("%s"), COLOR_RED);
UE_LOG(LogShooterGameMode, Log, TEXT("ERROR: InitSDK failed : ("));
FGameLiftError GameLiftError = InitSdkOutcome.GetError();
UE_LOG(LogShooterGameMode, Log, TEXT("ERROR: %s"), *GameLiftError.m_errorMessage);
UE_LOG(LogShooterGameMode, SetColor, TEXT("%s"), COLOR_NONE);
return;
}
ProcessParameters = MakeShared<FProcessParameters>();
//When a game session is created, Amazon GameLift Servers sends an activation request to the game server and passes along the game session object containing game properties and other settings.
//Here is where a game server should take action based on the game session object.
//Once the game server is ready to receive incoming player connections, it should invoke GameLiftServerAPI.ActivateGameSession()
ProcessParameters->OnStartGameSession.BindLambda([=](Aws::GameLift::Server::Model::GameSession InGameSession)
{
FString GameSessionId = FString(InGameSession.GetGameSessionId());
UE_LOG(LogShooterGameMode, Log, TEXT("GameSession Initializing: %s"), *GameSessionId);
GameLiftSdkModule->ActivateGameSession();
});
//OnProcessTerminate callback. Amazon GameLift Servers will invoke this callback before shutting down an instance hosting this game server.
//It gives this game server a chance to save its state, communicate with services, etc., before being shut down.
//In this case, we simply tell Amazon GameLift Servers we are indeed going to shutdown.
ProcessParameters->OnTerminate.BindLambda([=]()
{
UE_LOG(LogShooterGameMode, Log, TEXT("Game Server Process is terminating"));
// First call ProcessEnding()
FGameLiftGenericOutcome processEndingOutcome = GameLiftSdkModule->ProcessEnding();
// Then call Destroy() to free the SDK from memory
FGameLiftGenericOutcome destroyOutcome = GameLiftSdkModule->Destroy();
// Exit the process with success or failure
if (processEndingOutcome.IsSuccess() && destroyOutcome.IsSuccess()) {
UE_LOG(LogShooterGameMode, Log, TEXT("Server process ending successfully"));
}
else {
if (!processEndingOutcome.IsSuccess()) {
const FGameLiftError& error = processEndingOutcome.GetError();
UE_LOG(LogShooterGameMode, Error, TEXT("ProcessEnding() failed. Error: %s"),
error.m_errorMessage.IsEmpty() ? TEXT("Unknown error") : *error.m_errorMessage);
}
if (!destroyOutcome.IsSuccess()) {
const FGameLiftError& error = destroyOutcome.GetError();
UE_LOG(LogShooterGameMode, Error, TEXT("Destroy() failed. Error: %s"),
error.m_errorMessage.IsEmpty() ? TEXT("Unknown error") : *error.m_errorMessage);
}
}
});
//This is the HealthCheck callback.
//Amazon GameLift Servers will invoke this callback every 60 seconds or so.
//Here, a game server might want to check the health of dependencies and such.
//Simply return true if healthy, false otherwise.
//The game server has 60 seconds to respond with its health status. Amazon GameLift Servers will default to 'false' if the game server doesn't respond in time.
//In this case, we're always healthy!
ProcessParameters->OnHealthCheck.BindLambda([]()
{
UE_LOG(LogShooterGameMode, Log, TEXT("Performing Health Check"));
return true;
});
ProcessParameters->port = GameLiftConfig.ServerPort;
TArray<FString> Logfiles;
Logfiles.Add(TEXT("FPSTemplate/Saved/Log/server.log"));
ProcessParameters->logParameters = Logfiles;
UE_LOGFMT(LogShooterGameMode, Log, "Calling Process Ready...");
FGameLiftGenericOutcome ProcessReadyOutcome = GameLiftSdkModule->ProcessReady(*ProcessParameters);
if (ProcessReadyOutcome.IsSuccess())
{
UE_LOG(LogShooterGameMode, SetColor, TEXT("%s"), COLOR_GREEN);
UE_LOG(LogShooterGameMode, Log, TEXT("Process Ready!"));
UE_LOG(LogShooterGameMode, SetColor, TEXT("%s"), COLOR_NONE);
}
else
{
UE_LOG(LogShooterGameMode, SetColor, TEXT("%s"), COLOR_RED);
UE_LOG(LogShooterGameMode, Log, TEXT("ERROR: Process Ready Failed!"));
FGameLiftError ProcessReadyError = ProcessReadyOutcome.GetError();
UE_LOG(LogShooterGameMode, Log, TEXT("ERROR: %s"), *ProcessReadyError.m_errorMessage);
UE_LOG(LogShooterGameMode, SetColor, TEXT("%s"), COLOR_NONE);
}
UE_LOGFMT(LogShooterGameMode, Log, "InitGameLift completed!");
}
#endif
}
bool AShooterGameMode::GetAnywhereFleetParameters(const FString& CommandLineString)
{
bool bAllAnywhereFleetParametersValid = true;
GameLiftConfig.AuthTokenResult = cmdlineparser::GetValueOfToken(CommandLineString, cmdlineparser::details::EAvailableTokens::AuthToken);
if (!GameLiftConfig.AuthTokenResult.bIsValid) bAllAnywhereFleetParametersValid = false;
GameLiftConfig.FleetIdResult = cmdlineparser::GetValueOfToken(CommandLineString, cmdlineparser::details::EAvailableTokens::FleetId);
if (!GameLiftConfig.FleetIdResult.bIsValid) bAllAnywhereFleetParametersValid = false;
GameLiftConfig.HostIdResult = cmdlineparser::GetValueOfToken(CommandLineString, cmdlineparser::details::EAvailableTokens::HostId);
if (!GameLiftConfig.HostIdResult.bIsValid) bAllAnywhereFleetParametersValid = false;
GameLiftConfig.WebSocketUrlResult = cmdlineparser::GetValueOfToken(CommandLineString, cmdlineparser::details::EAvailableTokens::WebsocketUrl);
if (!GameLiftConfig.WebSocketUrlResult.bIsValid) bAllAnywhereFleetParametersValid = false;
return bAllAnywhereFleetParametersValid;
}
void AShooterGameMode::LogAnywhereFleetParameters()
{
// Lambda for getting the token name from token
auto GetTokenName = [](const cmdlineparser::details::FParseResult& Result) -> FString
{
return cmdlineparser::details::CLI_TOKENS[static_cast<int32>(Result.Token)];
};
UE_LOGFMT(LogShooterGameMode, Log, "Anywhere Fleet Parameters:");
if (GameLiftConfig.AuthTokenResult.bIsValid)
{
UE_LOGFMT(LogShooterGameMode, Log, "AuthToken: {0}", GetValueOrHash(GameLiftConfig.AuthTokenResult.Value));
}
else
{
UE_LOGFMT(
LogShooterGameMode,
Error,
"AuthToken: {0}",
FString::Format(
*GameLiftConfig.AuthTokenResult.ErrorMessage,
{
FStringFormatArg(GetTokenName(GameLiftConfig.AuthTokenResult)),
FStringFormatArg(GetValueOrHash(GameLiftConfig.AuthTokenResult.Value)),
}
)
);
}
if (GameLiftConfig.FleetIdResult.bIsValid)
{
UE_LOGFMT(LogShooterGameMode, Log, "FleetId: {0}", GameLiftConfig.FleetIdResult.Value);
}
else
{
UE_LOGFMT(
LogShooterGameMode,
Error,
"FleetId: {0}",
FString::Format(
*GameLiftConfig.FleetIdResult.ErrorMessage,
{
FStringFormatArg(GetTokenName(GameLiftConfig.FleetIdResult)),
FStringFormatArg(GameLiftConfig.FleetIdResult.Value)
}
)
);
}
if (GameLiftConfig.HostIdResult.bIsValid)
{
UE_LOGFMT(LogShooterGameMode, Log, "HostId: {0}", GameLiftConfig.HostIdResult.Value);
}
else
{
UE_LOGFMT(
LogShooterGameMode,
Error,
"HostId: {0}",
FString::Format(
*GameLiftConfig.HostIdResult.ErrorMessage,
{
FStringFormatArg(GetTokenName(GameLiftConfig.HostIdResult)),
FStringFormatArg(GameLiftConfig.HostIdResult.Value)
}
)
);
}
if (GameLiftConfig.WebSocketUrlResult.bIsValid)
{
UE_LOGFMT(LogShooterGameMode, Log, "WebSocketUrl: {0}", GameLiftConfig.WebSocketUrlResult.Value);
}
else
{
UE_LOGFMT(
LogShooterGameMode,
Error,
"WebSocketUrl: {0}",
FString::Format(
*GameLiftConfig.WebSocketUrlResult.ErrorMessage,
{
FStringFormatArg(GetTokenName(GameLiftConfig.WebSocketUrlResult)),
FStringFormatArg(GameLiftConfig.WebSocketUrlResult.Value)
}
)
);
}
UE_LOGFMT(LogShooterGameMode, Log, "Server Port: {0}", GameLiftConfig.ServerPort);
if (GameLiftConfig.bAllOptionsFound)
{
UE_LOGFMT(LogShooterGameMode, Log, "Anywhere Fleet Parameters Loaded Successfully....");
}
else
{
UE_LOGFMT(LogShooterGameMode, Error, "Anywhere Fleet Parameters Load FAILED....");
}
}
void AShooterGameMode::LogServerParameters(const FServerParameters& InServerParameters)
{
UE_LOGFMT(LogShooterGameMode, Log, ">>>> WebSocket URL: {WebSocketUrl}", InServerParameters.m_webSocketUrl);
UE_LOGFMT(LogShooterGameMode, Log, ">>>> Fleet ID: {FleetId}", InServerParameters.m_fleetId);
UE_LOGFMT(LogShooterGameMode, Log, ">>>> Process ID: {ProcessId}", InServerParameters.m_processId);
UE_LOGFMT(LogShooterGameMode, Log, ">>>> Host ID (Compute Name): {HostId}", InServerParameters.m_hostId);
UE_LOGFMT(LogShooterGameMode, Log, ">>>> Auth Token: {AuthToken}", GetValueOrHash(InServerParameters.m_authToken));
if (!InServerParameters.m_awsRegion.IsEmpty())
{
UE_LOGFMT(LogShooterGameMode, Log, ">>>> Aws Region: {AwsRegion}", InServerParameters.m_awsRegion);
}
if (!InServerParameters.m_accessKey.IsEmpty())
{
UE_LOGFMT(LogShooterGameMode, Log, ">>>> Access Key: {AccessKey}", GetValueOrHash(InServerParameters.m_accessKey));
}
if (!InServerParameters.m_secretKey.IsEmpty())
{
UE_LOGFMT(LogShooterGameMode, Log, ">>>> Secret Key: {SecretKey}", GetValueOrHash(InServerParameters.m_secretKey));
}
if (!InServerParameters.m_sessionToken.IsEmpty())
{
UE_LOGFMT(LogShooterGameMode, Log, ">>>> Session Token: {SessionToken}", GetValueOrHash(InServerParameters.m_sessionToken));
}
}
FString AShooterGameMode::GetValueOrHash(const FString& Value)
{
#if UE_BUILD_DEBUG || UE_BUILD_DEVELOPMENT
return Value;
#else
return TEXT("HASH:") + GetSHA256Hash(Value);
#endif
}

View File

@@ -0,0 +1,94 @@
#include "GameLift/GameLiftClp.h"
int32 cmdlineparser::GetConfiguredOrDefaultPort(const FString& Token)
{
return details::GetConfiguredOrDefaultPort(FCommandLine::Get(), Token);
}
int32 cmdlineparser::GetConfiguredOrDefaultPort(const FString& CommandLine, const FString& Token)
{
return details::GetConfiguredOrDefaultPort(CommandLine, Token);
}
cmdlineparser::details::FParseResult cmdlineparser::GetValueOfToken(const FString& CommandLine, const details::EAvailableTokens Token)
{
details::FParseResult Result;
FString ValueOfToken;
Result.Token = Token;
ensure(Token < details::EAvailableTokens::MaxToken);
const bool bTokenFound = FParse::Value(
*CommandLine,
*details::EnsureEndsWith(details::CLI_TOKENS[static_cast<int32>(Token)],
TEXT("=")),
ValueOfToken
);
if (!bTokenFound)
{
Result.Value = FString();
Result.ErrorCode = details::EErrorCodes::TokenNotFound;
Result.bIsValid = false;
}
else
{
if (ValueOfToken.IsEmpty())
{
Result.Value = FString();
Result.ErrorCode = details::EErrorCodes::ValueEmpty;
Result.bIsValid = false;
}
else
{
if (details::DoesRegExMatch(ValueOfToken, details::REGEX_PATTERNS[static_cast<int32>(Token)]))
{
Result.ErrorCode = details::EErrorCodes::NoError;
Result.bIsValid = true;
}
else
{
Result.ErrorCode = details::EErrorCodes::FailedValidation;
Result.bIsValid = false;
}
Result.Value = ValueOfToken;
}
}
ensure(Result.ErrorCode < details::EErrorCodes::MaxCode);
FString ErrorMessage = details::ERROR_MESSAGES[static_cast<int32>(Result.ErrorCode)];
FString TokenName = details::CLI_TOKENS[static_cast<int32>(Result.Token)];
FString Value = Result.Value;
// Result.ErrorMessage = FString::Format(*ErrorMessage, {FStringFormatArg(TokenName), FStringFormatArg(Value)});
Result.ErrorMessage = ErrorMessage;
return Result;
}
// cmdlineparser::Details namespace
FString cmdlineparser::details::EnsureEndsWith(const FString& Token, const TCHAR* Suffix)
{
return Token.EndsWith(Suffix) ? Token : Token + Suffix;
}
int32 cmdlineparser::details::GetConfiguredOrDefaultPort(const FString& CommandLine, const FString& Token)
{
const int32 Port = FURL::UrlConfig.DefaultPort;
if (int32 CliPort; FParse::Value(*CommandLine, *EnsureEndsWith(Token, TEXT("=")), CliPort))
{
if (CliPort >= details::MIN_PORT && CliPort <= details::MAX_PORT)
{
return CliPort;
}
}
return Port;
}
bool cmdlineparser::details::DoesRegExMatch(const FString& Text, const FString& Pattern)
{
const FRegexPattern RegexPattern(Pattern);
FRegexMatcher Matcher(RegexPattern, Text);
return Matcher.FindNext();
}

View File

@@ -0,0 +1,32 @@
#include "GameLiftClpTypes.h"
const TArray<FString>& cmdlineparser::details::ERROR_MESSAGES = []() -> const TArray<FString>&
{
static TArray<FString> Error_Messages;
Error_Messages.Add(TEXT("VALID: {0}: {1}"));
Error_Messages.Add(TEXT("INVALID TOKEN: [-{0}=] not found in command line arguments"));
Error_Messages.Add(TEXT("EMPTY VALUE: [-{0}=] found. No value assigned"));
Error_Messages.Add(TEXT("VALIDATION FAILED: [-{0}=] found.... Value: [{1}]"));
return Error_Messages;
}();
const TArray<FString>& cmdlineparser::details::CLI_TOKENS = []() -> const TArray<FString>&
{
static TArray<FString> Cli_Tokens;
Cli_Tokens.Add(TEXT("authtoken"));
Cli_Tokens.Add(TEXT("hostid"));
Cli_Tokens.Add(TEXT("fleetid"));
Cli_Tokens.Add(TEXT("websocketurl"));
return Cli_Tokens;
}();
const TArray<FString>& cmdlineparser::details::REGEX_PATTERNS = []() -> const TArray<FString>&
{
static TArray<FString> Cli_Tokens;
Cli_Tokens.Add(TEXT("^[a-zA-Z0-9\\-]+$"));
Cli_Tokens.Add(TEXT("^[a-zA-Z0-9][a-zA-Z0-9\\-]{0,62}[a-zA-Z0-9]?$"));
Cli_Tokens.Add(TEXT("^[a-z]*fleet-[a-zA-Z0-9\\-]+$|^arn:.*:[a-z]*fleet\\/[a-z]*fleet-[a-zA-Z0-9\\-]+$"));
Cli_Tokens.Add(TEXT("^wss://[a-z0-9-]+(\\.[a-z0-9-]+)*\\.api\\.amazongamelift\\.com(:[0-9]+)?/?$"));
return Cli_Tokens;
}();

View File

@@ -3,8 +3,8 @@
#pragma once
#include "CoreMinimal.h"
#include "GameLiftClpTypes.h"
#include "ShooterGameModeBase.h"
#include "ShooterGameMode.generated.h"
DECLARE_LOG_CATEGORY_EXTERN(LogShooterGameMode, Log, All);
@@ -12,48 +12,19 @@ DECLARE_LOG_CATEGORY_EXTERN(LogShooterGameMode, Log, All);
struct FProcessParameters;
struct FServerParameters;
struct FGameLiftCliConfig
struct FGameLiftConfig
{
bool bDebugMode = false;
bool bIsAnywhereFleet = false;
bool bIsCriticalError = false;
int32 ServerPort = 0;
bool bAllOptionsFound = false;
FString AuthToken;
FString FleetId;
FString HostId;
FString WebSocketUrl;
FString ServerRegion;
int32 ServerPort = 7777;
cmdlineparser::details::FParseResult AuthTokenResult;
cmdlineparser::details::FParseResult FleetIdResult;
cmdlineparser::details::FParseResult HostIdResult;
cmdlineparser::details::FParseResult WebSocketUrlResult;
};
namespace GameLiftValidators
{
extern const FRegexPattern FleetIdPattern;
extern const int32 FleetIdLengthMin;
extern const int32 FleetIdLengthMax;
extern const FString ServerRegionPattern;
extern const int32 ServerRegionLengthMin;
extern const int32 ServerRegionLengthMax;
extern const FString WebSocketUrlPattern;
extern const int32 WebSocketUrlLengthMin;
extern const int32 WebSocketUrlLengthMax;
extern const FString AuthTokenPattern;
extern const int32 AuthTokenLengthMin;
extern const int32 AuthTokenLengthMax;
extern const FString HostIdPattern;
extern const int32 HostIdLengthMin;
extern const int32 HostIdLengthMax;
extern const int32 ServerPortMin;
extern const int32 ServerPortMax;
extern const int32 WebSocketPortMin;
extern const int32 WebSocketPortMax;
bool IsStringValid(const FString& Value, const FRegexPattern& OptionalPattern, int32 Min, int32 Max);
bool IsNumberValid(int32 Value, int32 Min, int32 Max);
}
/**
*
*/
@@ -61,55 +32,26 @@ UCLASS()
class FPSTEMPLATE_API AShooterGameMode : public AShooterGameModeBase
{
GENERATED_BODY()
public:
AShooterGameMode();
protected:
UPROPERTY(Config, BlueprintReadOnly)
bool bIsAnywhereFleet = false;
UPROPERTY(Config, BlueprintReadOnly)
FString FleetId;
UPROPERTY(Config, BlueprintReadOnly)
FString AuthToken;
UPROPERTY(Config, BlueprintReadOnly)
FString HostId;
UPROPERTY(Config, BlueprintReadOnly)
FString WebSocketUrl;
UPROPERTY(Config)
FString ServerRegion;
UPROPERTY(Config, BlueprintReadOnly)
int32 ServerPort;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
bool bDebugMode = false;
virtual void BeginPlay() override;
virtual void InitGame(const FString& MapName, const FString& Options, FString& ErrorMessage) override;
void InitGame_original(const FString& MapName, const FString& Options, FString& ErrorMessage);
private:
FGameLiftCliConfig GameLiftConfig;
FString CachedCommandLine;
TSharedPtr<FProcessParameters> ProcessParameters;
TSharedPtr<FServerParameters> ServerParameters;
int32 GetConfiguredOrDefaultPort() const;
static FString GetSHA256Hash(const FString& Input);
bool ParseAndOutputResult(const FString& InString, FString& OutValue, bool bRequired = false);
bool ParseAndValidate(const FString& InArguments, FGameLiftCliConfig& Config);
static bool ValidateFleetId(const FString& InFleetId);
void InitGameLift();
};
private:
FGameLiftConfig GameLiftConfig;
FString CachedCommandLine;
static FString GetSHA256Hash(const FString& CommandLineString);
void InitGameLift();
bool GetAnywhereFleetParameters(const FString& CommandLineString);
void LogAnywhereFleetParameters();
static void LogServerParameters(const FServerParameters& InServerParameters);
static FString GetValueOrHash(const FString& Value);
TSharedPtr<FProcessParameters> ProcessParameters;
// TSharedPtr<FServerParameters> ServerParameters;
};

View File

@@ -0,0 +1,24 @@
#pragma once
#include "GameLiftClpTypes.h"
#include "CoreMinimal.h"
namespace cmdlineparser
{
// int32 GetConfiguredOrDefaultPort();
int32 GetConfiguredOrDefaultPort(const FString& Token = TEXT("port="));
int32 GetConfiguredOrDefaultPort(const FString& CommandLine, const FString& Token = TEXT("port="));
details::FParseResult GetValueOfToken(const FString& CommandLine, const details::EAvailableTokens Token);
}
namespace cmdlineparser::details
{
inline static constexpr int32 MIN_PORT = 1024;
inline static constexpr int32 MAX_PORT = 65535;
inline static constexpr const TCHAR* DEFAULT_PORT_TOKEN = TEXT("port=");
FString EnsureEndsWith(const FString& Token, const TCHAR* Suffix);
int32 GetConfiguredOrDefaultPort(const FString& CommandLine, const FString& Token);
bool DoesRegExMatch(const FString& Text, const FString& Pattern);
}

View File

@@ -0,0 +1,36 @@
#pragma once
namespace cmdlineparser::details
{
enum EAvailableTokens
{
AuthToken,
HostId,
FleetId,
WebsocketUrl,
MaxToken
};
enum EErrorCodes
{
NoError,
TokenNotFound,
ValueEmpty,
FailedValidation,
MaxCode
};
extern const TArray<FString>& ERROR_MESSAGES;
extern const TArray<FString>& CLI_TOKENS;
extern const TArray<FString>& REGEX_PATTERNS;
struct FParseResult
{
EAvailableTokens Token;
FString Value;
bool bIsValid;
EErrorCodes ErrorCode;
FString ErrorMessage;
};
}