Skip to content

Commit

Permalink
Refactor IStorage::OpenFile function
Browse files Browse the repository at this point in the history
Add assertion to ensure the file opening flags match the storage type.

Reduce indentation to improve readability.

Ensure result buffer is initialized with path also when opening fails, so the path can be logged in error messages.
  • Loading branch information
Robyt3 committed Jan 4, 2025
1 parent cd6c099 commit a30c3f7
Showing 1 changed file with 24 additions and 27 deletions.
51 changes: 24 additions & 27 deletions src/engine/shared/storage.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -452,64 +452,61 @@ class CStorage : public IStorage
Type = fs_is_relative_path(pPath) ? TYPE_ALL : TYPE_ABSOLUTE;
}

IOHANDLE OpenFile(const char *pFilename, int Flags, int Type, char *pBuffer = 0, int BufferSize = 0) override
IOHANDLE OpenFile(const char *pFilename, int Flags, int Type, char *pBuffer = nullptr, int BufferSize = 0) override
{
TranslateType(Type, pFilename);

dbg_assert((Flags & IOFLAG_WRITE) == 0 || Type == TYPE_SAVE || Type == TYPE_ABSOLUTE, "IOFLAG_WRITE only usable with TYPE_SAVE and TYPE_ABSOLUTE");

char aBuffer[IO_MAX_PATH_LENGTH];
if(!pBuffer)
{
pBuffer = aBuffer;
BufferSize = sizeof(aBuffer);
}
pBuffer[0] = '\0';

if(Type == TYPE_ABSOLUTE)
{
return io_open(GetPath(TYPE_ABSOLUTE, pFilename, pBuffer, BufferSize), Flags);
}

if(str_startswith(pFilename, "mapres/../skins/"))
{
pFilename = pFilename + 10; // just start from skins/
}
if(pFilename[0] == '/' || pFilename[0] == '\\' || str_find(pFilename, "../") != NULL || str_find(pFilename, "..\\") != NULL
if(pFilename[0] == '/' || pFilename[0] == '\\' || str_find(pFilename, "../") != nullptr || str_find(pFilename, "..\\") != nullptr
#ifdef CONF_FAMILY_WINDOWS
|| (pFilename[0] && pFilename[1] == ':')
#endif
)
{
// don't escape base directory
return nullptr;
}
else if(Flags & IOFLAG_WRITE)
{
return io_open(GetPath(TYPE_SAVE, pFilename, pBuffer, BufferSize), Flags);
}
else
else if(Type == TYPE_ALL)
{
if(Type == TYPE_ALL)
{
// check all available directories
for(int i = TYPE_SAVE; i < m_NumPaths; ++i)
{
IOHANDLE Handle = io_open(GetPath(i, pFilename, pBuffer, BufferSize), Flags);
if(Handle)
return Handle;
}
}
else if(Type >= TYPE_SAVE && Type < m_NumPaths)
// check all available directories
for(int i = TYPE_SAVE; i < m_NumPaths; ++i)
{
// check wanted directory
IOHANDLE Handle = io_open(GetPath(Type, pFilename, pBuffer, BufferSize), Flags);
IOHANDLE Handle = io_open(GetPath(i, pFilename, pBuffer, BufferSize), Flags);
if(Handle)
{
return Handle;
}
}
else
{
dbg_assert(false, "Type invalid");
}
return nullptr;
}
else if(Type >= TYPE_SAVE && Type < m_NumPaths)
{
// check wanted directory
return io_open(GetPath(Type, pFilename, pBuffer, BufferSize), Flags);
}
else
{
dbg_assert(false, "Type invalid");
return nullptr;
}

pBuffer[0] = 0;
return 0;
}

template<typename F>
Expand Down

0 comments on commit a30c3f7

Please sign in to comment.