Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.
C++ cmakecnccommand-and-conquercppdirectx11game-enginegame-preservationgeneralsrtssage-enginex64zero-hour
feat(gamenetwork): online adapters for EA's GameSpy queues
Olcay Seyganbd866e315d78
diff --git a/GeneralsMD/Code/BuildFingerprint.manifest b/GeneralsMD/Code/BuildFingerprint.manifestindex af57647a7..fafa726e9 100644--- a/GeneralsMD/Code/BuildFingerprint.manifest+++ b/GeneralsMD/Code/BuildFingerprint.manifest@@ -1104,6 +1104,8 @@ GameEngine/Include/GameNetwork/NetworkDefs.hGameEngine/Include/GameNetwork/NetworkInterface.hGameEngine/Include/GameNetwork/NetworkUtil.hGameEngine/Include/GameNetwork/Online/OnlineConnection.h+GameEngine/Include/GameNetwork/Online/OnlineQueues.h+GameEngine/Include/GameNetwork/Online/OnlineSession.hGameEngine/Include/GameNetwork/RankPointValue.hGameEngine/Include/GameNetwork/StallJudgement.hGameEngine/Include/GameNetwork/Transport.hdiff --git a/GeneralsMD/Code/CMakeLists.txt b/GeneralsMD/Code/CMakeLists.txtindex 179ed4370..9877f33a0 100644--- a/GeneralsMD/Code/CMakeLists.txt+++ b/GeneralsMD/Code/CMakeLists.txt@@ -2310,7 +2310,21 @@ add_lib_test(test_compression compression)# The online service's connection: the JSON line reader and writer, and a TLS loopback against a server# inside the test, verified against a CA the test makes on the spot (no key or certificate is committed).-add_lib_test(test_online onlineconnection mbedtls)+# Then the adapters (OnlinePeer, OnlineBuddy, OnlineStats) fed scripted server lines, which are engine+# code: so it links gameengine the way test_water_grid does.+add_lib_test(test_online gameengine onlineconnection mbedtls)+target_sources(test_online PRIVATE ${TESTS}/test_gameengine_stubs.cpp)+set_target_properties(test_online PROPERTIES CXX_STANDARD 17)+if(ZH_PLATFORM_POSIX)+ target_link_libraries(test_online PRIVATE posixdevice w3ddevice)+else()+ target_sources(test_online PRIVATE+ ${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudUnsupported.cpp)+endif()+if(MSVC)+ target_sources(test_online PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/Tests/debug_build_stubs.cpp)+ target_compile_definitions(test_online PRIVATE ZH_DEBUG_STUBS_ENGINE)+endif()# .w3d on-disk layout pins. Deliberately OUTSIDE the ZH_PLATFORM_WINDOWS guard# below: it is header-only, asserts sizeof/offsetof and links nothing but thediff --git a/GeneralsMD/Code/GameEngine/Include/GameNetwork/Online/OnlineQueues.h b/GeneralsMD/Code/GameEngine/Include/GameNetwork/Online/OnlineQueues.hnew file mode 100644index 000000000..646afd459--- /dev/null+++ b/GeneralsMD/Code/GameEngine/Include/GameNetwork/Online/OnlineQueues.h@@ -0,0 +1,108 @@+/*+** Command & Conquer Generals Zero Hour(tm)+** Copyright 2025 Electronic Arts Inc.+**+** This program is free software: you can redistribute it and/or modify+** it under the terms of the GNU General Public License as published by+** the Free Software Foundation, either version 3 of the License, or+** (at your option) any later version.+**+** This program is distributed in the hope that it will be useful,+** but WITHOUT ANY WARRANTY; without even the implied warranty of+** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+** GNU General Public License for more details.+**+** You should have received a copy of the GNU General Public License+** along with this program. If not, see <http://www.gnu.org/licenses/>.+*/++// FILE: OnlineQueues.h ///////////////////////////////////////////////////////////////////////////+// Desc: EA's GameSpy queue interfaces answered from the online service. What the game glue and the+// WOL screens call; the adapters behind it are OnlinePeer, OnlineBuddy and OnlineStats.+///////////////////////////////////////////////////////////////////////////////////////////////////++#pragma once++#ifndef _ONLINE_QUEUES_H_+#define _ONLINE_QUEUES_H_++#include "Lib/BaseType.h"+#include "Common/AsciiString.h"+#include "GameNetwork/NetworkDefs.h"++class GameSpyPeerMessageQueueInterface;+class GameSpyBuddyMessageQueueInterface;+class GameSpyPSMessageQueueInterface;+class PingerInterface;+class GameResultsInterface;++/* True when -online named a server. Every other call here is harmless without it: the factories still+ make working (empty) queues, the getters answer FALSE or empty, the senders do nothing. */+Bool OnlineIsEnabled( void );++/* One per GameSpy factory (PeerDefs.cpp's SetUpGameSpy, GameEngine.cpp's TheGameResultsQueue). The+ queues need no thread: startThread/startThreads only mark them running, requests go to the server+ when added, and every getResponse pumps the connection first. All of them share one connection. */+GameSpyPeerMessageQueueInterface *OnlineCreatePeerQueue( void );+GameSpyBuddyMessageQueueInterface *OnlineCreateBuddyQueue( void );+GameSpyPSMessageQueueInterface *OnlineCreatePSQueue( void );+PingerInterface *OnlineCreatePinger( void ); ///< answers every ping at once, 1 ms: the relay is the only route+GameResultsInterface *OnlineCreateGameResults( void ); ///< drops EA's results: the server rates from OnlineSendReport++/* The connection. OnlineUpdate opens it on the first call (TLS to -online, then hello) and reads what+ arrived; call it once a frame from the main thread while anything online is up. Not needed while a+ screen polls a queue (getResponse pumps too), but the welcome is waited for before any queue exists. */+void OnlineUpdate( void );++enum OnlineStatus+{+ ONLINE_OFF, ///< no -online, or OnlineDisconnect ran+ ONLINE_CONNECTING, ///< TLS or hello under way+ ONLINE_WELCOMED, ///< welcome arrived: OnlineGetMOTD/OnlineGetConfig hold it, login can be sent+ ONLINE_FAILED, ///< the connection failed or closed; the next login request (or OnlineDisconnect) dials again+};+OnlineStatus OnlineGetStatus( void );+AsciiString OnlineGetMOTD( void ); ///< welcome.motd, for SetUpGameSpy's motdBuffer+AsciiString OnlineGetConfig( void ); ///< welcome.config (<QMMaps>), for SetUpGameSpy's configBuffer+void OnlineDisconnect( void ); ///< hangs up; the next OnlineUpdate dials again++/* The relay. Both are FALSE until a login succeeded (auth.ok). The ticket goes into the UDP HELLO_AUTH,+ which has to be sent right after login: the peer queue answers PEERREQUEST_LOGIN only once the server+ says relay.ok, and puts that virtual IP in PEERRESPONSE_LOGIN's internalIP and externalIP. */+Bool OnlineGetRelayTicket( UnsignedByte out[16] );+Bool OnlineGetRelayEndpoint( AsciiString &host, UnsignedShort &port ); ///< -online's host, welcome.relayPort+UnsignedInt OnlineGetRelayVip( void ); ///< relay.ok's virtual IP, 0 before it++/* Session tokens replace EA's stored password. After a login, OnlineGetSessionToken is the token the+ server gave (64 hex characters, too long for BuddyRequest's password field); OnlineSaveToken keeps it+ under the login name in GeneralsOnline/OnlineTokens.ini in the user data folder, an empty token forgets+ it. OnlineResume logs in with a saved token instead of BUDDYREQUEST_LOGIN; the answers are the same+ (BUDDYRESPONSE_LOGIN, then PEERRESPONSE_LOGIN, or PEERRESPONSE_DISCONNECT on a refusal). */+AsciiString OnlineGetSessionToken( void );+AsciiString OnlineGetSavedToken( const AsciiString &login );+void OnlineSaveToken( const AsciiString &login, const AsciiString &token );+void OnlineResume( const AsciiString &token );++/* The match result, EA's ladder packet (StagingRoomGameInfo.cpp's generateLadderGameResultsPacket) plus+ endFrame and surrendered. Sent for the match the last game.start or qm.matched named, at most once per+ match however often it is called, so the end-of-match frame and the score screen can both call it. */+struct OnlineReport+{+ Int seed;+ Int endFrame; ///< TheVictoryConditions->getEndFrame(); every report of a match must agree on it+ Int winningTeam; ///< index of the winner in the match's player order (qm.matched/game.start ids;+ ///< a Quick Match's slot number), -1 for none. Not EA's team number.+ Bool sawDesync;+ Bool sawGameEnd;+ Bool disconEnd;+ Bool surrendered; ///< the local player conceded+ Int duration; ///< EA's duration, which is the end frame again+ Int numPlayers; ///< how many of discon[] and side[] are filled+ Bool discon[MAX_SLOTS];+ AsciiString side[MAX_SLOTS];++ OnlineReport();+};+void OnlineSendReport( const OnlineReport &report );++#endif // _ONLINE_QUEUES_H_diff --git a/GeneralsMD/Code/GameEngine/Include/GameNetwork/Online/OnlineSession.h b/GeneralsMD/Code/GameEngine/Include/GameNetwork/Online/OnlineSession.hnew file mode 100644index 000000000..e578e1d28--- /dev/null+++ b/GeneralsMD/Code/GameEngine/Include/GameNetwork/Online/OnlineSession.h@@ -0,0 +1,174 @@+/*+** Command & Conquer Generals Zero Hour(tm)+** Copyright 2025 Electronic Arts Inc.+**+** This program is free software: you can redistribute it and/or modify+** it under the terms of the GNU General Public License as published by+** the Free Software Foundation, either version 3 of the License, or+** (at your option) any later version.+**+** This program is distributed in the hope that it will be useful,+** but WITHOUT ANY WARRANTY; without even the implied warranty of+** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+** GNU General Public License for more details.+**+** You should have received a copy of the GNU General Public License+** along with this program. If not, see <http://www.gnu.org/licenses/>.+*/++// FILE: OnlineSession.h //////////////////////////////////////////////////////////////////////////+// Desc: Inside the online adapters: the one connection they share, what the server has told them,+// and the three queues it answers into. The game calls OnlineQueues.h; test_online calls this.+///////////////////////////////////////////////////////////////////////////////////////////////////++#pragma once++#ifndef _ONLINE_SESSION_H_+#define _ONLINE_SESSION_H_++#include <deque>+#include <map>+#include <string>+#include <vector>++#include "Lib/WideCharFns.h"+#include "GameNetwork/Online/OnlineConnection.h"+#include "GameNetwork/Online/OnlineQueues.h"+#include "GameNetwork/GameSpy/BuddyThread.h"+#include "GameNetwork/GameSpy/PeerThread.h"+#include "GameNetwork/GameSpy/PersistentStorageThread.h"++/* Everything runs on the main thread: a request becomes a line the moment it is added, and a line+ becomes responses when a queue's getResponse (or OnlineUpdate) pumps. OnlineConnection's own thread+ is the only other one, behind its queues. */++class OnlinePeerQueue : public GameSpyPeerMessageQueueInterface+{+public:+ OnlinePeerQueue();+ virtual ~OnlinePeerQueue();+ virtual void startThread( void ) { m_running = TRUE; }+ virtual void endThread( void );+ virtual Bool isThreadRunning( void ) { return m_running; }+ virtual Bool isConnected( void );+ virtual Bool isConnecting( void );+ virtual void addRequest( const PeerRequest& req );+ virtual Bool getRequest( PeerRequest& req ) { return FALSE; }+ virtual void addResponse( const PeerResponse& resp ) { m_responses.push_back( resp ); }+ virtual Bool getResponse( PeerResponse& resp );+ virtual SerialAuthResult getSerialAuthResult( void ) { return SERIAL_OK; }++private:+ std::deque<PeerResponse> m_responses;+ Bool m_running;+};++class OnlineBuddyQueue : public GameSpyBuddyMessageQueueInterface+{+public:+ OnlineBuddyQueue();+ virtual ~OnlineBuddyQueue();+ virtual void startThread( void ) { m_running = TRUE; }+ virtual void endThread( void ) { m_running = FALSE; }+ virtual Bool isThreadRunning( void ) { return m_running; }+ virtual Bool isConnected( void );+ virtual Bool isConnecting( void );+ virtual void addRequest( const BuddyRequest& req );+ virtual Bool getRequest( BuddyRequest& req ) { return FALSE; }+ virtual void addResponse( const BuddyResponse& resp ) { m_responses.push_back( resp ); }+ virtual Bool getResponse( BuddyResponse& resp );+ virtual GPProfile getLocalProfileID( void );++private:+ std::deque<BuddyResponse> m_responses;+ Bool m_running;+};++class OnlinePSQueue : public GameSpyPSMessageQueueInterface+{+public:+ OnlinePSQueue();+ virtual ~OnlinePSQueue();+ virtual void startThread( void ) { m_running = TRUE; }+ virtual void endThread( void ) { m_running = FALSE; }+ virtual Bool isThreadRunning( void ) { return m_running; }+ virtual void addRequest( const PSRequest& req );+ virtual Bool getRequest( PSRequest& req ) { return FALSE; }+ virtual void addResponse( const PSResponse& resp ) { m_responses.push_back( resp ); }+ virtual Bool getResponse( PSResponse& resp );+ virtual void trackPlayerStats( PSPlayerStats stats );+ virtual PSPlayerStats findPlayerStatsByID( Int id );++ void statsArrived( long long id, const std::string &kv ); ///< a stats line, as PSRESPONSE_PLAYERSTATS++private:+ std::deque<PSResponse> m_responses;+ std::map<Int, PSPlayerStats> m_stats;+ Bool m_running;+};++struct OnlineSession+{+ static OnlineSession &get();++ /* Tests: lines the adapters send go here instead of out, nothing dials, and the status is WELCOMED. */+ void beginTest( std::vector<OnlineMessage> *capture );++ void send( const OnlineMessage &m );+ void pump(); ///< dial if due, then dispatch every line that arrived+ void dispatch( const OnlineMessage &m ); ///< one server line into responses+ void disconnect();+ void requestAuth( const OnlineMessage &m ); ///< login, register or resume: sent now, or once welcomed++ OnlineConnection *connection;+ std::vector<OnlineMessage> *capture;+ OnlineStatus status;+ std::string motd; ///< std::string, not AsciiString: this outlives the engine's allocator+ std::string config;+ UnsignedShort relayPort;++ // the account+ Bool authed; ///< auth.ok arrived+ Bool peerLoggedIn; ///< PEERRESPONSE_LOGIN went out (it waits for relay.ok)+ long long id;+ std::string nick;+ std::string token;+ UnsignedByte ticket[16];+ UnsignedInt vip;+ OnlineMessage pendingAuth; ///< sent once the welcome arrives+ Bool hasPendingAuth;+ Bool authWaiting; ///< a login, register or resume is out (or pending) with no answer yet++ // where the player is+ Int groupRoom; ///< 0 outside a chat room; rooms are the server's ids as decimal text+ long long gameId; ///< the staging room, 0 outside one+ long long joiningGame; ///< game.join sent, game.joined not back yet+ Bool hosting;+ OnlineMessage hostInfo; ///< CREATESTAGINGROOM's CRCs and ladder, repeated in every game.opts+ std::string hostNick;+ long long hostLeftGame; ///< a game removed under a guest: host left, unless game.start follows+ Int hostLeftPumps;+ std::map<long long, UnsignedInt> vips; ///< account id -> relay address, as the server tells them+ std::string matchId; ///< the last game.start or qm.matched+ std::string reportedMatch;++ OnlinePeerQueue *peer;+ OnlineBuddyQueue *buddy;+ OnlinePSQueue *ps;++ void dial();+ void forgetAccount();+ void peerResponse( const PeerResponse &r );+ void finishPeerLogin();+ void loginFailed( DisconnectReason reason );+ void gameListEntry( const OnlineMessage &m );+ void resolveHostLeft();++private:+ OnlineSession();+};++/* Bytes a server line's number field holds, for vips and ids. */+UnsignedInt OnlineHostToNet( UnsignedInt v );++#endif // _ONLINE_SESSION_H_diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/Online/OnlineBuddy.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/Online/OnlineBuddy.cppindex b83506d83..751233053 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/Online/OnlineBuddy.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/Online/OnlineBuddy.cpp@@ -17,6 +17,183 @@*/// FILE: OnlineBuddy.cpp //////////////////////////////////////////////////////////////////////////-// Desc: The buddy queue answered from the online service instead of GameSpy. Empty until that-// phase lands.+// Desc: The buddy queue answered from the online service instead of GameSpy: the login and account+// creation, and private messages. With it the two queues that need no server at all: the+// pinger (the relay is the only route) and the game results (the server rates from reports).///////////////////////////////////////////////////////////////////////////////////////////////////++#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine++#include "GameNetwork/GameSpy/GameResultsThread.h"+#include "GameNetwork/GameSpy/PingThread.h"+#include "GameNetwork/GameSpy/ThreadUtils.h"+#include "GameNetwork/Online/OnlineSession.h"++#include <deque>+#include <map>++//-------------------------------------------------------------------------------------------------+// the buddy queue+//-------------------------------------------------------------------------------------------------++OnlineBuddyQueue::OnlineBuddyQueue() : m_running( FALSE )+{+ OnlineSession::get().buddy = this;+}++OnlineBuddyQueue::~OnlineBuddyQueue()+{+ if (OnlineSession::get().buddy == this)+ OnlineSession::get().buddy = NULL;+}++Bool OnlineBuddyQueue::isConnected( void )+{+ return OnlineSession::get().authed;+}++Bool OnlineBuddyQueue::isConnecting( void )+{+ return OnlineSession::get().authWaiting;+}++GPProfile OnlineBuddyQueue::getLocalProfileID( void )+{+ return (GPProfile)OnlineSession::get().id;+}++Bool OnlineBuddyQueue::getResponse( BuddyResponse& resp )+{+ OnlineSession::get().pump();+ if (m_responses.empty())+ return FALSE;+ resp = m_responses.front();+ m_responses.pop_front();+ return TRUE;+}++void OnlineBuddyQueue::addRequest( const BuddyRequest& req )+{+ OnlineSession &s = OnlineSession::get();+ OnlineMessage m;+ switch (req.buddyRequestType)+ {+ case BuddyRequest::BUDDYREQUEST_LOGIN:+ // the server takes a nick in "email" too; the login screen always fills the address+ m.setString( "t", "login" ).setString( "email", req.arg.login.email ).setString( "pass", req.arg.login.password );+ s.requestAuth( m );+ return;++ case BuddyRequest::BUDDYREQUEST_LOGINNEW:+ m.setString( "t", "register" ).setString( "email", req.arg.login.email );+ m.setString( "nick", req.arg.login.nick ).setString( "pass", req.arg.login.password );+ s.requestAuth( m );+ return;++ case BuddyRequest::BUDDYREQUEST_LOGOUT:+ s.disconnect();+ return;++ case BuddyRequest::BUDDYREQUEST_MESSAGE:+ m.setString( "t", "say" ).setInt( "to", req.arg.message.recipient );+ m.setString( "text", WideCharStringToMultiByte( req.arg.message.text ) );+ s.send( m );+ return;++ default:+ return; // buddy lists and status come later; RELOGIN has no saved password to use+ }+}++GameSpyBuddyMessageQueueInterface *OnlineCreateBuddyQueue( void )+{+ return new OnlineBuddyQueue;+}++//-------------------------------------------------------------------------------------------------+// the pinger: every ping answered at once+//-------------------------------------------------------------------------------------------------++class OnlinePinger : public PingerInterface+{+public:+ OnlinePinger() : m_running( FALSE ) {}+ virtual void startThreads( void ) { m_running = TRUE; }+ virtual void endThreads( void ) { m_running = FALSE; }+ virtual Bool areThreadsRunning( void ) { return m_running; }++ virtual void addRequest( const PingRequest& req )+ {+ m_pings[req.hostname] = 1;+ PingResponse r;+ r.hostname = req.hostname;+ r.avgPing = 1;+ r.repetitions = req.repetitions;+ m_responses.push_back( r );+ }+ virtual Bool getRequest( PingRequest& req ) { return FALSE; }+ virtual void addResponse( const PingResponse& resp ) { m_responses.push_back( resp ); }+ virtual Bool getResponse( PingResponse& resp )+ {+ if (m_responses.empty())+ return FALSE;+ resp = m_responses.front();+ m_responses.pop_front();+ return TRUE;+ }++ virtual Bool arePingsInProgress( void ) { return FALSE; }+ virtual Int getPing( AsciiString hostname )+ {+ std::map<std::string, Int>::const_iterator it = m_pings.find( hostname.str() );+ return it == m_pings.end() ? -1 : it->second;+ }+ virtual void clearPingMap( void ) { m_pings.clear(); }+ virtual AsciiString getPingString( Int timeout )+ {+ // GameSpy's format: two hex digits a server, the ping scaled to the timeout+ AsciiString s;+ for (size_t i = 0; i < m_pings.size(); ++i)+ s.concat( "00" );+ return s;+ }++private:+ std::map<std::string, Int> m_pings;+ std::deque<PingResponse> m_responses;+ Bool m_running;+};++PingerInterface *OnlineCreatePinger( void )+{+ return new OnlinePinger;+}++//-------------------------------------------------------------------------------------------------+// game results: dropped, the server rates from OnlineSendReport+//-------------------------------------------------------------------------------------------------++class OnlineGameResults : public GameResultsInterface+{+public:+ OnlineGameResults() : m_running( FALSE ) {}+ virtual void init() {}+ virtual void reset() {}+ virtual void update() {}+ virtual void startThreads( void ) { m_running = TRUE; }+ virtual void endThreads( void ) { m_running = FALSE; }+ virtual Bool areThreadsRunning( void ) { return m_running; }+ virtual void addRequest( const GameResultsRequest& req ) {}+ virtual Bool getRequest( GameResultsRequest& req ) { return FALSE; }+ virtual void addResponse( const GameResultsResponse& resp ) {}+ virtual Bool getResponse( GameResultsResponse& resp ) { return FALSE; }+ virtual Bool areGameResultsBeingSent( void ) { return FALSE; }++private:+ Bool m_running;+};++GameResultsInterface *OnlineCreateGameResults( void )+{+ return new OnlineGameResults;+}diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/Online/OnlinePeer.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/Online/OnlinePeer.cppindex bac2d85af..df3d81a26 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/Online/OnlinePeer.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/Online/OnlinePeer.cpp@@ -18,5 +18,976 @@// FILE: OnlinePeer.cpp ///////////////////////////////////////////////////////////////////////////// Desc: The peer queue (login, chat rooms, game list, staging room, Quick Match) answered from the-// online service instead of GameSpy. Empty until that phase lands.+// online service instead of GameSpy, and the session every adapter shares: the connection,+// the server's lines turned into PeerResponses, and OnlineQueues.h's calls.///////////////////////////////////////////////////////////////////////////////////////////////////++#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine++#include "Common/GlobalData.h"+#include "Common/UserPreferences.h"+#include "Common/version.h"+#include "GameNetwork/GameSpy/ThreadUtils.h"+#include "GameNetwork/Online/OnlineSession.h"+#include "zhio.h"++#include <stdio.h>+#include <stdlib.h>+#include <string.h>++// FirewallHelperClass::FIREWALL_TYPE_SIMPLE: every route goes through the relay, nothing to negotiate+static const Int ONLINE_NAT_SIMPLE = 1;+// The one chat room the login lists. Its name is looked up as GUI:<name> for the lobby's combo box.+static const Int ONLINE_LOBBY_ROOM = 1;+static const char *ONLINE_LOBBY_NAME = "Lobby";++UnsignedInt OnlineHostToNet( UnsignedInt v )+{+ return ((v & 0xFF) << 24) | ((v & 0xFF00) << 8) | ((v >> 8) & 0xFF00) | (v >> 24);+}++static std::string decimal( long long v )+{+ char buf[32];+ snprintf( buf, sizeof(buf), "%lld", v );+ return buf;+}++static PeerResponse makePeer( Int type )+{+ PeerResponse r;+ memset( &r.stagingRoom, 0, sizeof(r.stagingRoom) ); // the union's two largest members+ memset( &r.qmStatus, 0, sizeof(r.qmStatus) );+ r.peerResponseType = (decltype(r.peerResponseType))type;+ return r;+}++//-------------------------------------------------------------------------------------------------+// the session+//-------------------------------------------------------------------------------------------------++OnlineSession &OnlineSession::get()+{+ static OnlineSession s;+ return s;+}++OnlineSession::OnlineSession() :+ connection( NULL ), capture( NULL ), status( ONLINE_OFF ), relayPort( 0 ),+ peer( NULL ), buddy( NULL ), ps( NULL )+{+ forgetAccount();+}++void OnlineSession::forgetAccount()+{+ authed = FALSE;+ peerLoggedIn = FALSE;+ id = 0;+ nick.clear();+ token.clear();+ memset( ticket, 0, sizeof(ticket) );+ vip = 0;+ pendingAuth.clear();+ hasPendingAuth = FALSE;+ authWaiting = FALSE;+ groupRoom = 0;+ gameId = 0;+ joiningGame = 0;+ hosting = FALSE;+ hostInfo.clear();+ hostNick.clear();+ hostLeftGame = 0;+ hostLeftPumps = 0;+ vips.clear();+}++void OnlineSession::beginTest( std::vector<OnlineMessage> *lines )+{+ disconnect();+ capture = lines;+ matchId.clear();+ reportedMatch.clear();+ motd.clear();+ config.clear();+ relayPort = 8094;+ status = lines ? ONLINE_WELCOMED : ONLINE_OFF;+}++void OnlineSession::send( const OnlineMessage &m )+{+ if (capture)+ capture->push_back( m );+ else if (connection && !connection->send( m ))+ DEBUG_LOG(("online: could not send %s\n", m.type().c_str()));+}++void OnlineSession::dial()+{+ if (capture || !OnlineIsEnabled())+ return;++ std::string ca;+ if (!TheGlobalData->m_onlineCAFile.isEmpty())+ {+ FILE *f = zh_fopen( TheGlobalData->m_onlineCAFile.str(), "rb" );+ if (f)+ {+ char buf[4096];+ size_t n;+ while ((n = fread( buf, 1, sizeof(buf), f )) > 0)+ ca.append( buf, n );+ fclose( f );+ }+ else+ {+ DEBUG_LOG(("online: cannot read -onlineca %s\n", TheGlobalData->m_onlineCAFile.str()));+ }+ }++ if (!connection)+ connection = new OnlineConnection;+ if (!connection->connect( TheGlobalData->m_onlineHost.str(), TheGlobalData->m_onlinePort, ca ))+ {+ DEBUG_LOG(("online: cannot connect: %s\n", connection->error().c_str()));+ status = ONLINE_FAILED;+ return;+ }+ status = ONLINE_CONNECTING;++ OnlineMessage hello;+ hello.setString( "t", "hello" );+ hello.setInt( "exe", TheGlobalData->m_exeCRC );+ hello.setInt( "ini", TheGlobalData->m_iniCRC );+ hello.setString( "ver", TheVersion ? TheVersion->getReleaseVersion().str() : "" );+ connection->send( hello );+}++void OnlineSession::disconnect()+{+ if (connection)+ {+ connection->close();+ delete connection;+ connection = NULL;+ }+ if (!capture)+ status = ONLINE_OFF;+ forgetAccount();+}++void OnlineSession::requestAuth( const OnlineMessage &m )+{+ authWaiting = TRUE;+ if (status == ONLINE_WELCOMED)+ {+ send( m );+ return;+ }+ pendingAuth = m;+ hasPendingAuth = TRUE;+ if (status == ONLINE_OFF || status == ONLINE_FAILED)+ dial();+ if (status == ONLINE_FAILED)+ loginFailed( DISCONNECT_COULDNOTCONNECT );+}++void OnlineSession::pump()+{+ if (status == ONLINE_OFF)+ dial();++ if (connection && !capture)+ {+ OnlineMessage m;+ while (connection->receive( m ))+ dispatch( m );++ if (connection->state() == OnlineConnection::CLOSED && status != ONLINE_FAILED)+ {+ DEBUG_LOG(("online: connection closed: %s\n", connection->error().c_str()));+ status = ONLINE_FAILED;+ Bool wasIn = authed;+ Bool wasTrying = authWaiting;+ forgetAccount();+ if (wasIn || wasTrying)+ {+ PeerResponse r = makePeer( PeerResponse::PEERRESPONSE_DISCONNECT );+ r.discon.reason = wasIn ? DISCONNECT_LOSTCON : DISCONNECT_COULDNOTCONNECT;+ peerResponse( r );+ }+ }+ }++ if (hostLeftGame && ++hostLeftPumps >= 2)+ resolveHostLeft();+}++void OnlineSession::peerResponse( const PeerResponse &r )+{+ if (peer)+ peer->addResponse( r );+}++void OnlineSession::loginFailed( DisconnectReason reason )+{+ authWaiting = FALSE;+ hasPendingAuth = FALSE;+ PeerResponse r = makePeer( PeerResponse::PEERRESPONSE_DISCONNECT );+ r.discon.reason = reason;+ peerResponse( r );+}++/* PEERRESPONSE_LOGIN waits for relay.ok: its addresses are the relay's virtual one, and a player whose UDP+ never reaches the relay should find out at the login screen, not in a staging room. */+void OnlineSession::finishPeerLogin()+{+ peerLoggedIn = TRUE;++ PeerResponse r = makePeer( PeerResponse::PEERRESPONSE_LOGIN );+ r.nick = nick;+ r.player.profileID = (Int)id;+ r.player.internalIP = vip;+ r.player.externalIP = vip;+ peerResponse( r );++ PeerResponse room = makePeer( PeerResponse::PEERRESPONSE_GROUPROOM );+ room.groupRoom.id = ONLINE_LOBBY_ROOM;+ room.groupRoom.maxWaiting = 1000;+ room.groupRoomName = ONLINE_LOBBY_NAME;+ peerResponse( room );+ peerResponse( makePeer( PeerResponse::PEERRESPONSE_GROUPROOM ) ); // id 0: the end of the list, as GameSpy's++ OnlineMessage stats;+ stats.setString( "t", "stats.get" ).setInt( "id", id );+ send( stats );+}++void OnlineSession::resolveHostLeft()+{+ if (!hostLeftGame)+ return;+ PeerResponse r = makePeer( PeerResponse::PEERRESPONSE_PLAYERLEFT );+ r.nick = hostNick;+ r.player.roomType = StagingRoom;+ hostLeftGame = 0;+ hostLeftPumps = 0;+ gameId = 0;+ peerResponse( r );+}++static DisconnectReason authFailReason( const std::string &code )+{+ if (code == "bademail" || code == "emailtaken") return DISCONNECT_GP_LOGIN_BAD_EMAIL;+ if (code == "badnick") return DISCONNECT_GP_NEWUSER_BAD_NICK;+ if (code == "nicktaken") return DISCONNECT_NICKTAKEN;+ if (code == "badpass") return DISCONNECT_GP_NEWUSER_BAD_PASSWORD;+ if (code == "badlogin" || code == "badtoken") return DISCONNECT_GP_LOGIN_BAD_PASSWORD;+ if (code == "banned") return DISCONNECT_SERIAL_BANNED;+ if (code == "elsewhere") return DISCONNECT_LOSTCON;+ return DISCONNECT_COULDNOTCONNECT; // reglimit, throttled, anything new+}++static Bool hexTicket( const std::string &hex, UnsignedByte out[16] )+{+ if (hex.size() != 32)+ return FALSE;+ for (Int i = 0; i < 16; ++i)+ {+ char pair[3] = { hex[i*2], hex[i*2+1], 0 };+ char *end = NULL;+ out[i] = (UnsignedByte)strtoul( pair, &end, 16 );+ if (end != pair + 2)+ return FALSE;+ }+ return TRUE;+}++/* A game{action:add|update}: the server's fields plus what the host put in game.opts (OnlinePeerQueue's+ SETGAMEOPTIONS writes it as a line of its own), as the lobby's game list wants it. */+void OnlineSession::gameListEntry( const OnlineMessage &m )+{+ PeerResponse r = makePeer( PeerResponse::PEERRESPONSE_STAGINGROOM );+ r.stagingRoom.action = m.getString( "action" ) == "add" ? PEER_ADD : PEER_UPDATE;+ r.stagingRoom.isStaging = TRUE;+ r.stagingRoom.percentComplete = 100;+ r.stagingRoom.id = (Int)m.getInt( "id" );+ r.stagingServerName = MultiByteToWideCharSingleLine( m.getString( "name" ).c_str() );+ r.stagingRoom.numPlayers = (Int)m.getInt( "count" );+ r.stagingRoom.maxPlayers = (Int)m.getInt( "maxp", MAX_SLOTS );+ r.stagingRoom.useStats = TRUE;+ r.stagingRoomPlayerNames[0] = m.getString( "host" );++ OnlineMessage o;+ const std::string opts = m.getString( "opts" );+ if (!opts.empty() && OnlineMessage::parse( opts.data(), opts.size(), o ))+ {+ r.stagingRoom.exeCRC = (UnsignedInt)o.getInt( "exe" );+ r.stagingRoom.iniCRC = (UnsignedInt)o.getInt( "ini" );+ r.stagingRoom.version = (UnsignedInt)o.getInt( "ver" );+ r.stagingRoom.allowObservers = o.getBool( "obs" );+ r.stagingRoom.useStats = o.getBool( "stats", true );+ r.stagingRoom.ladderPort = (UnsignedShort)o.getInt( "ladPort" );+ r.stagingServerLadderIP = o.getString( "ladIP" );+ r.stagingServerPingString = o.getString( "ping" );+ r.stagingRoomMapName = o.getString( "map" );+ r.stagingRoom.numPlayers = (Int)o.getInt( "np", r.stagingRoom.numPlayers );+ r.stagingRoom.numObservers = (Int)o.getInt( "no" );+ r.stagingRoom.maxPlayers = (Int)o.getInt( "mp", r.stagingRoom.maxPlayers );+ const std::vector<std::string> names = o.getStrings( "names" );+ const std::vector<long long> wins = o.getInts( "wins" ), losses = o.getInts( "losses" ), pids = o.getInts( "pids" );+ const std::vector<long long> factions = o.getInts( "factions" ), colors = o.getInts( "colors" );+ for (Int i = 0; i < MAX_SLOTS; ++i)+ {+ if (i < (Int)names.size() && !names[i].empty())+ r.stagingRoomPlayerNames[i] = names[i];+ if (i < (Int)wins.size()) r.stagingRoom.wins[i] = (Int)wins[i];+ if (i < (Int)losses.size()) r.stagingRoom.losses[i] = (Int)losses[i];+ if (i < (Int)pids.size()) r.stagingRoom.profileID[i] = (Int)pids[i];+ if (i < (Int)factions.size()) r.stagingRoom.faction[i] = (Int)factions[i];+ if (i < (Int)colors.size()) r.stagingRoom.color[i] = (Int)colors[i];+ }+ }+ peerResponse( r );+}++static void playerResponse( OnlineSession &s, Int type, RoomType roomType, long long who, const std::string &nick )+{+ PeerResponse r = makePeer( type );+ r.nick = nick;+ r.player.roomType = roomType;+ r.player.profileID = (Int)who;+ std::map<long long, UnsignedInt>::const_iterator it = s.vips.find( who );+ if (it != s.vips.end())+ r.player.IP = OnlineHostToNet( it->second ); // GameSpy's player IP is in network order+ if (s.peer)+ s.peer->addResponse( r );+}++static void rememberVips( OnlineSession &s, const OnlineMessage &m )+{+ const std::vector<long long> ids = m.getInts( "ids" ), v = m.getInts( "vips" );+ for (size_t i = 0; i < ids.size() && i < v.size(); ++i)+ if (v[i])+ s.vips[ids[i]] = (UnsignedInt)v[i];+ if (m.has( "vip" ) && m.has( "id" ))+ s.vips[m.getInt( "id" )] = (UnsignedInt)m.getInt( "vip" );+}++void OnlineSession::dispatch( const OnlineMessage &m )+{+ const std::string t = m.type();++ // A game removed under a guest is the host leaving, unless it was removed because it started.+ if (hostLeftGame && t != "game.start")+ resolveHostLeft();++ if (t == "welcome")+ {+ motd = m.getString( "motd" );+ config = m.getString( "config" );+ relayPort = (UnsignedShort)m.getInt( "relayPort" );+ status = ONLINE_WELCOMED;+ if (hasPendingAuth)+ {+ hasPendingAuth = FALSE;+ send( pendingAuth );+ }+ }+ else if (t == "auth.ok")+ {+ authWaiting = FALSE;+ authed = TRUE;+ peerLoggedIn = FALSE;+ id = m.getInt( "id" );+ nick = m.getString( "nick" );+ token = m.getString( "token" );+ vip = 0;+ if (!hexTicket( m.getString( "ticket" ), ticket ))+ DEBUG_LOG(("online: auth.ok carries no usable relay ticket\n"));++ if (buddy)+ {+ BuddyResponse b;+ memset( &b, 0, sizeof(b) );+ b.buddyResponseType = BuddyResponse::BUDDYRESPONSE_LOGIN;+ b.result = GP_NO_ERROR;+ b.profile = (GPProfile)id;+ buddy->addResponse( b );+ }+ }+ else if (t == "auth.fail")+ {+ const std::string code = m.getString( "code" );+ DEBUG_LOG(("online: auth.fail %s\n", code.c_str()));+ if (code == "already")+ return;+ Bool wasIn = authed;+ forgetAccount();+ if (code == "elsewhere" || wasIn)+ {+ PeerResponse r = makePeer( PeerResponse::PEERRESPONSE_DISCONNECT );+ r.discon.reason = DISCONNECT_LOSTCON;+ peerResponse( r );+ }+ else+ loginFailed( authFailReason( code ) );+ }+ else if (t == "relay.ok")+ {+ vip = (UnsignedInt)m.getInt( "vip" );+ vips[id] = vip;+ if (authed && !peerLoggedIn)+ finishPeerLogin();+ }+ else if (t == "error")+ {+ const std::string what = m.getString( "for" ), code = m.getString( "code" );+ DEBUG_LOG(("online: %s refused: %s\n", what.c_str(), code.c_str()));+ if (what == "room.join")+ {+ PeerResponse r = makePeer( PeerResponse::PEERRESPONSE_JOINGROUPROOM );+ r.joinGroupRoom.id = groupRoom;+ r.joinGroupRoom.ok = FALSE;+ groupRoom = 0;+ peerResponse( r );+ }+ else if (what == "game.host")+ {+ hosting = FALSE;+ PeerResponse r = makePeer( PeerResponse::PEERRESPONSE_CREATESTAGINGROOM );+ r.createStagingRoom.result = PEERJoinFailed;+ peerResponse( r );+ }+ else if (what == "game.join")+ {+ PeerResponse r = makePeer( PeerResponse::PEERRESPONSE_JOINSTAGINGROOM );+ r.joinStagingRoom.id = (Int)joiningGame;+ r.joinStagingRoom.ok = FALSE;+ r.joinStagingRoom.result = code == "full" ? PEERFullRoom : PEERJoinFailed;+ joiningGame = 0;+ peerResponse( r );+ }+ else if (what == "qm.join")+ {+ PeerResponse r = makePeer( PeerResponse::PEERRESPONSE_QUICKMATCHSTATUS );+ r.qmStatus.status = code == "norelay" ? QM_COULDNOTNEGOTIATEFIREWALLS : QM_COULDNOTFINDBOT;+ peerResponse( r );+ }+ }+ else if (t == "room")+ {+ groupRoom = atoi( m.getString( "id" ).c_str() );+ rememberVips( *this, m );+ PeerResponse r = makePeer( PeerResponse::PEERRESPONSE_JOINGROUPROOM );+ r.joinGroupRoom.id = groupRoom;+ r.joinGroupRoom.ok = TRUE;+ peerResponse( r );+ const std::vector<long long> ids = m.getInts( "ids" );+ const std::vector<std::string> nicks = m.getStrings( "nicks" );+ for (size_t i = 0; i < ids.size() && i < nicks.size(); ++i)+ playerResponse( *this, PeerResponse::PEERRESPONSE_PLAYERJOIN, GroupRoom, ids[i], nicks[i] );+ }+ else if (t == "player" || t == "player.left")+ {+ rememberVips( *this, m );+ const Int type = t == "player" ? PeerResponse::PEERRESPONSE_PLAYERJOIN : PeerResponse::PEERRESPONSE_PLAYERLEFT;+ if (m.has( "game" ) && gameId && m.getInt( "game" ) == gameId)+ playerResponse( *this, type, StagingRoom, m.getInt( "id" ), m.getString( "nick" ) );+ else if (m.has( "room" ) && groupRoom && atoi( m.getString( "room" ).c_str() ) == groupRoom)+ playerResponse( *this, type, GroupRoom, m.getInt( "id" ), m.getString( "nick" ) );+ }+ else if (t == "said")+ {+ PeerResponse r = makePeer( PeerResponse::PEERRESPONSE_MESSAGE );+ r.nick = m.getString( "nick" );+ r.text = MultiByteToWideCharSingleLine( m.getString( "text" ).c_str() );+ r.message.isAction = m.getInt( "action" ) != 0 || m.getBool( "action" );+ r.message.profileID = (Int)m.getInt( "from" );+ const std::string room = m.getString( "room" );+ if (m.has( "to" ))+ r.message.isPrivate = TRUE;+ else if (!((gameId && room == decimal( gameId )) || (groupRoom && atoi( room.c_str() ) == groupRoom)))+ return; // a room this player has left+ peerResponse( r );+ }+ else if (t == "game")+ {+ const std::string action = m.getString( "action" );+ const long long g = m.getInt( "id" );+ if (action == "remove")+ {+ PeerResponse r = makePeer( PeerResponse::PEERRESPONSE_STAGINGROOM );+ r.stagingRoom.action = PEER_REMOVE;+ r.stagingRoom.isStaging = TRUE;+ r.stagingRoom.id = (Int)g;+ r.stagingRoom.percentComplete = 100;+ peerResponse( r );+ if (g == gameId && !hosting)+ {+ hostLeftGame = g;+ hostLeftPumps = 0;+ }+ }+ else+ {+ if (g == gameId)+ hostNick = m.getString( "host" );+ gameListEntry( m );+ }+ }+ else if (t == "game.joined")+ {+ gameId = m.getInt( "id" );+ joiningGame = 0;+ groupRoom = 0;+ hostNick = m.getString( "host" );+ hosting = m.getInt( "hostId" ) == id;+ rememberVips( *this, m );+ const std::vector<long long> ids = m.getInts( "ids" );+ const std::vector<std::string> nicks = m.getStrings( "nicks" );+ if (hosting)+ {+ PeerResponse r = makePeer( PeerResponse::PEERRESPONSE_CREATESTAGINGROOM );+ r.createStagingRoom.result = PEERJoinSuccess;+ peerResponse( r );+ }+ else+ {+ PeerResponse r = makePeer( PeerResponse::PEERRESPONSE_JOINSTAGINGROOM );+ r.joinStagingRoom.id = (Int)gameId;+ r.joinStagingRoom.ok = TRUE;+ r.joinStagingRoom.result = PEERJoinSuccess;+ for (size_t i = 0; i < nicks.size() && i < (size_t)MAX_SLOTS; ++i)+ {+ r.stagingRoomPlayerNames[i] = nicks[i];+ if (nicks[i] == hostNick)+ r.joinStagingRoom.isHostPresent = TRUE;+ }+ peerResponse( r );+ }+ for (size_t i = 0; i < ids.size(); ++i)+ {+ if (ids[i] == id)+ continue;+ OnlineMessage stats;+ stats.setString( "t", "stats.get" ).setInt( "id", ids[i] );+ send( stats );+ }+ }+ else if (t == "utm")+ {+ PeerResponse r = makePeer( PeerResponse::PEERRESPONSE_PLAYERUTM );+ r.nick = m.getString( "nick" );+ r.command = m.getString( "cmd" );+ r.commandOptions = m.getString( "opts" );+ if (!m.has( "to" ))+ {+ if (!gameId || m.getString( "room" ) != decimal( gameId ))+ return; // GameSpy's room UTMs only ever reached a staging room+ r.peerResponseType = PeerResponse::PEERRESPONSE_ROOMUTM;+ }+ peerResponse( r );+ }+ else if (t == "game.start")+ {+ matchId = m.getString( "match" );+ hostLeftGame = 0;+ hostLeftPumps = 0;+ rememberVips( *this, m );+ const Bool wasHost = hosting;+ gameId = 0;+ hosting = FALSE;+ if (!wasHost)+ peerResponse( makePeer( PeerResponse::PEERRESPONSE_GAMESTART ) ); // the host started on its own click+ }+ else if (t == "qm.status")+ {+ const std::string st = m.getString( "status" );+ PeerResponse r = makePeer( PeerResponse::PEERRESPONSE_QUICKMATCHSTATUS );+ r.qmStatus.poolSize = (Int)m.getInt( "pool" );+ if (st == "searching")+ r.qmStatus.status = QM_WORKING;+ else if (st == "left")+ r.qmStatus.status = QM_STOPPED;+ else+ r.qmStatus.status = QM_COULDNOTFINDBOT; // locked: the leaver lock+ peerResponse( r );+ }+ else if (t == "qm.matched")+ {+ matchId = m.getString( "match" );+ rememberVips( *this, m );+ PeerResponse r = makePeer( PeerResponse::PEERRESPONSE_QUICKMATCHSTATUS );+ r.qmStatus.status = QM_MATCHED;+ r.qmStatus.seed = (Int)m.getInt( "seed" );+ r.qmStatus.mapIdx = (Int)m.getInt( "mapIdx" );+ const std::vector<std::string> nicks = m.getStrings( "nicks" );+ const std::vector<long long> v = m.getInts( "vips" ), sides = m.getInts( "sides" ), colors = m.getInts( "colors" );+ for (size_t i = 0; i < nicks.size() && i < (size_t)MAX_SLOTS; ++i)+ {+ r.stagingRoomPlayerNames[i] = nicks[i];+ r.qmStatus.IP[i] = i < v.size() ? (UnsignedInt)v[i] : 0; // host order, as GameSpy's matchbot sent it+ r.qmStatus.side[i] = i < sides.size() ? (Int)sides[i] : -1;+ r.qmStatus.color[i] = i < colors.size() ? (Int)colors[i] : -1;+ r.qmStatus.nat[i] = ONLINE_NAT_SIMPLE;+ }+ peerResponse( r );+ }+ else if (t == "stats")+ {+ if (ps)+ ps->statsArrived( m.getInt( "id" ), m.getString( "kv" ) );+ }+ else if (t == "rated" || t == "unrated")+ {+ DEBUG_LOG(("online: match %s %s (%s)\n", m.getString( "match" ).c_str(), t.c_str(), m.getString( "reason" ).c_str()));+ if (authed)+ {+ OnlineMessage stats;+ stats.setString( "t", "stats.get" ).setInt( "id", id );+ send( stats );+ }+ }+ else+ {+ DEBUG_LOG(("online: ignored a %s line\n", t.c_str()));+ }+}++//-------------------------------------------------------------------------------------------------+// the peer queue+//-------------------------------------------------------------------------------------------------++OnlinePeerQueue::OnlinePeerQueue() : m_running( FALSE )+{+ OnlineSession::get().peer = this;+}++OnlinePeerQueue::~OnlinePeerQueue()+{+ if (OnlineSession::get().peer == this)+ OnlineSession::get().peer = NULL;+}++void OnlinePeerQueue::endThread( void )+{+ // TearDownGameSpy: the login ends with the queues+ m_running = FALSE;+ OnlineSession::get().disconnect();+}++Bool OnlinePeerQueue::isConnected( void )+{+ return OnlineSession::get().peerLoggedIn;+}++Bool OnlinePeerQueue::isConnecting( void )+{+ OnlineSession &s = OnlineSession::get();+ return s.authWaiting || (s.authed && !s.peerLoggedIn);+}++Bool OnlinePeerQueue::getResponse( PeerResponse& resp )+{+ OnlineSession::get().pump();+ if (m_responses.empty())+ return FALSE;+ resp = m_responses.front();+ m_responses.pop_front();+ return TRUE;+}++static void leaveGame( OnlineSession &s )+{+ if (s.gameId || s.hosting || s.joiningGame)+ {+ OnlineMessage m;+ m.setString( "t", "game.leave" );+ s.send( m );+ }+ s.gameId = 0;+ s.joiningGame = 0;+ s.hosting = FALSE;+ s.hostLeftGame = 0;+}++void OnlinePeerQueue::addRequest( const PeerRequest& req )+{+ OnlineSession &s = OnlineSession::get();+ OnlineMessage m;+ switch (req.peerRequestType)+ {+ case PeerRequest::PEERREQUEST_LOGIN:+ // the buddy login does the work; this only asks for the answer GameSpy's chat login gave+ if (s.authed && s.vip && !s.peerLoggedIn)+ s.finishPeerLogin();+ return;++ case PeerRequest::PEERREQUEST_LOGOUT:+ s.disconnect();+ return;++ case PeerRequest::PEERREQUEST_MESSAGEPLAYER:+ m.setString( "t", "say" ).setString( "to", req.nick );+ break;++ case PeerRequest::PEERREQUEST_MESSAGEROOM:+ m.setString( "t", "say" );+ if (s.gameId)+ m.setString( "room", decimal( s.gameId ) );+ else if (s.groupRoom)+ m.setString( "room", decimal( s.groupRoom ) );+ else+ return;+ break;++ case PeerRequest::PEERREQUEST_JOINGROUPROOM:+ leaveGame( s );+ s.groupRoom = req.groupRoom.id;+ m.setString( "t", "room.join" ).setString( "id", decimal( req.groupRoom.id ) );+ s.send( m );+ return;++ case PeerRequest::PEERREQUEST_LEAVEGROUPROOM:+ s.groupRoom = 0; // the server has no leave; the room's lines are dropped from here on+ return;++ case PeerRequest::PEERREQUEST_STARTGAMELIST:+ {+ PeerResponse clear = makePeer( PeerResponse::PEERRESPONSE_STAGINGROOM );+ clear.stagingRoom.action = PEER_CLEAR;+ clear.stagingRoom.isStaging = TRUE;+ addResponse( clear );+ // games.watch answers with every game at once and marks no end; the list is complete as it lands+ addResponse( makePeer( PeerResponse::PEERRESPONSE_STAGINGROOMLISTCOMPLETE ) );+ m.setString( "t", "games.watch" );+ s.send( m );+ }+ return;++ case PeerRequest::PEERREQUEST_CREATESTAGINGROOM:+ leaveGame( s );+ s.groupRoom = 0;+ s.hosting = TRUE;+ s.hostInfo.clear();+ s.hostInfo.setInt( "exe", req.stagingRoomCreation.exeCRC );+ s.hostInfo.setInt( "ini", req.stagingRoomCreation.iniCRC );+ s.hostInfo.setInt( "ver", req.stagingRoomCreation.gameVersion );+ s.hostInfo.setBool( "obs", req.stagingRoomCreation.allowObservers != 0 );+ s.hostInfo.setBool( "stats", req.stagingRoomCreation.useStats != 0 );+ s.hostInfo.setInt( "ladPort", req.stagingRoomCreation.ladPort );+ s.hostInfo.setString( "ladIP", req.ladderIP );+ s.hostInfo.setString( "ping", req.hostPingStr );+ // the map is chosen in the staging room, after this; game.opts carries it to the list+ m.setString( "t", "game.host" ).setString( "name", WideCharStringToMultiByte( req.text.c_str() ) );+ m.setString( "map", "-" ).setInt( "maxp", MAX_SLOTS );+ s.send( m );+ return;++ case PeerRequest::PEERREQUEST_SETGAMEOPTIONS:+ {+ if (!s.gameId || !s.hosting)+ return;+ OnlineMessage o = s.hostInfo;+ o.setString( "map", req.gameOptsMapName );+ o.setInt( "np", req.gameOptions.numPlayers );+ o.setInt( "no", req.gameOptions.numObservers );+ o.setInt( "mp", req.gameOptions.maxPlayers );+ std::vector<std::string> names;+ std::vector<long long> wins, losses, pids, factions, colors;+ for (Int i = 0; i < MAX_SLOTS; ++i)+ {+ names.push_back( req.gameOptsPlayerNames[i] );+ wins.push_back( req.gameOptions.wins[i] );+ losses.push_back( req.gameOptions.losses[i] );+ pids.push_back( req.gameOptions.profileID[i] );+ factions.push_back( req.gameOptions.faction[i] );+ colors.push_back( req.gameOptions.color[i] );+ }+ o.setStrings( "names", names ).setInts( "wins", wins ).setInts( "losses", losses );+ o.setInts( "pids", pids ).setInts( "factions", factions ).setInts( "colors", colors );+ std::string line;+ if (o.toLine( line ))+ {+ line.resize( line.size() - 1 ); // the newline+ m.setString( "t", "game.opts" ).setString( "opts", line );+ s.send( m );+ }+ // and the slot list to the room, as GameSpy's SL/ UTM+ OnlineMessage sl;+ sl.setString( "t", "utm" ).setString( "room", decimal( s.gameId ) ).setString( "cmd", "SL/" ).setString( "opts", req.options );+ s.send( sl );+ }+ return;++ case PeerRequest::PEERREQUEST_JOINSTAGINGROOM:+ leaveGame( s );+ s.groupRoom = 0;+ s.joiningGame = req.stagingRoom.id;+ m.setString( "t", "game.join" ).setInt( "id", req.stagingRoom.id );+ s.send( m );+ return;++ case PeerRequest::PEERREQUEST_LEAVESTAGINGROOM:+ leaveGame( s );+ return;++ case PeerRequest::PEERREQUEST_UTMPLAYER:+ if (req.nick.empty())+ return;+ m.setString( "t", "utm" ).setString( "to", req.nick ).setString( "cmd", req.id ).setString( "opts", req.options );+ s.send( m );+ return;++ case PeerRequest::PEERREQUEST_UTMROOM:+ m.setString( "t", "utm" ).setString( "room", decimal( req.UTM.isStagingRoom ? s.gameId : s.groupRoom ) );+ m.setString( "cmd", req.id ).setString( "opts", req.options );+ s.send( m );+ return;++ case PeerRequest::PEERREQUEST_STARTGAME:+ m.setString( "t", "game.start" );+ s.send( m );+ return;++ case PeerRequest::PEERREQUEST_STARTQUICKMATCH:+ {+ leaveGame( s );+ s.groupRoom = 0;+ std::vector<long long> maps;+ for (size_t i = 0; i < req.qmMaps.size(); ++i)+ if (req.qmMaps[i])+ maps.push_back( (long long)i );+ m.setString( "t", "qm.join" ).setInts( "maps", maps );+ m.setInt( "side", req.QM.side ).setInt( "color", req.QM.color );+ s.send( m );+ }+ return;++ case PeerRequest::PEERREQUEST_WIDENQUICKMATCHSEARCH:+ {+ m.setString( "t", "qm.widen" );+ s.send( m );+ PeerResponse r = makePeer( PeerResponse::PEERRESPONSE_QUICKMATCHSTATUS );+ r.qmStatus.status = QM_WIDENINGSEARCH;+ addResponse( r );+ }+ return;++ case PeerRequest::PEERREQUEST_STOPQUICKMATCH:+ m.setString( "t", "qm.leave" );+ s.send( m );+ return;++ default:+ return; // PUSHSTATS (the server keeps stats), GETEXTENDEDSTAGINGROOMINFO, STOPGAMELIST+ }++ // the two says+ m.setString( "text", WideCharStringToMultiByte( req.text.c_str() ) );+ m.setBool( "action", req.message.isAction != 0 );+ s.send( m );+}++//-------------------------------------------------------------------------------------------------+// OnlineQueues.h+//-------------------------------------------------------------------------------------------------++Bool OnlineIsEnabled( void )+{+ if (OnlineSession::get().capture)+ return TRUE;+ return TheGlobalData && !TheGlobalData->m_onlineHost.isEmpty() && TheGlobalData->m_onlinePort != 0;+}++GameSpyPeerMessageQueueInterface *OnlineCreatePeerQueue( void )+{+ return new OnlinePeerQueue;+}++void OnlineUpdate( void )+{+ if (OnlineIsEnabled())+ OnlineSession::get().pump();+}++OnlineStatus OnlineGetStatus( void )+{+ return OnlineIsEnabled() ? OnlineSession::get().status : ONLINE_OFF;+}++AsciiString OnlineGetMOTD( void )+{+ return OnlineSession::get().motd.c_str();+}++AsciiString OnlineGetConfig( void )+{+ return OnlineSession::get().config.c_str();+}++void OnlineDisconnect( void )+{+ OnlineSession::get().disconnect();+}++Bool OnlineGetRelayTicket( UnsignedByte out[16] )+{+ OnlineSession &s = OnlineSession::get();+ if (!s.authed)+ return FALSE;+ memcpy( out, s.ticket, sizeof(s.ticket) );+ return TRUE;+}++Bool OnlineGetRelayEndpoint( AsciiString &host, UnsignedShort &port )+{+ OnlineSession &s = OnlineSession::get();+ if (!s.authed || !s.relayPort || !TheGlobalData)+ return FALSE;+ host = TheGlobalData->m_onlineHost;+ port = s.relayPort;+ return TRUE;+}++UnsignedInt OnlineGetRelayVip( void )+{+ return OnlineSession::get().vip;+}++AsciiString OnlineGetSessionToken( void )+{+ return OnlineSession::get().token.c_str();+}++static const char *ONLINE_TOKEN_FILE = "GeneralsOnline\\OnlineTokens.ini";++AsciiString OnlineGetSavedToken( const AsciiString &login )+{+ AsciiString key = login;+ key.toLower();+ UserPreferences p;+ p.load( ONLINE_TOKEN_FILE );+ return p.getAsciiString( key, AsciiString::TheEmptyString );+}++void OnlineSaveToken( const AsciiString &login, const AsciiString &token )+{+ AsciiString key = login;+ key.toLower();+ UserPreferences p;+ p.load( ONLINE_TOKEN_FILE );+ if (token.isEmpty())+ p.erase( key );+ else+ p[key] = token;+ p.write();+}++void OnlineResume( const AsciiString &token )+{+ OnlineMessage m;+ m.setString( "t", "resume" ).setString( "token", token.str() );+ OnlineSession::get().requestAuth( m );+}diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/Online/OnlineStats.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/Online/OnlineStats.cppindex dfb443b7b..599aaa747 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/Online/OnlineStats.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/Online/OnlineStats.cpp@@ -17,6 +17,137 @@*/// FILE: OnlineStats.cpp //////////////////////////////////////////////////////////////////////////-// Desc: The persistent-storage queue (player stats, match results) answered from the online-// service instead of GameSpy. Empty until that phase lands.+// Desc: The persistent-storage queue (player stats) answered from the online service instead of+// GameSpy, and the match report. The server owns every number: a client's stats writes are+// dropped, and the result goes up as OnlineSendReport, once a match.///////////////////////////////////////////////////////////////////////////////////////////////////++#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine++#include "GameNetwork/Online/OnlineSession.h"++#include <stdlib.h>++OnlinePSQueue::OnlinePSQueue() : m_running( FALSE )+{+ OnlineSession::get().ps = this;+}++OnlinePSQueue::~OnlinePSQueue()+{+ if (OnlineSession::get().ps == this)+ OnlineSession::get().ps = NULL;+}++void OnlinePSQueue::addRequest( const PSRequest& req )+{+ if (req.requestType != PSRequest::PSREQUEST_READPLAYERSTATS || req.player.id == 0)+ return; // writes, locale, results, CD keys: the server keeps the numbers+ OnlineMessage m;+ m.setString( "t", "stats.get" ).setInt( "id", req.player.id );+ OnlineSession::get().send( m );+}++Bool OnlinePSQueue::getResponse( PSResponse& resp )+{+ OnlineSession::get().pump();+ if (m_responses.empty())+ return FALSE;+ resp = m_responses.front();+ m_responses.pop_front();+ return TRUE;+}++void OnlinePSQueue::trackPlayerStats( PSPlayerStats stats )+{+ std::map<Int, PSPlayerStats>::iterator it = m_stats.find( stats.id );+ if (it == m_stats.end())+ m_stats[stats.id] = stats;+ else+ it->second.incorporate( stats );+}++PSPlayerStats OnlinePSQueue::findPlayerStatsByID( Int id )+{+ std::map<Int, PSPlayerStats>::const_iterator it = m_stats.find( id );+ if (it != m_stats.end())+ return it->second;+ PSPlayerStats empty;+ empty.id = 0;+ return empty;+}++/* The server's kv is \nick\N\wins\W\losses\L\games\G\rating\R. EA's parser keeps wins, losses and games+ only per general (wins3, losses3) and drops a bare key, so the totals go under general 0: every+ reader of them (CalculateRank, the player popup) sums over the generals. */+static std::string totalsUnderGeneralZero( const std::string &kv )+{+ std::string out;+ size_t at = 0;+ Bool isKey = TRUE;+ while (at < kv.size())+ {+ size_t next = kv.find( '\\', at + 1 );+ if (next == std::string::npos)+ next = kv.size();+ std::string field = kv.substr( at, next - at ); // "\name"+ out += field;+ if (isKey && (field == "\\wins" || field == "\\losses" || field == "\\games"))+ out += "0";+ isKey = !isKey;+ at = next;+ }+ return out;+}++void OnlinePSQueue::statsArrived( long long id, const std::string &kv )+{+ PSResponse r;+ r.responseType = PSResponse::PSRESPONSE_PLAYERSTATS;+ r.player = GameSpyPSMessageQueueInterface::parsePlayerKVPairs( totalsUnderGeneralZero( kv ) );+ r.player.id = (Int)id;+ r.preorder = FALSE;+ m_stats[r.player.id] = r.player; // the server's numbers replace what was cached+ addResponse( r );+}++GameSpyPSMessageQueueInterface *OnlineCreatePSQueue( void )+{+ return new OnlinePSQueue;+}++//-------------------------------------------------------------------------------------------------+// the match report+//-------------------------------------------------------------------------------------------------++OnlineReport::OnlineReport() :+ seed( 0 ), endFrame( 0 ), winningTeam( -1 ), sawDesync( FALSE ), sawGameEnd( FALSE ), disconEnd( FALSE ),+ surrendered( FALSE ), duration( 0 ), numPlayers( 0 )+{+ for (Int i = 0; i < MAX_SLOTS; ++i)+ discon[i] = FALSE;+}++void OnlineSendReport( const OnlineReport &report )+{+ OnlineSession &s = OnlineSession::get();+ if (s.matchId.empty() || s.matchId == s.reportedMatch)+ return; // no match, or the score screen's second call+ s.reportedMatch = s.matchId;++ OnlineMessage m;+ m.setString( "t", "report" ).setString( "match", s.matchId );+ m.setInt( "seed", report.seed ).setInt( "endFrame", report.endFrame ).setInt( "winningTeam", report.winningTeam );+ m.setBool( "sawDesync", report.sawDesync != 0 ).setBool( "sawGameEnd", report.sawGameEnd != 0 );+ m.setBool( "disconEnd", report.disconEnd != 0 ).setBool( "surrendered", report.surrendered != 0 );+ m.setInt( "duration", report.duration );+ std::vector<long long> discon;+ std::vector<std::string> side;+ for (Int i = 0; i < report.numPlayers && i < MAX_SLOTS; ++i)+ {+ discon.push_back( report.discon[i] ? 1 : 0 );+ side.push_back( report.side[i].str() );+ }+ m.setInts( "discon", discon ).setStrings( "side", side );+ s.send( m );+}diff --git a/GeneralsMD/Code/Tests/test_online.cpp b/GeneralsMD/Code/Tests/test_online.cppindex b72f3a55b..1528b1bd4 100644--- a/GeneralsMD/Code/Tests/test_online.cpp+++ b/GeneralsMD/Code/Tests/test_online.cpp@@ -6,11 +6,21 @@* in this process. The server's certificate is signed by a CA the test makes on the spot, so nothing* secret is committed and nothing expires: the client has to accept it against that CA and refuse it* against another.+ *+ * Last the adapters (OnlinePeer, OnlineBuddy, OnlineStats): the GameSpy queue interfaces fed the+ * server's lines as online/server.js writes them, checked for the responses EA's WOL screens read and+ * for the lines the screens' requests send.*/#include "test_harness.h"+#include "Lib/BaseType.h"+#include "Common/AsciiString.h"+#include "Common/GameMemory.h"+#include "Lib/WideCharFns.h"+#include <map>#include "GameNetwork/Online/OnlineConnection.h"+#include "GameNetwork/Online/OnlineSession.h"#include <chrono>#include <string>@@ -615,3 +625,515 @@ TEST(online_connect_refuses_bad_arguments)CHECK_EQ( count, 2 );mbedtls_x509_crt_free( &roots );}++//-------------------------------------------------------------------------------------------------+// the adapters, fed scripted server lines+//-------------------------------------------------------------------------------------------------++/* The three queues over a session that sends into `sent` and dials nothing. feed() is one server line. */+struct AdapterRig+{+ std::vector<OnlineMessage> sent;+ OnlinePeerQueue *peer;+ OnlineBuddyQueue *buddy;+ OnlinePSQueue *ps;++ AdapterRig()+ {+ static bool booted = false;+ if (!booted)+ {+ initMemoryManager();+ booted = true;+ }+ OnlineSession::get().beginTest( &sent );+ peer = new OnlinePeerQueue;+ buddy = new OnlineBuddyQueue;+ ps = new OnlinePSQueue;+ }+ ~AdapterRig()+ {+ delete ps;+ delete buddy;+ delete peer;+ OnlineSession::get().beginTest( NULL );+ }++ void feed( const OnlineMessage &m ) { OnlineSession::get().dispatch( m ); }+ void feed( const char *json )+ {+ OnlineMessage m;+ CHECK( parseText( json, m ) );+ feed( m );+ }+ std::vector<PeerResponse> peerResponses()+ {+ std::vector<PeerResponse> out;+ PeerResponse r;+ while (peer->getResponse( r ))+ out.push_back( r );+ return out;+ }+ std::string sentType( size_t i ) const { return i < sent.size() ? sent[i].type() : std::string(); }++ /* Logged in as Tank, id 7, at 10.0.0.3, with the login's answers read and the sent lines cleared. */+ void login()+ {+ BuddyRequest req;+ memset( &req, 0, sizeof(req) );+ req.buddyRequestType = BuddyRequest::BUDDYREQUEST_LOGIN;+ strcpy( req.arg.login.email, "[email protected]" );+ strcpy( req.arg.login.password, "secret" );+ buddy->addRequest( req );+ feed( "{\"t\":\"auth.ok\",\"id\":7,\"nick\":\"Tank\",\"token\":\"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\",\"ticket\":\"00112233445566778899aabbccddeeff\"}" );+ feed( "{\"t\":\"relay.ok\",\"vip\":167772163}" );+ peerResponses();+ BuddyResponse b;+ while (buddy->getResponse( b )) {}+ sent.clear();+ }+};++TEST(online_adapter_login_waits_for_the_relay)+{+ AdapterRig rig;+ BuddyRequest req;+ memset( &req, 0, sizeof(req) );+ req.buddyRequestType = BuddyRequest::BUDDYREQUEST_LOGIN;+ strcpy( req.arg.login.nick, "Tank" );+ strcpy( req.arg.login.email, "[email protected]" );+ strcpy( req.arg.login.password, "secret" );+ rig.buddy->addRequest( req );++ CHECK_EQ( rig.sent.size(), (size_t)1 );+ CHECK_STR( rig.sentType( 0 ).c_str(), "login" );+ CHECK_STR( rig.sent[0].getString( "email" ).c_str(), "[email protected]" );+ CHECK_STR( rig.sent[0].getString( "pass" ).c_str(), "secret" );+ CHECK( rig.peer->isConnecting() );+ CHECK( !rig.peer->isConnected() );++ rig.feed( "{\"t\":\"auth.ok\",\"id\":7,\"nick\":\"Tank\",\"token\":\"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\",\"ticket\":\"00112233445566778899aabbccddeeff\"}" );+ BuddyResponse b;+ CHECK( rig.buddy->getResponse( b ) );+ CHECK_EQ( (int)b.buddyResponseType, (int)BuddyResponse::BUDDYRESPONSE_LOGIN );+ CHECK_EQ( b.profile, 7 );+ CHECK_EQ( rig.buddy->getLocalProfileID(), 7 );++ // the ticket is out for HELLO_AUTH, but the game's login waits for the relay's answer+ UnsignedByte ticket[16];+ CHECK( OnlineGetRelayTicket( ticket ) );+ CHECK_EQ( ticket[0], 0x00 );+ CHECK_EQ( ticket[1], 0x11 );+ CHECK_EQ( ticket[15], 0xff );+ CHECK_STR( OnlineGetSessionToken().str(), "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" );+ CHECK( rig.peerResponses().empty() );++ rig.feed( "{\"t\":\"relay.ok\",\"vip\":167772163}" );+ std::vector<PeerResponse> r = rig.peerResponses();+ CHECK_EQ( r.size(), (size_t)3 );+ if (r.size() == 3)+ {+ CHECK_EQ( (int)r[0].peerResponseType, (int)PeerResponse::PEERRESPONSE_LOGIN );+ CHECK_STR( r[0].nick.c_str(), "Tank" );+ CHECK_EQ( r[0].player.profileID, 7 );+ CHECK_EQ( r[0].player.internalIP, 0x0A000003u );+ CHECK_EQ( r[0].player.externalIP, 0x0A000003u );+ CHECK_EQ( (int)r[1].peerResponseType, (int)PeerResponse::PEERRESPONSE_GROUPROOM );+ CHECK_EQ( r[1].groupRoom.id, 1 );+ CHECK_EQ( (int)r[2].peerResponseType, (int)PeerResponse::PEERRESPONSE_GROUPROOM );+ CHECK_EQ( r[2].groupRoom.id, 0 ); // the end of the list+ }+ CHECK( rig.peer->isConnected() );+ CHECK_EQ( OnlineGetRelayVip(), 0x0A000003u );+ CHECK_STR( rig.sentType( 1 ).c_str(), "stats.get" ); // our own stats, as GameSpy's login read them+}++TEST(online_adapter_register_and_refusal)+{+ AdapterRig rig;+ BuddyRequest req;+ memset( &req, 0, sizeof(req) );+ req.buddyRequestType = BuddyRequest::BUDDYREQUEST_LOGINNEW;+ strcpy( req.arg.login.nick, "Tank" );+ strcpy( req.arg.login.email, "[email protected]" );+ strcpy( req.arg.login.password, "secret" );+ rig.buddy->addRequest( req );+ CHECK_EQ( rig.sent.size(), (size_t)1 );+ CHECK_STR( rig.sentType( 0 ).c_str(), "register" );+ CHECK_STR( rig.sent[0].getString( "nick" ).c_str(), "Tank" );+ CHECK_STR( rig.sent[0].getString( "email" ).c_str(), "[email protected]" );+ CHECK_STR( rig.sent[0].getString( "pass" ).c_str(), "secret" );++ rig.feed( "{\"t\":\"auth.fail\",\"code\":\"nicktaken\"}" );+ std::vector<PeerResponse> r = rig.peerResponses();+ CHECK_EQ( r.size(), (size_t)1 );+ if (r.size() == 1)+ {+ CHECK_EQ( (int)r[0].peerResponseType, (int)PeerResponse::PEERRESPONSE_DISCONNECT );+ CHECK_EQ( (int)r[0].discon.reason, (int)DISCONNECT_NICKTAKEN );+ }+ CHECK( !rig.peer->isConnecting() );+ UnsignedByte ticket[16];+ CHECK( !OnlineGetRelayTicket( ticket ) );++ // a resume with a saved token is the same login+ OnlineResume( "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" );+ CHECK_STR( rig.sentType( 1 ).c_str(), "resume" );+ CHECK_EQ( rig.sent[1].getString( "token" ).size(), (size_t)64 );+}++TEST(online_adapter_room_and_chat)+{+ AdapterRig rig;+ rig.login();++ PeerRequest join;+ join.peerRequestType = PeerRequest::PEERREQUEST_JOINGROUPROOM;+ join.groupRoom.id = 1;+ rig.peer->addRequest( join );+ CHECK_STR( rig.sentType( 0 ).c_str(), "room.join" );+ CHECK_STR( rig.sent[0].getString( "id" ).c_str(), "1" );++ rig.feed( "{\"t\":\"room\",\"id\":\"1\",\"ids\":[7,9],\"nicks\":[\"Tank\",\"Kim\"]}" );+ std::vector<PeerResponse> r = rig.peerResponses();+ CHECK_EQ( r.size(), (size_t)3 );+ if (r.size() == 3)+ {+ CHECK_EQ( (int)r[0].peerResponseType, (int)PeerResponse::PEERRESPONSE_JOINGROUPROOM );+ CHECK_EQ( r[0].joinGroupRoom.id, 1 );+ CHECK( r[0].joinGroupRoom.ok );+ CHECK_EQ( (int)r[2].peerResponseType, (int)PeerResponse::PEERRESPONSE_PLAYERJOIN );+ CHECK_STR( r[2].nick.c_str(), "Kim" );+ CHECK_EQ( r[2].player.profileID, 9 );+ CHECK_EQ( (int)r[2].player.roomType, (int)GroupRoom );+ }++ PeerRequest say;+ say.peerRequestType = PeerRequest::PEERREQUEST_MESSAGEROOM;+ say.text = WideCharString( u"merhaba " ) + (WideChar)0x011F; // g with breve: UTF-8 c4 9f+ say.message.isAction = FALSE;+ rig.peer->addRequest( say );+ CHECK_STR( rig.sentType( 1 ).c_str(), "say" );+ CHECK_STR( rig.sent[1].getString( "room" ).c_str(), "1" );+ CHECK_STR( rig.sent[1].getString( "text" ).c_str(), "merhaba \xc4\x9f" );++ rig.feed( "{\"t\":\"said\",\"room\":\"1\",\"from\":9,\"nick\":\"Kim\",\"text\":\"selam \xc4\x9f\",\"action\":0}" );+ rig.feed( "{\"t\":\"said\",\"room\":\"2\",\"from\":9,\"nick\":\"Kim\",\"text\":\"elsewhere\",\"action\":0}" );+ rig.feed( "{\"t\":\"said\",\"to\":\"Tank\",\"from\":9,\"nick\":\"Kim\",\"text\":\"psst\",\"action\":1}" );+ r = rig.peerResponses();+ CHECK_EQ( r.size(), (size_t)2 );+ if (r.size() == 2)+ {+ CHECK_EQ( (int)r[0].peerResponseType, (int)PeerResponse::PEERRESPONSE_MESSAGE );+ CHECK_STR( r[0].nick.c_str(), "Kim" );+ CHECK( r[0].text == WideCharString( u"selam " ) + (WideChar)0x011F );+ CHECK( !r[0].message.isPrivate );+ CHECK_EQ( r[0].message.profileID, 9 );+ CHECK( r[1].message.isPrivate );+ CHECK( r[1].message.isAction );+ }++ rig.feed( "{\"t\":\"player.left\",\"room\":\"1\",\"id\":9,\"nick\":\"Kim\"}" );+ r = rig.peerResponses();+ CHECK_EQ( r.size(), (size_t)1 );+ if (r.size() == 1)+ CHECK_EQ( (int)r[0].peerResponseType, (int)PeerResponse::PEERRESPONSE_PLAYERLEFT );+}++TEST(online_adapter_game_list_round_trips_the_host_options)+{+ AdapterRig rig;+ rig.login();++ // host: the CRCs given at creation travel in every game.opts+ PeerRequest create;+ create.peerRequestType = PeerRequest::PEERREQUEST_CREATESTAGINGROOM;+ create.text = u"fun game";+ create.stagingRoomCreation.exeCRC = 0x12345678;+ create.stagingRoomCreation.iniCRC = 0x9abcdef0;+ create.stagingRoomCreation.gameVersion = 3;+ create.stagingRoomCreation.allowObservers = TRUE;+ create.stagingRoomCreation.useStats = TRUE;+ create.stagingRoomCreation.ladPort = 0;+ create.stagingRoomCreation.restrictGameList = FALSE;+ rig.peer->addRequest( create );+ CHECK_STR( rig.sentType( 0 ).c_str(), "game.host" );+ CHECK_STR( rig.sent[0].getString( "name" ).c_str(), "fun game" );++ rig.feed( "{\"t\":\"game.joined\",\"action\":\"joined\",\"id\":6,\"name\":\"fun game\",\"map\":\"-\",\"maxp\":8,\"host\":\"Tank\",\"hostId\":7,\"count\":1,\"opts\":\"\",\"ids\":[7],\"nicks\":[\"Tank\"]}" );+ std::vector<PeerResponse> r = rig.peerResponses();+ CHECK_EQ( r.size(), (size_t)1 );+ if (r.size() == 1)+ {+ CHECK_EQ( (int)r[0].peerResponseType, (int)PeerResponse::PEERRESPONSE_CREATESTAGINGROOM );+ CHECK_EQ( r[0].createStagingRoom.result, (Int)PEERJoinSuccess );+ }++ PeerRequest opts;+ opts.peerRequestType = PeerRequest::PEERREQUEST_SETGAMEOPTIONS;+ opts.options = "M=maps/a.map;S=Tank,0,0";+ opts.gameOptsMapName = "maps/a/a.map";+ opts.gameOptsPlayerNames[0] = "Tank";+ for (Int i = 0; i < MAX_SLOTS; ++i)+ {+ opts.gameOptions.wins[i] = opts.gameOptions.losses[i] = opts.gameOptions.profileID[i] = 0;+ opts.gameOptions.faction[i] = opts.gameOptions.color[i] = 0;+ }+ opts.gameOptions.wins[0] = 4;+ opts.gameOptions.numPlayers = 1;+ opts.gameOptions.numObservers = 0;+ opts.gameOptions.maxPlayers = 2;+ rig.peer->addRequest( opts );+ CHECK_STR( rig.sentType( 1 ).c_str(), "game.opts" );+ CHECK_STR( rig.sentType( 2 ).c_str(), "utm" );+ CHECK_STR( rig.sent[2].getString( "room" ).c_str(), "6" );+ CHECK_STR( rig.sent[2].getString( "cmd" ).c_str(), "SL/" );+ CHECK_STR( rig.sent[2].getString( "opts" ).c_str(), "M=maps/a.map;S=Tank,0,0" );++ // the list as another player sees it, from the server's game line carrying those opts+ OnlineMessage game;+ game.setString( "t", "game" ).setString( "action", "add" ).setInt( "id", 6 ).setString( "name", "fun game" );+ game.setString( "map", "-" ).setInt( "maxp", 8 ).setString( "host", "Tank" ).setInt( "hostId", 7 ).setInt( "count", 1 );+ game.setString( "opts", rig.sent.size() > 1 ? rig.sent[1].getString( "opts" ) : std::string() );++ PeerRequest list;+ list.peerRequestType = PeerRequest::PEERREQUEST_STARTGAMELIST;+ list.gameList.restrictGameList = FALSE;+ rig.peer->addRequest( list );+ CHECK_STR( rig.sentType( 3 ).c_str(), "games.watch" );+ rig.feed( game );+ r = rig.peerResponses();+ CHECK_EQ( r.size(), (size_t)3 );+ if (r.size() == 3)+ {+ CHECK_EQ( (int)r[0].peerResponseType, (int)PeerResponse::PEERRESPONSE_STAGINGROOM );+ CHECK_EQ( r[0].stagingRoom.action, PEER_CLEAR );+ CHECK_EQ( (int)r[1].peerResponseType, (int)PeerResponse::PEERRESPONSE_STAGINGROOMLISTCOMPLETE );+ CHECK_EQ( r[2].stagingRoom.action, PEER_ADD );+ CHECK_EQ( r[2].stagingRoom.id, 6 );+ CHECK( r[2].stagingServerName == WideCharString( u"fun game" ) );+ CHECK_EQ( r[2].stagingRoom.exeCRC, 0x12345678u );+ CHECK_EQ( r[2].stagingRoom.iniCRC, 0x9abcdef0u );+ CHECK_EQ( r[2].stagingRoom.version, 3u );+ CHECK( r[2].stagingRoom.allowObservers );+ CHECK_STR( r[2].stagingRoomMapName.c_str(), "maps/a/a.map" );+ CHECK_STR( r[2].stagingRoomPlayerNames[0].c_str(), "Tank" );+ CHECK_EQ( r[2].stagingRoom.wins[0], 4 );+ CHECK_EQ( r[2].stagingRoom.maxPlayers, 2 );+ }+}++TEST(online_adapter_join_utm_and_start)+{+ AdapterRig rig;+ rig.login();++ PeerRequest join;+ join.peerRequestType = PeerRequest::PEERREQUEST_JOINSTAGINGROOM;+ join.stagingRoom.id = 5;+ rig.peer->addRequest( join );+ CHECK_STR( rig.sentType( 0 ).c_str(), "game.join" );+ CHECK_EQ( rig.sent[0].getInt( "id" ), 5 );++ rig.feed( "{\"t\":\"game.joined\",\"action\":\"joined\",\"id\":5,\"name\":\"g\",\"map\":\"-\",\"maxp\":8,\"host\":\"Kim\",\"hostId\":9,\"count\":2,\"opts\":\"\",\"ids\":[9,7],\"nicks\":[\"Kim\",\"Tank\"]}" );+ std::vector<PeerResponse> r = rig.peerResponses();+ CHECK_EQ( r.size(), (size_t)1 );+ if (r.size() == 1)+ {+ CHECK_EQ( (int)r[0].peerResponseType, (int)PeerResponse::PEERRESPONSE_JOINSTAGINGROOM );+ CHECK( r[0].joinStagingRoom.ok );+ CHECK_EQ( r[0].joinStagingRoom.id, 5 );+ CHECK( r[0].joinStagingRoom.isHostPresent );+ CHECK_STR( r[0].stagingRoomPlayerNames[0].c_str(), "Kim" );+ CHECK_STR( r[0].stagingRoomPlayerNames[1].c_str(), "Tank" );+ }+ CHECK_STR( rig.sentType( 1 ).c_str(), "stats.get" ); // the host's stats, as GameSpy's join read them+ CHECK_EQ( rig.sent[1].getInt( "id" ), 9 );++ rig.feed( "{\"t\":\"utm\",\"from\":9,\"nick\":\"Kim\",\"cmd\":\"SL/\",\"opts\":\"M=maps/a.map\",\"room\":\"5\"}" );+ rig.feed( "{\"t\":\"utm\",\"from\":9,\"nick\":\"Kim\",\"cmd\":\"KICK/\",\"opts\":\"GameFull\",\"to\":\"Tank\"}" );+ rig.feed( "{\"t\":\"utm\",\"from\":9,\"nick\":\"Kim\",\"cmd\":\"X\",\"opts\":\"\",\"room\":\"1\"}" ); // a chat room's: dropped+ r = rig.peerResponses();+ CHECK_EQ( r.size(), (size_t)2 );+ if (r.size() == 2)+ {+ CHECK_EQ( (int)r[0].peerResponseType, (int)PeerResponse::PEERRESPONSE_ROOMUTM );+ CHECK_STR( r[0].nick.c_str(), "Kim" );+ CHECK_STR( r[0].command.c_str(), "SL/" );+ CHECK_STR( r[0].commandOptions.c_str(), "M=maps/a.map" );+ CHECK_EQ( (int)r[1].peerResponseType, (int)PeerResponse::PEERRESPONSE_PLAYERUTM );+ CHECK_STR( r[1].command.c_str(), "KICK/" );+ }++ PeerRequest utm;+ utm.peerRequestType = PeerRequest::PEERREQUEST_UTMPLAYER;+ utm.nick = "Kim";+ utm.id = "REQ/";+ utm.options = "accept";+ rig.peer->addRequest( utm );+ CHECK_STR( rig.sentType( 2 ).c_str(), "utm" );+ CHECK_STR( rig.sent[2].getString( "to" ).c_str(), "Kim" );+ CHECK_STR( rig.sent[2].getString( "cmd" ).c_str(), "REQ/" );++ // the server removes a started game from the list before it says game.start: no "host left"+ rig.feed( "{\"t\":\"game\",\"action\":\"remove\",\"id\":5}" );+ rig.feed( "{\"t\":\"game.start\",\"match\":\"m1\",\"ids\":[9,7],\"nicks\":[\"Kim\",\"Tank\"],\"vips\":[167772162,167772163]}" );+ r = rig.peerResponses();+ CHECK_EQ( r.size(), (size_t)2 );+ if (r.size() == 2)+ {+ CHECK_EQ( (int)r[0].peerResponseType, (int)PeerResponse::PEERRESPONSE_STAGINGROOM );+ CHECK_EQ( r[0].stagingRoom.action, PEER_REMOVE );+ CHECK_EQ( (int)r[1].peerResponseType, (int)PeerResponse::PEERRESPONSE_GAMESTART );+ }+ CHECK_STR( OnlineSession::get().matchId.c_str(), "m1" );+}++TEST(online_adapter_host_leaving_reads_as_player_left)+{+ AdapterRig rig;+ rig.login();+ PeerRequest join;+ join.peerRequestType = PeerRequest::PEERREQUEST_JOINSTAGINGROOM;+ join.stagingRoom.id = 5;+ rig.peer->addRequest( join );+ rig.feed( "{\"t\":\"game.joined\",\"action\":\"joined\",\"id\":5,\"name\":\"g\",\"map\":\"-\",\"maxp\":8,\"host\":\"Kim\",\"hostId\":9,\"count\":2,\"opts\":\"\",\"ids\":[9,7],\"nicks\":[\"Kim\",\"Tank\"]}" );+ rig.peerResponses();++ rig.feed( "{\"t\":\"game\",\"action\":\"remove\",\"id\":5}" );+ std::vector<PeerResponse> r = rig.peerResponses();+ CHECK_EQ( r.size(), (size_t)2 );+ if (r.size() == 2)+ {+ CHECK_EQ( r[0].stagingRoom.action, PEER_REMOVE );+ CHECK_EQ( (int)r[1].peerResponseType, (int)PeerResponse::PEERRESPONSE_PLAYERLEFT );+ CHECK_STR( r[1].nick.c_str(), "Kim" );+ CHECK_EQ( (int)r[1].player.roomType, (int)StagingRoom );+ }+}++TEST(online_adapter_quick_match)+{+ AdapterRig rig;+ rig.login();++ PeerRequest qm;+ qm.peerRequestType = PeerRequest::PEERREQUEST_STARTQUICKMATCH;+ qm.qmMaps.push_back( true );+ qm.qmMaps.push_back( false );+ qm.qmMaps.push_back( true );+ qm.QM.side = 2;+ qm.QM.color = 3;+ rig.peer->addRequest( qm );+ CHECK_STR( rig.sentType( 0 ).c_str(), "qm.join" );+ if (!rig.sent.empty())+ {+ const std::vector<long long> maps = rig.sent[0].getInts( "maps" );+ CHECK_EQ( maps.size(), (size_t)2 );+ CHECK( maps.size() == 2 && maps[0] == 0 && maps[1] == 2 );+ CHECK_EQ( rig.sent[0].getInt( "side" ), 2 );+ CHECK_EQ( rig.sent[0].getInt( "color" ), 3 );+ }++ rig.feed( "{\"t\":\"qm.status\",\"status\":\"searching\",\"pool\":4}" );+ PeerRequest widen;+ widen.peerRequestType = PeerRequest::PEERREQUEST_WIDENQUICKMATCHSEARCH;+ rig.peer->addRequest( widen );+ CHECK_STR( rig.sentType( 1 ).c_str(), "qm.widen" );+ rig.feed( "{\"t\":\"qm.matched\",\"match\":\"q1\",\"seed\":77,\"mapIdx\":1,\"nicks\":[\"Tank\",\"Kim\"],\"ids\":[7,9],\"vips\":[167772163,167772162],\"sides\":[2,-1],\"colors\":[3,-1]}" );++ std::vector<PeerResponse> r = rig.peerResponses();+ CHECK_EQ( r.size(), (size_t)3 );+ if (r.size() == 3)+ {+ CHECK_EQ( (int)r[0].qmStatus.status, (int)QM_WORKING );+ CHECK_EQ( r[0].qmStatus.poolSize, 4 );+ CHECK_EQ( (int)r[1].qmStatus.status, (int)QM_WIDENINGSEARCH );+ CHECK_EQ( (int)r[2].peerResponseType, (int)PeerResponse::PEERRESPONSE_QUICKMATCHSTATUS );+ CHECK_EQ( (int)r[2].qmStatus.status, (int)QM_MATCHED );+ CHECK_EQ( r[2].qmStatus.seed, 77 );+ CHECK_EQ( r[2].qmStatus.mapIdx, 1 );+ CHECK_STR( r[2].stagingRoomPlayerNames[0].c_str(), "Tank" );+ CHECK_STR( r[2].stagingRoomPlayerNames[1].c_str(), "Kim" );+ CHECK( r[2].stagingRoomPlayerNames[2].empty() );+ CHECK_EQ( r[2].qmStatus.IP[1], 0x0A000002u );+ CHECK_EQ( r[2].qmStatus.side[0], 2 );+ CHECK_EQ( r[2].qmStatus.color[1], -1 );+ CHECK_EQ( r[2].qmStatus.nat[0], 1 );+ }+ CHECK_STR( OnlineSession::get().matchId.c_str(), "q1" );+}++TEST(online_adapter_stats_read_and_writes_dropped)+{+ AdapterRig rig;+ rig.login();++ PSRequest read;+ read.requestType = PSRequest::PSREQUEST_READPLAYERSTATS;+ read.player.id = 9;+ rig.ps->addRequest( read );+ PSRequest write;+ write.requestType = PSRequest::PSREQUEST_UPDATEPLAYERSTATS;+ write.player.id = 7;+ write.player.wins[3] = 1000;+ rig.ps->addRequest( write );+ CHECK_EQ( rig.sent.size(), (size_t)1 ); // the write never leaves+ CHECK_STR( rig.sentType( 0 ).c_str(), "stats.get" );+ CHECK_EQ( rig.sent[0].getInt( "id" ), 9 );++ rig.feed( "{\"t\":\"stats\",\"id\":9,\"kv\":\"\\\\nick\\\\Kim\\\\wins\\\\5\\\\losses\\\\2\\\\games\\\\7\\\\rating\\\\31\"}" );+ PSResponse resp;+ CHECK( rig.ps->getResponse( resp ) );+ CHECK_EQ( (int)resp.responseType, (int)PSResponse::PSRESPONSE_PLAYERSTATS );+ CHECK_EQ( resp.player.id, 9 );+ CHECK_EQ( (int)resp.player.wins[0], 5 );+ CHECK_EQ( (int)resp.player.losses[0], 2 );+ CHECK_EQ( (int)resp.player.games[0], 7 );+ CHECK_EQ( (int)rig.ps->findPlayerStatsByID( 9 ).wins[0], 5 );+ CHECK_EQ( rig.ps->findPlayerStatsByID( 12 ).id, 0 );+}++TEST(online_adapter_report_goes_once_a_match)+{+ AdapterRig rig;+ rig.login();++ OnlineReport report;+ report.seed = 77;+ report.endFrame = 9000;+ report.duration = 9000;+ report.winningTeam = 1;+ report.sawGameEnd = TRUE;+ report.surrendered = TRUE;+ report.numPlayers = 2;+ report.side[0] = "America";+ report.side[1] = "China";+ report.discon[1] = TRUE;++ OnlineSendReport( report );+ CHECK( rig.sent.empty() ); // no match yet++ rig.feed( "{\"t\":\"qm.matched\",\"match\":\"q1\",\"seed\":77,\"mapIdx\":0,\"nicks\":[\"Tank\",\"Kim\"],\"ids\":[7,9],\"vips\":[1,2],\"sides\":[0,0],\"colors\":[0,1]}" );+ OnlineSendReport( report );+ OnlineSendReport( report ); // the score screen's second call+ CHECK_EQ( rig.sent.size(), (size_t)1 );+ if (rig.sent.size() == 1)+ {+ const OnlineMessage &m = rig.sent[0];+ CHECK_STR( m.type().c_str(), "report" );+ CHECK_STR( m.getString( "match" ).c_str(), "q1" );+ CHECK_EQ( m.getInt( "seed" ), 77 );+ CHECK_EQ( m.getInt( "endFrame" ), 9000 );+ CHECK_EQ( m.getInt( "winningTeam" ), 1 );+ CHECK( m.getBool( "surrendered" ) );+ CHECK( !m.getBool( "sawDesync" ) );+ CHECK( m.getInts( "discon" ).size() == 2 && m.getInts( "discon" )[1] == 1 );+ CHECK( m.getStrings( "side" ).size() == 2 && m.getStrings( "side" )[1] == "China" );+ }++ // the next match reports again+ rig.feed( "{\"t\":\"game.start\",\"match\":\"m2\",\"ids\":[7,9],\"nicks\":[\"Tank\",\"Kim\"],\"vips\":[1,2]}" );+ OnlineSendReport( report );+ CHECK_EQ( rig.sent.size(), (size_t)2 );+}