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
fix(gamenetwork): refuse hostile packets, carry selections over 254 units
Olcay Seygand4f1d96fd979
diff --git a/GeneralsMD/Code/GameEngine/Include/GameNetwork/NetCommandWrapperList.h b/GeneralsMD/Code/GameEngine/Include/GameNetwork/NetCommandWrapperList.hindex c650a3203..5142d5992 100644--- a/GeneralsMD/Code/GameEngine/Include/GameNetwork/NetCommandWrapperList.h+++ b/GeneralsMD/Code/GameEngine/Include/GameNetwork/NetCommandWrapperList.h@@ -41,6 +41,7 @@ public:Bool isComplete();UnsignedShort getCommandID();+ UnsignedByte getPlayerID() const { return m_playerID; }UnsignedInt getRawDataLength();void copyChunkData(NetWrapperCommandMsg *msg);UnsignedByte * getRawData();@@ -51,6 +52,7 @@ public:protected:UnsignedShort m_commandID;+ UnsignedByte m_playerID; ///< who is sending it; two senders' command ids are separate countersUnsignedByte *m_data;UnsignedInt m_dataLength;Bool *m_chunksPresent;@@ -76,6 +78,7 @@ public:protected:void removeFromList(NetCommandWrapperListNode *node);+ Bool isWithinSenderCap(NetWrapperCommandMsg *msg);NetCommandWrapperListNode *m_list;};diff --git a/GeneralsMD/Code/GameEngine/Include/GameNetwork/NetPacket.h b/GeneralsMD/Code/GameEngine/Include/GameNetwork/NetPacket.hindex 4cf40925c..67d9472d8 100644--- a/GeneralsMD/Code/GameEngine/Include/GameNetwork/NetPacket.h+++ b/GeneralsMD/Code/GameEngine/Include/GameNetwork/NetPacket.h@@ -66,7 +66,7 @@ public:NetCommandList *getCommandList();- static NetCommandRef * ConstructNetCommandMsgFromRawData(UnsignedByte *data, UnsignedShort dataLength);+ static NetCommandRef * ConstructNetCommandMsgFromRawData(UnsignedByte *data, UnsignedInt dataLength);static NetPacketList ConstructBigCommandPacketList(NetCommandRef *ref);UnsignedByte *getData();diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cppindex 9db433047..069b1cebd 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp@@ -4295,8 +4295,8 @@ void Player::processCreateTeamGameMessage(Int hotkeyNum, GameMessage *msg) {m_squads[hotkeyNum]->clearSquad();- UnsignedByte numArgs = msg->getArgumentCount();- for (UnsignedByte i = 0; i < numArgs; ++i) {+ Int numArgs = msg->getArgumentCount();+ for (Int i = 0; i < numArgs; ++i) {ObjectID objID = msg->getArgument(i)->objectID;Object *obj = TheGameLogic->findObjectByID(objID);if (obj != NULL) {diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/ConnectionManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/ConnectionManager.cppindex dc3a6e84a..2ef137ed1 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/ConnectionManager.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/ConnectionManager.cpp@@ -732,6 +732,19 @@ void ConnectionManager::processFile(NetFileCommandMsg *msg)AsciiString realFileName = msg->getRealFilename();+ // Only the host sends map files, and only after announcing each one to the players who need it+ // (FileTransfer.cpp). A file nobody announced, under another name, or for somebody else, is a+ // peer writing to our disk on its own say-so.+ FileCommandMap::iterator announced = s_fileCommandMap.find(msg->getID());+ FileMaskMap::iterator recipients = s_fileRecipientMaskMap.find(msg->getID());+ if (msg->getPlayerID() != 0 || announced == s_fileCommandMap.end() || announced->second != realFileName ||+ recipients == s_fileRecipientMaskMap.end() || (recipients->second & (1 << m_localSlot)) == 0)+ {+ DEBUG_LOG(("ConnectionManager::processFile - '%s' from player %d was never announced to us, dropped\n",+ realFileName.str(), msg->getPlayerID()));+ return;+ }+if (!IsSafeTransferPath(msg->getPortableFilename()) || !IsSafeTransferPath(realFileName)){DEBUG_LOG(("ConnectionManager::processFile - refused '%s'\n", realFileName.str()));@@ -832,6 +845,12 @@ void ConnectionManager::processFile(NetFileCommandMsg *msg)void ConnectionManager::processFileAnnounce(NetFileAnnounceCommandMsg *msg){DEBUG_LOG(("ConnectionManager::processFileAnnounce() - expecting '%s' (%s) in command %d\n", msg->getPortableFilename().str(), msg->getRealFilename().str(), msg->getFileID()));+ // the host (slot 0) is the one who transfers maps; an announce from anyone else would let+ // processFile accept a file the host never sent+ if (msg->getPlayerID() != 0) {+ DEBUG_LOG(("ConnectionManager::processFileAnnounce() - player %d is not the host, ignored\n", msg->getPlayerID()));+ return;+ }s_fileCommandMap[msg->getFileID()] = msg->getRealFilename();s_fileRecipientMaskMap[msg->getFileID()] = msg->getPlayerMask();for (Int i=0; i<MAX_SLOTS; ++i)diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameMessageParser.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameMessageParser.cppindex 45dc9f5e3..4e64b4c7f 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameMessageParser.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameMessageParser.cpp@@ -40,13 +40,18 @@ GameMessageParser::GameMessageParser(GameMessage *msg)m_first = NULL;m_argTypeCount = 0;- UnsignedByte argCount = msg->getArgumentCount();+ Int argCount = msg->getArgumentCount();GameMessageArgumentDataType lasttype = ARGUMENTDATATYPE_UNKNOWN;Int thisTypeCount = 0;- for (UnsignedByte i = 0; i < argCount; ++i) {+ // The packet and the replay both write each run's count in one byte, so a run of more than+ // 255 arguments of one type (a big selection is one ObjectID per unit) is cut into runs of+ // 255. Readers already walk the runs one after another, so the bytes on the wire keep+ // their old meaning and old replays still read.+ const Int MAX_RUN = 255;+ for (Int i = 0; i < argCount; ++i) {GameMessageArgumentDataType type = msg->getArgumentDataType(i);- if (type != lasttype) {+ if (type != lasttype || thisTypeCount == MAX_RUN) {if (thisTypeCount > 0) {addArgType(lasttype, thisTypeCount);++m_argTypeCount;diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/Chat.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/Chat.cppindex bc629d67a..e39f77dcb 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/Chat.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/Chat.cpp@@ -320,7 +320,9 @@ Int GameSpyInfo::addText( UnicodeString message, Color c, GameWindow *win )static AudioEventRTS messageFromChatSound("GUIMessageReceived");TheAudio->addAudioEvent(&messageFromChatSound);- TheInGameUI->message(message);+ // another player's words, so they are an argument and never the format: a "%s" in chat+ // would have read a pointer that was never passed+ TheInGameUI->message(UnicodeString(u"%ls"), message.str());}if (!win)diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPI.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPI.cppindex f32a5e030..9a4bf904b 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPI.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPI.cpp@@ -334,6 +334,61 @@ void LANAPI::checkMOTD( void )#endif}+/* A LAN message is a fixed struct read straight out of a datagram, and every string in it a fixed+ array that the sender is trusted to terminate. Anyone on the network can send one, so zero what+ the datagram did not carry and cut each string this type uses at its last character: a short or+ hostile message then reads as short text instead of running off the end of its array. The+ union's arms overlap, so only the arm the type names is touched. */+static void terminateLANMessageStrings( LANMessage *msg, Int length )+{+ if (length < (Int)sizeof(LANMessage))+ memset((char *)msg + length, 0, sizeof(LANMessage) - length);++ msg->name[g_lanPlayerNameLength] = 0;+ msg->userName[g_lanLoginNameLength] = 0;+ msg->hostName[g_lanHostNameLength] = 0;++ switch (msg->LANMessageType)+ {+ case LANMessage::MSG_GAME_ANNOUNCE:+ msg->GameInfo.gameName[g_lanGameNameLength] = 0;+ msg->GameInfo.options[m_lanMaxOptionsLength] = 0;+ break;+ case LANMessage::MSG_REQUEST_GAME_LEAVE:+ msg->GameToLeave.gameName[g_lanGameNameLength] = 0;+ break;+ case LANMessage::MSG_REQUEST_GAME_INFO:+ msg->PlayerInfo.playerName[g_lanPlayerNameLength] = 0;+ break;+ case LANMessage::MSG_REQUEST_JOIN:+ msg->GameToJoin.modNamePad = 0; // ends the serial, which has no room of its own for it+ msg->GameToJoin.modName[g_lanModNameLength] = 0;+ break;+ case LANMessage::MSG_JOIN_ACCEPT:+ msg->GameJoined.gameName[g_lanGameNameLength] = 0;+ break;+ case LANMessage::MSG_JOIN_DENY:+ msg->GameNotJoined.gameName[g_lanGameNameLength] = 0;+ msg->GameNotJoined.modName[g_lanModNameLength] = 0;+ break;+ case LANMessage::MSG_SET_ACCEPT:+ msg->Accept.gameName[g_lanGameNameLength] = 0;+ break;+ case LANMessage::MSG_MAP_AVAILABILITY:+ msg->MapStatus.gameName[g_lanGameNameLength] = 0;+ break;+ case LANMessage::MSG_CHAT:+ msg->Chat.gameName[g_lanGameNameLength] = 0;+ msg->Chat.message[g_lanMaxChatLength] = 0;+ break;+ case LANMessage::MSG_GAME_OPTIONS:+ msg->GameOptions.options[m_lanMaxOptionsLength] = 0;+ break;+ default:+ break;+ }+}+extern Bool LANbuttonPushed;extern Bool LANSocketErrorDetected;void LANAPI::update( void )@@ -377,6 +432,7 @@ void LANAPI::update( void )}LANMessage *msg = (LANMessage *)(m_transport->m_inBuffer[i].data);+ terminateLANMessageStrings(msg, m_transport->m_inBuffer[i].length);//DEBUG_LOG(("LAN message type %s from %ls (%s@%s)\n", GetMessageTypeString(msg->LANMessageType).str(),// msg->name, msg->userName, msg->hostName));switch (msg->LANMessageType)diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPIhandlers.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPIhandlers.cppindex 25b7d8612..2900387c6 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPIhandlers.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPIhandlers.cpp@@ -145,6 +145,14 @@ void LANAPI::handleGameAnnounce( LANMessage *msg, UnsignedInt senderIP )else{LANGameInfo *game = LookupGame(UnicodeString(msg->GameInfo.gameName));+ // Games are listed by name, so an announce under a name already listed used to rewrite that+ // game, or remove it when the options did not parse, whoever sent it. Only its host may.+ if (game && game->getIP(0) != senderIP)+ {+ DEBUG_LOG(("LANAPI::handleGameAnnounce - 0x%08x announced game '%s' hosted by 0x%08x, ignored\n",+ senderIP, WideCharAsUtf8( msg->GameInfo.gameName ).str(), game->getIP(0)));+ return;+ }if (!game){game = NEW LANGameInfo;@@ -416,10 +424,22 @@ void LANAPI::handleJoinAccept( LANMessage *msg, UnsignedInt senderIP ){if (msg->GameJoined.playerIP == m_localIP) // Is it for us?{+ // The slot is the sender's number and indexes our slot array, and the accept has to come from+ // the game's own host; anyone else could seat us in a game, or past the end of one. A direct+ // connect host behind a router lists his inside address, so the address we dialled counts too.+ LANGameInfo *joined = LookupGame(UnicodeString(msg->GameJoined.gameName));+ const Int pos = msg->GameJoined.slotPosition;+ const Bool fromHost = joined && (joined->getIP(0) == senderIP || senderIP == m_directConnectRemoteIP);+ if (joined && (!fromHost || pos <= 0 || pos >= MAX_SLOTS))+ {+ DEBUG_LOG(("LANAPI::handleJoinAccept - accept from 0x%08x for slot %d is not the host's, ignored\n", senderIP, pos));+ return;+ }+if (m_pendingAction == ACT_JOIN) // Are we trying to join?{- m_currentGame = LookupGame(UnicodeString(msg->GameJoined.gameName));-+ m_currentGame = joined;+if (!m_currentGame){DEBUG_ASSERTCRASH(false, ("Could not find game to join!"));@@ -540,7 +560,8 @@ void LANAPI::handleRequestGameLeave( LANMessage *msg, UnsignedInt senderIP )LANGameInfo *game = m_games;while (game){- if (game->getName().compare(msg->GameToLeave.gameName) == 0)+ // only the host closing his own game takes it off the list, not anyone who names it+ if (game->getName().compare(msg->GameToLeave.gameName) == 0 && game->getIP(0) == senderIP){removeGame(game);delete game;diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/NetCommandWrapperList.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/NetCommandWrapperList.cppindex 5c7bfd85f..2e050cc8c 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/NetCommandWrapperList.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/NetCommandWrapperList.cpp@@ -55,6 +55,7 @@ NetCommandWrapperListNode::NetCommandWrapperListNode(NetWrapperCommandMsg *msg)m_data = NEW UnsignedByte[m_dataLength]; // pool[]ifym_commandID = msg->getWrappedCommandID();+ m_playerID = msg->getPlayerID();}NetCommandWrapperListNode::~NetCommandWrapperListNode() {@@ -188,15 +189,54 @@ Int NetCommandWrapperList::getPercentComplete(UnsignedShort wrappedCommandID)return temp->getPercentComplete();}+// The first chunk of a wrapped command makes us allocate the whole command's buffer at once, at a+// size the sender names, and an unfinished command is never let go. So one peer could make us+// hold any amount of memory by opening commands it never completes. A sender gets this many open+// at a time and this many bytes across them. A 65 KB map transfer is one command; normal play+// never comes near either figure.+static const Int MAX_WRAPPED_COMMANDS_PER_SENDER = 64;+static const UnsignedInt MAX_WRAPPED_BYTES_PER_SENDER = 16 * 1024 * 1024;++Bool NetCommandWrapperList::isWithinSenderCap(NetWrapperCommandMsg *msg) {+ const UnsignedInt totalLength = msg->getTotalDataLength();+ const UnsignedInt numChunks = msg->getNumChunks();++ // every chunk carries at least one byte, and an empty command has nothing to rebuild+ if (numChunks == 0 || totalLength == 0 || numChunks > totalLength || totalLength > MAX_WRAPPED_BYTES_PER_SENDER) {+ DEBUG_LOG(("NetCommandWrapperList - refused a wrapped command of %u bytes in %u chunks from player %d\n",+ totalLength, numChunks, msg->getPlayerID()));+ return FALSE;+ }++ Int openCommands = 0;+ UnsignedInt openBytes = 0;+ for (NetCommandWrapperListNode *node = m_list; node != NULL; node = node->m_next) {+ if (node->getPlayerID() == msg->getPlayerID()) {+ ++openCommands;+ openBytes += node->getRawDataLength();+ }+ }++ if (openCommands >= MAX_WRAPPED_COMMANDS_PER_SENDER || totalLength > MAX_WRAPPED_BYTES_PER_SENDER - openBytes) {+ DEBUG_LOG(("NetCommandWrapperList - player %d already has %d wrapped commands of %u bytes open, refused one more of %u\n",+ msg->getPlayerID(), openCommands, openBytes, totalLength));+ return FALSE;+ }+ return TRUE;+}+void NetCommandWrapperList::processWrapper(NetCommandRef *ref) {NetCommandWrapperListNode *temp = m_list;NetWrapperCommandMsg *msg = (NetWrapperCommandMsg *)(ref->getCommand());- while ((temp != NULL) && (temp->getCommandID() != msg->getWrappedCommandID())) {+ while ((temp != NULL) && ((temp->getCommandID() != msg->getWrappedCommandID()) || (temp->getPlayerID() != msg->getPlayerID()))) {temp = temp->m_next;}if (temp == NULL) {+ if (!isWithinSenderCap(msg)) {+ return;+ }temp = newInstance(NetCommandWrapperListNode)(msg);temp->m_next = m_list;m_list = temp;@@ -217,11 +257,21 @@ NetCommandList * NetCommandWrapperList::getReadyCommands()next = temp->m_next;if (temp->isComplete()) {NetCommandRef *msg = NetPacket::ConstructNetCommandMsgFromRawData(temp->getRawData(), temp->getRawDataLength());- NetCommandRef *ret = retlist->addMessage(msg->getCommand());- ret->setRelay(msg->getRelay());-- msg->deleteInstance();- msg = NULL;+ // NULL when the rebuilt bytes do not read as a command; the sender's problem, not ours. And+ // the chunks carry their sender, so the command inside cannot claim to be somebody else's.+ if (msg != NULL && msg->getCommand()->getPlayerID() != temp->getPlayerID()) {+ DEBUG_LOG(("NetCommandWrapperList - player %d wrapped a command from player %d, dropped\n",+ temp->getPlayerID(), msg->getCommand()->getPlayerID()));+ msg->deleteInstance();+ msg = NULL;+ }+ if (msg != NULL) {+ NetCommandRef *ret = retlist->addMessage(msg->getCommand());+ ret->setRelay(msg->getRelay());++ msg->deleteInstance();+ msg = NULL;+ }removeFromList(temp);temp = NULL;@@ -240,7 +290,7 @@ void NetCommandWrapperList::removeFromList(NetCommandWrapperListNode *node) {NetCommandWrapperListNode *temp = m_list;NetCommandWrapperListNode *prev = NULL;- while ((temp != NULL) && (temp->getCommandID() != node->getCommandID())) {+ while ((temp != NULL) && (temp != node)) {prev = temp;temp = temp->m_next;}diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/NetPacket.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/NetPacket.cppindex eb0b1786d..b1edc5781 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/NetPacket.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/NetPacket.cpp@@ -71,10 +71,78 @@ static UnsignedByte usableChatTextLength(const UnicodeString &text)return (UnsignedByte)((len > MAX_CHAT_TEXT_LENGTH) ? MAX_CHAT_TEXT_LENGTH : len);}+// Every byte the readers below take came from another machine, and EA's readers trusted each+// length and count they found, so a short or lying packet was read out of whatever memory followed+// it. The two entry points (getCommandList and ConstructNetCommandMsgFromRawData) set how far the+// data reaches; a field that would cross that end is not read, and the read is marked bad, which+// makes the entry point throw the command away. Reading happens on the network update only, one+// packet at a time.+static Int s_readEnd = 0;+static Bool s_readBad = FALSE;++static void beginRead(Int dataLength)+{+ s_readEnd = dataLength;+ s_readBad = FALSE;+}++static Bool canRead(Int i, size_t size)+{+ if (s_readBad || i < 0 || i > s_readEnd || size > (size_t)(s_readEnd - i))+ s_readBad = TRUE;+ return !s_readBad;+}++// copies size bytes at i into dest and steps over them; dest keeps what it held when they are not there+static void readBytes(void *dest, const UnsignedByte *data, Int &i, size_t size)+{+ if (!canRead(i, size))+ return;+ memcpy(dest, data + i, size);+ i += (Int)size;+}++// A terminated string at i, whose terminator is inside the data.+static Bool canReadString(const UnsignedByte *data, Int i)+{+ if (!canRead(i, 1))+ return FALSE;+ if (memchr(data + i, 0, s_readEnd - i) == NULL)+ s_readBad = TRUE;+ return !s_readBad;+}++// The slot numbers a command names index arrays of MAX_SLOTS, and shift a byte mask, wherever it+// is handled. One out of range is a forged command; refuse it here, before any of them sees it.+static Bool namesValidSlots(NetCommandMsg *msg)+{+ if (msg->getPlayerID() >= (UnsignedInt)MAX_SLOTS)+ return FALSE;+ switch (msg->getNetCommandType())+ {+ case NETCOMMANDTYPE_ACKSTAGE1:+ return ((NetAckStage1CommandMsg *)msg)->getOriginalPlayerID() < MAX_SLOTS;+ case NETCOMMANDTYPE_ACKSTAGE2:+ return ((NetAckStage2CommandMsg *)msg)->getOriginalPlayerID() < MAX_SLOTS;+ case NETCOMMANDTYPE_ACKBOTH:+ return ((NetAckBothCommandMsg *)msg)->getOriginalPlayerID() < MAX_SLOTS;+ case NETCOMMANDTYPE_PLAYERLEAVE:+ return ((NetPlayerLeaveCommandMsg *)msg)->getLeavingPlayerID() < MAX_SLOTS;+ case NETCOMMANDTYPE_DISCONNECTVOTE:+ return ((NetDisconnectVoteCommandMsg *)msg)->getSlot() < MAX_SLOTS;+ case NETCOMMANDTYPE_DISCONNECTPLAYER:+ return ((NetDisconnectPlayerCommandMsg *)msg)->getDisconnectSlot() < MAX_SLOTS;+ default:+ return TRUE;+ }+}+// This function assumes that all of the fields are either of default value or are// present in the raw data.-NetCommandRef * NetPacket::ConstructNetCommandMsgFromRawData(UnsignedByte *data, UnsignedShort dataLength) {- NetCommandType commandType = NETCOMMANDTYPE_GAMECOMMAND;+// The data length is the whole wrapped command, a map file included, so it is not a 16-bit count:+// an UnsignedShort here cut every command over 64 KB short.+NetCommandRef * NetPacket::ConstructNetCommandMsgFromRawData(UnsignedByte *data, UnsignedInt dataLength) {+ UnsignedByte commandType = NETCOMMANDTYPE_GAMECOMMAND;UnsignedShort commandID = 0;UnsignedInt frame = 0;UnsignedByte playerID = 0;@@ -85,27 +153,23 @@ NetCommandRef * NetPacket::ConstructNetCommandMsgFromRawData(UnsignedByte *data,NetCommandRef *ref = NULL;NetCommandMsg *msg = NULL;- while ((offset < (Int)dataLength) && notDone) {+ beginRead((Int)dataLength);+ while ((offset < (Int)dataLength) && notDone && !s_readBad) {if (data[offset] == 'T') {++offset;- memcpy(&commandType, data + offset, sizeof(UnsignedByte));- offset += sizeof(UnsignedByte);+ readBytes(&commandType, data, offset, sizeof(UnsignedByte));} else if (data[offset] == 'R') {++offset;- memcpy(&relay, data + offset, sizeof(UnsignedByte));- offset += sizeof(UnsignedByte);+ readBytes(&relay, data, offset, sizeof(UnsignedByte));} else if (data[offset] == 'P') {++offset;- memcpy(&playerID, data + offset, sizeof(UnsignedByte));- offset += sizeof(UnsignedByte);+ readBytes(&playerID, data, offset, sizeof(UnsignedByte));} else if (data[offset] == 'C') {++offset;- memcpy(&commandID, data + offset, sizeof(UnsignedShort));- offset += sizeof(UnsignedShort);+ readBytes(&commandID, data, offset, sizeof(UnsignedShort));} else if (data[offset] == 'F') {++offset;- memcpy(&frame, data + offset, sizeof(UnsignedInt));- offset += sizeof(UnsignedInt);+ readBytes(&frame, data, offset, sizeof(UnsignedInt));} else if (data[offset] == 'D') {++offset;if (commandType == NETCOMMANDTYPE_GAMECOMMAND) {@@ -164,10 +228,22 @@ NetCommandRef * NetPacket::ConstructNetCommandMsgFromRawData(UnsignedByte *data,msg = readFrameResendRequestMessage(data, offset);}+ // an unknown type reads nothing, and a short or lying body reads part of one+ if (msg == NULL) {+ return NULL;+ }+msg->setExecutionFrame(frame);msg->setID(commandID);msg->setPlayerID(playerID);- msg->setNetCommandType(commandType);+ msg->setNetCommandType((NetCommandType)commandType);++ if (s_readBad || !namesValidSlots(msg)) {+ DEBUG_LOG(("NetPacket::ConstructNetCommandMsgFromRawData - dropped a malformed command of type %d from player %d\n",+ commandType, playerID));+ msg->detach();+ return NULL;+ }ref = NEW_NETCOMMANDREF(msg);@@ -177,6 +253,9 @@ NetCommandRef * NetPacket::ConstructNetCommandMsgFromRawData(UnsignedByte *data,msg = NULL;notDone = FALSE;+ } else {+ // EA's loop never stepped past a byte it did not know, and spun on it forever+ return NULL;}}@@ -4989,27 +5068,24 @@ NetCommandList * NetPacket::getCommandList() {NetCommandRef *lastCommand = NULL;Int i = 0;- while (i < m_packetLen) {+ beginRead(m_packetLen);+ // a bad read leaves the rest of the packet unreadable, since nothing says where the next command starts+ while (i < m_packetLen && !s_readBad) {if (m_packet[i] == 'T') {++i;- memcpy(&commandType, m_packet + i, sizeof(UnsignedByte));- i += sizeof(UnsignedByte);+ readBytes(&commandType, m_packet, i, sizeof(UnsignedByte));} else if (m_packet[i] == 'F') {++i;- memcpy(&frame, m_packet + i, sizeof(UnsignedInt));- i += sizeof(UnsignedInt);+ readBytes(&frame, m_packet, i, sizeof(UnsignedInt));} else if (m_packet[i] == 'P') {++i;- memcpy(&playerID, m_packet + i, sizeof(UnsignedByte));- i += sizeof(UnsignedByte);+ readBytes(&playerID, m_packet, i, sizeof(UnsignedByte));} else if (m_packet[i] == 'R') {++i;- memcpy(&relay, m_packet + i, sizeof(UnsignedByte));- i += sizeof(UnsignedByte);+ readBytes(&relay, m_packet, i, sizeof(UnsignedByte));} else if (m_packet[i] == 'C') {++i;- memcpy(&commandID, m_packet + i, sizeof(UnsignedShort));- i += sizeof(UnsignedShort);+ readBytes(&commandID, m_packet, i, sizeof(UnsignedShort));} else if (m_packet[i] == 'D') {++i;@@ -5129,8 +5205,9 @@ NetCommandList * NetPacket::getCommandList() {}if (msg == NULL) {- DEBUG_CRASH(("Didn't read a message from the packet. Things are about to go wrong."));- continue;+ // an unknown type: its body has no known length, so nothing after it can be found+ DEBUG_LOG(("NetPacket::getCommandList - command type %d is not one we know, rest of the packet dropped\n", commandType));+ break;}// set the info@@ -5139,6 +5216,13 @@ NetCommandList * NetPacket::getCommandList() {msg->setNetCommandType((NetCommandType)commandType);msg->setID(commandID);+ if (s_readBad || !namesValidSlots(msg)) {+ DEBUG_LOG(("NetPacket::getCommandList - malformed command of type %d from player %d, rest of the packet dropped\n",+ commandType, playerID));+ msg->detach();+ break;+ }+// DEBUG_LOG(("frame = %d, player = %d, command type = %d, id = %d\n", frame, playerID, commandType, commandID));// increment to the next command ID.@@ -5167,8 +5251,11 @@ NetCommandList * NetPacket::getCommandList() {} else if (m_packet[i] == 'Z') {++i;// Repeat the last command, doing some funky cool byte-saving stuff- if (lastCommand == NULL) {- DEBUG_CRASH(("Got a repeat command with no command to repeat."));+ // The repeat copies fields out of the last command as the type the 'T' now names, so it+ // needs a last command, of that same type; anything else read another class's memory.+ if (lastCommand == NULL || lastCommand->getCommand()->getNetCommandType() != (NetCommandType)commandType) {+ DEBUG_LOG(("NetPacket::getCommandList - a repeat with nothing of type %d to repeat, rest of the packet dropped\n", commandType));+ break;}NetCommandMsg *msg = NULL;if (commandType == NETCOMMANDTYPE_ACKSTAGE1) {@@ -5249,29 +5336,25 @@ NetCommandMsg * NetPacket::readGameMessage(UnsignedByte *data, Int &i)// DEBUG_LOG(("NetPacket::readGameMessage\n"));// Get the GameMessage command type.- GameMessage::Type newType;- memcpy(&newType, data + i, sizeof(GameMessage::Type));- i += sizeof(GameMessage::Type);+ GameMessage::Type newType = (GameMessage::Type)0;+ readBytes(&newType, data, i, sizeof(GameMessage::Type));msg->setGameMessageType(newType);// Get the number of argument typesUnsignedByte numArgTypes = 0;- memcpy(&numArgTypes, data + i, sizeof(numArgTypes));- i += sizeof(numArgTypes);+ readBytes(&numArgTypes, data, i, sizeof(numArgTypes));// Get the types and the number of arguments of those types.Int totalArgCount = 0;GameMessageParser *parser = newInstance(GameMessageParser)();// j is used after the loop; VC6 for-scope let it escape.Int j;- for (j = 0; j < numArgTypes; ++j) {+ for (j = 0; j < numArgTypes && !s_readBad; ++j) {UnsignedByte type = (UnsignedByte)ARGUMENTDATATYPE_UNKNOWN;- memcpy(&type, data + i, sizeof(type));- i += sizeof(type);+ readBytes(&type, data, i, sizeof(type));UnsignedByte argCount = 0;- memcpy(&argCount, data + i, sizeof(argCount));- i += sizeof(argCount);+ readBytes(&argCount, data, i, sizeof(argCount));parser->addArgType((GameMessageArgumentDataType)type, argCount);totalArgCount += argCount;@@ -5284,7 +5367,7 @@ NetCommandMsg * NetPacket::readGameMessage(UnsignedByte *data, Int &i)lasttype = parserArgType->getType();argsLeftForType = parserArgType->getArgCount();}- for (j = 0; j < totalArgCount; ++j) {+ for (j = 0; j < totalArgCount && !s_readBad; ++j) {readGameMessageArgumentFromPacket(lasttype, msg, data, i);--argsLeftForType;@@ -5313,80 +5396,72 @@ void NetPacket::readGameMessageArgumentFromPacket(GameMessageArgumentDataType tyif (type == ARGUMENTDATATYPE_INTEGER) {GameMessageArgumentType arg;Int theint;- memcpy(&theint, data + i, sizeof(theint));- i += sizeof(theint);+ readBytes(&theint, data, i, sizeof(theint));arg.integer = theint;msg->addArgument(type, arg);} else if (type == ARGUMENTDATATYPE_REAL) {GameMessageArgumentType arg;Real thereal;- memcpy(&thereal, data + i, sizeof(thereal));- i += sizeof(thereal);+ readBytes(&thereal, data, i, sizeof(thereal));arg.real = thereal;msg->addArgument(type, arg);} else if (type == ARGUMENTDATATYPE_BOOLEAN) {GameMessageArgumentType arg;Bool thebool;- memcpy(&thebool, data + i, sizeof(thebool));- i += sizeof(thebool);+ readBytes(&thebool, data, i, sizeof(thebool));arg.boolean = thebool;msg->addArgument(type, arg);} else if (type == ARGUMENTDATATYPE_OBJECTID) {GameMessageArgumentType arg;ObjectID theint;- memcpy(&theint, data + i, sizeof(theint));- i += sizeof(theint);+ readBytes(&theint, data, i, sizeof(theint));arg.objectID = theint;msg->addArgument(type, arg);} else if (type == ARGUMENTDATATYPE_DRAWABLEID) {GameMessageArgumentType arg;DrawableID theint;- memcpy(&theint, data + i, sizeof(theint));- i += sizeof(theint);+ readBytes(&theint, data, i, sizeof(theint));arg.drawableID = theint;msg->addArgument(type, arg);} else if (type == ARGUMENTDATATYPE_TEAMID) {GameMessageArgumentType arg;UnsignedInt theint;- memcpy(&theint, data + i, sizeof(theint));- i += sizeof(theint);+ readBytes(&theint, data, i, sizeof(theint));arg.teamID = theint;msg->addArgument(type, arg);} else if (type == ARGUMENTDATATYPE_LOCATION) {GameMessageArgumentType arg;Coord3D coord;- memcpy(&coord, data + i, sizeof(coord));- i += sizeof(coord);+ readBytes(&coord, data, i, sizeof(coord));arg.location = coord;msg->addArgument(type, arg);} else if (type == ARGUMENTDATATYPE_PIXEL) {GameMessageArgumentType arg;ICoord2D pixel;- memcpy(&pixel, data + i, sizeof(pixel));- i += sizeof(pixel);+ readBytes(&pixel, data, i, sizeof(pixel));arg.pixel = pixel;msg->addArgument(type, arg);} else if (type == ARGUMENTDATATYPE_PIXELREGION) {GameMessageArgumentType arg;IRegion2D reg;- memcpy(®, data + i, sizeof(reg));- i += sizeof(reg);+ readBytes(®, data, i, sizeof(reg));arg.pixelRegion = reg;msg->addArgument(type, arg);} else if (type == ARGUMENTDATATYPE_TIMESTAMP) {GameMessageArgumentType arg;UnsignedInt stamp;- memcpy(&stamp, data + i, sizeof(stamp));- i += sizeof(stamp);+ readBytes(&stamp, data, i, sizeof(stamp));arg.timestamp = stamp;msg->addArgument(type, arg);} else if (type == ARGUMENTDATATYPE_WIDECHAR) {GameMessageArgumentType arg;WideChar c;- memcpy(&c, data + i, sizeof(c));- i += sizeof(c);+ readBytes(&c, data, i, sizeof(c));arg.wChar = c;msg->addArgument(type, arg);+ } else {+ // no type of ours, so no size to step over: everything after it is unreadable+ s_readBad = TRUE;}}@@ -5399,14 +5474,12 @@ NetCommandMsg * NetPacket::readAckBothMessage(UnsignedByte *data, Int &i) {//DEBUG_LOG(("NetPacket::readAckMessage, "));UnsignedShort cmdID = 0;- memcpy(&cmdID, data + i, sizeof(UnsignedShort));- i += sizeof(UnsignedShort);+ readBytes(&cmdID, data, i, sizeof(UnsignedShort));msg->setCommandID(cmdID);//DEBUG_LOG(("commandID = %d, ", cmdID));UnsignedByte origPlayerID = 0;- memcpy(&origPlayerID, data + i, sizeof(UnsignedByte));- i += sizeof(UnsignedByte);+ readBytes(&origPlayerID, data, i, sizeof(UnsignedByte));msg->setOriginalPlayerID(origPlayerID);//DEBUG_LOG(("original player id = %d\n", origPlayerID));@@ -5422,14 +5495,12 @@ NetCommandMsg * NetPacket::readAckStage1Message(UnsignedByte *data, Int &i) {// DEBUG_LOG(("NetPacket::readAckMessage, "));UnsignedShort cmdID = 0;- memcpy(&cmdID, data + i, sizeof(UnsignedShort));- i += sizeof(UnsignedShort);+ readBytes(&cmdID, data, i, sizeof(UnsignedShort));msg->setCommandID(cmdID);// DEBUG_LOG(("commandID = %d, ", cmdID));UnsignedByte origPlayerID = 0;- memcpy(&origPlayerID, data + i, sizeof(UnsignedByte));- i += sizeof(UnsignedByte);+ readBytes(&origPlayerID, data, i, sizeof(UnsignedByte));msg->setOriginalPlayerID(origPlayerID);// DEBUG_LOG(("original player id = %d\n", origPlayerID));@@ -5445,14 +5516,12 @@ NetCommandMsg * NetPacket::readAckStage2Message(UnsignedByte *data, Int &i) {// DEBUG_LOG(("NetPacket::readAckMessage, "));UnsignedShort cmdID = 0;- memcpy(&cmdID, data + i, sizeof(UnsignedShort));- i += sizeof(UnsignedShort);+ readBytes(&cmdID, data, i, sizeof(UnsignedShort));msg->setCommandID(cmdID);// DEBUG_LOG(("commandID = %d, ", cmdID));UnsignedByte origPlayerID = 0;- memcpy(&origPlayerID, data + i, sizeof(UnsignedByte));- i += sizeof(UnsignedByte);+ readBytes(&origPlayerID, data, i, sizeof(UnsignedByte));msg->setOriginalPlayerID(origPlayerID);// DEBUG_LOG(("original player id = %d\n", origPlayerID));@@ -5468,8 +5537,7 @@ NetCommandMsg * NetPacket::readFrameMessage(UnsignedByte *data, Int &i) {// DEBUG_LOG(("NetPacket::readFrameMessage, "));UnsignedShort cmdCount = 0;- memcpy(&cmdCount, data + i, sizeof(UnsignedShort));- i += sizeof(UnsignedShort);+ readBytes(&cmdCount, data, i, sizeof(UnsignedShort));msg->setCommandCount(cmdCount);// DEBUG_LOG(("command count = %d, ", cmdCount));@@ -5484,8 +5552,7 @@ NetCommandMsg * NetPacket::readPlayerLeaveMessage(UnsignedByte *data, Int &i) {UnsignedByte leavingPlayerID = 0;- memcpy(&leavingPlayerID, data + i, sizeof(UnsignedByte));- i += sizeof(UnsignedByte);+ readBytes(&leavingPlayerID, data, i, sizeof(UnsignedByte));msg->setLeavingPlayerID(leavingPlayerID);return msg;@@ -5500,12 +5567,10 @@ NetCommandMsg * NetPacket::readRunAheadMetricsMessage(UnsignedByte *data, Int &iReal averageLatency = (Real)0.2;UnsignedShort averageFps = 30;- memcpy(&averageLatency, data + i, sizeof(Real));- i += sizeof(Real);+ readBytes(&averageLatency, data, i, sizeof(Real));msg->setAverageLatency(averageLatency);- memcpy(&averageFps, data + i, sizeof(UnsignedShort));- i += sizeof(UnsignedShort);+ readBytes(&averageFps, data, i, sizeof(UnsignedShort));msg->setAverageFps((Int)averageFps);return msg;}@@ -5517,13 +5582,11 @@ NetCommandMsg * NetPacket::readRunAheadMessage(UnsignedByte *data, Int &i) {NetRunAheadCommandMsg *msg = newInstance(NetRunAheadCommandMsg);UnsignedShort newRunAhead = 20;- memcpy(&newRunAhead, data + i, sizeof(UnsignedShort));- i += sizeof(UnsignedShort);+ readBytes(&newRunAhead, data, i, sizeof(UnsignedShort));msg->setRunAhead(newRunAhead);UnsignedByte newFrameRate = 30;- memcpy(&newFrameRate, data + i, sizeof(UnsignedByte));- i += sizeof(UnsignedByte);+ readBytes(&newFrameRate, data, i, sizeof(UnsignedByte));msg->setFrameRate(newFrameRate);return msg;@@ -5536,8 +5599,7 @@ NetCommandMsg * NetPacket::readDestroyPlayerMessage(UnsignedByte *data, Int &i)NetDestroyPlayerCommandMsg *msg = newInstance(NetDestroyPlayerCommandMsg);UnsignedInt newVal = 0;- memcpy(&newVal, data + i, sizeof(UnsignedInt));- i += sizeof(UnsignedInt);+ readBytes(&newVal, data, i, sizeof(UnsignedInt));msg->setPlayerIndex(newVal);//DEBUG_LOG(("Saw CRC of 0x%8.8X\n", newCRC));@@ -5569,13 +5631,11 @@ NetCommandMsg * NetPacket::readDisconnectPlayerMessage(UnsignedByte *data, Int &NetDisconnectPlayerCommandMsg *msg = newInstance(NetDisconnectPlayerCommandMsg);UnsignedByte slot = 0;- memcpy(&slot, data + i, sizeof(slot));- i += sizeof(slot);+ readBytes(&slot, data, i, sizeof(slot));msg->setDisconnectSlot(slot);UnsignedInt disconnectFrame = 0;- memcpy(&disconnectFrame, data + i, sizeof(disconnectFrame));- i += sizeof(disconnectFrame);+ readBytes(&disconnectFrame, data, i, sizeof(disconnectFrame));msg->setDisconnectFrame(disconnectFrame);return msg;@@ -5610,11 +5670,11 @@ NetCommandMsg * NetPacket::readDisconnectChatMessage(UnsignedByte *data, Int &i)// which was the same two bytes only while WideChar happened to be; they say// sizeof(WideChar) now, and WideChar is two bytes by static_assert (B1).WideChar text[256];- UnsignedByte length;- memcpy(&length, data + i, sizeof(UnsignedByte));- ++i;- memcpy(text, data + i, length * sizeof(WideChar));- i += length * sizeof(WideChar);+ UnsignedByte length = 0;+ readBytes(&length, data, i, sizeof(UnsignedByte));+ if (!canRead(i, length * sizeof(WideChar)))+ length = 0;+ readBytes(text, data, i, length * sizeof(WideChar));text[length] = 0;UnicodeString unitext;@@ -5637,15 +5697,14 @@ NetCommandMsg * NetPacket::readChatMessage(UnsignedByte *data, Int &i) {// which was the same two bytes only while WideChar happened to be; they say// sizeof(WideChar) now, and WideChar is two bytes by static_assert (B1).WideChar text[256];- UnsignedByte length;- Int playerMask;- memcpy(&length, data + i, sizeof(UnsignedByte));- ++i;- memcpy(text, data + i, length * sizeof(WideChar));- i += length * sizeof(WideChar);+ UnsignedByte length = 0;+ Int playerMask = 0;+ readBytes(&length, data, i, sizeof(UnsignedByte));+ if (!canRead(i, length * sizeof(WideChar)))+ length = 0;+ readBytes(text, data, i, length * sizeof(WideChar));text[length] = 0;- memcpy(&playerMask, data + i, sizeof(Int));- i += sizeof(Int);+ readBytes(&playerMask, data, i, sizeof(Int));UnicodeString unitext;@@ -5665,13 +5724,11 @@ NetCommandMsg * NetPacket::readDisconnectVoteMessage(UnsignedByte *data, Int &i)NetDisconnectVoteCommandMsg *msg = newInstance(NetDisconnectVoteCommandMsg);UnsignedByte slot = 0;- memcpy(&slot, data + i, sizeof(slot));- i += sizeof(slot);+ readBytes(&slot, data, i, sizeof(slot));msg->setSlot(slot);UnsignedInt voteFrame = 0;- memcpy(&voteFrame, data + i, sizeof(voteFrame));- i += sizeof(voteFrame);+ readBytes(&voteFrame, data, i, sizeof(voteFrame));msg->setVoteFrame(voteFrame);return msg;@@ -5684,8 +5741,7 @@ NetCommandMsg * NetPacket::readProgressMessage(UnsignedByte *data, Int &i) {NetProgressCommandMsg *msg = newInstance(NetProgressCommandMsg);UnsignedByte percentage = 0;- memcpy(&percentage, data + i, sizeof(UnsignedByte));- i += sizeof(UnsignedByte);+ readBytes(&percentage, data, i, sizeof(UnsignedByte));msg->setPercentage(percentage);return msg;@@ -5706,46 +5762,43 @@ NetCommandMsg * NetPacket::readWrapperMessage(UnsignedByte *data, Int &i) {// get the wrapped command IDUnsignedShort wrappedCommandID = 0;- memcpy(&wrappedCommandID, data + i, sizeof(wrappedCommandID));+ readBytes(&wrappedCommandID, data, i, sizeof(wrappedCommandID));msg->setWrappedCommandID(wrappedCommandID);- i += sizeof(wrappedCommandID);DEBUG_LOG(("NetPacket::readWrapperMessage - wrapped command ID == %d\n", wrappedCommandID));// get the chunk number.UnsignedInt chunkNumber = 0;- memcpy(&chunkNumber, data + i, sizeof(chunkNumber));+ readBytes(&chunkNumber, data, i, sizeof(chunkNumber));msg->setChunkNumber(chunkNumber);- i += sizeof(chunkNumber);DEBUG_LOG(("NetPacket::readWrapperMessage - chunk number = %d\n", chunkNumber));// get the number of chunksUnsignedInt numChunks = 0;- memcpy(&numChunks, data + i, sizeof(numChunks));+ readBytes(&numChunks, data, i, sizeof(numChunks));msg->setNumChunks(numChunks);- i += sizeof(numChunks);DEBUG_LOG(("NetPacket::readWrapperMessage - number of chunks = %d\n", numChunks));// get the total data lengthUnsignedInt totalDataLength = 0;- memcpy(&totalDataLength, data + i, sizeof(totalDataLength));+ readBytes(&totalDataLength, data, i, sizeof(totalDataLength));msg->setTotalDataLength(totalDataLength);- i += sizeof(totalDataLength);DEBUG_LOG(("NetPacket::readWrapperMessage - total data length = %d\n", totalDataLength));// get the data length for this chunkUnsignedInt dataLength = 0;- memcpy(&dataLength, data + i, sizeof(dataLength));- i += sizeof(dataLength);+ readBytes(&dataLength, data, i, sizeof(dataLength));DEBUG_LOG(("NetPacket::readWrapperMessage - data length = %d\n", dataLength));UnsignedInt dataOffset = 0;- memcpy(&dataOffset, data + i, sizeof(dataOffset));+ readBytes(&dataOffset, data, i, sizeof(dataOffset));msg->setDataOffset(dataOffset);- i += sizeof(dataOffset);DEBUG_LOG(("NetPacket::readWrapperMessage - data offset = %d\n", dataOffset));- msg->setData(data + i, dataLength);- i += dataLength;+ // the chunk has to be in the packet: its length is the sender's word, and the copy trusted it+ if (canRead(i, dataLength)) {+ msg->setData(data + i, dataLength);+ i += dataLength;+ }return msg;}@@ -5758,22 +5811,23 @@ NetCommandMsg * NetPacket::readFileMessage(UnsignedByte *data, Int &i) {// stack buffer one byte at a time with nothing stopping it - a longer name overwrote the// stack. Bound the copy; i still advances over the whole name, truncated or not, so the// rest of the message is read from the right offset either way.- i += strlcpy(filename, (const char *)(data + i), sizeof(filename));- ++i; // step over the terminator+ // And the terminator has to be inside the packet, or strlcpy's walk to it reads past the end.+ filename[0] = 0;+ if (canReadString(data, i)) {+ i += strlcpy(filename, (const char *)(data + i), sizeof(filename));+ ++i; // step over the terminator+ }msg->setPortableFilename(AsciiString(filename)); // it's transferred as a portable filenameUnsignedInt dataLength = 0;- memcpy(&dataLength, data + i, sizeof(dataLength));- i += sizeof(dataLength);-- UnsignedByte *buf = NEW UnsignedByte[dataLength];- memcpy(buf, data + i, dataLength);- i += dataLength;+ readBytes(&dataLength, data, i, sizeof(dataLength));- msg->setFileData(buf, dataLength);- // setFileData keeps a copy of its own; this was the sender's chunk of the file and nothing- // else ever frees it.- delete [] buf;+ // setFileData keeps a copy of its own, straight out of the packet once the length is known+ // to be in it; the sender's length used to size a heap block and a copy it never had+ if (canRead(i, dataLength)) {+ msg->setFileData(data + i, dataLength);+ i += dataLength;+ }return msg;}@@ -5786,18 +5840,20 @@ NetCommandMsg * NetPacket::readFileAnnounceMessage(UnsignedByte *data, Int &i) {// stack buffer one byte at a time with nothing stopping it - a longer name overwrote the// stack. Bound the copy; i still advances over the whole name, truncated or not, so the// rest of the message is read from the right offset either way.- i += strlcpy(filename, (const char *)(data + i), sizeof(filename));- ++i; // step over the terminator+ // And the terminator has to be inside the packet, or strlcpy's walk to it reads past the end.+ filename[0] = 0;+ if (canReadString(data, i)) {+ i += strlcpy(filename, (const char *)(data + i), sizeof(filename));+ ++i; // step over the terminator+ }msg->setPortableFilename(AsciiString(filename)); // it's transferred as a portable filenameUnsignedShort fileID = 0;- memcpy(&fileID, data + i, sizeof(fileID));- i += sizeof(fileID);+ readBytes(&fileID, data, i, sizeof(fileID));msg->setFileID(fileID);UnsignedByte playerMask = 0;- memcpy(&playerMask, data + i, sizeof(playerMask));- i += sizeof(playerMask);+ readBytes(&playerMask, data, i, sizeof(playerMask));msg->setPlayerMask(playerMask);return msg;@@ -5807,13 +5863,11 @@ NetCommandMsg * NetPacket::readFileProgressMessage(UnsignedByte *data, Int &i) {NetFileProgressCommandMsg *msg = newInstance(NetFileProgressCommandMsg);UnsignedShort fileID = 0;- memcpy(&fileID, data + i, sizeof(fileID));- i += sizeof(fileID);+ readBytes(&fileID, data, i, sizeof(fileID));msg->setFileID(fileID);Int progress = 0;- memcpy(&progress, data + i, sizeof(progress));- i += sizeof(progress);+ readBytes(&progress, data, i, sizeof(progress));msg->setProgress(progress);return msg;@@ -5823,8 +5877,7 @@ NetCommandMsg * NetPacket::readDisconnectFrameMessage(UnsignedByte *data, Int &iNetDisconnectFrameCommandMsg *msg = newInstance(NetDisconnectFrameCommandMsg);UnsignedInt disconnectFrame = 0;- memcpy(&disconnectFrame, data + i, sizeof(disconnectFrame));- i += sizeof(disconnectFrame);+ readBytes(&disconnectFrame, data, i, sizeof(disconnectFrame));msg->setDisconnectFrame(disconnectFrame);DEBUG_LOG(("NetPacket::readDisconnectFrameMessage - read disconnect frame for frame %d\n", disconnectFrame));@@ -5836,8 +5889,7 @@ NetCommandMsg * NetPacket::readDisconnectScreenOffMessage(UnsignedByte *data, InNetDisconnectScreenOffCommandMsg *msg = newInstance(NetDisconnectScreenOffCommandMsg);UnsignedInt newFrame = 0;- memcpy(&newFrame, data + i, sizeof(newFrame));- i += sizeof(newFrame);+ readBytes(&newFrame, data, i, sizeof(newFrame));msg->setNewFrame(newFrame);return msg;@@ -5847,8 +5899,7 @@ NetCommandMsg * NetPacket::readFrameResendRequestMessage(UnsignedByte *data, IntNetFrameResendRequestCommandMsg *msg = newInstance(NetFrameResendRequestCommandMsg);UnsignedInt frameToResend = 0;- memcpy(&frameToResend, data + i, sizeof(frameToResend));- i += sizeof(frameToResend);+ readBytes(&frameToResend, data, i, sizeof(frameToResend));msg->setFrameToResend(frameToResend);return msg;diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cppindex 3b9b19f6e..18480b609 100644--- a/GeneralsMD/Code/Tests/test_gameengine.cpp+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp@@ -249,7 +249,12 @@ public:virtual Bool createDirectory( AsciiString ) { return FALSE; }virtual Bool copyFile( const Char *, const Char *, Bool ) { return FALSE; }virtual Bool deleteFile( const Char * ) { return FALSE; }- virtual Bool moveFileReplacing( const Char *, const Char * ) { return FALSE; }+ // XferSave::close writes "<name>.tmp" and puts it in place through this+ virtual Bool moveFileReplacing( const Char *from, const Char *to )+ {+ remove( to );+ return rename( from, to ) == 0;+ }virtual void getFilesInDirectory( const AsciiString&, const AsciiString&, std::vector<AsciiString>& ) const {}virtual AsciiString getCurrentDirectory() const { return AsciiString::TheEmptyString; }};@@ -6238,8 +6243,6 @@ TEST(netcommand_list_orders_a_burst_of_acks_by_acknowledged_command)over the whole name, so everything after it in the message is still read from the right place. */struct NetPacketFileReader : public NetPacket{- using NetPacket::readFileMessage;- using NetPacket::readFileAnnounceMessage;using NetPacket::GetBufferSizeNeededForCommand;using NetPacket::FillBufferWithCommand;};@@ -6315,8 +6318,11 @@ TEST(sizing_a_null_command_asks_for_no_bytes)TEST(an_overlong_transfer_filename_is_truncated_instead_of_overflowing){static const Int NAME_LEN = 400; // _MAX_PATH is 260- UnsignedByte buf[NAME_LEN + 1 + sizeof(UnsignedInt) + 4];+ UnsignedByte buf[3 + NAME_LEN + 1 + sizeof(UnsignedInt) + 4];Int at = 0;+ buf[at++] = 'T';+ buf[at++] = NETCOMMANDTYPE_FILE;+ buf[at++] = 'D';Int k;for( k = 0; k < NAME_LEN; ++k )buf[at++] = (UnsignedByte)('a' + (k % 26));@@ -6327,27 +6333,29 @@ TEST(an_overlong_transfer_filename_is_truncated_instead_of_overflowing)at += sizeof(dataLength);buf[at++] = 0xDE; buf[at++] = 0xAD; buf[at++] = 0xBE; buf[at++] = 0xEF;- Int i = 0;- NetCommandMsg *msg = NetPacketFileReader::readFileMessage( buf, i );- NetFileCommandMsg *fileMsg = (NetFileCommandMsg *)msg;+ // through the entry point, which tells the readers how far the data reaches+ NetCommandRef *ref = NetPacket::ConstructNetCommandMsgFromRawData( buf, (UnsignedInt)at );+ NetFileCommandMsg *fileMsg = (NetFileCommandMsg *)ref->getCommand();// the name is cut to the buffer rather than written past itCHECK_EQ( fileMsg->getPortableFilename().getLength(), _MAX_PATH - 1 );// ...but the offset walked the whole name, so what follows it still parses- CHECK_EQ( i, at );CHECK_EQ( (Int)fileMsg->getFileLength(), 4 );CHECK_EQ( (Int)fileMsg->getFileData()[0], 0xDE );CHECK_EQ( (Int)fileMsg->getFileData()[3], 0xEF );- msg->detach();+ ref->deleteInstance();}TEST(an_overlong_announced_filename_is_truncated_instead_of_overflowing){static const Int NAME_LEN = 400;- UnsignedByte buf[NAME_LEN + 1 + sizeof(UnsignedShort) + sizeof(UnsignedByte)];+ UnsignedByte buf[3 + NAME_LEN + 1 + sizeof(UnsignedShort) + sizeof(UnsignedByte)];Int at = 0;+ buf[at++] = 'T';+ buf[at++] = NETCOMMANDTYPE_FILEANNOUNCE;+ buf[at++] = 'D';Int k;for( k = 0; k < NAME_LEN; ++k )buf[at++] = (UnsignedByte)('a' + (k % 26));@@ -6358,16 +6366,14 @@ TEST(an_overlong_announced_filename_is_truncated_instead_of_overflowing)at += sizeof(fileID);buf[at++] = 0x5A; // player mask- Int i = 0;- NetCommandMsg *msg = NetPacketFileReader::readFileAnnounceMessage( buf, i );- NetFileAnnounceCommandMsg *announce = (NetFileAnnounceCommandMsg *)msg;+ NetCommandRef *ref = NetPacket::ConstructNetCommandMsgFromRawData( buf, (UnsignedInt)at );+ NetFileAnnounceCommandMsg *announce = (NetFileAnnounceCommandMsg *)ref->getCommand();CHECK_EQ( announce->getPortableFilename().getLength(), _MAX_PATH - 1 );- CHECK_EQ( i, at );CHECK_EQ( (Int)announce->getFileID(), 0x1234 );CHECK_EQ( (Int)announce->getPlayerMask(), 0x5A );- msg->detach();+ ref->deleteInstance();}/* A map transfer arrives as a filename and a block of bytes, both chosen by the other machine, anddiff --git a/GeneralsMD/Code/Tests/test_selection_priority.inc b/GeneralsMD/Code/Tests/test_selection_priority.incindex 0cfc1a330..a5354cac5 100644--- a/GeneralsMD/Code/Tests/test_selection_priority.inc+++ b/GeneralsMD/Code/Tests/test_selection_priority.inc@@ -1,4 +1,5 @@#include "GameClient/SelectionPriority.h"+#include "GameNetwork/GameMessageParser.h"namespace{@@ -90,3 +91,49 @@ TEST(selection_priority_empty_box_and_military_support)CHECK(!isMilitaryBoxSelectionUnit(&cashUnit));CHECK(!isMilitaryBoxSelectionUnit<SelectionPriorityUnit>(NULL));}++TEST(selection_of_more_than_254_units_survives_the_one_byte_run_counts)+{+ CHECK(bootOnce());+ // a GameMessage stamps itself with the local player's index, and a Player resets its rank and+ // score from the global data and the rank store when it is built+ GlobalData *savedGlobal = TheWritableGlobalData;+ RankInfoStore *savedRanks = TheRankInfoStore;+ PlayerList *savedPlayers = ThePlayerList;+ GlobalData *global = NEW GlobalData;+ TheWritableGlobalData = global;+ static RankInfoStore *ranks = NEW RankInfoStore;+ TheRankInfoStore = ranks;+ static PlayerList *players = NEW PlayerList;+ ThePlayerList = players;+ // 255, 511, 767 and 1023 units used to arrive as none, 1000 as 232: the count was a byte, and so+ // is each run's count in the packet and the replay.+ const Int sizes[] = { 254, 255, 256, 511, 1000, 1023 };+ for (Int s = 0; s < 6; ++s)+ {+ GameMessage *msg = newInstance(GameMessage)(GameMessage::MSG_CREATE_SELECTED_GROUP);+ msg->appendBooleanArgument(TRUE);+ for (Int i = 0; i < sizes[s]; ++i)+ msg->appendObjectIDArgument((ObjectID)(i + 1));+ CHECK_EQ(msg->getArgumentCount(), sizes[s] + 1);++ GameMessageParser *parser = newInstance(GameMessageParser)(msg);+ CHECK(parser->getNumTypes() <= 255);+ Int read = 0;+ for (GameMessageParserArgumentType *run = parser->getFirstArgumentType(); run; run = run->getNext())+ {+ // what a reader gets back from the byte the writer stored+ const UnsignedByte count = (UnsignedByte)run->getArgCount();+ CHECK_EQ((Int)count, run->getArgCount());+ CHECK_EQ(run->getType(), read == 0 ? ARGUMENTDATATYPE_BOOLEAN : ARGUMENTDATATYPE_OBJECTID);+ read += count;+ }+ CHECK_EQ(read, sizes[s] + 1);+ parser->deleteInstance();+ msg->deleteInstance();+ }+ ThePlayerList = savedPlayers;+ TheRankInfoStore = savedRanks;+ delete global; // while it is the current one: a Debug build's ~GlobalData reads TheWritableGlobalData+ TheWritableGlobalData = savedGlobal;+}