From f9ad35badf2effb36cdaadb4fd990ef3a1b012e4 Mon Sep 17 00:00:00 2001 From: Oliver John Hitchcock Date: Fri, 26 Apr 2024 00:19:04 +0100 Subject: [PATCH] Stop EntRefToEntIndex returning garbage if a bad parameter is passed (#1323) * Stop EntRefToEntIndex returning garbage if a bad parameter is passed Seen multiple bad usage of this function that works only because whatever was passed in was returned as it wasnt an entity reference. This code should have worked and would be expected to have returned something invalid but instead the the input was returned which allowed the code to work when really it is bad code. See for one such case https://discordapp.com/channels/335290997317697536/335290997317697536/736518488314871868 * Update documentation of EntRefToEntIndex Added the error text saying what shall be returned when a invalid parameter is passed. * Validate entity index instead of just returning INVALID_EHANDLE_INDEX Not sure if it needs this much validation but this just mirrors how IsValidEntity works, so the entity index returned should be valid else INVALID_EHANDLE_INDEX is returned. * EntRefToEntIndex improve doc comments to better represent functionality --------- Co-authored-by: Kyle Sanderson --- core/HalfLife2.cpp | 20 +++++++++++++++++++- plugins/include/halflife.inc | 7 ++++--- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/core/HalfLife2.cpp b/core/HalfLife2.cpp index 53af3dc8..7600917b 100644 --- a/core/HalfLife2.cpp +++ b/core/HalfLife2.cpp @@ -1099,8 +1099,26 @@ int CHalfLife2::ReferenceToIndex(cell_t entRef) return hndl.GetEntryIndex(); } + else + { + CEntInfo *pInfo = LookupEntity(entRef); + if (!pInfo) + { + return INVALID_EHANDLE_INDEX; + } + IServerUnknown *pUnk = static_cast(pInfo->m_pEntity); + if (!pUnk) + { + return INVALID_EHANDLE_INDEX; + } + CBaseEntity *pEntity = pUnk->GetBaseEntity(); + if (!pEntity) + { + return INVALID_EHANDLE_INDEX; + } - return entRef; + return entRef; + } } cell_t CHalfLife2::EntityToBCompatRef(CBaseEntity *pEntity) diff --git a/plugins/include/halflife.inc b/plugins/include/halflife.inc index ccb5bf90..38626f23 100644 --- a/plugins/include/halflife.inc +++ b/plugins/include/halflife.inc @@ -667,10 +667,11 @@ stock void DisplayAskConnectBox(int client, float time, const char[] ip, const c native int EntIndexToEntRef(int entity); /** - * Retrieves the entity index from a reference. + * Retrieves the entity index from a reference or validates an entity index. + * The input ref is checked that it is still valid and refers to the same entity. * - * @param ref Entity reference. - * @return Entity index or -1 on invalid reference. + * @param ref Entity reference or index. + * @return Entity index or returns INVALID_ENT_REFERENCE if ref is invalid. */ native int EntRefToEntIndex(int ref);