diff --git a/Engine/Source/BlizzardCore/CMakeLists.txt b/Engine/Source/BlizzardCore/CMakeLists.txt index 443f6ff..3888d66 100644 --- a/Engine/Source/BlizzardCore/CMakeLists.txt +++ b/Engine/Source/BlizzardCore/CMakeLists.txt @@ -15,3 +15,16 @@ target_link_libraries(BlizzardCore lzma zlib ) + +if(WIN32) + target_link_libraries(BlizzardCore + PUBLIC + wininet + ) +endif() + +target_include_directories(BlizzardCore + PRIVATE + ${CMAKE_SOURCE_DIR}/Engine/Source/SoundEngine/fmodex/lib/ogg_vorbis/ogg/include + ${CMAKE_SOURCE_DIR}/Engine/Source/SoundEngine/fmodex/lib/ogg_vorbis/vorbis/include +) diff --git a/Engine/Source/BlizzardCore/Include/Blizzard/Util/Digest.h b/Engine/Source/BlizzardCore/Include/Blizzard/Util/Digest.h index 9f4c02e..a6f1327 100644 --- a/Engine/Source/BlizzardCore/Include/Blizzard/Util/Digest.h +++ b/Engine/Source/BlizzardCore/Include/Blizzard/Util/Digest.h @@ -11,14 +11,30 @@ template struct Digest { /* 0000 */ uint8_t m_data[N]; + Digest& FromHexString(const char* hex); bool operator<(const Digest& other) const; bool operator==(const Digest& other) const; bool operator!=(const Digest& other) const; }; +extern const uint8_t s_hexDigits[256]; + } } +// VERIFY: 4cd92949 auto +// OFFSET: 0x00429580<16> +template +Blizzard::Util::Digest& Blizzard::Util::Digest::FromHexString(const char* hex) { + if (hex && strlen(hex) == 2 * N) { + for (int32_t i = 0; i < 2 * N; i += 2) { + this->m_data[i >> 1] = (s_hexDigits[hex[i]] << 4) | s_hexDigits[hex[i + 1]]; + } + } + + return *this; +} + // VERIFY: 182eff5b manual // OFFSET: 0x00429540 template diff --git a/Engine/Source/BlizzardCore/Include/Blizzard/Util/MD5.h b/Engine/Source/BlizzardCore/Include/Blizzard/Util/MD5.h index c9912fb..0c85a0b 100644 --- a/Engine/Source/BlizzardCore/Include/Blizzard/Util/MD5.h +++ b/Engine/Source/BlizzardCore/Include/Blizzard/Util/MD5.h @@ -18,6 +18,8 @@ class MD5 { void Process(const void* data, uint32_t size); }; +void HashString(uint8_t* digest, const char* str); + } } diff --git a/Engine/Source/BlizzardCore/OggDecompress.cpp b/Engine/Source/BlizzardCore/OggDecompress.cpp index f79502e..a715178 100644 --- a/Engine/Source/BlizzardCore/OggDecompress.cpp +++ b/Engine/Source/BlizzardCore/OggDecompress.cpp @@ -1 +1,181 @@ #include "OggDecompress.h" +#include +#include +#include +#include +#include "Engine/Source/BlizzardCore/SFile2-Core.h" +#include "Engine/Source/BlizzardCore/Source/System/Memory/MemoryStorm.h" + +// VERIFY: 70759a69 manual +// OFFSET: 0x0041D140 +static int OggSeek(void* source, ogg_int64_t offset, int whence) { + OggMemoryStream* stream = static_cast(source); + uint32_t position; + + if (whence == 0) { + position = static_cast(offset); + } else if (whence == 1) { + position = static_cast(offset) + stream->m_position; + } else if (whence == 2) { + position = static_cast(offset) + stream->m_size; + } else { + position = stream->m_position; + } + + if (position > stream->m_size) { + return -1; + } + + stream->m_position = position; + return 0; +} + +// VERIFY: 4c4b1c84 auto +// OFFSET: 0x0041D190 +static ogg_int32_t OggTell(void* source) { + return static_cast(source)->m_position; +} + +// VERIFY: 37fbe6bc manual +// OFFSET: 0x0041D1A0 +size_t OggMemoryStream::Read(void* buffer, size_t size, size_t count) { + size_t left = this->m_size - this->m_position; + size_t bytes = size * count; + size_t copy = size * ((left < bytes ? left : bytes) / size); + + memcpy(buffer, this->m_data + this->m_position, copy); + this->m_position += copy; + + return copy; +} + +// VERIFY: ca21f279 auto +// OFFSET: 0x0041D300 +static size_t OggRead(void* buffer, size_t size, size_t count, void* source) { + return static_cast(source)->Read(buffer, size, count); +} + +// VERIFY: 41efffe8 auto +// OFFSET: 0x008E5250 +static int OggClose(void* source) { + return 0; +} + +// VERIFY: f640fb08 manual +// OFFSET: 0x0041D600 +OggChunkList::~OggChunkList() { + for (std::vector::iterator it = this->m_chunks->begin(); it != this->m_chunks->end(); ++it) { + Blizzard::Memory::Free(it->m_data, 0, __FILE__, __LINE__); + } +} + +// VERIFY: 3701e837 manual +// OFFSET: 0x0041DDA0 +bool DecompressOgg(const void* data, uint32_t size, OggDecompressBuffer* buffer) { + std::vector chunks; + OggChunkList chunkList; + chunkList.m_chunks = &chunks; + + OggMemoryStream stream; + stream.m_data = static_cast(data); + stream.m_size = size; + stream.m_position = 0; + + ov_callbacks callbacks; + callbacks.read_func = OggRead; + callbacks.seek_func = OggSeek; + callbacks.close_func = OggClose; + callbacks.tell_func = OggTell; + + OggVorbis_File file; + + if (ov_open_callbacks(&stream, &file, nullptr, 0, callbacks)) { + return false; + } + + uint32_t rate = 0; + uint32_t channels = 0; + uint32_t total = 0; + + vorbis_info* info = ov_info(&file, -1); + + while (info) { + if (info->channels != 1 && info->channels != 2) { + ov_clear(&file); + return false; + } + + rate = rate < static_cast(info->rate) ? info->rate : rate; + channels = channels < static_cast(info->channels) ? info->channels : channels; + + char samples[0x2000]; + ogg_int32_t read = ov_read(&file, samples, sizeof(samples), 0, 2, 1, nullptr); + + if (read < 0) { + ov_clear(&file); + return false; + } + + if (!read) { + buffer->Resize(total + 44); + + uint8_t* header = buffer->m_data; + *reinterpret_cast(header + 0) = 'FFIR'; + *reinterpret_cast(header + 4) = total + 36; + *reinterpret_cast(header + 8) = 'EVAW'; + *reinterpret_cast(header + 12) = ' tmf'; + *reinterpret_cast(header + 16) = 16; + *reinterpret_cast(header + 20) = 1; + *reinterpret_cast(header + 22) = channels; + *reinterpret_cast(header + 24) = rate; + *reinterpret_cast(header + 28) = 2 * rate * channels; + *reinterpret_cast(header + 32) = 2 * channels; + *reinterpret_cast(header + 34) = 16; + *reinterpret_cast(header + 36) = 'atad'; + *reinterpret_cast(header + 40) = total; + + uint32_t offset = 44; + + for (std::vector::iterator it = chunks.begin(); it != chunks.end(); ++it) { + if (it->m_rate != rate || it->m_channels != channels) { + ov_clear(&file); + return false; + } + + memcpy(buffer->m_data + offset, it->m_data, it->m_size); + offset += it->m_size; + } + + ov_clear(&file); + return true; + } + + void* chunkData = Blizzard::Memory::Allocate(read, 0, __FILE__, __LINE__); + memcpy(chunkData, samples, 2 * (read >> 1)); + + OggChunk chunk; + chunk.m_rate = info->rate; + chunk.m_channels = info->channels; + chunk.m_data = chunkData; + chunk.m_size = read; + chunks.push_back(chunk); + + info = ov_info(&file, -1); + total += read; + } + + ov_clear(&file); + return false; +} + +// VERIFY: 90d5a819 auto +// OFFSET: 0x0041D0B0 +bool ShutdownOggDecompression() { + return System_SFile2::ShutdownSoundCache(); +} + +// VERIFY: 06689c00 auto +// OFFSET: 0x0041E170 +bool InitOggDecompression() { + return System_SFile2::InitSoundCache(DecompressOgg); +} diff --git a/Engine/Source/BlizzardCore/OggDecompress.h b/Engine/Source/BlizzardCore/OggDecompress.h index f1f5d49..51a2aa2 100644 --- a/Engine/Source/BlizzardCore/OggDecompress.h +++ b/Engine/Source/BlizzardCore/OggDecompress.h @@ -3,34 +3,34 @@ #include #include +#include +#include "Engine/Source/BlizzardCore/Source/System/Memory/TempBuffer.h" -struct vorbis_comment; -struct vorbis_info; +typedef Blizzard::Memory::TempBuffer OggDecompressBuffer; -struct OggVorbis_File { - /* 0000 */ void* m_datasource; - /* 0004 */ int32_t m_seekable; - /* 0008 */ uint8_t m_offset[8]; - /* 0010 */ uint8_t m_end[8]; - /* 0018 */ uint8_t m_oy[28]; - /* 0034 */ int32_t m_links; - /* 0038 */ int64_t* m_offsets; - /* 003C */ int64_t* m_dataoffsets; - /* 0040 */ int32_t* m_serialnos; - /* 0044 */ int64_t* m_pcmlengths; - /* 0048 */ vorbis_info* m_vi; - /* 004C */ vorbis_comment* m_vc; - /* 0050 */ uint8_t m_pcmOffset[8]; - /* 0058 */ int32_t m_readyState; - /* 005C */ int32_t m_currentSerialno; - /* 0060 */ int32_t m_currentLink; - /* 0064 */ float m_bittrack; - /* 0068 */ float m_samptrack; - /* 006C */ uint8_t unk_006C[4]; - /* 0070 */ uint8_t m_os[360]; - /* 01D8 */ uint8_t m_vd[112]; - /* 0248 */ uint8_t m_vb[112]; - /* 02B8 */ uint8_t m_callbacks[16]; +struct OggMemoryStream { + /* 0000 */ const uint8_t* m_data; + /* 0004 */ uint32_t m_size; + /* 0008 */ uint32_t m_position; + + size_t Read(void* buffer, size_t size, size_t count); }; +struct OggChunk { + /* 0000 */ uint32_t m_rate; + /* 0004 */ uint32_t m_channels; + /* 0008 */ void* m_data; + /* 000C */ uint32_t m_size; +}; + +struct OggChunkList { + /* 0000 */ std::vector* m_chunks; + + ~OggChunkList(); +}; + +bool DecompressOgg(const void* data, uint32_t size, OggDecompressBuffer* buffer); +bool InitOggDecompression(); +bool ShutdownOggDecompression(); + #endif diff --git a/Engine/Source/BlizzardCore/SFile2-Core.cpp b/Engine/Source/BlizzardCore/SFile2-Core.cpp index bd05912..3acbb17 100644 --- a/Engine/Source/BlizzardCore/SFile2-Core.cpp +++ b/Engine/Source/BlizzardCore/SFile2-Core.cpp @@ -15,6 +15,7 @@ #include "Engine/Source/BlizzardCore/Source/System/Memory/MemoryStorm.h" #include "Engine/Source/BlizzardCore/Source/System/String/Path.h" #include "Engine/Source/BlizzardCore/Source/System/String/String.h" +#include "Engine/Source/BlizzardCore/Source/System/Thread/Thread.h" #include "Engine/Source/BlizzardCore/Source/Packages/Util/Hash.h" #include "Engine/Source/Storm/H/storm.h" #include "Engine/Source/Storm/Source/MD5.h" @@ -73,6 +74,36 @@ System_SFile2::FileHash System_SFile2::s_fileHash; // STATIC: 0x00B324FC Blizzard::Thread::LocalObject System_SFile2::s_fatalInfo; +// STATIC: 0x00B32044 +Blizzard::Memory::TempBuffer* System_SFile2::s_soundCacheBuffer; + +// STATIC: 0x00B32498 +volatile int32_t System_SFile2::s_soundCacheStop; + +// STATIC: 0x00B3249C +volatile int32_t System_SFile2::s_soundCacheStopped; + +// STATIC: 0x00B324A0 +System_SFile2::SOUNDCACHECALLBACK System_SFile2::s_soundCacheCallback; + +// VERIFY: d5074791 auto +// OFFSET: 0x00421650 +bool System_SFile2::WriteSoundCacheFile(const char* name, const void* data, uint32_t size) { + Blizzard::Lock::MutexEnter(s_soundCacheLock); + + IOMpqUnit* file; + bool result = Blizzard::Mopaq::SFileCreateFile(s_soundCacheArchive, name, size, 0, &file); + + if (result) { + result = Blizzard::Mopaq::SFileWriteFile(file, data, size); + } + + Blizzard::Mopaq::SFileCloseFile(file); + Blizzard::Lock::MutexLeave(s_soundCacheLock); + + return result; +} + // VERIFY: 99b101b5 manual // OFFSET: 0x004216C0 static void BlizzardAssertCallback(const char* expression, const char* message, const char* fileName, uint32_t lineNumber) { @@ -279,6 +310,13 @@ void SFile::SetStreamingStatus(bool enabled, bool initialized, bool flag2, bool } } +// VERIFY: 3ccd63c7 auto +// OFFSET: 0x00422100 +int32_t STORMAPI SFile::InitializeStreaming(const char* mfilPath) { + Blizzard::File::SetLastErrorStack(0); + return Blizzard::Streaming::InitializeStreaming(mfilPath, nullptr, nullptr, nullptr, false); +} + // VERIFY: 3e9c3828 auto // OFFSET: 0x00422130 int32_t SFile::IsStreamingMode() { @@ -558,6 +596,26 @@ bool System_SFile2::OldFindFile(const char* name, char* path, uint32_t size, uin return false; } +// VERIFY: 9f1ce062 manual +// OFFSET: 0x00421F50 +int32_t STORMAPI SFileAuthenticateArchiveEx(SArchive* archive, uint32_t* result, const uint8_t* modulus, uint32_t modulusSize, const uint8_t* exponent, uint32_t exponentSize) { + Blizzard::Mopaq::AuthResult authResult; + bool success = Blizzard::Mopaq::SFileAuthenticateArchiveEx(reinterpret_cast(archive), &authResult, modulus, modulusSize, exponent, exponentSize, "ARCHIVE"); + *result = authResult; + + if (!success) { + SErrSetLastError(Blizzard::Mopaq::SFileGetLastError()); + } + + return success; +} + +// VERIFY: e70abfa4 auto +// OFFSET: 0x00421FA0 +int32_t STORMAPI SFileCloseArchive(SArchive* archive) { + return Blizzard::Mopaq::SFileCloseArchive(reinterpret_cast(archive)); +} + // VERIFY: cd537558 auto // OFFSET: 0x00421FC0 int32_t STORMAPI SFile::FileExistsInArchives(const char* name) { @@ -570,6 +628,38 @@ int32_t STORMAPI SFile::FileExistsInArchives(const char* name) { return result; } +// VERIFY: 00e4abfa auto +// OFFSET: 0x00421FF0 +int32_t STORMAPI SFileLoadFileEx(SArchive* archive, const char* name, void** data, uint32_t* size, uint32_t extra, uint32_t flags, SOVERLAPPED* overlapped) { + bool result = Blizzard::Mopaq::SFileLoadFile(reinterpret_cast(archive), name, data, size, extra, flags); + + if (!result) { + SErrSetLastError(Blizzard::Mopaq::SFileGetLastError()); + } + + return result; +} + +// VERIFY: 3136a141 manual +// OFFSET: 0x00422040 +int32_t STORMAPI SFileOpenArchive(const char* path, int32_t priority, uint32_t flags, SArchive** archive) { + System_SFile::ARCHIVEREC* result; + + if (!Blizzard::Mopaq::SFileOpenArchive(path, priority, flags, &result)) { + SErrSetLastError(Blizzard::Mopaq::SFileGetLastError()); + return 0; + } + + *archive = reinterpret_cast(result); + return 1; +} + +// VERIFY: 17efbea9 auto +// OFFSET: 0x00422090 +int32_t STORMAPI SFileUnloadFile(void* data) { + return Blizzard::Mopaq::SFileUnloadFile(data); +} + // VERIFY: 43a7d076 manual // OFFSET: 0x00422330 SFileImpl::SFileImpl(uint32_t type) { @@ -1152,3 +1242,123 @@ int32_t STORMAPI SFile::LoadFile(const char* name, void** data, uint32_t* size, int32_t STORMAPI SFileOpenFile(const char* name, SFileImpl** result) { return SFile::OpenEx(nullptr, name, 0, result); } + +// VERIFY: 933721df auto +// OFFSET: 0x004217A0 +int32_t STORMAPI SFile::FileIsLocal(const char* name, int32_t flags) { + return Blizzard::Mopaq::SFileFileIsLocal(name, flags); +} + +// VERIFY: bc7e8291 auto +// OFFSET: 0x004217C0 +int32_t STORMAPI SFile::FileIsLocal(SFileImpl* file, int32_t flags) { + return Blizzard::Mopaq::SFileFileIsLocal(file->m_file, flags); +} + +// VERIFY: 06d4e040 auto +// OFFSET: 0x00421800 +int32_t STORMAPI SFile::MakeFileLocal(const char* name, int32_t priority, bool wait) { + return Blizzard::Mopaq::SFileMakeFileLocal(name, priority, wait); +} + +// VERIFY: f939f7d6 auto +// OFFSET: 0x00421820 +int32_t STORMAPI SFile::MakeFileLocal(SFileImpl* file, int32_t priority, bool wait) { + return Blizzard::Mopaq::SFileMakeFileLocal(file->m_file->GetPath(), priority, wait); +} + +// VERIFY: 0022578c auto +// OFFSET: 0x004222A0 +bool System_SFile2::VerifyAndCacheFile(const char* name) { + void* data = nullptr; + + if (!s_soundCacheCallback) { + return false; + } + + uint32_t size; + bool result = Blizzard::Mopaq::SFileLoadFile(nullptr, name, &data, &size, 0, 0); + + if (result) { + result = s_soundCacheCallback(data, size, s_soundCacheBuffer); + + if (result) { + result = WriteSoundCacheFile(name, s_soundCacheBuffer->m_data, s_soundCacheBuffer->m_count); + } + } + + if (data) { + Blizzard::Mopaq::SFileUnloadFile(data); + } + + return result; +} + +// VERIFY: bdbe70b9 auto +// OFFSET: 0x00422870 +bool System_SFile2::ShutdownSoundCache() { + if (!s_soundCacheArchive) { + return false; + } + + Blizzard::Mopaq::SFileCloseArchive(s_soundCacheArchive); + + delete s_soundCacheBuffer; + + s_soundCacheStop = 1; + Blizzard::Lock::EventSet(s_asyncOpenEvent); + + while (!s_soundCacheStopped) { + Blizzard::Thread::Sleep(10); + } + + Blizzard::Lock::EventDestroy(s_asyncOpenEvent); + Blizzard::Lock::MutexDestroy(s_asyncOpenLock); + Blizzard::Lock::MutexDestroy(s_soundCacheLock); + + return true; +} + +// VERIFY: 02dbd616 manual +// OFFSET: 0x00422F60 +uint32_t System_SFile2::SoundCacheThread(void* param) { + while (!s_soundCacheStop) { + Blizzard::Lock::EventWaitForever(s_asyncOpenEvent); + + Blizzard::Lock::MutexEnter(s_asyncOpenLock); + int32_t count = s_asyncOpenQueue.size(); + Blizzard::Lock::MutexLeave(s_asyncOpenLock); + + while (count > 0) { + Blizzard::Lock::MutexEnter(s_asyncOpenLock); + + std::string name = s_asyncOpenQueue.front(); + VerifyAndCacheFile(name.c_str()); + s_asyncOpenQueue.pop_front(); + count = s_asyncOpenQueue.size(); + + Blizzard::Lock::MutexLeave(s_asyncOpenLock); + Blizzard::Thread::Sleep(500); + } + } + + s_soundCacheStopped = 1; + return 0; +} + +// VERIFY: e0ff8232 manual +// OFFSET: 0x00423610 +bool System_SFile2::InitSoundCache(SOUNDCACHECALLBACK callback) { + bool result = Blizzard::Mopaq::SFileOpenArchive("Data/SoundCache.MPQ", 100, 0x10, &s_soundCacheArchive); + + if (result || (result = Blizzard::Mopaq::SFileCreateArchive("Data/SoundCache.MPQ", 100, 0x10, &s_soundCacheArchive, nullptr))) { + s_soundCacheBuffer = new (0, __FILE__, __LINE__) Blizzard::Memory::TempBuffer(0); + s_soundCacheCallback = callback; + Blizzard::Lock::EventCreate(s_asyncOpenEvent); + Blizzard::Lock::MutexCreate(s_asyncOpenLock); + Blizzard::Lock::MutexCreate(s_soundCacheLock); + Blizzard::Thread::CreateDetached(SoundCacheThread, nullptr, nullptr); + } + + return result; +} diff --git a/Engine/Source/BlizzardCore/SFile2-Core.h b/Engine/Source/BlizzardCore/SFile2-Core.h index 99c0b12..f570dce 100644 --- a/Engine/Source/BlizzardCore/SFile2-Core.h +++ b/Engine/Source/BlizzardCore/SFile2-Core.h @@ -8,6 +8,7 @@ #include #include "Engine/Source/BlizzardCore/Source/System/File/Types.h" #include "Engine/Source/BlizzardCore/Source/System/Lock/Lock.h" +#include "Engine/Source/BlizzardCore/Source/System/Memory/TempBuffer.h" #include "Engine/Source/BlizzardCore/Source/System/Thread/ThreadLocalStorage.h" #include "Engine/Source/Storm/H/Types.h" @@ -90,7 +91,7 @@ class SFile { static const char* GetErrorDetails(); static int32_t Initialize(); static int32_t IsStreamingMode(); - static int32_t InitializeStreaming(const char* mfilPath); + static int32_t STORMAPI InitializeStreaming(const char* mfilPath); static int32_t IsTrial(); static void SetStreamingStatus(bool enabled, bool initialized, bool flag2, bool flag3, uint32_t build); static int32_t STORMAPI List(SArchive* archive, int32_t (*callback)(const char* fileName, void* param), void* param); @@ -133,6 +134,8 @@ struct FileHashCompare { typedef std::map FileHash; +typedef bool (*SOUNDCACHECALLBACK)(const void* data, uint32_t size, Blizzard::Memory::TempBuffer* buffer); + struct ScanDirCookie { /* 0000 */ uint32_t unk_0000; /* 0004 */ const char* m_root; @@ -155,8 +158,17 @@ extern std::deque s_asyncOpenQueue; extern Blizzard::Lock::RMutex s_fileHashLock; extern FileHash s_fileHash; extern Blizzard::Thread::LocalObject s_fatalInfo; +extern Blizzard::Memory::TempBuffer* s_soundCacheBuffer; +extern volatile int32_t s_soundCacheStop; +extern volatile int32_t s_soundCacheStopped; +extern SOUNDCACHECALLBACK s_soundCacheCallback; void BuildFileSystemHash(); +bool InitSoundCache(SOUNDCACHECALLBACK callback); +bool ShutdownSoundCache(); +uint32_t SoundCacheThread(void* param); +bool VerifyAndCacheFile(const char* name); +bool WriteSoundCacheFile(const char* name, const void* data, uint32_t size); bool FindFile(const char* name, char* path, uint32_t size, uint32_t flags, uint32_t* type, System_SFile::ARCHIVEREC** archive); bool OldFindFile(const char* name, char* path, uint32_t size, uint32_t flags, uint32_t* type); bool QueueAsyncOpen(const char* name); @@ -166,6 +178,11 @@ bool ScanDirForFileSystemHash(const char* directory); int32_t STORMAPI SFileCloseFile(SFileImpl* file); uint32_t STORMAPI SFileGetFileSize(SFileImpl* file, uint32_t* sizeHigh); +int32_t STORMAPI SFileAuthenticateArchiveEx(SArchive* archive, uint32_t* result, const uint8_t* modulus, uint32_t modulusSize, const uint8_t* exponent, uint32_t exponentSize); +int32_t STORMAPI SFileCloseArchive(SArchive* archive); +int32_t STORMAPI SFileLoadFileEx(SArchive* archive, const char* name, void** data, uint32_t* size, uint32_t extra, uint32_t flags, SOVERLAPPED* overlapped); +int32_t STORMAPI SFileOpenArchive(const char* path, int32_t priority, uint32_t flags, SArchive** archive); +int32_t STORMAPI SFileUnloadFile(void* data); int32_t STORMAPI SFileOpenFile(const char* name, SFileImpl** result); int32_t STORMAPI SFileReadFile(SFileImpl* file, void* buffer, uint32_t count, uint32_t* bytesRead, SOVERLAPPED* overlapped, uint32_t unused); diff --git a/Engine/Source/BlizzardCore/Source/Packages/Mopaq/IOMpqUnit.cpp b/Engine/Source/BlizzardCore/Source/Packages/Mopaq/IOMpqUnit.cpp index f156d03..6c6c04d 100644 --- a/Engine/Source/BlizzardCore/Source/Packages/Mopaq/IOMpqUnit.cpp +++ b/Engine/Source/BlizzardCore/Source/Packages/Mopaq/IOMpqUnit.cpp @@ -881,3 +881,331 @@ bool IOMpqReadUnit::VerifyRun(uint32_t first, uint32_t count, uint8_t** dest, ui *dest += total; return true; } + +// VERIFY: 41bc2f9a manual +// OFFSET: 0x004397B0 +IOMpqArchiveWriteUnit* IOMpqArchiveWriteUnit::Create(IOUnitContainer* container, System_SFile::ARCHIVEREC* archive, const char* name, uint32_t blockIndex, IOUnit* next) { + if (!next) { + return nullptr; + } + + bool ownsMemory; + void* memory = IOUnitContainer::Alloc(container, sizeof(IOMpqArchiveWriteUnit), &ownsMemory); + + if (!memory) { + return nullptr; + } + + return new (memory) IOMpqArchiveWriteUnit(archive, name, blockIndex, ownsMemory, next); +} + +// INLINED +IOMpqArchiveWriteUnit::IOMpqArchiveWriteUnit(System_SFile::ARCHIVEREC* archive, const char* name, uint32_t blockIndex, bool ownsMemory, IOUnit* next) : IOMpqArchiveUnit(archive, name, blockIndex, ownsMemory, next) { +} + +bool IOMpqArchiveWriteUnit::Read(void* buffer, int64_t offset, uint32_t count, uint32_t* bytesRead) { + return false; +} + +// VERIFY: b7df5c48 manual +// OFFSET: 0x004268B0 +void IOMpqWriteUnit::SetContext(void* context) { + this->m_context = context; +} + +// VERIFY: 295973cf auto +// OFFSET: 0x00429780 +uint32_t IOMpqWriteUnit::GetType() { + return 'mpqW'; +} + +// VERIFY: f1455b0b manual +// OFFSET: 0x0042BB70 +bool IOMpqWriteUnit::GetFileSize(int64_t* size) { + *size = std::min(this->m_sectorSize * this->m_sectorIndex, this->m_fileSize); + return true; +} + +bool IOMpqWriteUnit::Read(void* buffer, int64_t offset, uint32_t count, uint32_t* bytesRead) { + return false; +} + +bool IOMpqWriteUnit::SetFileSize(int64_t size) { + return false; +} + +bool IOMpqWriteUnit::Close() { + return true; +} + +// VERIFY: 00b11648 manual +// OFFSET: 0x00443AC0 +IOMpqWriteUnit::IOMpqWriteUnit(const std::vector& compression, uint32_t fileSize, uint32_t sectorCount, uint32_t sectorSize, Callback callback, IOMpqWriteUnit** self, bool ownsMemory, IOUnit* next) : IOUnit(next, ownsMemory), m_checksums(sectorCount), m_sectorOffsets(sectorCount + 2), m_compression(compression) { + this->m_fileSize = fileSize; + this->m_hasChecksums = false; + this->m_sectorSize = sectorSize; + this->m_sectorIndex = 0; + this->m_callback = callback; + this->m_context = nullptr; + *self = this; + this->m_sectorOffsets.m_data[0] = 4 * (sectorCount + 2); + memset(this->m_sectorOffsets.m_data + 1, 0, 4 * sectorCount + 4); + memset(this->m_checksums.m_data, 0, 4 * sectorCount); +} + +// VERIFY: 8623bfd7 manual +// OFFSET: 0x00443BF0 +IOMpqWriteUnit::~IOMpqWriteUnit() { +} + +// VERIFY: 53dd2286 manual +// OFFSET: 0x00443C90 +IOMpqWriteUnit::IOMpqWriteUnit(const std::vector& compression, uint32_t fileSize, Callback callback, IOMpqWriteUnit** self, bool ownsMemory, IOUnit* next) : IOUnit(next, ownsMemory), m_checksums(0), m_sectorOffsets(0), m_compression(compression) { + this->m_fileSize = fileSize; + this->m_hasChecksums = false; + this->m_sectorSize = fileSize; + this->m_sectorIndex = 0; + this->m_callback = callback; + this->m_context = nullptr; + *self = this; +} + +// VERIFY: c03708dd manual +// OFFSET: 0x004460D0 +IOUnit* IOMpqWriteUnit::Create(IOUnitContainer* container, const std::vector& compression, uint32_t fileSize, uint32_t sectorSize, Callback callback, IOMpqWriteUnit** self, IOUnit* next) { + if (!next || !fileSize) { + return next; + } + + bool ownsMemory; + void* memory = IOUnitContainer::Alloc(container, sizeof(IOMpqWriteUnit), &ownsMemory); + + if (!memory) { + return nullptr; + } + + return new (memory) IOMpqWriteUnit(compression, fileSize, (fileSize + sectorSize - 1) / sectorSize, sectorSize, callback, self, ownsMemory, next); +} + +// VERIFY: 68f18f45 manual +// OFFSET: 0x00446180 +IOUnit* IOMpqWriteUnit::CreateSingle(IOUnitContainer* container, const std::vector& compression, uint32_t fileSize, Callback callback, IOMpqWriteUnit** self, IOUnit* next) { + if (!next) { + return nullptr; + } + + if (!fileSize || compression.empty()) { + return next; + } + + bool ownsMemory; + void* memory = IOUnitContainer::Alloc(container, sizeof(IOMpqWriteUnit), &ownsMemory); + + if (!memory) { + return nullptr; + } + + return new (memory) IOMpqWriteUnit(compression, fileSize, callback, self, ownsMemory, next); +} + +// VERIFY: 1a1255b6 manual +// OFFSET: 0x00459CE0 +void IOMpqWriteUnit::CompressBlock(void* param) { + CompressJob* job = static_cast(param); + IOMpqWriteUnit* unit = job->m_unit; + uint32_t sectorSize = job->m_sectorSize; + uint8_t* dst = job->m_dst; + uint32_t remaining = job->m_size; + const uint8_t* src = job->m_src; + uint32_t* sizes = job->m_sizes; + uint32_t* checksums = job->m_checksums; + + job->m_success = false; + + while (remaining) { + uint32_t chunk = std::min(sectorSize, remaining); + uint32_t size = chunk; + bool checksum = false; + bool compressed; + + if (!unit->m_compression.empty()) { + compressed = System_SComp::Compress(dst, &size, &checksum, src, chunk, unit->m_compression.size(), &unit->m_compression[0]); + } else { + compressed = System_SComp::Compress(dst, &size, &checksum, src, chunk, 0, nullptr); + } + + if (!compressed) { + return; + } + + if (checksum && unit->m_sectorOffsets.m_count) { + uint32_t adler = adler32(0, dst, size); + + if (!adler) { + adler = 0xFFFFFFFF; + } + + *checksums = adler; + unit->m_hasChecksums = true; + } + + checksums++; + src += chunk; + dst += size; + *sizes++ = size; + remaining -= chunk; + } + + job->m_success = true; +} + +// VERIFY: 46c75536 manual +// OFFSET: 0x00459E10 +bool IOMpqWriteUnit::Write(const void* buffer, int64_t offset, uint32_t count) { + if (!count) { + return true; + } + + if (count + static_cast(offset) > this->m_fileSize) { + return false; + } + + if (static_cast(offset) / this->m_sectorSize != this->m_sectorIndex) { + return false; + } + + bool single = !this->m_sectorOffsets.m_count; + uint32_t* offsets; + uint32_t offsetCount; + uint32_t singleOffsets[3]; + + if (!single) { + offsets = this->m_sectorOffsets.m_data; + offsetCount = this->m_sectorOffsets.m_count; + } else { + singleOffsets[1] = 0; + singleOffsets[0] = 0; + offsets = singleOffsets; + offsetCount = 3; + } + + uint32_t sectors = (count + this->m_sectorSize - 1) / this->m_sectorSize; + uint32_t workerCount = 0; + + if (sectors >= 8) { + workerCount = sectors >> 2; + Blizzard::Hardware::GetProcessorFeatures(); + workerCount = std::min(std::min(workerCount, System_Hardware::s_processorFeatures.m_processorCount), 8u) - 1; + } + + System_MPQGlobals::Worker* workers[7]; + System_MPQGlobals::GetWorkerPool()->Acquire(workerCount, workers); + + uint32_t extra = sectors % (workerCount + 1); + uint32_t perJob = sectors / (workerCount + 1); + Blizzard::Memory::TempBuffer output(count); + CompressJob jobs[8]; + uint32_t consumed = 0; + uint32_t sectorsDone = 0; + bool result = true; + + for (uint32_t i = 0;;) { + CompressJob* job = &jobs[i]; + uint32_t jobSectors = perJob + (i < extra); + job->m_src = static_cast(buffer) + consumed; + job->m_dst = output.m_data + consumed; + job->m_sectorSize = this->m_sectorSize; + job->m_unit = this; + + uint32_t bytes = std::min(jobSectors * this->m_sectorSize, count); + consumed += bytes; + count -= bytes; + + uint32_t index = sectorsDone + this->m_sectorIndex; + sectorsDone += jobSectors; + job->m_sizes = offsets + index + 1; + job->m_checksums = this->m_checksums.m_data + index; + job->m_size = bytes; + + if (i) { + System_MPQGlobals::Worker* worker = workers[i - 1]; + + if (!worker->m_proc) { + worker->m_param = job; + worker->m_proc = CompressBlock; + Blizzard::Lock::EventSet(worker->m_start.m_event); + } + } + + if (++i > workerCount) { + break; + } + } + + CompressBlock(&jobs[0]); + + for (uint32_t i = 0; i <= workerCount; i++) { + CompressJob* job = &jobs[i]; + + if (i) { + Blizzard::Lock::EventWaitForever(workers[i - 1]->m_done.m_event); + } + + if (!job->m_success) { + result = false; + } + + uint32_t* last = job->m_sizes + (perJob + (i < extra)) - 1; + + for (uint32_t* size = job->m_sizes; size <= last; size++) { + *size += size[-1]; + } + + if (!this->m_next->Write(job->m_dst, job->m_sizes[-1], *last - job->m_sizes[-1])) { + result = false; + } + } + + System_MPQGlobals::GetWorkerPool()->Release(workerCount, workers); + + if (!result) { + return false; + } + + this->m_sectorIndex += sectorsDone; + + if (this->m_sectorIndex == offsetCount - 2) { + uint32_t end = offsets[this->m_sectorIndex]; + + if (!single) { + if (this->m_hasChecksums) { + uint32_t size = 4 * this->m_checksums.m_count; + Blizzard::Mopaq::CompressionAlgorithm algorithm; + algorithm.m_type = 0x20; + algorithm.m_level = 0; + bool checksum; + + if (!System_SComp::Compress(this->m_checksums.m_data, &size, &checksum, this->m_checksums.m_data, size, 1, &algorithm)) { + return false; + } + + if (!this->m_next->Write(this->m_checksums.m_data, offsets[this->m_sectorIndex], size)) { + return false; + } + + end += size; + } + + offsets[this->m_sectorIndex + 1] = end; + this->m_sectorIndex++; + + if (!this->m_next->Write(offsets, 0, 4 * offsetCount)) { + return false; + } + } + + this->m_callback(this->m_context, end); + } + + return true; +} diff --git a/Engine/Source/BlizzardCore/Source/Packages/Mopaq/IOMpqUnit.h b/Engine/Source/BlizzardCore/Source/Packages/Mopaq/IOMpqUnit.h index bff7d60..24d6c30 100644 --- a/Engine/Source/BlizzardCore/Source/Packages/Mopaq/IOMpqUnit.h +++ b/Engine/Source/BlizzardCore/Source/Packages/Mopaq/IOMpqUnit.h @@ -2,9 +2,11 @@ #define ENGINE_SOURCE_BLIZZARDCORE_SOURCE_PACKAGES_MOPAQ_IOMPQUNIT_H #include +#include #include "Engine/Source/BlizzardCore/Include/Blizzard/Util/Digest.h" #include "Engine/Source/BlizzardCore/Source/Packages/iounit/IOUnit.h" #include "Engine/Source/BlizzardCore/Source/Packages/Mopaq/SFileArchives.h" +#include "Engine/Source/BlizzardCore/Source/Packages/Mopaq/Types.h" #include "Engine/Source/BlizzardCore/Source/System/Memory/TempBuffer.h" class IOMpqUnit : public IOUnit { @@ -67,6 +69,15 @@ class IOMpqArchiveReadUnit : public IOMpqArchiveUnit { IOMpqArchiveReadUnit(System_SFile::ARCHIVEREC* archive, const char* name, uint32_t blockIndex, bool ownsMemory, IOUnit* next); }; +class IOMpqArchiveWriteUnit : public IOMpqArchiveUnit { + public: + static IOMpqArchiveWriteUnit* Create(IOUnitContainer* container, System_SFile::ARCHIVEREC* archive, const char* name, uint32_t blockIndex, IOUnit* next); + + virtual bool Read(void* buffer, int64_t offset, uint32_t count, uint32_t* bytesRead); + + IOMpqArchiveWriteUnit(System_SFile::ARCHIVEREC* archive, const char* name, uint32_t blockIndex, bool ownsMemory, IOUnit* next); +}; + class IOMpqDiskUnit : public IOMpqUnit { public: static IOMpqDiskUnit* Create(IOUnitContainer* container, System_SFile::ARCHIVEREC* archive, const char* name, const char* path, IOUnit* next); @@ -139,4 +150,48 @@ class IOMpqReadUnit : public IOUnit { bool VerifyRun(uint32_t first, uint32_t count, uint8_t** dest, uint8_t** scratch, uint32_t* scratchLeft); }; +class IOMpqWriteUnit : public IOUnit { + public: + typedef void (*Callback)(void* context, uint32_t size); + + struct CompressJob { + /* 0000 */ IOMpqWriteUnit* m_unit; + /* 0004 */ const uint8_t* m_src; + /* 0008 */ uint8_t* m_dst; + /* 000C */ uint32_t m_sectorSize; + /* 0010 */ uint32_t m_size; + /* 0014 */ uint32_t* m_sizes; + /* 0018 */ uint32_t* m_checksums; + /* 001C */ bool m_success; + /* 001D */ uint8_t unk_001D[3]; + }; + + static void CompressBlock(void* param); + static IOUnit* Create(IOUnitContainer* container, const std::vector& compression, uint32_t fileSize, uint32_t sectorSize, Callback callback, IOMpqWriteUnit** self, IOUnit* next); + static IOUnit* CreateSingle(IOUnitContainer* container, const std::vector& compression, uint32_t fileSize, Callback callback, IOMpqWriteUnit** self, IOUnit* next); + + /* 0010 */ uint32_t m_fileSize; + /* 0014 */ Blizzard::Memory::TempBuffer m_checksums; + /* 003C */ bool m_hasChecksums; + /* 003D */ uint8_t unk_003D[3]; + /* 0040 */ Blizzard::Memory::TempBuffer m_sectorOffsets; + /* 0070 */ uint32_t m_sectorSize; + /* 0074 */ uint32_t m_sectorIndex; + /* 0078 */ std::vector m_compression; + /* 0088 */ Callback m_callback; + /* 008C */ void* m_context; + + virtual uint32_t GetType(); + virtual bool Read(void* buffer, int64_t offset, uint32_t count, uint32_t* bytesRead); + virtual bool Write(const void* buffer, int64_t offset, uint32_t count); + virtual bool GetFileSize(int64_t* size); + virtual bool SetFileSize(int64_t size); + virtual ~IOMpqWriteUnit(); + virtual bool Close(); + virtual void SetContext(void* context); + + IOMpqWriteUnit(const std::vector& compression, uint32_t fileSize, uint32_t sectorCount, uint32_t sectorSize, Callback callback, IOMpqWriteUnit** self, bool ownsMemory, IOUnit* next); + IOMpqWriteUnit(const std::vector& compression, uint32_t fileSize, Callback callback, IOMpqWriteUnit** self, bool ownsMemory, IOUnit* next); +}; + #endif diff --git a/Engine/Source/BlizzardCore/Source/Packages/Mopaq/MPQEncrypt.cpp b/Engine/Source/BlizzardCore/Source/Packages/Mopaq/MPQEncrypt.cpp index 18c20b8..18c6661 100644 --- a/Engine/Source/BlizzardCore/Source/Packages/Mopaq/MPQEncrypt.cpp +++ b/Engine/Source/BlizzardCore/Source/Packages/Mopaq/MPQEncrypt.cpp @@ -213,3 +213,17 @@ void System_MPQEncrypt::Decrypt(uint32_t* data, uint32_t size, uint32_t key) { seed = value + seed + (seed << 5) + 3; } } + +// VERIFY: fa28dc11 manual +// OFFSET: 0x00426670 +void System_MPQEncrypt::Encrypt(uint32_t* data, uint32_t size, uint32_t key) { + uint32_t seed = 0xEEEEEEEE; + + for (uint32_t count = size >> 2; count; count--) { + seed += s_cryptTable[0x400 + (key & 0xFF)]; + uint32_t value = *data; + *data++ = value ^ (key + seed); + key = ((~key << 21) + 0x11111111) | (key >> 11); + seed = value + seed + (seed << 5) + 3; + } +} diff --git a/Engine/Source/BlizzardCore/Source/Packages/Mopaq/MPQEncrypt.h b/Engine/Source/BlizzardCore/Source/Packages/Mopaq/MPQEncrypt.h index 5dbbbb3..f746a79 100644 --- a/Engine/Source/BlizzardCore/Source/Packages/Mopaq/MPQEncrypt.h +++ b/Engine/Source/BlizzardCore/Source/Packages/Mopaq/MPQEncrypt.h @@ -9,6 +9,7 @@ extern const uint32_t s_cryptTable[1280]; extern const uint8_t s_hashChars[256]; void Decrypt(uint32_t* data, uint32_t size, uint32_t key); +void Encrypt(uint32_t* data, uint32_t size, uint32_t key); uint32_t Hash(const char* str, uint32_t type); } diff --git a/Engine/Source/BlizzardCore/Source/Packages/Mopaq/MPQGlobals.cpp b/Engine/Source/BlizzardCore/Source/Packages/Mopaq/MPQGlobals.cpp index f1cfd96..63f5d9a 100644 --- a/Engine/Source/BlizzardCore/Source/Packages/Mopaq/MPQGlobals.cpp +++ b/Engine/Source/BlizzardCore/Source/Packages/Mopaq/MPQGlobals.cpp @@ -1,4 +1,6 @@ #include +#include +#include "Engine/Source/BlizzardCore/Source/Packages/Mopaq/SFileArchives.h" #include "Engine/Source/BlizzardCore/Source/Packages/Mopaq/MPQGlobals.h" #include "Engine/Source/BlizzardCore/Source/System/Process/Process.h" @@ -122,3 +124,17 @@ void System_MPQGlobals::WorkerPool::Release(uint32_t count, Worker** workers) { Blizzard::Lock::MutexLeave(this->m_mutex.m_mutex); } + +// VERIFY: 99eaeda8 manual +// OFFSET: 0x00453FC0 +System_SFile::ARCHIVEREC* System_MPQGlobals::FindArchiveByName(const char* name) { + ArchiveList* archives = GetArchiveList(); + + for (ArchiveList::iterator it = archives->begin(); it != archives->end(); ++it) { + if (name && *it && !_stricmp(name, (*it)->m_name)) { + return *it; + } + } + + return nullptr; +} diff --git a/Engine/Source/BlizzardCore/Source/Packages/Mopaq/MPQGlobals.h b/Engine/Source/BlizzardCore/Source/Packages/Mopaq/MPQGlobals.h index 54bec54..3285869 100644 --- a/Engine/Source/BlizzardCore/Source/Packages/Mopaq/MPQGlobals.h +++ b/Engine/Source/BlizzardCore/Source/Packages/Mopaq/MPQGlobals.h @@ -62,6 +62,7 @@ class Globals { extern Blizzard::Lock::ConstructOnce s_globals; +System_SFile::ARCHIVEREC* FindArchiveByName(const char* name); ArchiveList* GetArchiveList(); Blizzard::Lock::RMutex* GetArchiveLock(); MopaqGlobals* GetMopaqGlobals(); diff --git a/Engine/Source/BlizzardCore/Source/Packages/Mopaq/SComp.cpp b/Engine/Source/BlizzardCore/Source/Packages/Mopaq/SComp.cpp index 9bfb00d..09936fa 100644 --- a/Engine/Source/BlizzardCore/Source/Packages/Mopaq/SComp.cpp +++ b/Engine/Source/BlizzardCore/Source/Packages/Mopaq/SComp.cpp @@ -8,6 +8,7 @@ extern "C" { #include "ThirdParty/zlib/contrib/blast/blast.h" } +#include "ThirdParty/bzip2/bzlib.h" #include "ThirdParty/zlib/zlib.h" extern "C" { @@ -338,3 +339,506 @@ bool System_SComp::Decompress(void* dst, uint32_t* dstSize, const void* src, uin return DecompressBlock(dst, dstSize, static_cast(src) + 1, srcSize - 1, decompressors); } + +// STATIC: 0x009E6DF8 +static const System_SComp::COMPRESSOR s_rleCompressor = { 0x20, System_SComp::RLEZeroCompress }; + +// STATIC: 0x009E6E00 +static const System_SComp::COMPRESSOR s_zlibCompressor = { 0x02, System_SComp::ZlibCompress }; + +// STATIC: 0x009E6E08 +static const System_SComp::COMPRESSOR s_pkwareCompressor = { 0x08, System_SComp::PkwareCompress }; + +// STATIC: 0x009E6E10 +static const System_SComp::COMPRESSOR s_bzip2Compressor = { 0x10, System_SComp::Bzip2Compress }; + +// OFFSET: 0x004268D0 +void System_SComp::PkwareCompress(void* dest, uint32_t* destSize, const void* source, uint32_t sourceSize, uint32_t* hint, uint8_t level) { + *destSize = sourceSize; + *hint = 0; +} + +// OFFSET: 0x004269A0 +void System_SComp::Bzip2Compress(void* dest, uint32_t* destSize, const void* source, uint32_t sourceSize, uint32_t* hint, uint8_t level) { + int32_t result = BZ2_bzBuffToBuffCompress(static_cast(dest), destSize, static_cast(const_cast(source)), sourceSize, 9, 0, 0); + + if (result == BZ_OUTBUFF_FULL) { + *destSize = sourceSize; + *hint = 0; + return; + } + + if (result != BZ_OK) { + *destSize = sourceSize; + } + + *hint = 0; +} + +// VERIFY: ab400dc7 manual +// OFFSET: 0x004269F0 +uint8_t* System_SComp::BufferPool::Alloc() { + uint8_t* result = this->m_base; + uint32_t end = 1 << this->m_count; + uint32_t bit = 0; + + if (!end) { + return nullptr; + } + + while (this->m_used & bit) { + result += this->m_size; + bit *= 2; + + if (bit == end) { + return nullptr; + } + } + + this->m_used |= bit; + return result; +} + +// VERIFY: fc9c4cce manual +// OFFSET: 0x0042BBC0 +void System_SComp::RLEZeroCompress(void* dest, uint32_t* destSize, const void* source, uint32_t sourceSize, uint32_t* hint, uint8_t level) { + uint8_t* basedest = static_cast(dest); + uint8_t* enddest = basedest + *destSize; + const uint8_t* curr = static_cast(source); + const uint8_t* endsource = curr + sourceSize; + + if (basedest + 4 >= enddest) { + return; + } + + basedest[0] = static_cast(sourceSize >> 24); + basedest[1] = static_cast(sourceSize >> 16); + basedest[2] = static_cast(sourceSize >> 8); + basedest[3] = static_cast(sourceSize); + + uint8_t* currdest = basedest + 4; + + while (curr < endsource - 3) { + uint32_t zeros = 0; + const uint8_t* literalend = curr; + + for (const uint8_t* scan = curr; scan < endsource; scan++) { + if (*scan) { + if (zeros >= 3) { + break; + } + + zeros = 0; + literalend = scan + 1; + } else { + zeros++; + } + } + + uint32_t literal = static_cast(literalend - curr); + + if (literal) { + while (literal > 0x81) { + if (currdest + 129 >= enddest) { + return; + } + + *currdest++ = 0xFF; + memcpy(currdest, curr, 128); + currdest += 128; + curr += 128; + literal -= 128; + } + + if (literal > 0x80) { + if (currdest + 2 >= enddest) { + return; + } + + *currdest++ = 0x80; + memcpy(currdest, curr, 1); + currdest += 1; + curr += 1; + literal -= 1; + } + + if (literal < 1) { + if (currdest + 2 >= enddest) { + return; + } + + *currdest++ = 0x80; + memcpy(currdest, curr, 1); + currdest += 1; + curr += 1; + zeros = zeros + literal - 1; + } else { + if (currdest + literal + 1 >= enddest) { + return; + } + + *currdest++ = static_cast((literal - 1) | 0x80); + memcpy(currdest, curr, literal); + currdest += literal; + curr += literal; + } + } + + while (zeros > 0x85) { + if (currdest + 1 >= enddest) { + return; + } + + *currdest++ = 0x7F; + curr += 130; + zeros -= 130; + } + + if (zeros > 0x82) { + if (currdest + 1 >= enddest) { + return; + } + + *currdest++ = 0; + curr += 3; + zeros -= 3; + } + + if (zeros >= 3) { + if (currdest + 1 >= enddest) { + return; + } + + *currdest++ = static_cast(zeros - 3); + curr += zeros; + } + } + + if (curr < endsource) { + for (const uint8_t* scan = curr; scan < endsource; scan++) { + if (*scan) { + uint32_t literal = static_cast(endsource - curr); + + if (currdest + literal + 1 < enddest) { + *currdest++ = 0xFF; + memcpy(currdest, curr, literal); + *destSize = static_cast(currdest + literal - basedest); + } + + return; + } + } + + if (currdest + 1 >= enddest) { + return; + } + + *currdest++ = 0x7F; + } + + *destSize = static_cast(currdest - basedest); +} + +// VERIFY: f852877e auto +// OFFSET: 0x004539A0 +int System_SComp::zlib_compress(uint8_t* dest, uint32_t* destLen, const uint8_t* source, uint32_t sourceLen, int level) { + z_stream stream; + stream.next_in = const_cast(source); + stream.avail_in = sourceLen; + stream.next_out = dest; + stream.avail_out = *destLen; + + ZlibAllocBuffer* buffer = &static_cast(s_zlibAllocBuffer); + buffer->m_next = buffer->m_buffer; + stream.zalloc = ZlibAlloc; + stream.zfree = ZlibFree; + stream.opaque = buffer; + + int windowBits; + + if (sourceLen <= 0x100) { + windowBits = 8; + } else if (sourceLen <= 0x200) { + windowBits = 9; + } else if (sourceLen <= 0x400) { + windowBits = 10; + } else if (sourceLen <= 0x800) { + windowBits = 11; + } else if (sourceLen <= 0x1000) { + windowBits = 12; + } else if (sourceLen <= 0x2000) { + windowBits = 13; + } else { + windowBits = (sourceLen > 0x4000) + 14; + } + + int result = deflateInit2_(&stream, level, Z_DEFLATED, windowBits, 8, Z_DEFAULT_STRATEGY, "1.2.3", sizeof(stream)); + + if (result != Z_OK) { + return result; + } + + result = deflate(&stream, Z_FINISH); + + if (result != Z_STREAM_END) { + deflateEnd(&stream); + return result ? result : Z_BUF_ERROR; + } + + *destLen = stream.total_out; + return deflateEnd(&stream); +} + +// OFFSET: 0x00453AB0 +void System_SComp::ZlibCompress(void* dest, uint32_t* destSize, const void* source, uint32_t sourceSize, uint32_t* hint, uint8_t level) { + int level2; + + switch (level) { + case 1: + level2 = Z_BEST_COMPRESSION; + break; + case 2: + level2 = Z_BEST_SPEED; + break; + default: + level2 = Z_DEFAULT_COMPRESSION; + break; + } + + uint32_t size = *destSize; + + if (!zlib_compress(static_cast(dest), &size, static_cast(source), sourceSize, level2)) { + *destSize = size; + } + + *hint = 0; +} + +// VERIFY: 804c8455 manual +// OFFSET: 0x00458080 +bool System_SComp::Compress(void* dst, uint32_t* dstSize, bool* checksum, const void* src, uint32_t srcSize, uint32_t count, const Blizzard::Mopaq::CompressionAlgorithm* algorithms) { + *checksum = false; + + const uint8_t* best = static_cast(src); + uint32_t bestSize = srcSize; + bool bestPooled = false; + uint8_t bestType = 0; + + if (count) { + bool overlap = static_cast(src) + srcSize > dst && static_cast(dst) + *dstSize > src; + bool multiple = count > 1; + bool twoStage = false; + + for (uint32_t i = 0; i < count; i++) { + switch (algorithms[i].m_type) { + case 0x02: + case 0x08: + case 0x10: + case 0x12: + case 0x20: + continue; + default: + twoStage = true; + break; + } + } + + uint32_t buffers = overlap + multiple + twoStage; + Blizzard::Memory::TempBuffer scratch(0); + + if (buffers) { + scratch.Resize(srcSize * buffers); + } + + BufferPool pool; + pool.m_base = scratch.m_data; + pool.m_size = srcSize; + pool.m_count = buffers; + pool.m_used = 0; + + for (uint32_t j = 0; j < count; j++) { + uint8_t type = algorithms[j].m_type; + uint8_t level = algorithms[j].m_level; + const COMPRESSOR* stages[2]; + uint32_t stageCount; + + switch (type) { + case 0x02: + stages[0] = &s_zlibCompressor; + stageCount = 1; + break; + case 0x08: + stages[0] = &s_pkwareCompressor; + stageCount = 1; + break; + case 0x10: + stages[0] = &s_bzip2Compressor; + stageCount = 1; + break; + case 0x12: + Blizzard::File::AddToLastErrorStack(type, "System_SComp::Compress - Lzma compression isn't enabled", 4); + return false; + case 0x20: + stageCount = 1; + stages[0] = &s_rleCompressor; + break; + case 0x22: + stages[1] = &s_zlibCompressor; + stageCount = 2; + stages[0] = &s_rleCompressor; + break; + case 0x30: + stages[1] = &s_bzip2Compressor; + stageCount = 2; + stages[0] = &s_rleCompressor; + break; + default: + Blizzard::File::AddToLastErrorStack(type, "System_SComp::Compress - Unrecognized Compression Type", 4); + return false; + } + + uint8_t* output; + bool outputPooled; + + if (!overlap && best != dst) { + output = static_cast(dst); + outputPooled = false; + } else { + output = pool.Alloc(); + outputPooled = true; + } + + uint8_t* intermediate = nullptr; + const uint8_t* inputs[2]; + uint8_t* outputs[2]; + + if (stageCount == 1) { + outputs[0] = output + 1; + inputs[0] = static_cast(src); + } else { + intermediate = pool.Alloc(); + inputs[0] = static_cast(src); + outputs[0] = intermediate; + inputs[1] = intermediate; + outputs[1] = output + 1; + } + + uint32_t size = srcSize; + uint8_t combined = 0; + + for (uint32_t k = 0; k < stageCount; k++) { + const COMPRESSOR* stage = stages[k]; + uint32_t limit = size - 1; + uint32_t outSize = limit; + uint32_t hint = 0; + stage->m_func(outputs[k], &outSize, inputs[k], size, &hint, level); + size = outSize; + + if (outSize >= limit) { + size = 0xFFFFFFFF; + break; + } + + if (!combined) { + combined = static_cast(stage->m_type); + } else if (combined == 0x20 && static_cast(stage->m_type) == 0x02) { + combined = 0x22; + } else if (combined == 0x20 && static_cast(stage->m_type) == 0x10) { + combined = 0x30; + } else { + size = 0xFFFFFFFF; + break; + } + } + + if (size < bestSize) { + if (bestPooled && (1 << pool.m_count)) { + uint8_t* slot = pool.m_base; + uint32_t bit = 0; + + while (slot != best) { + slot += pool.m_size; + bit *= 2; + + if (bit == static_cast(1 << pool.m_count)) { + break; + } + } + + if (slot == best) { + pool.m_used &= ~bit; + } + } + + *output = combined; + bestType = combined; + best = output; + bestSize = size + 1; + bestPooled = outputPooled; + } else if (outputPooled && (1 << pool.m_count)) { + uint8_t* slot = pool.m_base; + uint32_t bit = 0; + + while (slot != output) { + slot += pool.m_size; + bit *= 2; + + if (bit == static_cast(1 << pool.m_count)) { + break; + } + } + + if (slot == output) { + pool.m_used &= ~bit; + } + } + + if (intermediate && (1 << pool.m_count)) { + uint8_t* slot = pool.m_base; + uint32_t bit = 0; + + while (slot != intermediate) { + bit *= 2; + slot += pool.m_size; + + if (bit == static_cast(1 << pool.m_count)) { + break; + } + } + + if (slot == intermediate) { + pool.m_used &= ~bit; + } + } + } + + if (best != dst) { + memcpy(dst, best, bestSize); + + if (bestPooled && (1 << pool.m_count)) { + uint8_t* slot = pool.m_base; + uint32_t bit = 0; + + while (slot != best) { + bit *= 2; + slot += pool.m_size; + + if (bit == static_cast(1 << pool.m_count)) { + break; + } + } + + if (slot == best) { + pool.m_used &= ~bit; + } + } + } + } else if (src != dst) { + memcpy(dst, src, srcSize); + } + + *dstSize = bestSize; + *checksum = !(bestType == 0x02 || bestType == 0x10 || bestType == 0x12); + + return true; +} diff --git a/Engine/Source/BlizzardCore/Source/Packages/Mopaq/SComp.h b/Engine/Source/BlizzardCore/Source/Packages/Mopaq/SComp.h index 096e247..7880a1e 100644 --- a/Engine/Source/BlizzardCore/Source/Packages/Mopaq/SComp.h +++ b/Engine/Source/BlizzardCore/Source/Packages/Mopaq/SComp.h @@ -2,14 +2,31 @@ #define ENGINE_SOURCE_BLIZZARDCORE_SOURCE_PACKAGES_MOPAQ_SCOMP_H #include +#include "Engine/Source/BlizzardCore/Source/Packages/Mopaq/Types.h" #include "Engine/Source/BlizzardCore/Source/System/Thread/ThreadLocalStorage.h" bool LzmaMemDecode(const uint8_t* source, uint32_t sourceSize, uint8_t* dest, uint32_t destSize, uint32_t* destProcessed, void* (*alloc)(uint32_t size), void (*free)(void* address)); namespace System_SComp { +typedef void (*Compressor)(void* dest, uint32_t* destSize, const void* source, uint32_t sourceSize, uint32_t* hint, uint8_t level); typedef int32_t (*Decompressor)(void* dest, uint32_t* destSize, const void* source, uint32_t sourceSize); +struct COMPRESSOR { + /* 0000 */ uint32_t m_type; + /* 0004 */ Compressor m_func; +}; + +class BufferPool { + public: + /* 0000 */ uint8_t* m_base; + /* 0004 */ uint32_t m_size; + /* 0008 */ uint32_t m_count; + /* 000C */ uint32_t m_used; + + uint8_t* Alloc(); +}; + struct PkwareBuffer { /* 0000 */ uint8_t* m_output; /* 0004 */ uint32_t m_outputPos; @@ -26,17 +43,23 @@ struct ZlibAllocBuffer { extern Blizzard::Thread::LocalObject s_zlibAllocBuffer; void* alloc_wrap(uint32_t size); +void Bzip2Compress(void* dest, uint32_t* destSize, const void* source, uint32_t sourceSize, uint32_t* hint, uint8_t level); +bool Compress(void* dst, uint32_t* dstSize, bool* checksum, const void* src, uint32_t srcSize, uint32_t count, const Blizzard::Mopaq::CompressionAlgorithm* algorithms); bool Decompress(void* dst, uint32_t* dstSize, const void* src, uint32_t srcSize); bool __stdcall DecompressBlock(void* dst, uint32_t* dstSize, const void* src, uint32_t srcSize, Decompressor* decompressors); void free_wrap(void* address); int32_t LzmaDecompress(void* dest, uint32_t* destSize, const void* source, uint32_t sourceSize); +void PkwareCompress(void* dest, uint32_t* destSize, const void* source, uint32_t sourceSize, uint32_t* hint, uint8_t level); unsigned int PkwareBufferRead(void* param, unsigned char** buffer); int PkwareBufferWrite(void* param, unsigned char* data, unsigned int size); int32_t PkwareDecompress(void* dest, uint32_t* destSize, const void* source, uint32_t sourceSize); +void RLEZeroCompress(void* dest, uint32_t* destSize, const void* source, uint32_t sourceSize, uint32_t* hint, uint8_t level); int32_t RLEZeroDecompress(void* dest, uint32_t* destSize, const void* source, uint32_t sourceSize); +void ZlibCompress(void* dest, uint32_t* destSize, const void* source, uint32_t sourceSize, uint32_t* hint, uint8_t level); void* ZlibAlloc(void* opaque, unsigned int items, unsigned int size); int32_t ZlibDecompress(void* dest, uint32_t* destSize, const void* source, uint32_t sourceSize); void ZlibFree(void* opaque, void* address); +int zlib_compress(uint8_t* dest, uint32_t* destLen, const uint8_t* source, uint32_t sourceLen, int level); int zlib_decompress(uint8_t* dest, uint32_t* destLen, const uint8_t* source, uint32_t sourceLen); } diff --git a/Engine/Source/BlizzardCore/Source/Packages/Mopaq/SFile.cpp b/Engine/Source/BlizzardCore/Source/Packages/Mopaq/SFile.cpp index 7db8c0f..ddbe5c6 100644 --- a/Engine/Source/BlizzardCore/Source/Packages/Mopaq/SFile.cpp +++ b/Engine/Source/BlizzardCore/Source/Packages/Mopaq/SFile.cpp @@ -264,6 +264,17 @@ uint32_t Blizzard::Mopaq::SFileGetFileSize(IOMpqUnit* file, uint32_t* sizeHigh) return -1; } +// VERIFY: 7d8723e2 auto +// OFFSET: 0x00426FA0 +bool Blizzard::Mopaq::SFileWriteFile(IOMpqUnit* file, const void* data, uint32_t size) { + if (!file->Write(data, file->m_position, size)) { + return false; + } + + file->m_position += size; + return true; +} + // VERIFY: 3d1301e5 auto // OFFSET: 0x004321A0 bool Blizzard::Mopaq::SFileCloseFile(IOMpqUnit* file) { @@ -337,6 +348,36 @@ bool Blizzard::Mopaq::SFileReadFile(IOMpqUnit* file, void* buffer, uint32_t coun return result; } +// VERIFY: dd4a5d22 manual +// OFFSET: 0x0045A610 +int32_t Blizzard::Mopaq::SFileFileIsLocal(IOMpqUnit* file, int32_t flags) { + if (!file) { + return 1; + } + + const char* path = file->GetPath(); + int32_t result = Blizzard::Streaming::CheckFileRange(nullptr, 0, 0, path, flags); + + if (result == 1) { + return result; + } + + int64_t offset = file->GetOffset(); + int64_t compressed = 0; + int32_t size = file->GetCompressedSize(&compressed) ? static_cast(compressed) : -1; + System_SFile::ARCHIVEREC* archive = file->GetArchive(); + + if (!archive) { + file->Release(); + return 1; + } + + char name[260]; + SFileGetArchiveName(archive, name, sizeof(name)); + + return Blizzard::Streaming::CheckFileRange(name, offset, size, path, flags); +} + // VERIFY: 672505f5 manual // OFFSET: 0x0045B5A0 bool Blizzard::Mopaq::SFileLoadFile(System_SFile::ARCHIVEREC* handle, const char* name, void** data, uint32_t* size, uint32_t extra, uint32_t flags) { diff --git a/Engine/Source/BlizzardCore/Source/Packages/Mopaq/SFile.h b/Engine/Source/BlizzardCore/Source/Packages/Mopaq/SFile.h index 782dfed..b54ea3a 100644 --- a/Engine/Source/BlizzardCore/Source/Packages/Mopaq/SFile.h +++ b/Engine/Source/BlizzardCore/Source/Packages/Mopaq/SFile.h @@ -44,10 +44,18 @@ IOUnit* OpenFileUnit(IOUnitContainer* container, const char* path, int32_t mode) } +namespace System_Mopaq { + +bool CreateDiskFile(const char* name, uint32_t flags, const char* path, System_SFile::ARCHIVEREC* archive, IOMpqUnit** result); + +} + namespace Blizzard { namespace Mopaq { bool SFileCloseFile(IOMpqUnit* file); +bool SFileCreateFile(System_SFile::ARCHIVEREC* handle, const char* name, uint32_t size, uint32_t flags, IOMpqUnit** result); +int32_t SFileFileIsLocal(IOMpqUnit* file, int32_t flags); bool SFileGetArchiveName(System_SFile::ARCHIVEREC* handle, char* name, uint32_t size); uint32_t SFileGetFileSize(IOMpqUnit* file, uint32_t* sizeHigh); bool SFileLoadFile(System_SFile::ARCHIVEREC* handle, const char* name, void** data, uint32_t* size, uint32_t extra, uint32_t flags); @@ -57,6 +65,7 @@ bool SFileReadFile(IOMpqUnit* file, void* buffer, uint32_t count, uint32_t* byte bool SFileUnloadFile(void* data); int32_t SFileSetFilePointer(IOMpqUnit* file, int32_t distance, int32_t* distanceHigh, uint32_t method); void SFileSetThreadingMode(uint32_t mode); +bool SFileWriteFile(IOMpqUnit* file, const void* data, uint32_t size); } } diff --git a/Engine/Source/BlizzardCore/Source/Packages/Mopaq/SFileArchives.cpp b/Engine/Source/BlizzardCore/Source/Packages/Mopaq/SFileArchives.cpp index fe48cd4..20d65f8 100644 --- a/Engine/Source/BlizzardCore/Source/Packages/Mopaq/SFileArchives.cpp +++ b/Engine/Source/BlizzardCore/Source/Packages/Mopaq/SFileArchives.cpp @@ -1,7 +1,14 @@ +#include #include #include #include +#include +#include +#include +#include "Engine/Source/BlizzardCore/Source/Packages/iounit/IOAlignUnit.h" +#include "Engine/Source/BlizzardCore/Source/Packages/iounit/IOChecksumUnit.h" #include "Engine/Source/BlizzardCore/Source/Packages/iounit/IOFileUnit.h" +#include "Engine/Source/BlizzardCore/Source/Packages/iounit/IOUnitContainer.h" #include "Engine/Source/BlizzardCore/Source/Packages/Mopaq/IOMpqUnit.h" #include "Engine/Source/BlizzardCore/Source/Packages/Mopaq/MPQEncrypt.h" #include "Engine/Source/BlizzardCore/Source/Packages/Mopaq/MPQGlobals.h" @@ -12,6 +19,7 @@ #include "Engine/Source/BlizzardCore/Source/Packages/Mopaq/SFileSignatures.h" #include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Streaming.h" #include "Engine/Source/BlizzardCore/Source/Packages/Util/Hash.h" +#include "Engine/Source/BlizzardCore/Source/Packages/Util/SBig.h" #include "Engine/Source/BlizzardCore/Source/System/Debug/Debug.h" #include "Engine/Source/BlizzardCore/Source/System/Debug/ErrorStack.h" #include "Engine/Source/BlizzardCore/Source/System/File/File.h" @@ -543,6 +551,105 @@ System_SFile::ARCHIVEREC* System_SFile::GetArchivePtr(ARCHIVEREC* handle, bool a return archive; } +// STATIC: 0x009E522C +static const uint8_t s_defaultAuthExponent[4] = { + 0x01, 0x00, 0x01, 0x00, +}; + +// STATIC: 0x009E5230 +static const uint8_t s_defaultAuthModulus[256] = { + 0x77, 0x64, 0xF8, 0x57, 0x1D, 0xFB, 0xB0, 0x09, 0xC4, 0xE6, 0x28, 0x91, 0x34, 0xE3, 0x55, 0x61, + 0x15, 0x8A, 0xE9, 0x07, 0xFC, 0xAA, 0x60, 0xB3, 0x82, 0xB7, 0xE2, 0xA4, 0x40, 0x15, 0x01, 0x3F, + 0xC2, 0x36, 0xA8, 0x9D, 0x95, 0xD0, 0x54, 0x69, 0xAA, 0xF5, 0xED, 0x5C, 0x7F, 0x21, 0xC5, 0x55, + 0x95, 0x56, 0x5B, 0x2F, 0xC6, 0xDD, 0x2C, 0xBD, 0x74, 0xA3, 0x5A, 0x0D, 0x70, 0x98, 0x9A, 0x01, + 0x36, 0x51, 0x78, 0x71, 0x9B, 0x8E, 0xCB, 0xB8, 0x84, 0x67, 0x30, 0xF4, 0x43, 0xB3, 0xA3, 0x50, + 0xA3, 0xBA, 0xA4, 0xF7, 0xB1, 0x94, 0xE5, 0x5B, 0x95, 0x8B, 0x1A, 0xE4, 0x04, 0x1D, 0xFB, 0xCF, + 0x0E, 0xE6, 0x97, 0x4C, 0xDC, 0xE4, 0x28, 0x7F, 0xB8, 0x58, 0x4A, 0x45, 0x1B, 0xC8, 0x8C, 0xD0, + 0xFD, 0x2E, 0x77, 0xC4, 0x30, 0xD8, 0x3D, 0xD2, 0xD5, 0xFA, 0xBA, 0x9D, 0x1E, 0x02, 0xF6, 0x7B, + 0xBE, 0x08, 0x95, 0xCB, 0xB0, 0x53, 0x3E, 0x1C, 0x41, 0x45, 0xFC, 0x27, 0x6F, 0x63, 0x6A, 0x73, + 0x91, 0xA9, 0x42, 0x00, 0x12, 0x93, 0xF8, 0x5B, 0x83, 0xED, 0x52, 0x77, 0x4E, 0x38, 0x08, 0x16, + 0x23, 0x10, 0x85, 0x4C, 0x0B, 0xA9, 0x8C, 0x9C, 0x40, 0x4C, 0xAF, 0x6E, 0xA7, 0x89, 0x02, 0xC5, + 0x06, 0x96, 0x99, 0x41, 0xD4, 0x31, 0x03, 0x4A, 0xA9, 0x2B, 0x17, 0x52, 0xDD, 0x5C, 0x4E, 0x5F, + 0x16, 0xC3, 0x81, 0x0F, 0x2E, 0xE2, 0x17, 0x45, 0x2B, 0x7B, 0x65, 0x7A, 0xA3, 0x18, 0x87, 0xC2, + 0xB2, 0xF5, 0xCD, 0x9C, 0xBA, 0xCB, 0xDE, 0x07, 0x6F, 0x7C, 0x8B, 0x03, 0x68, 0xE6, 0x3C, 0x5A, + 0x2C, 0xAE, 0xDC, 0xC3, 0xC8, 0x38, 0x35, 0x82, 0xDA, 0x4D, 0x04, 0xCE, 0x9C, 0x68, 0x47, 0x7D, + 0xB4, 0x1D, 0x98, 0x42, 0x8C, 0xF8, 0x27, 0x7E, 0xC8, 0x87, 0xF6, 0x24, 0xCE, 0x7E, 0x06, 0xB1, +}; + +// VERIFY: 4328d4d7 manual +// OFFSET: 0x0045A260 +bool Blizzard::Mopaq::SFileAuthenticateArchiveEx(System_SFile::ARCHIVEREC* handle, AuthResult* result, const uint8_t* modulus, uint32_t modulusSize, const uint8_t* exponent, uint32_t exponentSize, const char* salt) { + if ((!modulus || !modulusSize) && (!exponent || !exponentSize)) { + modulus = s_defaultAuthModulus; + modulusSize = sizeof(s_defaultAuthModulus); + exponent = s_defaultAuthExponent; + exponentSize = sizeof(s_defaultAuthExponent); + } + + AuthResult unused; + + if (!result) { + result = &unused; + } + + *result = AUTH_UNKNOWN; + + System_SFile::ArchivePtr archive(System_SFile::GetArchivePtr(handle, true)); + + if (archive.m_archive) { + Blizzard::Lock::MutexEnter(archive.m_archive->m_mutex.m_mutex); + } + + archive.m_locked = true; + + if (!archive.m_archive || !archive.m_archive->m_file || archive.m_archive->m_closeCallback) { + return false; + } + + SSignatureData* token = nullptr; + SSignatureVerifyStream_Begin(&token, modulusSize, exponentSize); + + uint8_t buffer[65536]; + int64_t pos = archive.m_archive->m_archiveOffset; + + if (pos < archive.m_archive->m_archiveEnd) { + uint32_t chunk = 0x10000; + + do { + uint32_t remaining = static_cast(archive.m_archive->m_archiveEnd - pos); + uint32_t size = remaining >= 0x10000 ? chunk : remaining; + + if (!archive.m_archive->m_file->Read(buffer, pos, size, nullptr)) { + break; + } + + SSignatureVerifyStream_ProvideData(token, buffer, size); + pos += 0x10000; + } while (pos < archive.m_archive->m_archiveEnd); + } + + SSignatureVerifyStream_ProvideData(token, reinterpret_cast(salt), salt ? static_cast(strlen(salt)) : 0); + uint32_t signatureSize = token->magicBufferSize; + + if (!archive.m_archive->m_file->Read(buffer, archive.m_archive->m_archiveEnd, signatureSize, nullptr)) { + return false; + } + + SSignatureVerifyStream_ProvideData(token, buffer, signatureSize); + + if (SSignatureVerifyStream_Finish(token, modulus, exponent)) { + *result = AUTH_VERIFIED; + return true; + } + + *result = AUTH_FAILED; + System_SFile::s_lastError = 1244; + Blizzard::String::QuickFormat<1024> message("SFileAuthenticateArchiveEx - SFILE_ERROR_NOT_AUTHENTICATED"); + Blizzard::File::AddToLastErrorStack(1244, message.m_buffer, 4); + + return false; +} + // VERIFY: 11a84348 manual // OFFSET: 0x00458980 bool Blizzard::Mopaq::SFileCloseArchive(System_SFile::ARCHIVEREC* handle) { @@ -563,7 +670,7 @@ bool Blizzard::Mopaq::SFileCloseArchive(System_SFile::ARCHIVEREC* handle) { return archive->RemoveInternalArchiveRef() && result; } -// VERIFY: 21794a23 manual +// VERIFY: b4413dba manual // OFFSET: 0x0045BFE0 bool System_SFile::s_OpenArchive(ARCHIVEREC* archive, uint32_t flags, ARCHIVEREC** result) { int64_t bufferPos = 0; @@ -679,11 +786,13 @@ bool System_SFile::s_OpenArchive(ARCHIVEREC* archive, uint32_t flags, ARCHIVEREC } archive->m_sectorSize = 512 << archive->m_header.m_sectorSizeShift; - archive->unk_01E0 = 1; + archive->m_attributeFlags = 1; { - uint16_t version = 2; - archive->unk_01E4.push_back(version); + Blizzard::Mopaq::CompressionAlgorithm algorithm; + algorithm.m_type = 2; + algorithm.m_level = 0; + archive->m_compression.push_back(algorithm); } { @@ -1369,6 +1478,107 @@ uint32_t System_SFile::FindBlockEntry(ARCHIVEREC* archive, const Blizzard::Util: return it->second; } +// VERIFY: bce72388 manual +// OFFSET: 0x0045F4F0 +bool System_SFile::CreateArchiveView(IOUnit* file, const char* name, int32_t priority, uint32_t userDataSize, ARCHIVEREC** result, const Blizzard::Mopaq::ArchiveOptions* options) { + file->m_refCount.Increment(); + + ARCHIVEREC* archive = NewZerofill(); + archive->m_priority = priority; + archive->m_id = s_nextArchiveId.Increment() - 1; + archive->m_flags = 16; + archive->m_externalRefs.Increment(); + archive->m_internalRefs.Increment(); + + { + Blizzard::Lock::ScopedMutex lock(System_MPQGlobals::GetArchiveLock()->m_mutex); + System_MPQGlobals::GetArchiveList()->insert(archive); + } + + Blizzard::String::Copy(archive->m_name, name, sizeof(archive->m_name)); + archive->m_file = file; + archive->m_header.m_formatVersion = 1; + archive->unk_0200 = 0; + + if (options) { + archive->m_sectorSize = options->m_sectorSize; + archive->unk_007C = options->unk_0004; + archive->m_compressedTables = options->m_compressedTables; + } else { + archive->m_sectorSize = 4096; + archive->unk_007C = 0; + archive->m_compressedTables = false; + } + + archive->m_attributeFlags = 1; + + { + Blizzard::Mopaq::CompressionAlgorithm algorithm; + algorithm.m_type = 2; + algorithm.m_level = 0; + archive->m_compression.push_back(algorithm); + } + + archive->m_closeCallback = ARCHIVEREC::WriteArchiveChanges; + archive->m_listfileLoaded = true; + archive->m_listfileRefcount = 1; + archive->m_dataEnd = -1; + + if (userDataSize) { + archive->m_userDataOffset = 12; + archive->m_userDataSize = userDataSize; + archive->m_archiveOffset = (userDataSize + 523) & 0xFFFFFE00; + archive->m_archiveEnd = archive->m_archiveOffset + 44; + + uint32_t header[3]; + header[1] = userDataSize; + header[0] = 0x1B51504D; + header[2] = static_cast(archive->m_archiveOffset); + + if (!file->Write(header, 0, 12)) { + archive->m_externalRefs.Decrement(); + archive->RemoveInternalArchiveRef(); + return false; + } + } else { + archive->m_archiveEnd = 44; + } + + InitEmptyTables(archive, 0x10000); + *result = archive; + + return true; +} + +// VERIFY: c5b61630 auto +// OFFSET: 0x0045F700 +bool Blizzard::Mopaq::SFileCreateArchive(const char* path, int32_t priority, uint32_t userDataSize, System_SFile::ARCHIVEREC** result, const ArchiveOptions* options) { + *result = nullptr; + + IOUnit* file = IOFileUnit::Create(nullptr, path, 0xC07); + + if (!file) { + System_SFile::s_lastError = 110; + Blizzard::String::QuickFormat<1024> message("SFileCreateArchive - SFILE_ERROR_INVALID_PARAMETERS - %s", path); + Blizzard::File::AddToLastErrorStack(110, message.m_buffer, 4); + return false; + } + + bool created = System_SFile::CreateArchiveView(file, path, priority, userDataSize, result, options); + file->Release(); + + if (created) { + return true; + } + + System_SFile::s_lastError = 110; + Blizzard::String::QuickFormat<1024> message("SFileCreateArchive - SFILE_ERROR_INVALID_PARAMETERS - %s", path); + Blizzard::File::AddToLastErrorStack(110, message.m_buffer, 4); + Blizzard::File::Delete(path); + + return false; +} + // VERIFY: 962c3879 manual // OFFSET: 0x0045F7D0 int32_t FindFileInOneArchive(System_SFile::ARCHIVEREC* archive, const char* name, const uint64_t& hash, const Blizzard::Util::Digest<16>& md5, uint32_t flags, System_SFile::FileLookup* lookup) { @@ -1580,6 +1790,32 @@ bool Blizzard::Mopaq::SFileGetFileDetails(System_SFile::ARCHIVEREC* handle, cons return true; } +// VERIFY: e90f2337 auto +// OFFSET: 0x00460FB0 +int32_t Blizzard::Mopaq::SFileFileIsLocal(const char* name, int32_t flags) { + int32_t result = Blizzard::Streaming::CheckFileRange(nullptr, 0, 0, name, flags); + + if (result == 1) { + return result; + } + + System_SFile::ARCHIVEREC* archive = nullptr; + int64_t offset; + uint32_t size; + + if (!Blizzard::Mopaq::SFileGetFileDetails(nullptr, name, &archive, &offset, &size)) { + return 1; + } + + result = Blizzard::Streaming::CheckFileRange(archive->m_name, offset, size, name, flags); + + if (archive) { + archive->RemoveInternalArchiveRef(); + } + + return result; +} + // VERIFY: eccb0185 auto // OFFSET: 0x00461040 bool Blizzard::Mopaq::SFileGetIsLocalAmount(const char* name, int64_t& local, int64_t& total) { @@ -1861,6 +2097,37 @@ void Blizzard::Mopaq::SetMd5Callback(bool (*callback)(void* context, const uint8 System_MPQGlobals::GetMopaqGlobals()->m_md5Callback = callback; } +// VERIFY: 2cf3f624 manual +// OFFSET: 0x004610D0 +bool Blizzard::Mopaq::SFileMakeFileLocal(const char* name, int32_t priority, bool wait) { + Blizzard::File::StreamRecord* stream = nullptr; + System_SFile::ARCHIVEREC* archive = nullptr; + bool found = false; + int64_t offset; + uint32_t size; + + if (!Blizzard::Mopaq::SFileGetFileDetails(nullptr, name, &archive, &offset, &size)) { + return found; + } + + if (archive->m_file) { + stream = static_cast(archive->m_file->Win32Handle()); + found = true; + } + + archive->RemoveInternalArchiveRef(); + + if (!found) { + return found; + } + + if (wait) { + return Blizzard::Streaming::MakeLocalBlocking(stream, offset, size, priority, name); + } + + return Blizzard::Streaming::MakeLocalAsync(stream, offset, size, priority, name); +} + // VERIFY: 7b6e108c manual // OFFSET: 0x00461180 bool Blizzard::Mopaq::SetFileSignature(const char* name, const Blizzard::Util::Digest<16>& md5) { @@ -1896,3 +2163,956 @@ bool Blizzard::Mopaq::SetFileSignature(const char* name, const Blizzard::Util::D return result; } + +struct BlockHash { + /* 0000 */ uint64_t m_hash; + /* 0008 */ bool m_listed; + /* 0009 */ uint8_t unk_0009[7]; + + bool operator<(const BlockHash& other) const { + return this->m_hash < other.m_hash; + } +}; + +struct NameHash { + /* 0000 */ uint64_t m_hash; + /* 0008 */ const char* m_name; + /* 000C */ uint8_t unk_000C[4]; + + bool operator<(const NameHash& other) const { + return this->m_hash < other.m_hash; + } +}; + +struct DISKBLOCKENTRY { + /* 0000 */ uint32_t m_offset; + /* 0004 */ uint32_t m_compressedSize; + /* 0008 */ uint32_t m_fileSize; + /* 000C */ uint32_t m_flags; +}; + +// VERIFY: a8b1614c auto +// OFFSET: 0x00426E40 +bool System_SFile::SetFileCrc(void* context, uint32_t crc) { + static_cast(context)->m_blockEntry.m_crc = crc; + return true; +} + +// VERIFY: 17632db2 auto +// OFFSET: 0x0042C7B0 +bool System_SFile::SetFileMd5(void* context, const uint8_t* md5) { + static_cast(context)->m_blockEntry.m_md5 = *reinterpret_cast*>(md5); + return true; +} + +// VERIFY: 9e348560 auto +// OFFSET: 0x0042E400 +char* System_SFile::BackslashPath(const char* path, char* buffer, uint32_t size) { + Blizzard::String::MakeBackslashPath(path, buffer, size); + return buffer; +} + +// VERIFY: 058e6146 manual +// OFFSET: 0x00431FD0 +void System_SFile::FinishFileWrite(void* context, uint32_t size) { + IOMpqArchiveUnit* file = static_cast(context); + file->m_blockEntry.m_compressedSize = size; + file->m_archive->SetBlockEntry(file->m_blockIndex, file->m_blockEntry); + file->m_archive->m_dataEnd += size; +} + +// VERIFY: c53e3591 manual +// OFFSET: 0x00437380 +int64_t System_SFile::GetDataEnd(ARCHIVEREC* archive) { + if (archive->m_dataEnd == -1) { + int64_t end = archive->m_archiveOffset + 44; + + for (std::vector::iterator it = archive->m_blockTable.begin(); it != archive->m_blockTable.end(); ++it) { + if (static_cast(it->m_flags) < 0) { + int64_t blockEnd = it->m_offset + it->m_compressedSize; + end = std::max(end, blockEnd); + } + } + + archive->m_dataEnd = end; + } + + return archive->m_dataEnd; +} + +// VERIFY: 44d2bb50 manual +// OFFSET: 0x00437730 +bool System_Mopaq::CreateDiskFile(const char* name, uint32_t flags, const char* path, System_SFile::ARCHIVEREC* archive, IOMpqUnit** result) { + char directory[260]; + + if (path) { + int32_t length = static_cast(Blizzard::String::FindFilename(path) + 1 - path); + Blizzard::String::Copy(directory, path, std::min(length, 260)); + } else { + directory[0] = 0; + } + + Blizzard::File::CreateDirectory(directory, true); + + IOUnitContainer container(sizeof(IOMpqDiskUnit), sizeof(IOUnbufferedFileUnit), 0); + int32_t mode = ~(flags << 11) & 0x800 | 0x407; + IOUnit* file; + + if (mode & 0x40) { + file = System_Mopaq::OpenDiskFile(&container, path, mode); + } else { + file = IOFileUnit::Create(&container, path, mode); + } + + *result = IOMpqDiskUnit::Create(&container, archive, name, path, file); + + if (!*result) { + System_SFile::s_lastError = 1006; + return false; + } + + return true; +} + +// VERIFY: fcdd7fb7 manual +// OFFSET: 0x00447480 +void System_SFile::ARCHIVEREC::ReleaseListfile() { + if (--this->m_listfileRefcount <= 0) { + this->m_listfile.clear(); + this->m_listfileLoaded = false; + } +} + +// VERIFY: 761ef484 manual +// OFFSET: 0x004599A0 +void System_SFile::ArchivePtr::Reset(ARCHIVEREC* handle) { + bool locked = this->m_locked; + + if (locked) { + if (this->m_archive) { + Blizzard::Lock::MutexLeave(this->m_archive->m_mutex.m_mutex); + } + + this->m_locked = false; + } + + if (this->m_archive) { + this->m_archive->RemoveInternalArchiveRef(); + } + + this->m_archive = GetArchivePtr(handle, true); + + if (locked) { + if (!this->m_locked && this->m_archive) { + Blizzard::Lock::MutexEnter(this->m_archive->m_mutex.m_mutex); + } + + this->m_locked = true; + } +} + +// VERIFY: 0c83da51 manual +// OFFSET: 0x0045CB20 +bool System_SFile::ARCHIVEREC::AcquireListfileUncompressedBlockHash() { + if (this->m_listfileRefcount++ > 0) { + return this->m_listfileLoaded; + } + + this->InitializeTables(); + + std::vector hashes; + uint32_t count = this->m_hashTable.size(); + hashes.reserve(count); + + for (uint32_t i = 0; i < count; i++) { + if (this->m_hashTable[i].m_blockIndex < 0xFFFFFFFE) { + BlockHash entry; + entry.m_hash = this->m_hashTable[i].m_hashA | static_cast(this->m_hashTable[i].m_hashB) << 32; + entry.m_listed = false; + hashes.push_back(entry); + } + } + + std::sort(hashes.begin(), hashes.end()); + + uint32_t unlisted = hashes.size(); + const char* special[3]; + special[0] = "(listfile)"; + special[1] = "(attributes)"; + special[2] = "(signature)"; + + for (uint32_t i = 0; i < 3; i++) { + const char* name = special[i]; + BlockHash probe; + probe.m_hash = System_MPQEncrypt::Hash(name, 1) | static_cast(System_MPQEncrypt::Hash(name, 2)) << 32; + probe.m_listed = false; + + std::vector::iterator it = std::lower_bound(hashes.begin(), hashes.end(), probe); + + if (it != hashes.end() && it->m_hash == probe.m_hash) { + this->m_listfile.insert(std::pair(name, false)); + + do { + if (!it->m_listed) { + unlisted--; + it->m_listed = true; + } + + ++it; + } while (it != hashes.end() && it->m_hash == probe.m_hash); + } + } + + Blizzard::Util::Digest<16> md5 = s_emptyMd5; + IOMpqUnit* file; + + if (Blizzard::Mopaq::SFileOpenFileEx(this, "(listfile)", md5, 16, &file) == 1) { + uint32_t size = Blizzard::Mopaq::SFileGetFileSize(file, nullptr); + + if (size != 0xFFFFFFFF) { + char buffer[4096]; + char line[1024]; + char* cursor = line; + uint32_t pos = 0; + uint32_t loaded = 0; + + if (size) { + for (;;) { + uint32_t end = std::min(size, loaded + 4096); + + if (end <= loaded || !Blizzard::Mopaq::SFileReadFile(file, buffer, end - loaded, nullptr)) { + break; + } + + loaded = end; + + if (pos >= size) { + break; + } + + while (pos < loaded) { + char c = buffer[pos++ & 0xFFF]; + + if (c == '\r' || c == '\n') { + if (cursor != line) { + *cursor = 0; + + BlockHash probe; + probe.m_hash = System_MPQEncrypt::Hash(line, 1) | static_cast(System_MPQEncrypt::Hash(line, 2)) << 32; + probe.m_listed = false; + + std::vector::iterator it = std::lower_bound(hashes.begin(), hashes.end(), probe); + + if (it != hashes.end() && it->m_hash == probe.m_hash) { + this->m_listfile.insert(std::pair(line, true)); + + do { + if (!it->m_listed) { + unlisted--; + it->m_listed = true; + } + + ++it; + } while (it != hashes.end() && it->m_hash == probe.m_hash); + } else { + Blizzard::String::QuickFormat<1024> message("Listfile references unknown file \"%s\"!\n", line); + fputs(message.m_buffer, stderr); + } + + cursor = line; + } + } else { + *cursor++ = c; + + if (cursor >= line + sizeof(line)) { + pos = size; + break; + } + } + } + } + } + } + + file->Release(); + } + + if (unlisted) { + Blizzard::String::QuickFormat<1024> message("Archive \"%s\" has an incomplete listfile!\n", this->m_name); + fputs(message.m_buffer, stderr); + this->m_listfileLoaded = false; + } else { + this->m_listfileLoaded = true; + } + + return this->m_listfileLoaded; +} + +// VERIFY: 8061fc10 manual +// OFFSET: 0x0045DC50 +bool System_SFile::RebuildHashTable(ARCHIVEREC* archive, uint32_t hashSize) { + if (!archive->AcquireListfileUncompressedBlockHash()) { + archive->ReleaseListfile(); + return false; + } + + std::vector names; + names.reserve(archive->m_listfile.size()); + + for (std::map::iterator it = archive->m_listfile.begin(); it != archive->m_listfile.end(); ++it) { + const char* name = it->first.c_str(); + NameHash entry; + entry.m_hash = System_MPQEncrypt::Hash(name, 1) | static_cast(System_MPQEncrypt::Hash(name, 2)) << 32; + entry.m_name = name; + names.push_back(entry); + } + + archive->ReleaseListfile(); + + std::sort(names.begin(), names.end()); + + HASHENTRY empty; + empty.m_hashA = 0xFFFFFFFF; + empty.m_hashB = 0xFFFFFFFF; + empty.m_locale = 0xFFFF; + empty.m_platform = 0xFF; + empty.unk_000B = 0xFF; + empty.m_blockIndex = 0xFFFFFFFF; + + std::vector table(hashSize, empty); + + for (std::vector::iterator it = archive->m_hashTable.begin(); it != archive->m_hashTable.end(); ++it) { + if (it->m_blockIndex >= 0xFFFFFFFE) { + continue; + } + + NameHash probe; + probe.m_hash = it->m_hashA | static_cast(it->m_hashB) << 32; + probe.m_name = nullptr; + + std::vector::iterator found = std::lower_bound(names.begin(), names.end(), probe); + + if (found == names.end() || found->m_hash != probe.m_hash) { + return false; + } + + uint32_t start = System_MPQEncrypt::Hash(found->m_name, 0) & (hashSize - 1); + uint32_t slot = start; + + while (table[slot].m_blockIndex < 0xFFFFFFFE) { + slot = (slot + 1) & (hashSize - 1); + + if (slot == start) { + return false; + } + } + + table[slot] = *it; + } + + archive->m_hashTable.swap(table); + archive->m_header.m_hashTableSize = hashSize; + + return true; +} + +// VERIFY: ab7e4e14 manual +// OFFSET: 0x0045E080 +bool System_SFile::ARCHIVEREC::WriteArchiveChanges(ARCHIVEREC* archive) { + bool result = true; + + archive->m_locale = 0; + archive->m_platform = 0; + archive->m_attributeFlags = 1; + + { + std::map remap; + uint32_t count = archive->m_blockTable.size(); + uint32_t kept = 0; + + for (uint32_t i = 0; i < count; i++) { + if (static_cast(archive->m_blockTable[i].m_flags) < 0) { + if (i != kept) { + archive->m_blockTable[kept] = archive->m_blockTable[i]; + remap.insert(std::pair(i, kept)); + } + + kept++; + } + } + + archive->m_blockTable.resize(kept); + + uint32_t hashCount = archive->m_hashTable.size(); + + for (uint32_t i = 0; i < hashCount; i++) { + uint32_t index = archive->m_hashTable[i].m_blockIndex; + + if (index <= count) { + std::map::iterator it = remap.find(index); + + if (it != remap.end()) { + archive->m_hashTable[i].m_blockIndex = it->second; + } + } + } + } + + { + std::vector listfile; + listfile.reserve(260 * archive->m_listfile.size()); + + for (std::map::iterator it = archive->m_listfile.begin(); it != archive->m_listfile.end(); ++it) { + if (it->second) { + listfile.insert(listfile.end(), it->first.begin(), it->first.end()); + listfile.push_back('\r'); + listfile.push_back('\n'); + } + } + + uint32_t size = listfile.size(); + IOMpqUnit* file; + + if (Blizzard::Mopaq::SFileCreateFile(archive, "(listfile)", size, 0x200, &file)) { + if (!listfile.empty() && !file->Write(&listfile[0], 0, size)) { + fputs("*** WriteArchiveChanges: writing listfile failed\n", stderr); + result = false; + } + + if (!file->Release()) { + fputs("*** WriteArchiveChanges: closing listfile failed\n", stderr); + result = false; + } + } else { + fputs("*** WriteArchiveChanges: creating listfile failed\n", stderr); + result = false; + } + } + + { + uint32_t count = archive->m_blockTable.size(); + std::vector crcs(count + 1, 0); + std::vector times(count + 1, 0); + std::vector> md5s(count + 1); + + for (uint32_t i = 0; i < count; i++) { + crcs[i] = archive->m_blockTable[i].m_crc; + times[i] = archive->m_blockTable[i].m_fileTime; + md5s[i] = archive->m_blockTable[i].m_md5; + } + + crcs.back() = 0; + times.back() = 0; + md5s.back() = s_emptyMd5; + + uint32_t header[2]; + header[0] = 100; + header[1] = 7; + + IOMpqUnit* file; + + if (Blizzard::Mopaq::SFileCreateFile(archive, "(attributes)", 4 * (crcs.size() + 2 * (times.size() + 2 * md5s.size()) + 2), 0x200, &file)) { + if (!Blizzard::Mopaq::SFileWriteFile(file, header, 8)) { + fputs("*** WriteArchiveChanges: writing attributes file header failed\n", stderr); + result = false; + } + + if (!Blizzard::Mopaq::SFileWriteFile(file, &crcs[0], 4 * crcs.size())) { + fputs("*** WriteArchiveChanges: writing attributes file CRC block failed\n", stderr); + result = false; + } + + if (!Blizzard::Mopaq::SFileWriteFile(file, ×[0], 8 * times.size())) { + fputs("*** WriteArchiveChanges: writing attributes file time block failed\n", stderr); + result = false; + } + + if (!Blizzard::Mopaq::SFileWriteFile(file, &md5s[0], 16 * md5s.size())) { + fputs("*** WriteArchiveChanges: writing attributes file MD5 block failed\n", stderr); + result = false; + } + + if (!file->Release()) { + fputs("*** WriteArchiveChanges: closing attributes file failed\n", stderr); + result = false; + } + } else { + fputs("*** WriteArchiveChanges: creating attributes file failed\n", stderr); + result = false; + } + } + + uint32_t blockCount = archive->m_blockTable.size(); + uint32_t hashSize; + + if (blockCount - 0x8000 <= 0x7FFF) { + hashSize = 0x10000; + } else { + uint32_t want = 4 * blockCount / 3; + + for (hashSize = 4; hashSize < want; hashSize *= 2) { + } + } + + RebuildHashTable(archive, hashSize); + + int64_t hashPos = GetDataEnd(archive); + uint32_t hashCount = archive->m_hashTable.size(); + uint32_t hashBytes = 16 * hashCount; + uint32_t hashWritten = hashBytes; + + { + HASHENTRY zero; + zero.m_hashA = 0; + zero.m_hashB = 0; + zero.m_locale = 0; + zero.m_platform = 0; + zero.unk_000B = 0; + zero.m_blockIndex = 0; + + std::vector hashes(hashCount, zero); + + for (uint32_t i = 0; i < hashCount; i++) { + hashes[i].m_hashA = archive->m_hashTable[i].m_hashA; + hashes[i].m_hashB = archive->m_hashTable[i].m_hashB; + hashes[i].m_locale = archive->m_hashTable[i].m_locale; + hashes[i].m_platform = archive->m_hashTable[i].m_platform; + hashes[i].unk_000B = archive->m_hashTable[i].unk_000B; + hashes[i].m_blockIndex = archive->m_hashTable[i].m_blockIndex; + } + + void* data = &hashes[0]; + + if (archive->m_header.m_formatVersion && archive->m_compressedTables) { + data = Blizzard::Memory::Allocate(hashBytes); + + Blizzard::Mopaq::CompressionAlgorithm algorithm; + algorithm.m_type = 2; + algorithm.m_level = 0; + bool checksum; + System_SComp::Compress(data, &hashWritten, &checksum, &hashes[0], hashBytes, 1, &algorithm); + + if (hashWritten >= hashBytes) { + Blizzard::Memory::Free(data); + data = &hashes[0]; + } + } + + System_MPQEncrypt::Encrypt(static_cast(data), hashWritten, 0xC3AF3770); + + if (!archive->m_file->Write(data, hashPos, hashWritten)) { + fputs("*** WriteArchiveChanges: writing hash table failed\n", stderr); + result = false; + } + + if (data != &hashes[0]) { + Blizzard::Memory::Free(data); + } + } + + bool extended = false; + int64_t blockPos = hashPos + hashWritten; + uint32_t blockTableCount = archive->m_blockTable.size(); + uint32_t blockBytes = 16 * blockTableCount; + uint32_t blockWritten = blockBytes; + + { + DISKBLOCKENTRY zero; + zero.m_offset = 0; + zero.m_compressedSize = 0; + zero.m_fileSize = 0; + zero.m_flags = 0; + + std::vector blocks(blockTableCount, zero); + + for (uint32_t i = 0; i < blockTableCount; i++) { + int64_t offset = archive->m_blockTable[i].m_offset - archive->m_archiveOffset; + + if (offset > 0xFFFFFFFF) { + extended = true; + } + + blocks[i].m_offset = static_cast(offset); + blocks[i].m_compressedSize = archive->m_blockTable[i].m_compressedSize; + blocks[i].m_fileSize = archive->m_blockTable[i].m_fileSize; + blocks[i].m_flags = archive->m_blockTable[i].m_flags; + } + + void* data = &blocks[0]; + + if (archive->m_header.m_formatVersion && archive->m_compressedTables) { + data = Blizzard::Memory::Allocate(blockBytes); + + Blizzard::Mopaq::CompressionAlgorithm algorithm; + algorithm.m_type = 2; + algorithm.m_level = 0; + bool checksum; + System_SComp::Compress(data, &blockWritten, &checksum, &blocks[0], blockBytes, 1, &algorithm); + + if (blockWritten >= blockBytes) { + Blizzard::Memory::Free(data); + data = &blocks[0]; + } + } + + System_MPQEncrypt::Encrypt(static_cast(data), blockWritten, 0xEC83B3A3); + + if (!archive->m_file->Write(data, blockPos, blockWritten)) { + fputs("*** WriteArchiveChanges: writing hash table failed\n", stderr); + result = false; + } + + if (data != &blocks[0]) { + Blizzard::Memory::Free(data); + } + } + + int64_t extendedPos = 0; + uint32_t extendedSize = 0; + + if (archive->m_header.m_formatVersion && extended) { + extendedSize = 2 * blockTableCount; + extendedPos = blockPos + blockWritten; + + std::vector high(blockTableCount, 0); + + for (uint32_t i = 0; i < blockTableCount; i++) { + high[i] = static_cast((archive->m_blockTable[i].m_offset - archive->m_archiveOffset) >> 32); + } + + if (!archive->m_file->Write(&high[0], extendedPos, extendedSize)) { + fputs("*** WriteArchiveChanges: writing extended block table failed\n", stderr); + result = false; + } + } + + int64_t extendedEnd = extendedPos + extendedSize; + int64_t blockEnd = blockPos + blockWritten; + int64_t end = std::max(blockEnd, extendedEnd); + + hashPos -= archive->m_archiveOffset; + blockPos -= archive->m_archiveOffset; + + MPQHEADER header; + header.m_formatVersion = archive->m_header.m_formatVersion; + header.m_magic = 0x1A51504D; + header.m_headerSize = header.m_formatVersion ? 44 : 32; + header.m_archiveSize = static_cast(end - archive->m_archiveOffset); + + uint16_t shift = 0; + + for (uint32_t sectors = archive->m_sectorSize >> 10; sectors; sectors >>= 1) { + shift++; + } + + header.m_hashTablePos = static_cast(hashPos); + header.m_blockTablePos = static_cast(blockPos); + header.m_hashTableSize = hashCount; + header.m_blockTableSize = blockTableCount; + header.m_hiBlockTablePos = extendedPos; + header.m_sectorSizeShift = shift; + header.m_hashTablePosHi = static_cast(hashPos >> 32); + header.m_blockTablePosHi = static_cast(blockPos >> 32); + + bool written; + + if (archive->m_file->Write(&header, archive->m_archiveOffset, header.m_formatVersion ? 44 : 32)) { + written = result; + } else { + fputs("*** WriteArchiveChanges: writing archive header failed\n", stderr); + written = false; + } + + archive->m_file->SetFileSize(end); + + if (!archive->m_file->Flush()) { + fputs("*** WriteArchiveChanges: flushing archive failed\n", stderr); + written = false; + } + + archive->ReleaseListfile(); + + if (archive->m_listfileRefcount > 0) { + fputs("*** WriteArchiveChanges: listfile was Acquired more than Released\n", stderr); + } + + return written; +} + +// VERIFY: 6704861d manual +// OFFSET: 0x0045FC20 +bool System_SFile::PrepareArchiveForWriting(ARCHIVEREC* archive) { + if (archive->m_file && !archive->m_closeCallback) { + archive->m_dataEnd = -1; + archive->AcquireListfileUncompressedBlockHash(); + + { + uint32_t index = SearchHashTable(archive, "(listfile)", true, nullptr); + + if (index != 0xFFFFFFFF) { + archive->m_listfile.erase(std::string("(listfile)")); + + HASHENTRY& entry = archive->m_hashTable[index]; + BLOCKENTRY block = archive->GetBlockEntry(entry.m_blockIndex); + HASHENTRY& next = archive->m_hashTable[(index + 1) & (archive->m_hashTable.size() - 1)]; + block.m_flags &= ~0x80000000; + archive->SetBlockEntry(entry.m_blockIndex, block); + entry.m_blockIndex = (next.m_blockIndex == 0xFFFFFFFF) - 2; + archive->m_dataEnd = -1; + } + } + + { + uint32_t index = SearchHashTable(archive, "(signature)", true, nullptr); + + if (index != 0xFFFFFFFF) { + archive->m_listfile.erase(std::string("(signature)")); + + HASHENTRY& entry = archive->m_hashTable[index]; + BLOCKENTRY block = archive->GetBlockEntry(entry.m_blockIndex); + HASHENTRY& next = archive->m_hashTable[(index + 1) & (archive->m_hashTable.size() - 1)]; + block.m_flags &= ~0x80000000; + archive->SetBlockEntry(entry.m_blockIndex, block); + entry.m_blockIndex = (next.m_blockIndex == 0xFFFFFFFF) - 2; + archive->m_dataEnd = -1; + } + } + + { + uint32_t index = SearchHashTable(archive, "(attributes)", true, nullptr); + + if (index != 0xFFFFFFFF) { + archive->m_listfile.erase(std::string("(attributes)")); + + HASHENTRY& entry = archive->m_hashTable[index]; + BLOCKENTRY block = archive->GetBlockEntry(entry.m_blockIndex); + HASHENTRY& next = archive->m_hashTable[(index + 1) & (archive->m_hashTable.size() - 1)]; + block.m_flags &= ~0x80000000; + archive->SetBlockEntry(entry.m_blockIndex, block); + entry.m_blockIndex = (next.m_blockIndex == 0xFFFFFFFF) - 2; + archive->m_dataEnd = -1; + } + } + + uint32_t zero = 0; + archive->m_file->Write(&zero, archive->m_archiveOffset, 4); + archive->m_closeCallback = ARCHIVEREC::WriteArchiveChanges; + } + + return true; +} + +// VERIFY: 8c9f2d53 manual +// OFFSET: 0x00460010 +bool Blizzard::Mopaq::SFileCreateFile(System_SFile::ARCHIVEREC* handle, const char* name, uint32_t size, uint32_t flags, IOMpqUnit** result) { + const char* path = name; + char buffer[260]; + + *result = nullptr; + + for (const char* c = name; *c; c++) { + if (*c == '\n' || *c == '\r') { + return false; + } + } + + System_SFile::ArchivePtr archive(System_SFile::GetArchivePtr(handle, true)); + + if (archive.m_archive) { + Blizzard::Lock::MutexEnter(archive.m_archive->m_mutex.m_mutex); + } + + archive.m_locked = true; + + if (flags & 2) { + if (!Blizzard::File::GetRootChars(name)) { + System_SFile::ConvertRelativePathName(name, buffer); + path = buffer; + } + + return System_Mopaq::CreateDiskFile(name, flags, path, archive.m_archive, result); + } + + if (!archive.m_archive) { + return false; + } + + if (!archive.m_archive->m_directPath.empty()) { + Blizzard::String::JoinPath(buffer, sizeof(buffer), archive.m_archive->m_directPath.c_str(), name); + path = buffer; + } + + if (archive.m_archive->m_parent) { + archive.Reset(archive.m_archive->m_parent); + } + + System_SFile::ARCHIVEREC* record = archive.m_archive; + + if (!record->m_file) { + return System_Mopaq::CreateDiskFile(name, flags, path, record, result); + } + + IOMpqWriteUnit* writer = nullptr; + IOChecksumUnit* md5Unit = nullptr; + IOChecksumUnit* crcUnit = nullptr; + + if (!System_SFile::PrepareArchiveForWriting(record)) { + return false; + } + + System_SFile::BackslashPath(path, buffer, sizeof(buffer)); + + uint16_t locale = record->m_locale; + uint8_t platform = record->m_platform; + + if (flags & 1) { + uint32_t index = System_SFile::SearchHashTable(record, buffer, true, nullptr); + + if (index != 0xFFFFFFFF) { + record->m_listfile.erase(std::string(buffer)); + + System_SFile::HASHENTRY& entry = record->m_hashTable[index]; + System_SFile::BLOCKENTRY block = record->GetBlockEntry(entry.m_blockIndex); + System_SFile::HASHENTRY& next = record->m_hashTable[(index + 1) & (record->m_hashTable.size() - 1)]; + block.m_flags &= ~0x80000000; + record->SetBlockEntry(entry.m_blockIndex, block); + entry.m_blockIndex = (next.m_blockIndex == 0xFFFFFFFF) - 2; + record->m_dataEnd = -1; + } + + flags &= ~1; + } else if (System_SFile::SearchHashTable(record, buffer, false, nullptr) != 0xFFFFFFFF) { + return false; + } + + int64_t dataEnd = System_SFile::GetDataEnd(record); + + if (!record->m_header.m_formatVersion) { + uint32_t listfileCount = record->m_listfile.size(); + int64_t total = static_cast(record->m_blockTable.size() * 49) + record->m_hashTable.size() * 16 + (size / (record->m_sectorSize >> 2) + 8) + listfileCount * 262 + size + dataEnd + 0x10000; + + if (total > 0xFFFFFFFF) { + return false; + } + } + + System_SFile::BLOCKENTRY entry; + entry.m_offset = dataEnd; + entry.m_compressedSize = 0; + entry.m_fileSize = size; + entry.m_flags = flags | 0x80000000; + entry.m_fileTime = 0; + entry.m_crc = 0; + entry.m_md5 = System_SFile::s_emptyMd5; + entry.m_md5Check = false; + + if ((flags & 0x1000200) == 0x200) { + entry.m_flags = flags | 0x84000000; + } + + uint32_t blockIndex = record->m_blockTable.size(); + uint32_t hash = System_MPQEncrypt::Hash(buffer, 0); + bool rebuilt = false; + System_SFile::HASHENTRY* slot; + + for (;;) { + uint32_t hashCount = record->m_hashTable.size(); + uint32_t index = hash & (hashCount - 1); + slot = nullptr; + + for (uint32_t i = 0; i < hashCount; i++) { + if (record->m_hashTable[index].m_blockIndex >= 0xFFFFFFFE) { + slot = &record->m_hashTable[index]; + break; + } + + index = (index + 1) & (hashCount - 1); + } + + if (slot) { + break; + } + + if (rebuilt) { + fputs("SFileCreateFile: unable to insert an entry into the hash table!\n", stderr); + return false; + } + + uint32_t newSize = std::max(2 * hashCount, 0x10000u); + + if (newSize >= 0x100000) { + fputs("SFileCreateFile: warning - hash table about to exceed 2^24 items!\n", stderr); + } + + if (!System_SFile::RebuildHashTable(record, newSize)) { + fputs("SFileCreateFile: unable to insert an entry into the hash table!\n", stderr); + return false; + } + + rebuilt = true; + } + + uint32_t hashA = System_MPQEncrypt::Hash(buffer, 1); + slot->m_hashB = System_MPQEncrypt::Hash(buffer, 2); + slot->m_locale = locale; + slot->m_hashA = hashA; + slot->m_platform = platform; + slot->unk_000B = 0; + slot->m_blockIndex = blockIndex; + + record->m_blockTable.push_back(entry); + record->m_file->m_refCount.Increment(); + + if (size && (flags & 0xFF00)) { + IOUnitContainer container(sizeof(IOMpqArchiveWriteUnit), sizeof(IOAlignUnit), sizeof(IOCrcUnit), sizeof(IOMd5Unit), sizeof(IOMpqWriteUnit), sizeof(IORangeUnit), 0); + IOUnit* unit; + + if (flags & 0x1000000) { + unit = System_SFile::CreateRangeUnit(&container, dataEnd, dataEnd + size, record->m_file); + unit = IOMpqWriteUnit::CreateSingle(&container, record->m_compression, size, System_SFile::FinishFileWrite, &writer, unit); + unit = IOMd5Unit::Create(&container, size, (record->m_attributeFlags & 4) ? System_SFile::SetFileMd5 : nullptr, false, &md5Unit, unit); + unit = IOCrcUnit::Create(&container, size, (record->m_attributeFlags & 1) ? System_SFile::SetFileCrc : nullptr, false, &crcUnit, unit); + unit = IOAlignUnit::Create(&container, 0, size, 1, false, false, 1, false, unit); + } else { + unit = System_SFile::CreateRangeUnit(&container, dataEnd, dataEnd + 0xFFFFFFFF, record->m_file); + unit = IOMpqWriteUnit::Create(&container, record->m_compression, size, record->m_sectorSize, System_SFile::FinishFileWrite, &writer, unit); + unit = IOMd5Unit::Create(&container, size, (record->m_attributeFlags & 4) ? System_SFile::SetFileMd5 : nullptr, false, &md5Unit, unit); + unit = IOCrcUnit::Create(&container, size, (record->m_attributeFlags & 1) ? System_SFile::SetFileCrc : nullptr, false, &crcUnit, unit); + unit = IOAlignUnit::Create(&container, 0, record->m_sectorSize, 1, true, true, 1, false, unit); + } + + *result = IOMpqArchiveWriteUnit::Create(&container, record, buffer, blockIndex, unit); + } else { + IOUnitContainer container(sizeof(IOMpqArchiveWriteUnit), sizeof(IOCrcUnit), sizeof(IOMd5Unit), sizeof(IORangeUnit), 0); + IOUnit* unit = IORangeUnit::Create(&container, dataEnd, dataEnd + size, record->m_file); + unit = IOMd5Unit::Create(&container, size, (record->m_attributeFlags & 4) ? System_SFile::SetFileMd5 : nullptr, false, &md5Unit, unit); + unit = IOCrcUnit::Create(&container, size, (record->m_attributeFlags & 1) ? System_SFile::SetFileCrc : nullptr, false, &crcUnit, unit); + + IOMpqArchiveWriteUnit* file = IOMpqArchiveWriteUnit::Create(&container, record, buffer, blockIndex, unit); + System_SFile::FinishFileWrite(file, size); + *result = file; + } + + if (!*result) { + System_SFile::s_lastError = 1006; + Blizzard::String::QuickFormat<1024> message("SFileCreateFile - SFILE_ERROR_FILE_INVALID"); + Blizzard::File::AddToLastErrorStack(1006, message.m_buffer, 4); + return false; + } + + if (writer) { + writer->SetContext(*result); + } + + if (crcUnit) { + crcUnit->SetContext(*result); + } + + if (md5Unit) { + md5Unit->SetContext(*result); + } + + record->m_listfile.insert(std::pair(buffer, true)); + + return true; +} diff --git a/Engine/Source/BlizzardCore/Source/Packages/Mopaq/SFileArchives.h b/Engine/Source/BlizzardCore/Source/Packages/Mopaq/SFileArchives.h index c223f1a..e1ee146 100644 --- a/Engine/Source/BlizzardCore/Source/Packages/Mopaq/SFileArchives.h +++ b/Engine/Source/BlizzardCore/Source/Packages/Mopaq/SFileArchives.h @@ -8,9 +8,16 @@ #include #include "Engine/Source/BlizzardCore/Include/Blizzard/Util/Digest.h" #include "Engine/Source/BlizzardCore/Source/Packages/iounit/IOUnit.h" +#include "Engine/Source/BlizzardCore/Source/Packages/Mopaq/Types.h" #include "Engine/Source/BlizzardCore/Source/System/Lock/Lock.h" #include "Engine/Source/BlizzardCore/Source/System/Memory/TempBuffer.h" +namespace Blizzard { +namespace Mopaq { +struct ArchiveOptions; +} +} + namespace System_SFile { #pragma pack(push, 1) @@ -133,6 +140,8 @@ struct ArchiveBuffers { class ARCHIVEREC { public: + static bool WriteArchiveChanges(ARCHIVEREC* archive); + /* 0000 */ Blizzard::Lock::RMutex m_mutex; /* 0018 */ IOUnit* m_file; /* 001C */ int32_t m_priority; @@ -161,23 +170,23 @@ class ARCHIVEREC { /* 01DA */ uint16_t m_locale; /* 01DC */ uint8_t m_platform; /* 01DD */ uint8_t unk_01DD[3]; - /* 01E0 */ uint32_t unk_01E0; - /* 01E4 */ std::vector unk_01E4; + /* 01E0 */ uint32_t m_attributeFlags; + /* 01E4 */ std::vector m_compression; /* 01F4 */ uint32_t unk_01F4; /* 01F8 */ ArchiveBuffers* m_buffers; /* 01FC */ bool (*m_closeCallback)(ARCHIVEREC* archive); /* 0200 */ uint32_t unk_0200; - /* 0204 */ std::map unk_0204; - /* 0210 */ bool unk_0210; + /* 0204 */ std::map m_listfile; + /* 0210 */ bool m_listfileLoaded; /* 0211 */ uint8_t unk_0211[3]; - /* 0214 */ uint32_t unk_0214; - /* 0218 */ uint32_t unk_0218; - /* 021C */ uint32_t unk_021C; + /* 0214 */ int32_t m_listfileRefcount; + /* 0218 */ int64_t m_dataEnd; /* 0220 */ Blizzard::Lock::Atomic m_internalRefs; /* 0224 */ Blizzard::Lock::Atomic m_externalRefs; ARCHIVEREC(); ~ARCHIVEREC(); + bool AcquireListfileUncompressedBlockHash(); void BuildBlockKeys(); void BuildBlockTable(); void ConvertToNewHashTableFormat(); @@ -187,6 +196,7 @@ class ARCHIVEREC { void InitializeTables(); void PackBlockTable(); bool ReadAdditionalAttributes(); + void ReleaseListfile(); bool RemoveInternalArchiveRef(); void SetBlockCrc(uint32_t index, uint32_t crc); void SetBlockEntry(uint32_t index, const BLOCKENTRY& entry); @@ -212,6 +222,7 @@ class ArchivePtr { ArchivePtr(ARCHIVEREC* archive); ~ArchivePtr(); + void Reset(ARCHIVEREC* handle); }; template @@ -228,15 +239,23 @@ extern Blizzard::Util::Digest<16> s_emptyMd5; extern Blizzard::Lock::Atomic s_nextArchiveId; extern uint32_t s_lastError; +char* BackslashPath(const char* path, char* buffer, uint32_t size); bool CheckFileExistsOnDisk(const char* name, uint32_t flags, char* result); void ClearAllFileFlags(); void ConvertRelativePathName(const char* path, char* result); +bool CreateArchiveView(IOUnit* file, const char* name, int32_t priority, uint32_t userDataSize, ARCHIVEREC** result, const Blizzard::Mopaq::ArchiveOptions* options); uint32_t FindBlockEntry(ARCHIVEREC* archive, const Blizzard::Util::Digest<16>& md5, bool* deleted); +void FinishFileWrite(void* context, uint32_t size); ARCHIVEREC* GetArchivePtr(ARCHIVEREC* handle, bool addRef); +int64_t GetDataEnd(ARCHIVEREC* archive); bool InitEmptyTables(ARCHIVEREC* archive, uint32_t hashCount); bool OpenDirectPathAsArchive(const char* path, int32_t priority, uint32_t flags, ARCHIVEREC** result); +bool PrepareArchiveForWriting(ARCHIVEREC* archive); +bool RebuildHashTable(ARCHIVEREC* archive, uint32_t hashSize); bool s_OpenArchive(ARCHIVEREC* archive, uint32_t flags, ARCHIVEREC** result); uint32_t SearchHashTable(ARCHIVEREC* archive, const char* name, bool matchNeutral, bool* deleted); +bool SetFileCrc(void* context, uint32_t crc); +bool SetFileMd5(void* context, const uint8_t* md5); } @@ -246,11 +265,22 @@ int32_t GetFileBlockEntry(System_SFile::ARCHIVEREC* handle, const char* name, co namespace Blizzard { namespace Mopaq { +bool SFileAuthenticateArchiveEx(System_SFile::ARCHIVEREC* handle, AuthResult* result, const uint8_t* modulus, uint32_t modulusSize, const uint8_t* exponent, uint32_t exponentSize, const char* salt); +struct ArchiveOptions { + /* 0000 */ uint32_t m_sectorSize; + /* 0004 */ uint32_t unk_0004; + /* 0008 */ bool m_compressedTables; + /* 0009 */ uint8_t unk_0009[3]; +}; + bool SFileCloseArchive(System_SFile::ARCHIVEREC* handle); +bool SFileCreateArchive(const char* path, int32_t priority, uint32_t userDataSize, System_SFile::ARCHIVEREC** result, const ArchiveOptions* options); bool SFileEnableDirectAccess(uint32_t enable); int32_t SFileFileExists(System_SFile::ARCHIVEREC* handle, const char* name, uint32_t flags, System_SFile::ARCHIVEREC** archiveOut); bool SFileGetFileDetails(System_SFile::ARCHIVEREC* handle, const char* name, System_SFile::ARCHIVEREC** archiveOut, int64_t* offset, uint32_t* size); +int32_t SFileFileIsLocal(const char* name, int32_t flags); bool SFileGetIsLocalAmount(const char* name, int64_t& local, int64_t& total); +bool SFileMakeFileLocal(const char* name, int32_t priority, bool wait); uint32_t SFileGetLastError(); bool SFileOpenArchive(const char* path, int32_t priority, uint32_t flags, System_SFile::ARCHIVEREC** result); bool SFileOpenArchive(IOUnit* file, const char* name, int32_t priority, uint32_t flags, System_SFile::ARCHIVEREC** result); diff --git a/Engine/Source/BlizzardCore/Source/Packages/Mopaq/Types.h b/Engine/Source/BlizzardCore/Source/Packages/Mopaq/Types.h new file mode 100644 index 0000000..98cd4c6 --- /dev/null +++ b/Engine/Source/BlizzardCore/Source/Packages/Mopaq/Types.h @@ -0,0 +1,23 @@ +#ifndef ENGINE_SOURCE_BLIZZARDCORE_SOURCE_PACKAGES_MOPAQ_TYPES_H +#define ENGINE_SOURCE_BLIZZARDCORE_SOURCE_PACKAGES_MOPAQ_TYPES_H + +#include + +namespace Blizzard { +namespace Mopaq { + +struct CompressionAlgorithm { + /* 0000 */ uint8_t m_type; + /* 0001 */ uint8_t m_level; +}; + +enum AuthResult { + AUTH_UNKNOWN = 0, + AUTH_FAILED = 1, + AUTH_VERIFIED = 5, +}; + +} +} + +#endif diff --git a/Engine/Source/BlizzardCore/Source/Packages/Streaming/Manifests.cpp b/Engine/Source/BlizzardCore/Source/Packages/Streaming/Manifests.cpp new file mode 100644 index 0000000..fa2844f --- /dev/null +++ b/Engine/Source/BlizzardCore/Source/Packages/Streaming/Manifests.cpp @@ -0,0 +1,1570 @@ +#include "Manifests.h" +#include +#include +#include +#include +#include +#include +#include +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Streaming.h" +#include "Engine/Source/BlizzardCore/Source/System/File/File.h" +#include "Engine/Source/BlizzardCore/Source/System/Memory/MemoryStorm.h" +#include "Engine/Source/BlizzardCore/Source/System/String/Path.h" +#include "Engine/Source/BlizzardCore/Source/System/String/String.h" +#include "Engine/Source/BlizzardCore/Source/System/Time/Time.h" + +// STATIC: 0x00AB90A4 +const char* Blizzard::Streaming::s_httpPrefix = "http://"; + +// STATIC: 0x00AB90A8 +const char* Blizzard::Streaming::s_filePrefix = "file://"; + +// STATIC: 0x00B38170 +Blizzard::Streaming::ManifestInfo* Blizzard::Streaming::ManifestInfo::s_instance; + +// STATIC: 0x00B38660 +static Blizzard::Streaming::Manifests::ServerItem s_serverItem; + +// VERIFY: 87b3943b auto +// OFFSET: 0x004268C0 +bool Blizzard::Streaming::Manifests::ManifestItem::HandleTag(const char* tag, const char* value) { + return false; +} + +// VERIFY: 1e529c00 manual +// OFFSET: 0x00427D60 +bool Blizzard::Streaming::SplitLine(char* line, char** value, char** tag, int32_t* length) { + if (!*line) { + return false; + } + + *tag = nullptr; + *value = line; + + char* cursor = line; + + while (*cursor) { + char c = *cursor; + + if (c == '=') { + *cursor = '\0'; + *tag = line; + *value = cursor + 1; + } else if (c == '\r' || c == '\n') { + while (*cursor == '\r' || *cursor == '\n') { + *cursor++ = '\0'; + } + + *length = cursor - line; + return true; + } + + cursor++; + } + + *length = cursor - line; + return true; +} + +// VERIFY: 81de1fcb manual +// OFFSET: 0x00427EC0 +bool STORMAPI Blizzard::Streaming::ManifestInfo::GetItemTag(char* line, char** value, char** tag, int32_t* length) { + if (!*line) { + return false; + } + + *tag = nullptr; + *value = line; + + char* cursor = line; + + while (*cursor) { + char c = *cursor; + + if (c == '=') { + *cursor = '\0'; + *tag = line; + *value = cursor + 1; + } else if (c == '\r' || c == '\n') { + while (*cursor == '\r' || *cursor == '\n') { + *cursor++ = '\0'; + } + + *length = cursor - line; + return true; + } + + cursor++; + } + + *length = cursor - line; + return false; +} + +// VERIFY: 94f35d35 manual +// OFFSET: 0x0042D6B0 +bool Blizzard::Streaming::Manifests::TransportItem::HandleTag(const char* tag, const char* value) { + if (!tag) { + return false; + } + + if (!_stricmp(tag, "md5size")) { + this->m_md5Size = atol(value); + return true; + } + + if (_stricmp(tag, "splitsize")) { + return false; + } + + this->m_splitSize = atol(value); + return true; +} + +// VERIFY: abc1338a auto +// OFFSET: 0x0042D730 +Blizzard::Time::Timestamp Blizzard::Streaming::Manifests::TimeslotItem::ParseTimestamp(const char* time) { + Blizzard::Time::TimeRec rec; + memset(&rec.second, 0, 16); + rec.day = 1; + rec.month = 1; + rec.year = 2000; + + int32_t hour; + int32_t minute; + sscanf(time, "%d:%d", &hour, &minute); + + rec.hour = hour; + rec.minute = minute; + + return Blizzard::Time::MakeTime(rec); +} + +// VERIFY: f94ee91f auto +// OFFSET: 0x0042D7A0 +char* STORMAPI Blizzard::Streaming::TrimLine(char* line) { + char* start = line; + + if (!*start) { + return start; + } + + uint32_t length = strlen(line); + + while (*start == ' ' || *start == '\t' || *start == '\r' || *start == '\n') { + start++; + length--; + + if (!*start) { + break; + } + } + + for (char* end = &start[length]; *end; *end-- = '\0') { + char c = *end; + + if (c != ' ' && c != '\t' && c != '\r' && c != '\n') { + break; + } + } + + return start; +} + +// VERIFY: 3ee26353 manual +// OFFSET: 0x00432720 +bool Blizzard::Streaming::Manifests::TimeslotItem::HandleTag(const char* tag, const char* value) { + if (!tag) { + return false; + } + + if (!_stricmp(tag, "starttime")) { + this->m_startTime = ParseTimestamp(value); + return true; + } + + if (!_stricmp(tag, "endtime")) { + this->m_endTime = ParseTimestamp(value); + return true; + } + + if (_stricmp(tag, "usage")) { + return false; + } + + this->m_usage = atol(value); + return true; +} + +// VERIFY: 573566f6 manual +// OFFSET: 0x00437A80 +Blizzard::Streaming::Manifests::ManifestItem::~ManifestItem() { +} + +// VERIFY: af315f8d manual +// OFFSET: 0x00437D20 +Blizzard::Streaming::Manifests::ParameterItem::~ParameterItem() { +} + +// VERIFY: 2f850873 manual +// OFFSET: 0x00437D70 +Blizzard::Streaming::Manifests::ParameterItem::ParameterItem() { +} + +// VERIFY: 42880ac2 manual +// OFFSET: 0x00437DD0 +int32_t Blizzard::Streaming::Manifests::ServerItem::GetUsage(Blizzard::Time::Timestamp time) { + int32_t usage = 0; + + for (std::vector::iterator it = this->m_usageSlots.begin(); it != this->m_usageSlots.end(); ++it) { + if (it->m_time > time || !this->m_active) { + break; + } + + usage = it->m_usage; + } + + return usage; +} + +// VERIFY: 07f11350 manual +// OFFSET: 0x0043ACA0 +bool Blizzard::Streaming::FileManifest::SplitItem(char* line, MANIFEST_ITEM* item) { + char* field = line; + + if (!*line) { + return false; + } + + uint32_t index = 0; + char* cursor = field; + + do { + if (*cursor == ';') { + do { + *cursor++ = '\0'; + } while (*cursor == ';'); + + switch (index) { + case 0: { + char absolute[260]; + Blizzard::File::MakeAbsolutePath(field, absolute, 260, false); + + char normalized[260]; + char* dst = normalized; + const char* src = absolute; + uint32_t left = 260; + + while (true) { + char c = *src++; + left--; + + if (!c) { + *dst = '\0'; + break; + } + + *dst++ = c == '/' ? '\\' : c; + + if (!left) { + dst[-1] = '\0'; + break; + } + } + + item->m_absolutePath.assign(normalized, strlen(normalized)); + item->m_path.assign(field, strlen(field)); + break; + } + + case 1: + item->m_size = _atoi64(field); + break; + + case 2: + item->m_fileVersion.assign(field, strlen(field)); + break; + + case 3: + item->m_flags = atol(field); + break; + } + + index++; + field = cursor; + } + + cursor++; + } while (*cursor); + + if (index == 3) { + item->m_flags = atol(field); + } + + return true; +} + +// VERIFY: afa848ba manual +// OFFSET: 0x0043AE10 +bool Blizzard::Streaming::SourceManifest::SplitItem(char* line, MANIFEST_ITEM* item) { + char* field = line; + + if (!*line) { + return false; + } + + uint32_t index = 0; + char* cursor = field; + + do { + if (*cursor == ';') { + do { + *cursor++ = '\0'; + } while (*cursor == ';'); + + if (index == 0) { + item->m_name.assign(field, strlen(field)); + } else if (index == 1) { + item->m_path.assign(field, strlen(field)); + } + + index++; + field = cursor; + } + + cursor++; + } while (*cursor); + + if (index == 1) { + item->m_path.assign(field, strlen(field)); + } + + return true; +} + +// VERIFY: d2867546 manual +// OFFSET: 0x0043DBF0 +bool Blizzard::Streaming::Manifests::ServerPathItem::HandleTag(const char* tag, const char* value) { + if (!tag || _stricmp(tag, "path")) { + return false; + } + + this->m_path = std::string(value); + return true; +} + +// VERIFY: d5f9f625 manual +// OFFSET: 0x0043DCC0 +bool Blizzard::Streaming::Manifests::ParameterItem::HandleTag(const char* tag, const char* value) { + if (!tag || _stricmp(tag, "value")) { + return false; + } + + this->m_value = std::string(value); + return true; +} + +// VERIFY: 0df0b1e2 auto +// OFFSET: 0x0043DD90 +bool Blizzard::Streaming::FileManifest::SplitServerItem(char* line, std::string& base, std::string& path) { + if (!*line) { + return false; + } + + uint32_t prefixLength; + + if (s_httpPrefix && !_strnicmp(s_httpPrefix, line, strlen(s_httpPrefix))) { + prefixLength = s_httpPrefix ? strlen(s_httpPrefix) : 0; + } else if (s_filePrefix && !_strnicmp(s_filePrefix, line, strlen(s_filePrefix))) { + prefixLength = s_filePrefix ? strlen(s_filePrefix) : 0; + } else { + return false; + } + + char* cursor = &line[prefixLength]; + + if (!*cursor) { + return false; + } + + while (*cursor != '/') { + if (!*++cursor) { + return false; + } + } + + for (; *cursor == '/'; cursor++) { + *cursor = '\0'; + } + + base.assign(line, strlen(line)); + base.append("/", 1); + path.assign(cursor, strlen(cursor)); + + return true; +} + +// VERIFY: 737c5b41 manual +// OFFSET: 0x0043D6E0 +std::string Blizzard::Streaming::Manifests::FileItem::GetRemotePath() { + return this->m_path + this->m_fileName; +} + +// VERIFY: b28e420e manual +// OFFSET: 0x00444000 +Blizzard::Streaming::Manifests::ServerItem::~ServerItem() { +} + +// VERIFY: 07f9cb91 manual +// OFFSET: 0x004440A0 +Blizzard::Streaming::Manifests::FileItem::FileItem() { +} + +// VERIFY: 6b2adeb3 manual +// OFFSET: 0x00444130 +Blizzard::Streaming::Manifests::FileItem::~FileItem() { +} + +// VERIFY: 50d349cb manual +// OFFSET: 0x004474D0 +Blizzard::Streaming::Manifests::ServerItem::ServerItem() { + UsageSlot slot; + slot.m_time = TimeslotItem::ParseTimestamp("0:00"); + slot.m_usage = 100; + this->m_usageSlots.push_back(slot); + + this->m_uses = 0; + this->m_canDeactivate = 0; + this->m_maxRetry = 5; + this->m_active = true; +} + +// VERIFY: ae616726 manual +// OFFSET: 0x004475B0 +void Blizzard::Streaming::Manifests::ServerItem::InsertUsageSlot(UsageSlot& slot, Blizzard::Time::Timestamp end) { + UsageSlot* endSlot = nullptr; + std::vector::iterator it = this->m_usageSlots.begin(); + + while (it != this->m_usageSlots.end()) { + if (endSlot) { + if (it->m_time > endSlot->m_time) { + break; + } + + if (&*it == endSlot) { + ++it; + } else { + endSlot->m_usage = it->m_usage; + it = this->m_usageSlots.erase(it); + } + } else { + if (slot.m_time > it->m_time) { + ++it; + continue; + } + + it = this->m_usageSlots.insert(it, slot); + ++it; + endSlot = &*it; + it->m_time = end; + } + } + + if (!endSlot) { + this->m_usageSlots.push_back(slot); + + if (end) { + UsageSlot endUsage; + endUsage.m_time = end; + endUsage.m_usage = 100; + this->m_usageSlots.push_back(endUsage); + } + } +} + +// VERIFY: 2407f93f manual +// OFFSET: 0x00447750 +void Blizzard::Streaming::Manifests::ServerItem::InsertTimeslot(TimeslotItem* timeslot) { + UsageSlot slot; + + if (timeslot->m_startTime == timeslot->m_endTime) { + this->m_usageSlots.clear(); + slot.m_time = TimeslotItem::ParseTimestamp("0:00"); + slot.m_usage = timeslot->m_usage; + this->InsertUsageSlot(slot, 0); + } else if (timeslot->m_startTime > timeslot->m_endTime) { + slot.m_time = TimeslotItem::ParseTimestamp("0:00"); + slot.m_usage = timeslot->m_usage; + this->InsertUsageSlot(slot, timeslot->m_endTime); + slot.m_time = timeslot->m_startTime; + this->InsertUsageSlot(slot, 0); + } else { + slot.m_time = timeslot->m_startTime; + slot.m_usage = timeslot->m_usage; + this->InsertUsageSlot(slot, timeslot->m_endTime); + } +} + +// VERIFY: 836a47f6 manual +// OFFSET: 0x00447810 +bool Blizzard::Streaming::ManifestInfo::FinalizeManifestItems() { + bool result = true; + + for (std::map::iterator it = this->m_files.begin(); it != this->m_files.end(); ++it) { + Manifests::FileItem& file = it->second; + + if (!file.m_size) { + Blizzard::File::CreateDirectory(it->first.c_str(), false); + continue; + } + + if (file.m_path.size()) { + std::map::iterator path = this->m_serverPaths.find(file.m_path); + + if (path == this->m_serverPaths.end()) { + result = false; + } else { + file.m_path = path->second.m_path; + } + } + + if (!file.m_transportItem.size()) { + file.m_transport = nullptr; + continue; + } + + std::map::iterator transport = this->m_transports.find(file.m_transportItem); + + if (transport == this->m_transports.end()) { + if (this->m_version <= 1) { + file.m_transport = nullptr; + } else { + result = false; + } + } else { + file.m_transport = &transport->second; + } + } + + for (std::map::iterator it = this->m_servers.begin(); it != this->m_servers.end(); ++it) { + for (std::vector::iterator id = it->second.m_timeslotIds.begin(); id != it->second.m_timeslotIds.end(); ++id) { + std::map::iterator timeslot = this->m_timeslots.find(*id); + + if (timeslot == this->m_timeslots.end()) { + result = false; + } else { + it->second.InsertTimeslot(×lot->second); + } + } + } + + return result; +} + +// VERIFY: c742dab3 manual +// OFFSET: 0x0044C630 +bool Blizzard::Streaming::Transport::SplitItem(char* line, TRANSPORT_ITEM* item) { + char* field = line; + + if (!*line) { + return false; + } + + uint32_t index = 0; + item->m_md5Size = 0; + item->m_splitSize = 0; + + char* cursor = field; + + if (!*cursor) { + return true; + } + + do { + if (*cursor == ';') { + do { + *cursor++ = '\0'; + } while (*cursor == ';'); + + switch (index) { + case 0: + item->m_name.assign(field, strlen(field)); + index = 1; + break; + + case 1: + item->m_md5Size = atol(field); + index = 2; + break; + + case 2: + item->m_splitSize = atol(field); + index = 3; + break; + + case 3: + index = 4; + break; + + case 4: + item->m_servers.push_back(std::string(field)); + break; + } + + field = cursor; + } + + cursor++; + } while (*cursor); + + if (index == 4) { + item->m_servers.push_back(std::string(field)); + } + + return true; +} + +// VERIFY: d05cb762 manual +// OFFSET: 0x0044C790 +bool Blizzard::Streaming::Manifests::FileItem::HandleTag(const char* tag, const char* value) { + if (tag) { + if (!_stricmp(tag, "name")) { + this->m_fileName = std::string(value); + return true; + } + + if (!_stricmp(tag, "size")) { + this->m_size = _atoi64(value); + return true; + } + + if (!_stricmp(tag, "fileversion")) { + this->m_fileVersion = std::string(value); + return true; + } + + if (!_stricmp(tag, "flags")) { + this->m_flags = atol(value); + return true; + } + } + + if (Blizzard::String::EqualI(tag, "path")) { + this->m_path = std::string(value); + return true; + } + + if (Blizzard::String::EqualI(tag, "transportitem")) { + this->m_transportItem = std::string(value); + return true; + } + + if (Blizzard::String::EqualI(tag, "validserver")) { + this->m_validServers.push_back(std::string(value)); + return true; + } + + return false; +} + +// VERIFY: e76cbe2c manual +// OFFSET: 0x0044C9F0 +bool Blizzard::Streaming::Manifests::ServerItem::HandleTag(const char* tag, const char* value) { + if (tag) { + if (!_stricmp(tag, "location")) { + this->m_location = std::string(value); + return true; + } + + if (!_stricmp(tag, "timeslotid")) { + this->m_timeslotIds.push_back(std::string(value)); + return true; + } + + if (!_stricmp(tag, "maxretry")) { + this->m_maxRetry = atol(value); + return true; + } + + if (!_stricmp(tag, "candeactivate")) { + this->m_canDeactivate = atol(value); + return true; + } + } + + return false; +} + +// VERIFY: 0d42f349 manual +// OFFSET: 0x004500B0 +Blizzard::Streaming::Manifests::ManifestItem* Blizzard::Streaming::ManifestInfo::HandleBaseTag(const char* tag, const char* value) { + if (tag) { + if (!_stricmp(tag, "file")) { + Manifests::FileItem item; + std::string name(value); + std::string key = ResolveFilePath(name); + + this->m_files[key] = item; + this->m_files[key].m_name = name; + this->m_files[key].m_localPath = std::string(key); + + return &this->m_files[key]; + } + + if (!_stricmp(tag, "server")) { + Manifests::ServerItem item; + std::string key(value); + + this->m_servers[key] = item; + this->m_servers[key].m_name = key; + + return &this->m_servers[key]; + } + + if (!_stricmp(tag, "serverpath")) { + Manifests::ServerPathItem item; + std::string key(value); + + this->m_serverPaths[key] = item; + + return &this->m_serverPaths[key]; + } + + if (!_stricmp(tag, "timeslot")) { + Manifests::TimeslotItem item; + std::string key(value); + + this->m_timeslots[key] = item; + + return &this->m_timeslots[key]; + } + } + + if (Blizzard::String::EqualI(tag, "transport")) { + Manifests::TransportItem item; + std::string key(value); + + this->m_transports[key] = item; + + return &this->m_transports[key]; + } + + if (Blizzard::String::EqualI(tag, "parameter")) { + Manifests::ParameterItem item; + std::string key(value); + + this->m_parameters[key] = item; + + return &this->m_parameters[key]; + } + + return nullptr; +} + +// VERIFY: bab63d86 manual +// OFFSET: 0x00450580 +std::string Blizzard::Streaming::ManifestInfo::GetRandomServerLocation(const std::vector& validServers) { + std::string names[5]; + int32_t weights[5]; + int32_t count = 0; + int32_t total = 0; + + Blizzard::Time::TimeRec rec; + Blizzard::Time::BreakTime(Blizzard::Time::GetTimestamp(), rec); + rec.year = 2000; + rec.month = 1; + rec.day = 1; + rec.nanosecond = 0; + rec.second = 0; + Blizzard::Time::Timestamp now = Blizzard::Time::MakeTime(rec); + + if (validServers.size()) { + for (std::vector::const_iterator it = validServers.begin(); it != validServers.end(); ++it) { + std::map::iterator server = this->m_servers.find(*it); + + if (server == this->m_servers.end()) { + continue; + } + + int32_t usage = server->second.GetUsage(now); + + if (usage > 0) { + total += usage; + names[count] = server->first; + weights[count++] = total; + } + } + } else { + for (std::map::iterator server = this->m_servers.begin(); server != this->m_servers.end(); ++server) { + int32_t usage = server->second.GetUsage(now); + + if (usage > 0) { + total += usage; + names[count] = server->first; + weights[count++] = total; + } + } + } + + if (total) { + int32_t roll = rand() % total; + + for (int32_t i = 0; i < count; i++) { + if (weights[i] > roll) { + Manifests::ServerItem& server = this->m_servers[names[i]]; + server.m_uses++; + return server.m_location; + } + } + } + + return std::string("", 0); +} + +// VERIFY: cf7fb8cc manual +// OFFSET: 0x00451EE0 +Blizzard::Streaming::ManifestInfo::ManifestInfo() { + this->m_version = 0; + srand(static_cast(time(nullptr))); +} + +// VERIFY: fb6c09d1 manual +// OFFSET: 0x00452040 +Blizzard::Streaming::ManifestInfo::~ManifestInfo() { +} + +// VERIFY: 3a1f4459 manual +// OFFSET: 0x004525A0 +Blizzard::Streaming::ManifestInfo* Blizzard::Streaming::ManifestInfo::Get() { + if (!s_instance) { + s_instance = new ManifestInfo(); + } + + return s_instance; +} + +// VERIFY: a7aefdb8 manual +// OFFSET: 0x00452610 +std::string Blizzard::Streaming::ManifestInfo::GetParameter(std::string name) { + std::map::iterator it = Get()->m_parameters.find(name); + + if (it == Get()->m_parameters.end()) { + return std::string(); + } + + return std::string(it->second.m_value); +} + +// VERIFY: 6be6b41c manual +// OFFSET: 0x004526F0 +void Blizzard::Streaming::ManifestInfo::SetParameter(std::string name, std::string value) { + std::string parameterName = name; + std::string parameterValue = value; + + Manifests::ParameterItem& parameter = Get()->m_parameters[name]; + parameter.m_name = parameterName; + parameter.m_value = parameterValue; +} + +// VERIFY: 2d8ac238 manual +// OFFSET: 0x00452810 +void Blizzard::Streaming::ManifestInfo::SetParameter(std::string name, int32_t value) { + char text[16]; + Blizzard::String::Format(text, sizeof(text), "%d", value); + + std::string parameterName = name; + std::string parameterValue = std::string(text); + + Manifests::ParameterItem& parameter = Get()->m_parameters[name]; + parameter.m_name = parameterName; + parameter.m_value = parameterValue; +} + +// VERIFY: ba9688a6 manual +// OFFSET: 0x00452970 +void Blizzard::Streaming::ManifestInfo::SetServerPathItem(std::string name, std::string path) { + std::string serverPathName = name; + std::string serverPathPath = path; + + Manifests::ServerPathItem& serverPath = Get()->m_serverPaths[name]; + serverPath.m_name = serverPathName; + serverPath.m_path = serverPathPath; +} + +// VERIFY: 93bd2e83 manual +// OFFSET: 0x00452A90 +void Blizzard::Streaming::ManifestInfo::SetTransportItem(std::string name, const Manifests::TransportItem& item) { + Get()->m_transports[name] = item; +} + +// VERIFY: d6041b06 manual +// OFFSET: 0x00452B10 +void Blizzard::Streaming::ManifestInfo::SetFileItem(std::string name, const Manifests::FileItem& item) { + Get()->m_files[name] = item; + + if (Get()->m_transports.find(item.m_name) != Get()->m_transports.end()) { + Get()->m_files[name].m_transportItem = item.m_name; + } + + if (Get()->m_serverPaths.find(item.m_name) != Get()->m_serverPaths.end()) { + Get()->m_files[name].m_path = item.m_name; + } +} + +// VERIFY: dc677d5a manual +// OFFSET: 0x00452C30 +void Blizzard::Streaming::ManifestInfo::SetServerItem(std::string name, const Manifests::ServerItem& item) { + Get()->m_servers[name] = item; +} + +// VERIFY: 6485535f manual +// OFFSET: 0x00452C90 +Blizzard::Streaming::Manifests::FileItem* Blizzard::Streaming::ManifestInfo::GetFileItem(const std::string& name) { + std::map::iterator it = Get()->m_files.find(name); + + if (it == Get()->m_files.end()) { + return nullptr; + } + + return &it->second; +} + +// VERIFY: dee498ff manual +// OFFSET: 0x00452D00 +Blizzard::Streaming::Manifests::TransportItem* Blizzard::Streaming::ManifestInfo::GetTransportItem(const std::string& name) { + std::map::iterator it = Get()->m_files.find(name); + + if (it == Get()->m_files.end()) { + return nullptr; + } + + return it->second.m_transport; +} + +// VERIFY: c8b57a76 manual +// OFFSET: 0x00452D70 +std::string Blizzard::Streaming::ManifestInfo::GetRemotePath(const std::string& name) { + Manifests::FileItem* file = GetFileItem(name); + + if (!file) { + return std::string(); + } + + std::string location = Get()->GetRandomServerLocation(file->m_validServers); + return location + file->GetRemotePath(); +} + +// VERIFY: 1ffd4246 manual +// OFFSET: 0x00452E50 +std::vector Blizzard::Streaming::ManifestInfo::GetFileList(const char* path) { + std::vector files; + + char directory[260]; + Blizzard::File::MakeAbsolutePath(path, directory, sizeof(directory), false); + + char separator = Blizzard::String::FirstPathSeparator(directory); + int32_t length = strlen(directory); + char last = length > 0 ? directory[length - 1] : '\0'; + + if (!length || last != separator) { + if (last == '/' || last == '\\') { + length--; + } + + if (length > 258) { + length = 258; + } + + directory[length] = separator; + directory[length + 1] = '\0'; + } + + char normalized[260]; + char* dst = normalized; + const char* src = directory; + uint32_t left = 260; + + while (true) { + char c = *src++; + left--; + + if (!c) { + break; + } + + *dst++ = c == '/' ? '\\' : c; + + if (!left) { + dst--; + break; + } + } + + *dst = '\0'; + + for (std::map::iterator it = Get()->m_files.begin(); it != Get()->m_files.end(); ++it) { + if (it->second.m_size <= 0) { + continue; + } + + const char* localPath = it->second.m_localPath.c_str(); + char localDirectory[260]; + char fileName[260]; + + if (localPath) { + const char* name = localPath; + + for (const char* cursor = localPath; *cursor; cursor++) { + if (*cursor == '/' || *cursor == '\\') { + name = cursor + 1; + } + } + + int32_t directoryLength = name - localPath + 1; + Blizzard::String::Copy(localDirectory, localPath, directoryLength <= 260 ? directoryLength : 260); + Blizzard::String::Copy(fileName, name, 260); + } else { + localDirectory[0] = '\0'; + fileName[0] = '\0'; + } + + if (!_stricmp(normalized, localDirectory)) { + files.push_back(std::string(fileName)); + } + } + + return files; +} + +// VERIFY: 0c387579 manual +// OFFSET: 0x00453150 +void Blizzard::Streaming::ManifestInfo::DeactivateServer(std::string url, const std::string& name) { + if (!GetFileItem(name)) { + return; + } + + for (std::map::iterator it = Get()->m_servers.begin(); it != Get()->m_servers.end(); ++it) { + uint32_t length = it->second.m_location.size(); + const char* location = it->second.m_location.c_str(); + + if (location && !_strnicmp(url.c_str(), location, length) && it->second.m_canDeactivate >= 1) { + it->second.m_active = false; + } + } +} + +// VERIFY: ca248d72 manual +// OFFSET: 0x00453280 +int32_t Blizzard::Streaming::ManifestInfo::GetServerItemMaxRetry(std::string url, const std::string& name) { + if (!GetFileItem(name)) { + return 5; + } + + for (std::map::iterator it = Get()->m_servers.begin(); it != Get()->m_servers.end(); ++it) { + uint32_t length = it->second.m_location.size(); + const char* location = it->second.m_location.c_str(); + + if (location && !_strnicmp(url.c_str(), location, length)) { + return it->second.m_maxRetry; + } + } + + return 5; +} + +// VERIFY: 362b874e manual +// OFFSET: 0x004533E0 +int32_t Blizzard::Streaming::FileManifest::GetBGPreloadSleep() { + std::string value = ManifestInfo::GetParameter(std::string("bgpreloadsleep")); + + if (!value.size()) { + return 100; + } + + int32_t sleep = atol(value.c_str()); + + if (sleep < 0) { + sleep = 0; + } + + return sleep; +} + +// VERIFY: d8f4bc70 manual +// OFFSET: 0x00453480 +bool Blizzard::Streaming::FileManifest::GetIsStreamingTrial() { + std::string value = ManifestInfo::GetParameter(std::string("istrial")); + + if (!value.size()) { + return false; + } + + return atol(value.c_str()) != 0; +} + +// VERIFY: c87346ca manual +// OFFSET: 0x00453510 +bool Blizzard::Streaming::FileManifest::SetSpeedTest(int32_t speedTest) { + if (!speedTest) { + return true; + } + + int32_t minimum = 10; + int32_t maximum = 1000; + + ManifestInfo::SetParameter(std::string("bgpreloadsleep"), 25000000 / speedTest); + + int32_t sleep = atol(ManifestInfo::GetParameter(std::string("bgpreloadsleep")).c_str()); + ManifestInfo::SetParameter(std::string("bgpreloadsleep"), sleep >= minimum ? sleep : minimum); + + sleep = atol(ManifestInfo::GetParameter(std::string("bgpreloadsleep")).c_str()); + ManifestInfo::SetParameter(std::string("bgpreloadsleep"), sleep <= maximum ? sleep : maximum); + + return true; +} + +// VERIFY: e96edca9 auto +// OFFSET: 0x004536B0 +std::vector Blizzard::Streaming::FileManifest::GetFileList(const char* path) { + return ManifestInfo::GetFileList(path); +} + +// VERIFY: 26fb72b5 manual +// OFFSET: 0x004536E0 +void Blizzard::Streaming::FileManifest::SetDefaultBgPreloadSleep(int32_t sleep) { + ManifestInfo::SetParameter(std::string("bgpreloadsleep"), sleep); +} + +// VERIFY: 18f21e75 manual +// OFFSET: 0x00455D40 +bool Blizzard::Streaming::Transport::ReadDirectFileFromBuffer(char* buffer, int32_t size) { + char* line = buffer; + + if (!*line) { + return true; + } + + char* end = buffer + size; + + while (line < end) { + char* value; + char* tag; + int32_t length; + + if (!SplitLine(line, &value, &tag, &length)) { + Blizzard::File::AddToLastErrorStack(0, "Transport::ReadDirectFile - GetItemTag failed", 20); + return false; + } + + line += length; + + if (tag && (tag == "version" || !_strnicmp(tag, "version", 7))) { + if (atol(value) != 1) { + return false; + } + } else { + TRANSPORT_ITEM item; + SplitItem(value, &item); + + Manifests::TransportItem transport; + transport.m_name = item.m_name; + transport.m_md5Size = item.m_md5Size; + transport.m_splitSize = item.m_splitSize; + + ManifestInfo::SetTransportItem(std::string(item.m_name), transport); + } + + if (!*line) { + return true; + } + } + + return true; +} + +// VERIFY: 8cb841ed manual +// OFFSET: 0x0045AD60 +bool Blizzard::Streaming::SourceManifest::Initialize(const char* path) { + if (!path || !*path) { + return true; + } + + if (s_httpPrefix && !_strnicmp(path, s_httpPrefix, strlen(s_httpPrefix))) { + return ReadIndirectFile(path); + } + + return ReadDirectFile(path); +} + +// VERIFY: e18b8494 auto +// OFFSET: 0x00456720 +bool Blizzard::Streaming::ManifestInfo::ReadDirectFile(const char* path) { + void* data; + uint32_t size; + + if (!System_File::LoadFile(path, &data, &size, 4)) { + Blizzard::File::AddToLastErrorStack(0, "Manifests::ReadDirectFile - LoadFile failed", 20); + return false; + } + + bool result = this->ReadDirectFileFromBuffer(static_cast(data), size); + Blizzard::Memory::Free(data); + + if (!result) { + Blizzard::File::AddToLastErrorStack(0, "Manifests::ReadDirectFile - ReadDirectFileFromBuffer failed", 20); + } + + return result; +} + +// VERIFY: 78da1596 auto +// OFFSET: 0x00456980 +bool Blizzard::Streaming::FileManifest::ReadDirectFile(const char* path) { + void* data; + uint32_t size; + + if (!System_File::LoadFile(path, &data, &size, 4)) { + Blizzard::File::AddToLastErrorStack(0, "FileManifest::ReadDirectFile - LoadFile failed", 20); + return false; + } + + bool result = ReadDirectFileFromBuffer(static_cast(data), size); + Blizzard::Memory::Free(data); + + if (!result) { + Blizzard::File::AddToLastErrorStack(0, "FileManifest::ReadDirectFile - ReadDirectFileFromBuffer failed", 20); + } + + return result; +} + +// VERIFY: 4ef7dc5c manual +// OFFSET: 0x00456A00 +bool Blizzard::Streaming::SourceManifest::ReadDirectFileFromBuffer(char* buffer, int32_t size) { + std::string base; + std::string path; + + char* line = buffer; + + if (!*line) { + return true; + } + + char* end = buffer + size; + + while (line < end) { + char* value; + char* tag; + int32_t length; + + if (!SplitLine(line, &value, &tag, &length)) { + Blizzard::Memory::Free(buffer); + Blizzard::File::AddToLastErrorStack(0, "SourceManifest::ReadDirectfile - GetItemTag failed", 20); + return false; + } + + char* next = &line[length]; + + if (tag && (tag == "version" || !_strnicmp(tag, "version", 7))) { + if (atol(value) != 1) { + return false; + } + } else if (tag && (tag == "source" || !_strnicmp(tag, "source", 6))) { + if (FileManifest::SplitServerItem(value, base, path)) { + Manifests::ServerItem server; + server.m_name = base; + server.m_location = base; + ManifestInfo::SetServerItem(std::string(base), server); + ManifestInfo::SetServerPathItem(std::string("old-version1-base"), std::string(path)); + } + } else { + MANIFEST_ITEM item; + SplitItem(value, &item); + + char sourcePath[260]; + + if (item.m_path.size() != static_cast(-1)) { + const char* src = item.m_path.c_str(); + + if (src) { + char* dst = sourcePath; + char* limit = &sourcePath[item.m_path.size()]; + + while (dst < limit) { + char c = *src++; + + if (!c) { + break; + } + + *dst++ = c; + } + + *dst = '\0'; + } else { + sourcePath[0] = '\0'; + } + } + + if (FileManifest::SplitServerItem(sourcePath, base, path)) { + ManifestInfo::SetServerPathItem(std::string(item.m_name), std::string(path)); + } + } + + if (!*next) { + return true; + } + + line = next; + } + + return true; +} + +// VERIFY: 4525f827 auto +// OFFSET: 0x00459240 +bool Blizzard::Streaming::Transport::ReadDirectFile(const char* path) { + void* data; + uint32_t size; + + if (!System_File::LoadFile(path, &data, &size, 4)) { + Blizzard::File::AddToLastErrorStack(0, "Transport::ReadDirectFile - failed to load file", 20); + return false; + } + + bool result = ReadDirectFileFromBuffer(static_cast(data), size); + Blizzard::Memory::Free(data); + + return result; +} + +// VERIFY: c1052c97 auto +// OFFSET: 0x004595F0 +bool Blizzard::Streaming::SourceManifest::ReadDirectFile(const char* path) { + void* data; + uint32_t size; + + if (!System_File::LoadFile(path, &data, &size, 4)) { + Blizzard::File::AddToLastErrorStack(0, "SourceManifest::ReadDirectfile - failed to load file", 20); + return false; + } + + bool result = ReadDirectFileFromBuffer(static_cast(data), size); + Blizzard::Memory::Free(data); + + return result; +} + +// VERIFY: a956c6ba manual +// OFFSET: 0x0045D1E0 +bool Blizzard::Streaming::FileManifest::ReadDirectFileFromBuffer(char* buffer, int32_t size) { + char* line = buffer; + + if (!*line) { + return true; + } + + char* end = buffer + size; + + while (line < end) { + char* value; + char* tag; + int32_t length; + + if (!SplitLine(line, &value, &tag, &length)) { + Blizzard::File::AddToLastErrorStack(0, "FileManifest::ReadDirectFileFromBuffer - GetItemTag failed", 20); + return false; + } + + char* next = &line[length]; + bool isItem = !tag; + + if (isItem) { + } else if (tag == "version" || !_strnicmp(tag, "version", 7)) { + if (atol(value) != 1) { + return false; + } + } else if (tag == "isTrial" || !_strnicmp(tag, "isTrial", 7)) { + ManifestInfo::SetParameter(std::string("istrial"), std::string(value)); + } else if (tag == "manifest" || !_strnicmp(tag, "manifest", 8)) { + uint32_t prefixLength = s_httpPrefix ? strlen(s_httpPrefix) : 0; + + if (value && s_httpPrefix && !_strnicmp(value, s_httpPrefix, prefixLength)) { + return ReadIndirectFile(value); + } + + return ReadDirectFile(value); + } else if (tag == "sourcemanifest" || !_strnicmp(tag, "sourcemanifest", 14)) { + if (!SourceManifest::Initialize(value)) { + Blizzard::File::AddToLastErrorStack(0, "FileManifest::ReadDirectFileFromBuffer - SourceManifest::Initialize failed", 20); + return false; + } + } else if (tag == "transportmanifest" || !_strnicmp(tag, "transportmanifest", 17)) { + if (value && *value) { + bool result = _strnicmp(value, "http://", 7) ? Transport::ReadDirectFile(value) : Transport::ReadIndirectFile(value); + + if (!result) { + Blizzard::File::AddToLastErrorStack(0, "FileManifest::ReadDirectFileFromBuffer - Transport::Initialize failed", 20); + return false; + } + } + } else if (tag == "source" || !_strnicmp(tag, "source", 6)) { + std::string base; + std::string path; + + if (SplitServerItem(value, base, path)) { + Manifests::ServerItem server; + server.m_name = base; + server.m_location = base; + ManifestInfo::SetServerItem(std::string(base), server); + ManifestInfo::SetServerPathItem(std::string("old-version1-base"), std::string(path)); + } + } else if (tag == "bgpreloadsleep" || !_strnicmp(tag, "bgpreloadsleep", 14)) { + ManifestInfo::SetParameter(std::string("bgpreloadsleep"), std::string(value)); + } else { + isItem = true; + } + + if (isItem) { + MANIFEST_ITEM item; + SplitItem(value, &item); + + if (!item.m_size) { + if (Blizzard::File::Exists(item.m_absolutePath.c_str()) != 2) { + Blizzard::File::CreateDirectory(item.m_absolutePath.c_str(), true); + } + } + + std::string key = ResolveFilePath(item.m_path); + + Manifests::FileItem file; + file.m_name = item.m_path; + file.m_fileName = item.m_path; + file.m_localPath = key; + file.m_size = item.m_size; + file.m_path.assign("old-version1-base", 17); + file.m_fileVersion = item.m_fileVersion; + file.m_transportItem = item.m_path; + + ManifestInfo::SetFileItem(std::string(key), file); + } + + line = next; + + if (!*line) { + return true; + } + } + + return true; +} + +// VERIFY: 1d033fdf manual +// OFFSET: 0x00461290 +bool Blizzard::Streaming::ManifestInfo::ReadDirectFileFromBuffer(char* buffer, int32_t size) { + Manifests::ManifestItem* item = nullptr; + char* line = buffer; + + if (!*line) { + return true; + } + + char* end = &buffer[size]; + + while (line < end) { + char* value; + char* tag; + int32_t length; + + if (!GetItemTag(line, &value, &tag, &length)) { + Blizzard::File::AddToLastErrorStack(0, "ManifestInfo::ReadDirectFileFromBuffer - GetItemTag failed", 20); + return false; + } + + char* next = &line[length]; + value = TrimLine(value); + tag = TrimLine(tag); + + if (tag && !_stricmp(tag, "version")) { + this->m_version = atol(value); + + if (this->m_version == 1) { + return FileManifest::ReadDirectFileFromBuffer(next, size + next - buffer); + } + } else if (tag && !_stricmp(tag, "manifest")) { + if (value && s_httpPrefix && !_strnicmp(value, s_httpPrefix, Blizzard::String::Length(s_httpPrefix))) { + this->ReadIndirectFile(value); + } else { + this->ReadDirectFile(value); + } + } else if (!item || !item->HandleTag(tag, value)) { + item = this->HandleBaseTag(tag, value); + + if (!item) { + Blizzard::File::AddToLastErrorStack(0, "ManifestInfo::ReadDirectFileFromBuffer - Tag Parsing failed", 20); + return false; + } + } + + if (!*next) { + return true; + } + + line = next; + } + + return true; +} + +// VERIFY: 85a3a88a manual +// OFFSET: 0x00461620 +bool Blizzard::Streaming::ManifestInfo::Initialize(const char* path) { + ManifestInfo* info = Get(); + + if (!path) { + return true; + } + + bool result; + + if (s_httpPrefix && !_strnicmp(path, s_httpPrefix, strlen(s_httpPrefix))) { + result = info->ReadIndirectFile(path); + } else { + result = info->ReadDirectFile(path); + } + + if (!result) { + return result; + } + + return info->FinalizeManifestItems() & result; +} + +// VERIFY: b443e1e7 manual +// OFFSET: 0x004383C0 +int32_t System_Streaming::HttpCallback::GetTimeout() { + return this->m_timeout; +} + +// VERIFY: 71266dc6 manual +// OFFSET: 0x004383D0 +void System_Streaming::HttpCallback::SetTimeOutValue(uint32_t timeout) { + this->m_timeout = timeout; +} + +// VERIFY: dba30a86 manual +// OFFSET: 0x0043B060 +bool System_Streaming::HttpCallback::ReceivedData(const void* data, int32_t size) { + if (size > 0) { + this->m_data.append(static_cast(data), size); + this->m_received += size; + } + + return true; +} + +// VERIFY: 3cf1ff27 auto +// OFFSET: 0x008A1420 +bool System_Streaming::HttpCallback::ShouldBlock() { + return true; +} diff --git a/Engine/Source/BlizzardCore/Source/Packages/Streaming/Manifests.h b/Engine/Source/BlizzardCore/Source/Packages/Streaming/Manifests.h new file mode 100644 index 0000000..f0370f8 --- /dev/null +++ b/Engine/Source/BlizzardCore/Source/Packages/Streaming/Manifests.h @@ -0,0 +1,278 @@ +#ifndef ENGINE_SOURCE_BLIZZARDCORE_SOURCE_PACKAGES_STREAMING_MANIFESTS_H +#define ENGINE_SOURCE_BLIZZARDCORE_SOURCE_PACKAGES_STREAMING_MANIFESTS_H + +#include +#include +#include +#include +#include "Engine/Source/BlizzardCore/Source/System/Time/Types.h" +#include "Engine/Source/BlizzardCore/Source/System/URL/URL.h" +#include "Engine/Source/Storm/H/Types.h" + +namespace Blizzard { +namespace Streaming { +namespace Manifests { + +class ManifestItem { + public: + /* 0004 */ std::string m_name; + + virtual bool HandleTag(const char* tag, const char* value); + virtual ~ManifestItem(); +}; + +class TransportItem : public ManifestItem { + public: + /* 0020 */ int32_t m_md5Size; + /* 0024 */ int32_t m_splitSize; + + bool HandleTag(const char* tag, const char* value) override; +}; + +class TimeslotItem : public ManifestItem { + public: + static Blizzard::Time::Timestamp ParseTimestamp(const char* time); + + /* 0020 */ Blizzard::Time::Timestamp m_startTime; + /* 0028 */ Blizzard::Time::Timestamp m_endTime; + /* 0030 */ int32_t m_usage; + + bool HandleTag(const char* tag, const char* value) override; +}; + +class ServerPathItem : public ManifestItem { + public: + /* 0020 */ std::string m_path; + + bool HandleTag(const char* tag, const char* value) override; +}; + +class ParameterItem : public ManifestItem { + public: + /* 0020 */ std::string m_value; + + bool HandleTag(const char* tag, const char* value) override; + ~ParameterItem() override; + + ParameterItem(); +}; + +class ServerItem : public ManifestItem { + public: + struct UsageSlot { + /* 0000 */ Blizzard::Time::Timestamp m_time; + /* 0008 */ int32_t m_usage; + }; + + /* 0020 */ std::string m_location; + /* 003C */ std::vector m_timeslotIds; + /* 004C */ std::vector m_usageSlots; + /* 005C */ int32_t m_uses; + /* 0060 */ int32_t m_canDeactivate; + /* 0064 */ int32_t m_maxRetry; + /* 0068 */ bool m_active; + + bool HandleTag(const char* tag, const char* value) override; + ~ServerItem() override; + + ServerItem(); + int32_t GetUsage(Blizzard::Time::Timestamp time); + void InsertTimeslot(TimeslotItem* timeslot); + void InsertUsageSlot(UsageSlot& slot, Blizzard::Time::Timestamp end); +}; + +class FileItem : public ManifestItem { + public: + /* 0020 */ std::string m_fileName; + /* 003C */ std::string m_path; + /* 0058 */ std::string m_localPath; + /* 0074 */ std::string m_transportItem; + /* 0090 */ int64_t m_size; + /* 0098 */ TransportItem* m_transport; + /* 009C */ int32_t m_flags; + /* 00A0 */ std::string m_fileVersion; + /* 00BC */ std::vector m_validServers; + + bool HandleTag(const char* tag, const char* value) override; + ~FileItem() override; + + FileItem(); + std::string GetRemotePath(); +}; + +} + +class ManifestInfo { + public: + static ManifestInfo* s_instance; + + static ManifestInfo* Get(); + static bool STORMAPI GetItemTag(char* line, char** value, char** tag, int32_t* length); + static void DeactivateServer(std::string url, const std::string& name); + static Manifests::FileItem* GetFileItem(const std::string& name); + static std::string GetParameter(std::string name); + static std::string GetRemotePath(const std::string& name); + static int32_t GetServerItemMaxRetry(std::string url, const std::string& name); + static Manifests::TransportItem* GetTransportItem(const std::string& name); + static std::vector GetFileList(const char* path); + static bool Initialize(const char* path); + static void SetFileItem(std::string name, const Manifests::FileItem& item); + static void SetParameter(std::string name, int32_t value); + static void SetParameter(std::string name, std::string value); + static void SetServerItem(std::string name, const Manifests::ServerItem& item); + static void SetServerPathItem(std::string name, std::string path); + static void SetTransportItem(std::string name, const Manifests::TransportItem& item); + + /* 0000 */ int32_t m_version; + /* 0004 */ std::map m_servers; + /* 0010 */ std::map m_timeslots; + /* 001C */ std::map m_serverPaths; + /* 0028 */ std::map m_parameters; + /* 0034 */ std::map m_transports; + /* 0040 */ std::map m_files; + /* 004C */ uint32_t unk_004C; + + ManifestInfo(); + ~ManifestInfo(); + bool FinalizeManifestItems(); + std::string GetRandomServerLocation(const std::vector& validServers); + Manifests::ManifestItem* HandleBaseTag(const char* tag, const char* value); + bool ReadDirectFile(const char* path); + bool ReadDirectFileFromBuffer(char* buffer, int32_t size); + bool ReadIndirectFile(const char* url); +}; + +class FileManifest { + public: + struct MANIFEST_ITEM { + /* 0000 */ std::string m_path; + /* 001C */ std::string m_absolutePath; + /* 0038 */ std::string m_fileVersion; + /* 0058 */ int64_t m_size; + /* 0060 */ int32_t m_flags; + }; + + static int32_t GetBGPreloadSleep(); + static std::vector GetFileList(const char* path); + static bool GetIsStreamingTrial(); + static bool ReadDirectFile(const char* path); + static bool ReadDirectFileFromBuffer(char* buffer, int32_t size); + static bool ReadIndirectFile(const char* url); + static void SetDefaultBgPreloadSleep(int32_t sleep); + static bool SetSpeedTest(int32_t speedTest); + static bool SplitItem(char* line, MANIFEST_ITEM* item); + static bool SplitServerItem(char* line, std::string& base, std::string& path); +}; + +class SourceManifest { + public: + struct MANIFEST_ITEM { + /* 0000 */ std::string m_name; + /* 001C */ std::string m_path; + }; + + static bool Initialize(const char* path); + static bool ReadDirectFile(const char* path); + static bool ReadDirectFileFromBuffer(char* buffer, int32_t size); + static bool ReadIndirectFile(const char* url); + static bool SplitItem(char* line, MANIFEST_ITEM* item); +}; + +struct URL_INFO { + /* 0000 */ std::string m_url; + /* 0020 */ int64_t m_start; + /* 0028 */ int64_t m_end; + /* 0030 */ int32_t m_size; + + URL_INFO(std::string url, int64_t start, int64_t end, int32_t size); +}; + +class TransportHttpCallback : public Blizzard::URL::DownloadCallback { + public: + /* 0004 */ std::string m_cookieName; + /* 0020 */ std::string m_cookieValue; + /* 003C */ std::string m_data; + /* 0058 */ int64_t m_received; + /* 0060 */ int64_t m_rangeStart; + /* 0068 */ int64_t m_rangeEnd; + /* 0070 */ uint32_t m_timeout; + /* 0074 */ void* m_event; + /* 0078 */ bool m_stop; + /* 007C */ Blizzard::URL::DownloadCallback::Status m_status; + /* 0080 */ bool m_success; + + ~TransportHttpCallback() override; + int32_t GetTimeout() override; + Blizzard::URL::DownloadCallback::ByteRange GetByteRange() override; + bool Stop() override; + bool ShouldBlock() override; + Blizzard::URL::DownloadCallback::Cookie GetCookie() override; + bool ReceivedData(const void* data, int32_t size) override; + void Completed(Blizzard::URL::DownloadCallback::Status status) override; + virtual void SetByteRange(int64_t start, int64_t end); + virtual void SetCookie(const char* name, const char* value); + virtual void SetTimeOutValue(uint32_t timeout); + + TransportHttpCallback(uint32_t size); +}; + +class Transport { + public: + struct THROTTLE { + /* 0000 */ Blizzard::Time::Timestamp m_start; + /* 0008 */ int64_t m_bytes; + + void Wait(); + }; + + struct TRANSPORT_ITEM { + /* 0000 */ std::string m_name; + /* 001C */ int32_t m_md5Size; + /* 0020 */ int32_t m_splitSize; + /* 0024 */ std::vector m_servers; + }; + + static int32_t AdjustRange(int64_t* start, int64_t* end, int32_t md5Size, int64_t fileSize); + static void GetSplitFileURL(const std::string& url, int64_t start, int64_t end, int32_t skip, int32_t splitSize, int32_t md5Size, int32_t size, std::vector* urls); + static bool MD5_Data(std::string* out, std::string* data, int32_t md5Size, int64_t start, int64_t end); + static bool Read(Manifests::TransportItem* transport, std::string url, int32_t maxRetry, void* data, int64_t fileSize, int64_t offset, int32_t size); + static bool ReadDirectFile(const char* path); + static bool ReadDirectFileFromBuffer(char* buffer, int32_t size); + static bool ReadFile(Manifests::TransportItem* transport, std::string url, int32_t maxRetry, void* data, int64_t fileSize, int64_t offset, int32_t size); + static bool ReadHttp(Manifests::TransportItem* transport, std::string url, int32_t maxRetry, void* data, int64_t fileSize, int64_t offset, int32_t size); + static bool ReadIndirectFile(const char* url); + static bool SplitItem(char* line, TRANSPORT_ITEM* item); +}; + +extern const char* s_httpPrefix; +extern const char* s_filePrefix; + +bool SplitLine(char* line, char** value, char** tag, int32_t* length); +char* STORMAPI TrimLine(char* line); + +} +} + +namespace System_Streaming { + +class HttpCallback : public Blizzard::URL::DownloadCallback { + public: + /* 0004 */ std::string m_data; + /* 0020 */ uint32_t m_received; + /* 0024 */ Blizzard::URL::DownloadCallback::Status m_status; + /* 0028 */ uint32_t m_timeout; + /* 002C */ void* m_event; + + ~HttpCallback() override; + int32_t GetTimeout() override; + bool ShouldBlock() override; + bool ReceivedData(const void* data, int32_t size) override; + void Completed(Blizzard::URL::DownloadCallback::Status status) override; + virtual void SetTimeOutValue(uint32_t timeout); + + HttpCallback(); +}; + +} + +#endif diff --git a/Engine/Source/BlizzardCore/Source/Packages/Streaming/RepairCache.cpp b/Engine/Source/BlizzardCore/Source/Packages/Streaming/RepairCache.cpp new file mode 100644 index 0000000..f811d53 --- /dev/null +++ b/Engine/Source/BlizzardCore/Source/Packages/Streaming/RepairCache.cpp @@ -0,0 +1,116 @@ +#include +#include +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/RepairCache.h" +#include "Engine/Source/BlizzardCore/Source/System/File/File.h" +#include "Engine/Source/BlizzardCore/Source/System/Memory/MemoryStorm.h" +#include "Engine/Source/BlizzardCore/Source/System/Process/Process.h" +#include "Engine/Source/BlizzardCore/Source/System/String/Path.h" + +struct RepairRecord { + /* 0000 */ Blizzard::Util::Digest<16> m_md5; + /* 0010 */ uint32_t m_index; + /* 0014 */ uint32_t m_offset; + /* 0018 */ uint32_t m_flags; + /* 001C */ uint32_t m_size; +}; + +// STATIC: 0x00B37FF8 +static void* s_reportContext; + +// STATIC: 0x00B3800C +static void (*s_reportCallback)(void* context, uint32_t count, uint32_t repaired, uint32_t size); + +// STATIC: 0x00B38360 +Blizzard::Repair::RepairCache Blizzard::Repair::s_repairCache; + +// INLINED +bool Blizzard::Repair::RepairKey::operator<(const RepairKey& other) const { + if (this->m_md5 == other.m_md5) { + return this->m_index < other.m_index; + } + + return this->m_md5 < other.m_md5; +} + +// VERIFY: 816b7dc5 manual +// OFFSET: 0x00440970 +Blizzard::Repair::RepairCache::~RepairCache() { + if (s_reportCallback && this->m_repairedCount) { + s_reportCallback(s_reportContext, this->m_entries.size(), this->m_repairedCount, this->m_repairedSize); + } + + for (std::map::iterator it = this->m_entries.begin(); it != this->m_entries.end(); ++it) { + if (it->second.m_data) { + Blizzard::Memory::Free(it->second.m_data); + } + } + + for (std::map::iterator it = this->m_repaired.begin(); it != this->m_repaired.end(); ++it) { + if (it->second.m_data) { + Blizzard::Memory::Free(it->second.m_data); + } + } +} + +// VERIFY: a2f4a974 manual +// OFFSET: 0x00440B10 +bool Blizzard::Repair::RepairCache::AddEntry(const Blizzard::Util::Digest<16>& md5, uint32_t index, uint32_t offset, uint32_t flags, uint32_t size) { + RepairKey key; + key.m_md5 = md5; + key.m_index = index; + + if (this->m_entries.find(key) == this->m_entries.end()) { + RepairEntry entry; + entry.m_offset = offset; + entry.m_flags = flags; + entry.m_size = size; + entry.m_data = nullptr; + entry.m_valid = true; + this->m_entries.insert(std::pair(key, entry)); + this->m_totalSize += size; + } + + return true; +} + +// VERIFY: 2140c012 manual +// OFFSET: 0x00440BD0 +bool Blizzard::Repair::RepairCache::Load(Blizzard::File::StreamRecord* file) { + int64_t offset = 32 * static_cast(this->m_entries.size()); + + for (;;) { + RepairRecord record; + int32_t count = sizeof(record); + + if (!Blizzard::File::Read(file, &record, offset, &count) || count != sizeof(record)) { + break; + } + + this->AddEntry(record.m_md5, record.m_index, record.m_offset, record.m_flags, record.m_size); + offset += sizeof(record); + } + + return true; +} + +// VERIFY: 8c309560 manual +// OFFSET: 0x00443EE0 +Blizzard::Repair::RepairCache::RepairCache() { + char directory[260]; + Blizzard::Process::GetProcessDirectory(directory, sizeof(directory)); + Blizzard::String::JoinPath(this->m_headPath, sizeof(this->m_headPath), directory, "Data/Repair.head"); + Blizzard::String::JoinPath(this->m_dataPath, sizeof(this->m_dataPath), directory, "Data/Repair.data"); + + this->m_totalSize = 0; + this->m_repairedCount = 0; + this->m_repairedSize = 0; + + if (Blizzard::File::Exists(this->m_headPath) == 1) { + Blizzard::File::StreamRecord* file = nullptr; + + if (Blizzard::File::Open(this->m_headPath, 0x1001, file)) { + this->Load(file); + Blizzard::File::Close(file); + } + } +} diff --git a/Engine/Source/BlizzardCore/Source/Packages/Streaming/RepairCache.h b/Engine/Source/BlizzardCore/Source/Packages/Streaming/RepairCache.h new file mode 100644 index 0000000..19e00b2 --- /dev/null +++ b/Engine/Source/BlizzardCore/Source/Packages/Streaming/RepairCache.h @@ -0,0 +1,54 @@ +#ifndef ENGINE_SOURCE_BLIZZARDCORE_SOURCE_PACKAGES_STREAMING_REPAIRCACHE_H +#define ENGINE_SOURCE_BLIZZARDCORE_SOURCE_PACKAGES_STREAMING_REPAIRCACHE_H + +#include +#include +#include "Engine/Source/BlizzardCore/Include/Blizzard/Util/Digest.h" + +namespace Blizzard { +namespace File { +struct StreamRecord; +} +} + +namespace Blizzard { +namespace Repair { + +struct RepairKey { + /* 0000 */ Blizzard::Util::Digest<16> m_md5; + /* 0010 */ uint32_t m_index; + + bool operator<(const RepairKey& other) const; +}; + +struct RepairEntry { + /* 0000 */ uint32_t m_offset; + /* 0004 */ uint32_t m_flags; + /* 0008 */ uint32_t m_size; + /* 000C */ void* m_data; + /* 0010 */ bool m_valid; + /* 0011 */ uint8_t unk_0011[3]; +}; + +class RepairCache { + public: + /* 0000 */ std::map m_entries; + /* 000C */ std::map m_repaired; + /* 0018 */ uint32_t m_totalSize; + /* 001C */ uint32_t m_repairedCount; + /* 0020 */ uint32_t m_repairedSize; + /* 0024 */ char m_headPath[260]; + /* 0128 */ char m_dataPath[260]; + + RepairCache(); + ~RepairCache(); + bool AddEntry(const Blizzard::Util::Digest<16>& md5, uint32_t index, uint32_t offset, uint32_t flags, uint32_t size); + bool Load(Blizzard::File::StreamRecord* file); +}; + +extern RepairCache s_repairCache; + +} +} + +#endif diff --git a/Engine/Source/BlizzardCore/Source/Packages/Streaming/Storage.h b/Engine/Source/BlizzardCore/Source/Packages/Streaming/Storage.h index 9e15bc9..b45954f 100644 --- a/Engine/Source/BlizzardCore/Source/Packages/Streaming/Storage.h +++ b/Engine/Source/BlizzardCore/Source/Packages/Streaming/Storage.h @@ -3,53 +3,84 @@ #include #include - -namespace Blizzard { namespace Storage { struct StorageUnit; }} +#include +#include +#include namespace Blizzard { namespace File { typedef int32_t INODE; +struct Filesystem; +struct StreamRecord; +} +} + +namespace Blizzard { +namespace Streaming { +struct LoadRange; +struct StorageEntry; +struct WriteRequest; } } namespace Blizzard { namespace Storage { -struct StorageUnitHandle { - /* 0000 */ Blizzard::File::INODE m_mNode; - /* 0004 */ Blizzard::Storage::StorageUnit* m_mUnit; + +class StorageEntryRef { + public: + /* 0000 */ Blizzard::Streaming::StorageEntry* m_entry; + + StorageEntryRef(Blizzard::Streaming::StorageEntry* entry); }; -} -} -namespace Blizzard { -namespace Storage { -struct StorageUnit { - /* 0000 */ uint32_t unk_0000; - /* 0004 */ uint32_t unk_0004; - /* 0008 */ uint32_t unk_0008; - /* 000C */ uint32_t unk_000C; - /* 0010 */ uint32_t unk_0010; - /* 0014 */ uint32_t unk_0014; - /* 0018 */ uint32_t unk_0018; - /* 001C */ uint32_t unk_001C; - /* 0020 */ uint32_t unk_0020; - /* 0024 */ uint32_t unk_0024; - /* 0028 */ uint32_t unk_0028; - /* 002C */ uint32_t unk_002C; - /* 0030 */ uint32_t unk_0030; - /* 0034 */ uint32_t unk_0034; - /* 0038 */ uint32_t unk_0038; +class PartialFile { + public: + static Blizzard::Streaming::StorageEntry* CreateShared(const std::string& key, const char* path, int64_t size, const char* version, int32_t flags); + static bool ParseFile(Blizzard::File::Filesystem* fs, Blizzard::File::StreamRecord* file); + static bool RebuildHeader(Blizzard::File::Filesystem* fs, Blizzard::File::StreamRecord* file); }; -} -} - -namespace Blizzard { -namespace Storage { extern int32_t s_variantIndex; extern char s_variantName[260]; +extern std::map* s_storage; +extern Blizzard::File::StreamRecord* s_storageFile; +extern bool s_storageReady; +extern bool s_storageDirty; +extern volatile bool s_storageStop; +extern volatile bool s_storageStopped; +extern bool s_usePartFiles; +extern int32_t s_blockSize; +extern std::string s_storagePath; +extern std::deque s_writeQueue; +Blizzard::Streaming::StorageEntry* Acquire(Blizzard::File::Filesystem* fs, const std::string& key, const char* path, int64_t size, const char* version, int32_t flags); void BuildVariantFileName(char* dest, uint32_t size, const char* name, const char* extension); +int32_t BuildRanges(Blizzard::Streaming::StorageEntry* entry, int64_t offset, int32_t size, Blizzard::Streaming::LoadRange* ranges); +int32_t BuildRangesFromStore(Blizzard::Streaming::StorageEntry* entry, int64_t offset, int32_t size, Blizzard::Streaming::LoadRange* ranges); +int32_t BuildRangesWithHeader(Blizzard::Streaming::StorageEntry* entry, int64_t offset, int32_t size, Blizzard::Streaming::LoadRange* ranges); +bool Close(Blizzard::File::Filesystem* fs, Blizzard::File::StreamRecord* file, Blizzard::Streaming::StorageEntry* entry); +int32_t CountRanges(Blizzard::Streaming::StorageEntry* entry, int64_t offset, int64_t size); +bool FlushFile(Blizzard::File::Filesystem* fs, Blizzard::File::StreamRecord* file); +int32_t GetBlockLength(Blizzard::Streaming::StorageEntry* entry, int32_t block); +int64_t GetNextHeaderOffset(); +Blizzard::Streaming::LoadRange* GetRange(Blizzard::Streaming::StorageEntry* entry, int64_t offset, int32_t size, int32_t* count, bool lock); +bool Initialize(); +bool Initialize(const char* path, bool required); +bool IsComplete(Blizzard::Streaming::StorageEntry* entry); +bool QueueWrite(Blizzard::File::Filesystem* fs, Blizzard::File::StreamRecord* file, uint8_t* data, int64_t offset, int32_t size, bool owned); +bool ReadAt(Blizzard::File::Filesystem* fs, Blizzard::File::StreamRecord* file, void* buffer, int64_t offset, int32_t size); +bool ReadLocal(Blizzard::File::Filesystem* fs, Blizzard::File::StreamRecord* file, Blizzard::Streaming::StorageEntry* entry, uint8_t* buffer, int64_t offset, int32_t size); +bool ReadStorageFile(const uint8_t* data, int32_t size); +bool Remove(const std::string& path); +bool RequestRange(Blizzard::Streaming::StorageEntry* entry, int64_t offset, int32_t size, int32_t state); +void Shutdown(); +void SetRangeAs(Blizzard::Streaming::StorageEntry* entry, int64_t offset, int32_t size, int32_t state); +uint32_t StorageThread(void* param); +bool WriteAt(Blizzard::File::StreamRecord* file, const void* buffer, int64_t offset, int32_t size); +bool WriteBlock(Blizzard::Streaming::WriteRequest* request); +bool WriteIndex(); +bool WriteIndexEntry(Blizzard::Streaming::StorageEntry* entry, int32_t block, bool header); +bool WritePartBlockInfo(Blizzard::Streaming::StorageEntry* entry, Blizzard::File::StreamRecord* file, int32_t block); } } diff --git a/Engine/Source/BlizzardCore/Source/Packages/Streaming/Streaming.cpp b/Engine/Source/BlizzardCore/Source/Packages/Streaming/Streaming.cpp index 3350980..922f368 100644 --- a/Engine/Source/BlizzardCore/Source/Packages/Streaming/Streaming.cpp +++ b/Engine/Source/BlizzardCore/Source/Packages/Streaming/Streaming.cpp @@ -12,10 +12,25 @@ #include "Engine/Source/BlizzardCore/Source/System/Time/Time.h" // STATIC: 0x00AB7AC8 -static uint8_t s_clientInitialized; +static uint8_t s_clientInitialized = 1; // STATIC: 0x00B38038 -static Blizzard::Time::Timestamp s_elapsedSinceStart; +Blizzard::Time::Timestamp Blizzard::Streaming::s_elapsedSinceStart; + +// STATIC: 0x00B38040 +int64_t Blizzard::Streaming::s_statBytesRead; + +// STATIC: 0x00B38048 +int64_t Blizzard::Streaming::s_statBytesDownloaded; + +// STATIC: 0x00B38050 +int64_t Blizzard::Streaming::s_statBytesLocal; + +// STATIC: 0x00B38058 +int32_t Blizzard::Streaming::s_statRetries; + +// STATIC: 0x00B38060 +char Blizzard::Streaming::s_statFrameTimes[260]; // STATIC: 0x00B38180 bool Blizzard::Streaming::s_streamingReady; @@ -127,14 +142,14 @@ void Blizzard::Streaming::MakePartFileName(char* name, uint32_t size) { Blizzard::String::Copy(name, part, size); } -// VERIFY: 76edbcda auto +// VERIFY: 4470ae4c auto // OFFSET: 0x00437A00 void Blizzard::Time::GetElapsedSinceStart(bool start) { // STATIC: 0x00B38A48 static Blizzard::Time::Timestamp s_startTime = Blizzard::Time::GetTimestamp(); if (!start) { - s_elapsedSinceStart = Blizzard::Time::GetTimestamp() - s_startTime; + Blizzard::Streaming::s_elapsedSinceStart = Blizzard::Time::GetTimestamp() - s_startTime; } } @@ -145,15 +160,15 @@ Blizzard::Streaming::DownloadProgress::DownloadProgress() { // INLINED Blizzard::Streaming::DownloadProgress::~DownloadProgress() { - this->unk_0018 = 0; - this->unk_0354 = nullptr; - memset(this->unk_0020, 0, sizeof(this->unk_0020)); + this->m_lastTime = 0; + this->m_callback = nullptr; + memset(this->m_samples, 0, sizeof(this->m_samples)); } -// VERIFY: 1ed002c0 manual +// VERIFY: c945173d manual // OFFSET: 0x00438300 void Blizzard::Streaming::DownloadProgress::ResetTime() { - this->unk_0018 = static_cast(Blizzard::Time::Milliseconds()); + this->m_lastTime = static_cast(Blizzard::Time::Milliseconds()); } // VERIFY: d9c84ab5 auto diff --git a/Engine/Source/BlizzardCore/Source/Packages/Streaming/Streaming.h b/Engine/Source/BlizzardCore/Source/Packages/Streaming/Streaming.h index ab1e582..02ea19f 100644 --- a/Engine/Source/BlizzardCore/Source/Packages/Streaming/Streaming.h +++ b/Engine/Source/BlizzardCore/Source/Packages/Streaming/Streaming.h @@ -4,80 +4,184 @@ #include #include #include +#include #include "Engine/Source/BlizzardCore/Include/Blizzard/Util/Digest.h" #include "Engine/Source/BlizzardCore/Source/System/File/Types.h" +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Manifests.h" +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Storage.h" +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/StreamingManager.h" +#include "Engine/Source/BlizzardCore/Source/System/Lock/Lock.h" +#include "Engine/Source/BlizzardCore/Source/System/Time/Time.h" +#include "Engine/Source/BlizzardCore/Source/System/URL/URL.h" namespace Blizzard { namespace Streaming { -struct FILE_THREAD_CMD { - /* 0000 */ uint32_t unk_0000; - /* 0004 */ uint32_t unk_0004; - /* 0008 */ uint32_t unk_0008; - /* 000C */ uint32_t unk_000C; - /* 0010 */ void* unk_0010; +struct Completion { + /* 0000 */ Blizzard::Lock::Event* m_event; + /* 0004 */ int32_t m_result; + /* 0008 */ bool m_done; + /* 0009 */ bool m_success; }; -struct DownloadSlot { - /* 0000 */ uint32_t unk_0000; - /* 0004 */ uint32_t unk_0004; - /* 0008 */ uint32_t unk_0008; - /* 000C */ uint32_t unk_000C; - /* 0010 */ uint32_t unk_0010; +#pragma pack(push, 4) +struct StorageBlock { + /* 0000 */ int32_t m_state; + /* 0004 */ int64_t m_offset; + /* 000C */ int64_t m_storeOffset; + /* 0014 */ int64_t m_partOffset; + /* 001C */ int32_t m_size; +}; +#pragma pack(pop) + +struct StorageEntry { + /* 0000 */ std::string m_path; + /* 001C */ std::string m_version; + /* 0038 */ bool m_closed; + /* 0039 */ bool m_headerWritten; + /* 003A */ bool m_parsed; + /* 003C */ int32_t m_flags; + /* 0040 */ int64_t m_size; + /* 0048 */ int64_t m_storeSize; + /* 0050 */ int32_t m_blockSize; + /* 0054 */ std::vector m_locality; + /* 0064 */ std::vector m_blocks; + /* 0078 */ int64_t m_headerOffset; + /* 0080 */ Blizzard::File::StreamRecord* m_file; + /* 0084 */ int32_t m_openCount; + /* 0088 */ Blizzard::Lock::Mutex m_lock; + /* 00A0 */ int32_t m_released; + /* 00A4 */ int32_t m_refCount; +}; + +#pragma pack(push, 1) +struct StorageHeader { + /* 0000 */ char m_path[260]; + /* 0104 */ char m_version[32]; + /* 0124 */ int32_t m_flags; + /* 0128 */ uint8_t m_closed; + /* 0129 */ int64_t m_size; + /* 0131 */ int64_t m_storeSize; + /* 0139 */ int32_t m_blockSize; + /* 013D */ int32_t m_blockCount; +}; + +struct StorageBlockRecord { + /* 0000 */ int32_t m_state; + /* 0004 */ int64_t m_offset; + /* 000C */ int64_t m_storeOffset; + /* 0014 */ int32_t m_size; +}; +#pragma pack(pop) + +#pragma pack(push, 4) +struct PartFileHeader { + /* 0000 */ int32_t m_magic; + /* 0004 */ char m_version[32]; + /* 0024 */ int32_t m_flags; + /* 0028 */ int64_t m_size; + /* 0030 */ int32_t m_blockSize; +}; + +struct PartBlockRecord { + /* 0000 */ int32_t m_state; + /* 0004 */ int64_t m_storeOffset; + /* 000C */ int64_t m_partOffset; +}; +#pragma pack(pop) + +struct LoadRange { + /* 0000 */ int64_t m_offset; + /* 0008 */ int32_t m_size; + /* 0010 */ int64_t m_blockOffset; + /* 0018 */ int32_t m_blockSize; + /* 001C */ int32_t m_state; +}; + +struct WriteRequest { + /* 0000 */ Blizzard::File::Filesystem* m_fs; + /* 0004 */ int32_t m_pending; + /* 0008 */ Blizzard::File::StreamRecord* m_file; + /* 000C */ StorageEntry* m_entry; + /* 0010 */ uint8_t* m_data; + /* 0018 */ int64_t m_offset; + /* 0020 */ int32_t m_size; +}; + +struct FILE_THREAD_CMD { + /* 0000 */ Blizzard::File::Filesystem* m_fs; + /* 0004 */ int32_t m_type; + /* 0008 */ Blizzard::File::StreamRecord* m_file; + /* 000C */ LoadRange* m_range; + /* 0010 */ Completion* m_completion; }; struct DigestState { - /* 0000 */ int32_t unk_0000; - /* 0004 */ int32_t unk_0004; -}; - -struct StorageEntry { - /* 0000 */ uint8_t unk_0000[168]; - - ~StorageEntry(); -}; - -class SourceManifest { - public: - /* 0000 */ uint8_t unk_0000[80]; - - ~SourceManifest(); + /* 0000 */ int32_t m_state; + /* 0004 */ int32_t m_priority; }; struct ProgressSample { - /* 0000 */ int64_t unk_0000; - /* 0008 */ int32_t unk_0008; - /* 000C */ uint8_t unk_000C[4]; + /* 0000 */ int64_t m_bytes; + /* 0008 */ uint32_t m_time; }; typedef void (*PROGRESSCALLBACK)(uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, int32_t); class DownloadProgress { public: - /* 0000 */ uint32_t unk_0000[6]; - /* 0018 */ uint32_t unk_0018; - /* 001C */ uint8_t unk_001C[4]; - /* 0020 */ ProgressSample unk_0020[51]; - /* 0350 */ uint32_t unk_0350; - /* 0354 */ PROGRESSCALLBACK unk_0354; - /* 0358 */ bool unk_0358; + /* 0000 */ int64_t m_total; + /* 0008 */ int64_t m_downloaded; + /* 0010 */ int64_t m_streamed; + /* 0018 */ uint32_t m_lastTime; + /* 0020 */ ProgressSample m_samples[51]; + /* 0350 */ uint32_t m_index; + /* 0354 */ PROGRESSCALLBACK m_callback; + /* 0358 */ bool m_enabled; DownloadProgress(); ~DownloadProgress(); - int32_t FindNextSlot(); void FireCallback(); + int32_t GetRate(); void ResetTime(); + void Sample(uint32_t time); }; typedef std::map, DigestState> DigestStateMap; typedef std::map PathMap; typedef std::map StorageEntryMap; +extern Blizzard::Time::Timestamp s_elapsedSinceStart; +extern int64_t s_statBytesRead; +extern int64_t s_statBytesDownloaded; +extern int64_t s_statBytesLocal; +extern int32_t s_statRetries; +extern char s_statFrameTimes[260]; extern bool s_streamingReady; extern bool s_isStreamingTrial; -int32_t CheckFileRange(const char* path, int64_t offset, uint32_t count, const char* name, int32_t flags); -uint32_t GetIsLocalAmount(const char* path, int64_t offset, uint32_t size, const char* name); +extern DownloadProgress s_progress; + +void AddDownloaded(int32_t size); +void AddStreamed(int32_t size); +bool CancelQueue(int32_t priority); +uint32_t DownloadThread(void* param); +int32_t GetIdleThread(); +int32_t GetNextCommand(FILE_THREAD_CMD** command, int32_t thread); +void HashFileName(Blizzard::Util::Digest<16>* digest, const char* name); +bool InitializeStreaming(const char* manifest, const char* storagePath, const char* variant, const char* dataPath, bool required); +bool LoadFile(Blizzard::File::Filesystem* fs, Blizzard::File::StreamRecord* file, LoadRange* range); +bool MakeLocalAsync(Blizzard::File::StreamRecord* file, int64_t offset, int32_t size, int32_t priority, const char* name); +bool MakeLocalBlocking(Blizzard::File::StreamRecord* file, int64_t offset, int32_t size, int32_t priority, const char* name); +bool PopCommand(FILE_THREAD_CMD* command, int32_t queue); +bool QueueLoad(Blizzard::File::StreamRecord* file, int32_t priority, LoadRange* range, Completion* completion); +bool RequestRanges(Blizzard::File::StreamRecord* file, LoadRange* ranges, int32_t count); +bool SelectQueue(FILE_THREAD_CMD* command, int32_t group, int32_t* queue); +void WaitForLoads(); +bool QueueCompletion(Completion* completion, int32_t priority); +bool RemoveCompletion(Completion* completion, int32_t priority); +int32_t CheckFileRange(const char* path, int64_t offset, int32_t size, const char* name, int32_t flags); +int32_t GetIsLocalAmount(const char* path, int64_t offset, int32_t size, const char* name); bool IsStreamedFile(const char* path); std::string ResolveFilePath(const std::string& path); bool IsStreamingMode(); @@ -88,10 +192,14 @@ void MakePartFileName(char* name, uint32_t size); } } -class StreamingManager { - public: - void Shutdown(); -}; +namespace Blizzard { +namespace Storage { + +extern Blizzard::Lock::Mutex s_storageLock; +extern void* s_storageEvent; + +} +} bool CheckIfStreamingAndTrial(); void StringToLower(char* str); @@ -107,7 +215,9 @@ void StreamingSetRace(int32_t raceID); void StreamingSetState(int32_t state); char* GetComponentVersionData(uint32_t* size); -void SetActiveDataSource(int32_t source); +void SetActiveDataSource(bool restore); +void StartDataPreloadThread(); +void StreamingSetEnabled(bool enabled); float StreamingGetLoadFraction(int32_t raceID); #endif diff --git a/Engine/Source/BlizzardCore/Source/Packages/Streaming/StreamingManager.cpp b/Engine/Source/BlizzardCore/Source/Packages/Streaming/StreamingManager.cpp new file mode 100644 index 0000000..7ea9fbc --- /dev/null +++ b/Engine/Source/BlizzardCore/Source/Packages/Streaming/StreamingManager.cpp @@ -0,0 +1,914 @@ +#include "StreamingManager.h" +#include +#include +#include +#include "Engine/Source/BlizzardCore/Source/Packages/Mopaq/MPQGlobals.h" +#include "Engine/Source/BlizzardCore/Source/Packages/Mopaq/SFile.h" +#include "Engine/Source/BlizzardCore/Source/Packages/Mopaq/SFileArchives.h" +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Streaming.h" +#include "Engine/Source/BlizzardCore/Source/System/String/Path.h" +#include "Engine/Source/BlizzardCore/Source/System/String/String.h" + +// STATIC: 0x00AB7AD0 +static std::string s_emptyFile; + +// STATIC: 0x00AB7AEC +static const char* s_localeArchives[8] = { "terrain.MPQ", "wmo.MPQ", "model.MPQ", "texture.MPQ", "misc.MPQ", "fonts.MPQ", "interface.MPQ", "dbc.MPQ" }; + +// STATIC: 0x00AB7B0C +static const char* s_regionArchives[5] = { "Installer Tome.MPQ", "Movies.MPQ", "expansion.MPQ", "expansionspeech.MPQ", "expansionloc.MPQ" }; + +// STATIC: 0x00AB7B20 +static const char* s_startClientList = "TrialLists/StartClient.lst"; + +// STATIC: 0x00AB7B24 +static const char* s_startCharacterList = "TrialLists/StartCharacter.lst"; + +// STATIC: 0x00AB7B28 +static const char* s_startRaceCommonList = "TrialLists/StartRaceCommon.lst"; + +// STATIC: 0x00AB7B2C +static const char* s_startRaceList = "TrialLists/Start%s.lst"; + +// STATIC: 0x00AB7B30 +static const char* s_startBackgroundZoneList = "TrialLists/StartBackgroundZone%d.lst"; + +// STATIC: 0x00AB7B34 +static const char* s_startBackgroundList = "TrialLists/StartBackground%s.lst"; + +// STATIC: 0x00AB7B74 +static const char* s_lineSeparator = "\r\n"; + +// STATIC: 0x009E4DB8 +static const int32_t s_manifestZones[7] = { 10, 44, 267, 331, 400, 406, 11 }; + +// STATIC: 0x00B31EEC +static int32_t s_savedBgPreloadSleep; + +// VERIFY: 543c851a auto +// OFFSET: 0x0041E220 +bool OpenDataArchive(const char* name, System_SFile::ARCHIVEREC** archive) { + char path[260]; + Blizzard::String::JoinPath(path, sizeof(path), "Data\\", name); + + *archive = System_MPQGlobals::FindArchiveByName(path); + + if (*archive) { + return true; + } + + return Blizzard::Mopaq::SFileOpenArchive(path, 0, 0, archive); +} + +// VERIFY: 64139cb0 manual +// OFFSET: 0x0041E280 +int32_t StreamingManager::GetNextState() { + switch (this->m_gameState) { + case 1: + return 1; + + case 2: + return 3; + + case 3: + return 4; + + case 4: + return 12; + + default: + return 0; + } +} + +// VERIFY: 467668b8 manual +// OFFSET: 0x0041E2C0 +void StreamingManager::AdvanceState(uint32_t& index) { + switch (this->m_state) { + case 0: + this->m_state = 1; + break; + + case 1: + case 3: + case 5: + this->m_state = 2; + break; + + case 2: + this->m_state = 6; + break; + + case 4: + this->m_state = 5; + break; + + case 6: + if (index == 8) { + this->m_state = 7; + index = 0; + } + + break; + + case 7: + if (index == 7) { + this->m_state = this->m_enabled ? 9 : 11; + index = 0; + } + + break; + + case 8: + if (index == 2) { + this->m_state = 9; + index = 0; + } + + break; + + case 9: + if (index == 8) { + this->m_state = 11; + index = 0; + } + + break; + + case 10: + if (index == 5) { + this->m_state = 11; + index = 0; + } + + break; + + default: + this->m_state = 12; + break; + } +} + +// VERIFY: 47a1ea71 manual +// OFFSET: 0x0041E3B0 +void StreamingManager::Shutdown() { + if (this->m_state != 12) { + this->m_state = 12; + this->m_gameState = 4; + this->m_dirty = true; + Blizzard::Lock::EventSet(this->m_event); + } + + if (this->m_thread) { + Blizzard::Thread::WaitForever(this->m_thread); + Blizzard::Thread::Close(this->m_thread); + } + + this->m_thread = nullptr; +} + +// VERIFY: 2dda1ba2 manual +// OFFSET: 0x0041E410 +int32_t GetManifestZone(uint32_t index) { + if (index > 6) { + return 0; + } + + return s_manifestZones[index]; +} + +// VERIFY: dffb6335 auto +// OFFSET: 0x0041E430 +const char* GetLocaleArchiveName(uint32_t index) { + if (index > 7) { + return ""; + } + + return s_localeArchives[index]; +} + +// VERIFY: 195557b2 auto +// OFFSET: 0x0041E450 +const char* GetRegionArchiveName(uint32_t index) { + if (index > 4) { + return ""; + } + + return s_regionArchives[index]; +} + +// VERIFY: 886669bf auto +// OFFSET: 0x0041E470 +int32_t GetManifestRace(int32_t index) { + switch (index) { + case 0: + return 1; + + case 1: + return 4; + + case 2: + return 5; + + case 3: + return 6; + + case 4: + return 2; + + case 5: + return 7; + + case 6: + return 3; + + case 7: + return 8; + + default: + return -1; + } +} + +// VERIFY: 1455f2fd auto +// OFFSET: 0x0041E4F0 +void SetActiveDataSource(bool restore) { + if (restore) { + Blizzard::Streaming::FileManifest::SetDefaultBgPreloadSleep(s_savedBgPreloadSleep); + return; + } + + if (Blizzard::Streaming::FileManifest::GetBGPreloadSleep()) { + s_savedBgPreloadSleep = Blizzard::Streaming::FileManifest::GetBGPreloadSleep(); + } + + Blizzard::Streaming::FileManifest::SetDefaultBgPreloadSleep(0); +} + +// VERIFY: c456bdee manual +// OFFSET: 0x0041E820 +float StreamingFileEntry::GetLocalFraction() { + if (this->m_complete) { + return 1.0f; + } + + int64_t local = this->m_localAmount; + int64_t total = this->m_localAmount; + + for (uint32_t i = this->m_cursor + 1; i < this->m_files.size(); i++) { + Blizzard::Mopaq::SFileGetIsLocalAmount(this->m_files[i].c_str(), local, total); + } + + return static_cast(static_cast(local) / static_cast(total)); +} + +// VERIFY: f2a68773 manual +// OFFSET: 0x0041EBB0 +std::string RaceIdToName(int32_t race) { + switch (race) { + case 1: + return std::string("Human"); + + case 2: + return std::string("Orc"); + + case 3: + return std::string("Dwarf"); + + case 4: + return std::string("NightElf"); + + case 5: + return std::string("Undead"); + + case 6: + return std::string("Tauren"); + + case 7: + return std::string("Gnome"); + + case 8: + return std::string("Troll"); + + default: + return std::string(); + } +} + +// VERIFY: 2e925757 manual +// OFFSET: 0x0041ECC0 +std::string BuildManifestKey(int32_t type, int32_t race, int32_t zone, uint32_t index) { + std::string key; + char name[260]; + + switch (type) { + case 0: + key = s_startClientList; + break; + + case 1: + key = s_startCharacterList; + break; + + case 2: + key = s_startRaceCommonList; + break; + + case 3: { + std::string raceName = RaceIdToName(race); + + if (raceName.size()) { + Blizzard::String::Format(name, sizeof(name), s_startRaceList, raceName.c_str()); + key = name; + } else { + key = s_startRaceCommonList; + } + + break; + } + + case 4: + case 7: { + int32_t number = type == 4 ? zone : GetManifestZone(index); + + if (number <= 0) { + break; + } + + Blizzard::String::Format(name, sizeof(name), s_startBackgroundZoneList, number); + key = std::string(name); + break; + } + + case 5: + case 6: { + std::string raceName = RaceIdToName(type == 5 ? race : GetManifestRace(index)); + + if (raceName.size()) { + Blizzard::String::Format(name, sizeof(name), s_startBackgroundList, raceName.c_str()); + key = name; + } + + break; + } + + case 9: + key = GetLocaleArchiveName(index); + break; + + case 10: + key = GetRegionArchiveName(index); + break; + } + + return key; +} + +// VERIFY: 3cb231be manual +// OFFSET: 0x0041F460 +float StreamingManager::GetBaseFraction() { + std::string key = BuildManifestKey(2, 0, 0, 0); + std::map::iterator it = this->m_entries.find(key); + + if (it == this->m_entries.end()) { + return 0.0f; + } + + return it->second->GetLocalFraction(); +} + +// VERIFY: 1da05e68 manual +// OFFSET: 0x0041F530 +float StreamingManager::GetLoadFraction(int32_t race) { + float base = this->GetBaseFraction() * 0.5f; + + std::string key = BuildManifestKey(3, race, 0, 0); + std::map::iterator it = this->m_entries.find(key); + + if (it == this->m_entries.end()) { + return base; + } + + return it->second->GetLocalFraction() * 0.5f + base; +} + +// VERIFY: 27921cff manual +// OFFSET: 0x0041FE70 +StreamingFileEntry::StreamingFileEntry() { + this->m_cursor = 0; + this->m_next = 0; + this->m_localAmount = 0; + this->m_complete = false; + this->m_archive = nullptr; + this->m_priority = 6; +} + +// VERIFY: 6ea96e53 manual +// OFFSET: 0x0041FED0 +StreamingFileEntry::~StreamingFileEntry() { + this->m_files.erase(this->m_files.begin(), this->m_files.end()); + + if (this->m_archive) { + Blizzard::Mopaq::SFileCloseArchive(this->m_archive); + } +} + +// INLINED +const std::string& StreamingFileEntry::NextFile() { + if (this->m_next < this->m_files.size()) { + return this->m_files[this->m_next++]; + } + + return s_emptyFile; +} + +// VERIFY: 37a9dd94 manual +// OFFSET: 0x0041FFA0 +void StreamingFileEntry::AdvanceCursor() { + uint32_t cursor = this->m_cursor; + this->m_cursor = this->m_next; + + if (this->m_next == this->m_files.size()) { + this->m_files.erase(this->m_files.begin(), this->m_files.end()); + this->m_complete = true; + return; + } + + int64_t total = 0; + + for (uint32_t i = cursor + 1; i < this->m_next; i++) { + Blizzard::Mopaq::SFileGetIsLocalAmount(this->m_files[i].c_str(), this->m_localAmount, total); + } +} + +// VERIFY: 595705af manual +// OFFSET: 0x004200A0 +void StreamingFileEntry::ProcessQueue() { + std::string file = this->NextFile(); + + while (file.size()) { + if (Blizzard::Mopaq::SFileFileIsLocal(file.c_str(), this->m_priority) != 1) { + this->m_next = this->m_cursor; + return; + } + + this->AdvanceCursor(); + file = this->NextFile(); + } +} + +// VERIFY: d758e44b manual +// OFFSET: 0x00420570 +StreamingManager::~StreamingManager() { + if (this->m_thread && Blizzard::Thread::IsRunning(this->m_thread)) { + this->Shutdown(); + } + + Blizzard::Lock::EventDestroy(this->m_event); + + for (std::map::iterator it = this->m_entries.begin(); it != this->m_entries.end(); ++it) { + if (it->second) { + delete it->second; + } + + it->second = nullptr; + } + + this->m_entries.clear(); +} + +// VERIFY: a962109b manual +// OFFSET: 0x00420770 +StreamingManager::StreamingManager() { + this->m_current = nullptr; + this->m_dirty = true; + this->m_gameState = 0; + this->m_enabled = false; + this->m_zone = -1; + this->m_mapId = -1; + this->m_race = -1; + this->m_subzone = -1; + this->m_area = -1; + this->m_areaChunk = -1; + this->m_state = 0; + Blizzard::Lock::EventCreate(this->m_event); + this->m_thread = nullptr; + + this->m_entries.insert(std::make_pair(std::string(), static_cast(nullptr))); + + this->unk_0031 = false; +} + +// VERIFY: fefe834e manual +// OFFSET: 0x004208D0 +StreamingManager* GetStreamingManagerSingleton() { + // STATIC: 0x00B31EF0 + static StreamingManager s_manager; + + return &s_manager; +} + +// VERIFY: a3524c67 manual +// OFFSET: 0x00420950 +void StreamingSetState(int32_t state) { + if (!CheckIfStreamingAndTrial()) { + return; + } + + StreamingManager* manager = GetStreamingManagerSingleton(); + + if (manager->m_gameState != state) { + manager->m_gameState = state; + manager->m_dirty = true; + Blizzard::Lock::EventSet(manager->m_event); + } +} + +// VERIFY: d36f57c2 manual +// OFFSET: 0x00420980 +void StreamingSetRace(int32_t raceID) { + StreamingManager* manager = GetStreamingManagerSingleton(); + + if (manager->m_race != raceID) { + manager->m_race = raceID; + manager->m_dirty = true; + Blizzard::Lock::EventSet(manager->m_event); + } +} + +// VERIFY: 7cf14a57 manual +// OFFSET: 0x004209B0 +void StreamingSetEnabled(bool enabled) { + if (!CheckIfStreamingAndTrial()) { + return; + } + + StreamingManager* manager = GetStreamingManagerSingleton(); + + if (manager->m_enabled != enabled) { + manager->m_enabled = enabled; + Blizzard::Lock::EventSet(manager->m_event); + } +} + +// VERIFY: 2688b484 auto +// OFFSET: 0x004209E0 +float StreamingGetLoadFraction(int32_t raceID) { + if (!CheckIfStreamingAndTrial()) { + return 1.0f; + } + + return GetStreamingManagerSingleton()->GetLoadFraction(raceID); +} + +// VERIFY: d971e27d manual +// OFFSET: 0x00420A10 +void Blizzard::Streaming::SetZone(int32_t areaId, int32_t subzoneId) { + StreamingManager* manager = GetStreamingManagerSingleton(); + + if (manager->m_zone != areaId) { + manager->m_zone = areaId; + manager->m_dirty = true; + Blizzard::Lock::EventSet(manager->m_event); + } + + manager->m_subzone = subzoneId; +} + +// VERIFY: b4d2aafc manual +// OFFSET: 0x00420A50 +void StreamingSetAreaOfInterest(int32_t chunkY, int32_t chunkX) { + StreamingManager* manager = GetStreamingManagerSingleton(); + + int32_t areaChunk = ((chunkY + 15) >> 4) + (((chunkX + 15) >> 4) << 6); + + if (manager->m_areaChunk != areaChunk) { + manager->m_areaChunk = areaChunk; + manager->m_dirty = true; + Blizzard::Lock::EventSet(manager->m_event); + } + + manager->m_area = chunkY + (chunkX << 10); +} + +// VERIFY: a90bb0db manual +// OFFSET: 0x00420AA0 +void StreamingSetMapId(int32_t mapId) { + StreamingManager* manager = GetStreamingManagerSingleton(); + + if (manager->m_mapId != mapId) { + manager->m_mapId = mapId; + manager->m_dirty = true; + Blizzard::Lock::EventSet(manager->m_event); + } +} + +// VERIFY: db85f2d0 manual +// OFFSET: 0x00420B80 +void StreamingFileEntry::ParseListfile(const char* text, const char* extension) { + while (text && *text) { + const char* end = Blizzard::String::Find(text, s_lineSeparator, 0x7FFFFFFF); + + if (!end) { + break; + } + + int32_t length = end - text; + char line[260]; + Blizzard::String::Copy(line, text, length + 1); + line[length] = '\0'; + text = end + Blizzard::String::Length(s_lineSeparator); + + if (extension && !Blizzard::String::EqualI(extension, Blizzard::String::FindExtension(line))) { + continue; + } + + this->m_files.push_back(std::string(line)); + } +} + +// VERIFY: b170d288 manual +// OFFSET: 0x00420CB0 +bool StreamingFileEntry::LoadListfile(const char* archiveName, const char* name, const char* extension) { + this->m_name = name; + + System_SFile::ARCHIVEREC* archive = nullptr; + + if (archiveName) { + name = "(listfile)"; + + if (OpenDataArchive(archiveName, &archive)) { + this->m_archive = archive; + } + + if (!archive) { + return false; + } + } + + void* data; + uint32_t size; + + if (!Blizzard::Mopaq::SFileLoadFile(archive, name, &data, &size, 1, 1)) { + return false; + } + + this->ParseListfile(static_cast(data), extension); + Blizzard::Mopaq::SFileUnloadFile(data); + + return true; +} + +// VERIFY: d3ba46c9 manual +// OFFSET: 0x00420D50 +StreamingFileEntry* StreamingManager::CreateEntry(int32_t type, const std::string& key) { + StreamingFileEntry* entry = nullptr; + + switch (type) { + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + entry = new StreamingFileEntry(); + entry->LoadListfile(nullptr, key.c_str(), nullptr); + break; + + case 9: + case 10: + entry = new StreamingFileEntry(); + entry->LoadListfile(key.c_str(), key.c_str(), nullptr); + break; + + default: + return nullptr; + } + + if (entry) { + this->m_entries.insert(std::make_pair(key, entry)); + } + + return entry; +} + +// VERIFY: cb64b588 manual +// OFFSET: 0x00420F00 +void StreamingManager::SelectEntry(StreamingFileEntry* previous) { + int32_t race = this->m_race; + uint32_t index = 0; + StreamingFileEntry* entry = previous; + + for (;;) { + if (entry) { + this->AdvanceState(index); + } + + do { + std::string key = BuildManifestKey(this->m_state, race, this->m_zone, index); + std::map::iterator it = this->m_entries.find(key); + + if (it == this->m_entries.end()) { + entry = this->CreateEntry(this->m_state, key); + } else { + entry = it->second; + + if (!entry) { + goto select; + } + } + + if (this->m_state >= 6) { + index++; + } + } while (!entry); + + if (!entry->m_complete) { + break; + } + } + +select: + if (entry == this->m_current) { + return; + } + + if (entry) { + int32_t priority; + + if (this->m_state < 0) { + priority = 6; + } else if (this->m_state <= 3) { + priority = 3; + } else if (this->m_state == 4) { + priority = 4; + } else { + priority = 6; + } + + entry->m_priority = priority; + } + + if (this->m_current) { + this->m_current->m_next = this->m_current->m_cursor; + Blizzard::Streaming::CancelQueue(this->m_current->m_priority); + } + + this->m_current = entry; +} + +// VERIFY: 43e92da7 manual +// OFFSET: 0x00421100 +uint32_t StreamingManager::Run() { + Blizzard::Streaming::Completion completion; + completion.m_event = &this->m_event; + + bool cancelled = false; + + do { + if (this->m_dirty) { + Blizzard::Lock::EventWait(0, this->m_event); + this->m_dirty = false; + this->m_state = this->GetNextState(); + + if (this->m_current && (cancelled || this->m_state == 12)) { + Blizzard::Streaming::RemoveCompletion(&completion, this->m_current->m_priority); + Blizzard::Lock::EventWait(0, this->m_event); + } + + if (this->m_state == 12) { + break; + } + + this->SelectEntry(nullptr); + } + + if (!this->m_current) { + Blizzard::Lock::EventWaitForever(this->m_event); + continue; + } + + completion.m_result = -1; + completion.m_done = false; + int32_t queued = 0; + + while (!this->m_dirty) { + std::string file = this->m_current->NextFile(); + + if (!file.size()) { + break; + } + + if (!Blizzard::Mopaq::SFileFileIsLocal(file.c_str(), this->m_current->m_priority)) { + Blizzard::Mopaq::SFileMakeFileLocal(file.c_str(), this->m_current->m_priority, false); + queued++; + } + + if (queued >= 20) { + break; + } + } + + if (queued > 0) { + if (this->m_dirty) { + continue; + } + + if (Blizzard::Streaming::QueueCompletion(&completion, this->m_current->m_priority)) { + Blizzard::Lock::EventWaitForever(this->m_event); + + if (this->m_dirty) { + cancelled = true; + continue; + } + } + } + + if (!this->m_dirty) { + if ((completion.m_result >= 0 && !completion.m_done) || !queued) { + this->m_current->AdvanceCursor(); + + if (this->m_current->m_complete) { + this->SelectEntry(this->m_current); + } + } + } + } while (this->m_state != 12); + + this->m_current = nullptr; + return 0; +} + +// VERIFY: 3e2a32db manual +// OFFSET: 0x004213A0 +bool StreamingManager::IsBaseDataReady() { + std::string key = BuildManifestKey(2, 0, 0, 0); + std::map::iterator it = this->m_entries.find(key); + + if (it == this->m_entries.end()) { + this->CreateEntry(2, key); + it = this->m_entries.find(key); + it->second->ProcessQueue(); + } + + return it->second->m_complete; +} + +// VERIFY: 18927a4c manual +// OFFSET: 0x00421490 +bool StreamingManager::IsRaceDataReady(int32_t race) { + if (!this->IsBaseDataReady()) { + return false; + } + + std::string key = BuildManifestKey(3, race, 0, 0); + std::map::iterator it = this->m_entries.find(key); + + if (it == this->m_entries.end()) { + this->CreateEntry(3, key); + it = this->m_entries.find(key); + it->second->ProcessQueue(); + } + + return it->second->m_complete; +} + +// VERIFY: e335d9d8 auto +// OFFSET: 0x00421590 +uint32_t StreamingThreadProc(void* param) { + return static_cast(param)->Run(); +} + +// VERIFY: fc1cd2c9 auto +// OFFSET: 0x004215A0 +bool StreamingIsRaceDataReady(int32_t raceID) { + if (!CheckIfStreamingAndTrial()) { + return true; + } + + return GetStreamingManagerSingleton()->IsRaceDataReady(raceID); +} + +// VERIFY: a9af6e8e manual +// OFFSET: 0x004215D0 +int32_t StreamingGetRace() { + return GetStreamingManagerSingleton()->m_race; +} + +// VERIFY: e6668dc4 manual +// OFFSET: 0x00421630 +void StartDataPreloadThread() { + if (!CheckIfStreamingAndTrial()) { + return; + } + + StreamingManager* manager = GetStreamingManagerSingleton(); + + if (manager->m_thread && Blizzard::Thread::IsRunning(manager->m_thread)) { + return; + } + + Blizzard::Thread::Create(StreamingThreadProc, manager, &manager->m_thread, "DataPreload", 0, 0); +} diff --git a/Engine/Source/BlizzardCore/Source/Packages/Streaming/StreamingManager.h b/Engine/Source/BlizzardCore/Source/Packages/Streaming/StreamingManager.h new file mode 100644 index 0000000..aa62326 --- /dev/null +++ b/Engine/Source/BlizzardCore/Source/Packages/Streaming/StreamingManager.h @@ -0,0 +1,79 @@ +#ifndef ENGINE_SOURCE_BLIZZARDCORE_SOURCE_PACKAGES_STREAMING_STREAMINGMANAGER_H +#define ENGINE_SOURCE_BLIZZARDCORE_SOURCE_PACKAGES_STREAMING_STREAMINGMANAGER_H + +#include +#include +#include +#include +#include "Engine/Source/BlizzardCore/Source/System/Lock/Lock.h" +#include "Engine/Source/BlizzardCore/Source/System/Thread/Thread.h" + +namespace System_SFile { +class ARCHIVEREC; +} + +class StreamingFileEntry { + public: + /* 0000 */ std::string m_name; + /* 001C */ std::vector m_files; + /* 002C */ uint32_t m_cursor; + /* 0030 */ uint32_t m_next; + /* 0034 */ uint32_t unk_0034; + /* 0038 */ int64_t m_localAmount; + /* 0040 */ bool m_complete; + /* 0044 */ int32_t m_priority; + /* 0048 */ System_SFile::ARCHIVEREC* m_archive; + + StreamingFileEntry(); + ~StreamingFileEntry(); + void AdvanceCursor(); + float GetLocalFraction(); + bool LoadListfile(const char* archiveName, const char* name, const char* extension); + const std::string& NextFile(); + void ParseListfile(const char* text, const char* extension); + void ProcessQueue(); +}; + +class StreamingManager { + public: + /* 0000 */ std::map m_entries; + /* 000C */ int32_t m_state; + /* 0010 */ int32_t m_gameState; + /* 0014 */ bool m_enabled; + /* 0018 */ int32_t m_zone; + /* 001C */ int32_t m_subzone; + /* 0020 */ int32_t m_mapId; + /* 0024 */ int32_t m_race; + /* 0028 */ int32_t m_area; + /* 002C */ int32_t m_areaChunk; + /* 0030 */ bool m_dirty; + /* 0031 */ bool unk_0031; + /* 0034 */ uint8_t unk_0034[260]; + /* 0138 */ StreamingFileEntry* m_current; + /* 013C */ Blizzard::Lock::Event m_event; + /* 0140 */ Blizzard::Thread::ThreadRecord* m_thread; + + StreamingManager(); + ~StreamingManager(); + void AdvanceState(uint32_t& index); + StreamingFileEntry* CreateEntry(int32_t type, const std::string& key); + float GetBaseFraction(); + float GetLoadFraction(int32_t race); + int32_t GetNextState(); + bool IsBaseDataReady(); + bool IsRaceDataReady(int32_t race); + uint32_t Run(); + void SelectEntry(StreamingFileEntry* previous); + void Shutdown(); +}; + +std::string BuildManifestKey(int32_t type, int32_t race, int32_t zone, uint32_t index); +const char* GetLocaleArchiveName(uint32_t index); +int32_t GetManifestZone(uint32_t index); +const char* GetRegionArchiveName(uint32_t index); +int32_t GetManifestRace(int32_t index); +bool OpenDataArchive(const char* name, System_SFile::ARCHIVEREC** archive); +std::string RaceIdToName(int32_t race); +uint32_t StreamingThreadProc(void* param); + +#endif diff --git a/Engine/Source/BlizzardCore/Source/Packages/Streaming/Tracker.cpp b/Engine/Source/BlizzardCore/Source/Packages/Streaming/Tracker.cpp new file mode 100644 index 0000000..2d54214 --- /dev/null +++ b/Engine/Source/BlizzardCore/Source/Packages/Streaming/Tracker.cpp @@ -0,0 +1,370 @@ +#include "Tracker.h" +#include +#include +#include +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Streaming.h" +#include "Engine/Source/BlizzardCore/Source/System/String/String.h" +#include "Engine/Source/Os/TimeManager.h" + +// STATIC: 0x00AB9414 +static const uint32_t s_frameTimeBuckets[25] = { 0, 1, 8, 11, 14, 18, 24, 32, 42, 56, 74, 97, 128, 170, 224, 295, 390, 515, 680, 897, 1184, 1563, 2063, 2724, 3595 }; + +// STATIC: 0x00B38B90 +static int32_t s_speedTest; + +// STATIC: 0x00B38B98 +static double s_frameTimeHistogram[24]; + +// STATIC: 0x00B38C58 +const char* Tracker::trackerAddress; + +// STATIC: 0x00B38C5C +static char s_locale[5]; + +// STATIC: 0x00B38C64 +static int32_t s_buildnum; + +// STATIC: 0x00B38C68 +static uint32_t s_lastFrameTime; + +// STATIC: 0x00B38C6C +static char s_peerId[21]; + +// STATIC: 0x00B38C84 +static char s_key[9]; + +// VERIFY: fab8b414 manual +// OFFSET: 0x004621F0 +void Tracker::TrackerHttpDataDownloadCallBack::Completed(Blizzard::URL::DownloadCallback::Status status) { + Blizzard::Lock::EventSet(this->m_event); +} + +// VERIFY: 6b51736a auto +// OFFSET: 0x00462200 +char* Tracker::GetPeerID() { + if (!s_peerId[0]) { + for (int32_t i = 0; i < 20; i++) { + s_peerId[i] = rand() % 222 + 33; + } + + s_peerId[20] = '\0'; + } + + return s_peerId; +} + +// VERIFY: 19df183c auto +// OFFSET: 0x00462240 +char* Tracker::GetKey() { + if (!s_key[0]) { + for (int32_t i = 0; i < 8; i++) { + s_key[i] = rand() % 9 + '0'; + } + + s_key[8] = '\0'; + } + + return s_key; +} + +// VERIFY: bb4bd1a3 auto +// OFFSET: 0x00462280 +const char* Tracker::GetTrackerAddress(const char* locale) { + if (!Blizzard::String::Equal(locale, "enUS") || !Blizzard::String::Equal(locale, "esMX")) { + return "http://us.tracker.worldofwarcraft.com:3724/announce"; + } + + if (!Blizzard::String::Equal(locale, "deDE") || !Blizzard::String::Equal(locale, "enGB") || !Blizzard::String::Equal(locale, "esES") || !Blizzard::String::Equal(locale, "frFR")) { + return "http://eu.tracker.worldofwarcraft.com:3724/announce"; + } + + return nullptr; +} + +// VERIFY: 2b68a577 auto +// OFFSET: 0x00462310 +void Tracker::SetLocale(const char* locale) { + Tracker::trackerAddress = GetTrackerAddress(locale); + Blizzard::String::Copy(s_locale, locale, sizeof(s_locale)); +} + +// VERIFY: 76903da7 auto +// OFFSET: 0x00462340 +void Tracker::SetBuildnum(int32_t buildnum) { + s_buildnum = buildnum; +} + +// VERIFY: 2cb7c213 auto +// OFFSET: 0x00462350 +void StartupReportSetSpeedTest(int32_t speedTest) { + s_speedTest = speedTest; +} + +// VERIFY: a213c71d auto +// OFFSET: 0x00462360 +void StartupReportFrameCallback() { + uint32_t now = OsGetAsyncTimeMs(); + + if (s_lastFrameTime) { + uint32_t elapsed = now - s_lastFrameTime; + + int32_t bucket = 0; + while (bucket < 24 && elapsed >= s_frameTimeBuckets[bucket + 1]) { + bucket++; + } + + if (bucket == 0) { + s_lastFrameTime = now; + s_frameTimeHistogram[0] += 1.0; + return; + } + + if (bucket >= 23) { + s_lastFrameTime = now; + s_frameTimeHistogram[23] += 1.0; + return; + } + + double low; + double high; + double middle = (s_frameTimeBuckets[bucket] + s_frameTimeBuckets[bucket + 1] - 1) * 0.5; + + if (middle <= elapsed) { + low = middle; + high = (s_frameTimeBuckets[bucket + 2] + s_frameTimeBuckets[bucket + 1] - 1) * 0.5; + } else { + high = middle; + low = (s_frameTimeBuckets[bucket - 1] + s_frameTimeBuckets[bucket] - 1) * 0.5; + bucket--; + } + + double weight = (high - elapsed) / (high - low); + s_frameTimeHistogram[bucket] += weight; + s_frameTimeHistogram[bucket + 1] += 1.0 - weight; + } + + s_lastFrameTime = now; +} + +// VERIFY: f7ae1f10 manual +// OFFSET: 0x00462500 +Tracker::TrackerHttpDataDownloadCallBack::TrackerHttpDataDownloadCallBack() { + this->m_timeout = 10000; + this->m_shouldBlock = true; + Blizzard::Lock::EventCreate(this->m_event); +} + +// VERIFY: 1664abee manual +// OFFSET: 0x00462570 +int32_t Tracker::TrackerHttpDataDownloadCallBack::GetTimeout() { + return this->m_timeout; +} + +// VERIFY: bef26aea manual +// OFFSET: 0x00462580 +bool Tracker::TrackerHttpDataDownloadCallBack::ShouldBlock() { + return this->m_shouldBlock; +} + +// VERIFY: 9b1fa545 manual +// OFFSET: 0x00462590 +void Tracker::TrackerHttpDataDownloadCallBack::SetTimeOutValue(uint32_t timeout) { + this->m_timeout = timeout; +} + +// VERIFY: 5d062b5f manual +// OFFSET: 0x004625A0 +Tracker::TrackerHttpDataDownloadCallBack::~TrackerHttpDataDownloadCallBack() { + Blizzard::Lock::EventDestroy(this->m_event); +} + +// VERIFY: 70242d9a auto +// OFFSET: 0x00462640 +bool Tracker::TrackerHttpDataDownloadCallBack::ReceivedData(const void* data, int32_t size) { + this->m_data.append(static_cast(data), size); + return true; +} + +// VERIFY: 5902bb30 manual +// OFFSET: 0x00462660 +std::string Tracker::ByteToHex(uint8_t byte) { + char digits[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; + + std::string hex; + hex.append(1, digits[byte >> 4]); + hex.append(1, digits[byte & 0xF]); + return hex; +} + +// VERIFY: 8039dbb0 manual +// OFFSET: 0x004627D0 +std::string Tracker::BytesToHex(const uint8_t* bytes, int32_t count) { + std::string hex; + + for (int32_t i = 0; i < count; i++) { + hex += ByteToHex(bytes[i]); + } + + return hex; +} + +// VERIFY: b29c0978 manual +// OFFSET: 0x00462870 +std::string Tracker::Quote(const char* str, uint32_t length) { + std::string quoted; + + for (uint32_t i = 0; i < length; i++) { + char c = str[i]; + + if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == '.' || c == '-' || c == '/') { + quoted.append(1, str[i]); + } else { + quoted.append(1, '%'); + quoted += BytesToHex(reinterpret_cast(&str[i]), 1); + } + } + + return quoted; +} + +// VERIFY: ed98d863 manual +// OFFSET: 0x00462970 +std::string Tracker::MakeTrackerURL(const char* address, const char* infoHash, int32_t event, int64_t downloaded, const char* stats) { + std::string key = GetKey(); + std::string peerId = GetPeerID(); + std::string port = "3724"; + + std::string url = address; + url += "?info_hash=" + Quote(infoHash, 20); + url += "&peer_id=" + Quote(peerId.c_str(), 20); + url += "&key=" + Quote(key.c_str(), 8); + url += "&port="; + url += port.c_str(); + + if (!downloaded) { + downloaded = 2; + } + + switch (event) { + case 0: + url += "&uploaded=0"; + url += "&downloaded=0"; + url += "&left=2"; + url += "&event=started"; + + if (stats) { + url += stats; + } else { + url += Blizzard::String::QuickFormat<1024>("&stats=v,%d,b,%d,l,%s", 5, s_buildnum, s_locale).m_buffer; + } + + break; + + case 1: + url += "&uploaded=0"; + url += Blizzard::String::QuickFormat<1024>("&downloaded=%lld", downloaded).m_buffer; + url += "&left=0"; + url += "&event=completed"; + + if (stats) { + url += stats; + } else { + url += Blizzard::String::QuickFormat<1024>("&stats=v,%d,b,%d,l,%s", 5, s_buildnum, s_locale).m_buffer; + } + + break; + + case 2: + url += "&uploaded=0"; + url += Blizzard::String::QuickFormat<1024>("&downloaded=%lld", downloaded).m_buffer; + url += "&left=0"; + url += "&event=stopped"; + + if (stats) { + url += stats; + } else { + url += Blizzard::String::QuickFormat<1024>("&stats=v,%d,b,%d,l,%s", 5, s_buildnum, s_locale).m_buffer; + } + + break; + + case 3: + url += "&uploaded=0"; + url += "&downloaded=1"; + url += "&left=1"; + url += "&event=stopped"; + + if (stats) { + url += stats; + } else { + url += Blizzard::String::QuickFormat<1024>("&stats=v,%d,b,%d,l,%s", 5, s_buildnum, s_locale).m_buffer; + } + + break; + } + + return url; +} + +// VERIFY: 514e4984 manual +// OFFSET: 0x00462E20 +void Tracker::SendToTracker(const char* infoHash, int32_t event, int64_t downloaded, const char* stats) { + if (!Tracker::trackerAddress) { + return; + } + + TrackerHttpDataDownloadCallBack callback; + std::string url = MakeTrackerURL(Tracker::trackerAddress, infoHash, event, downloaded, stats); + Blizzard::URL::DownloadURL(url.c_str(), &callback); + Blizzard::Lock::EventWaitForever(callback.m_event); +} + +// VERIFY: 498455b5 manual +// OFFSET: 0x00462EF0 +void StartupReportSendTelemetry(bool start, bool unique) { + if (start) { + if (unique) { + Tracker::SendToTracker("HOWMANYUNIQUEUSERARE", 0, 0, nullptr); + Tracker::SendToTracker("HOWMANYUNIQUEUSERARE", 1, 0, nullptr); + Tracker::SendToTracker("HOWMANYUNIQUEUSERARE", 2, 0, nullptr); + } + + Tracker::SendToTracker("DOUSERSLOVESTREAMING", 0, 0, nullptr); + return; + } + + double elapsed = static_cast(Blizzard::Streaming::s_elapsedSinceStart); + int32_t milliseconds = static_cast(elapsed * 0.000001); + double seconds = elapsed * 0.000000001; + int32_t readRate = static_cast(Blizzard::Streaming::s_statBytesRead / seconds); + int32_t downloadRate = static_cast(Blizzard::Streaming::s_statBytesDownloaded / seconds); + int32_t localRate = static_cast(Blizzard::Streaming::s_statBytesLocal / seconds); + + char stats[260]; + Blizzard::String::Format(stats, sizeof(stats), "&stats=v,%d,b,%d,l,%s,st,%d,t,%d,sr,%d,sd,%d,sl,%d,rt,%d,sl,%d,ft,", 5, s_buildnum, s_locale, s_speedTest, milliseconds, readRate, downloadRate, localRate, Blizzard::Streaming::s_statRetries, Blizzard::Streaming::FileManifest::GetBGPreloadSleep()); + + double histogram[24]; + Blizzard::String::MemCopy(histogram, s_frameTimeHistogram, sizeof(histogram)); + + double carry = 0.0; + + for (int32_t i = 0; i < 24; i++) { + double value = carry + histogram[i]; + histogram[i] = value; + + const char* format = "%d,"; + carry = value - static_cast(value + 0.5); + + if (i == 23) { + format = "%d"; + } + + char item[260]; + Blizzard::String::Format(item, sizeof(item), format, static_cast(value + 0.5)); + Blizzard::String::Append(stats, item, sizeof(stats)); + Blizzard::String::Append(Blizzard::Streaming::s_statFrameTimes, item, sizeof(Blizzard::Streaming::s_statFrameTimes)); + } + + Tracker::SendToTracker("DOUSERSLOVESTREAMING", 1, Blizzard::Streaming::s_statBytesRead + Blizzard::Streaming::s_statBytesDownloaded, stats); + Tracker::SendToTracker("DOUSERSLOVESTREAMING", 2, Blizzard::Streaming::s_statBytesRead + Blizzard::Streaming::s_statBytesDownloaded, nullptr); +} diff --git a/Engine/Source/BlizzardCore/Source/Packages/Streaming/Tracker.h b/Engine/Source/BlizzardCore/Source/Packages/Streaming/Tracker.h new file mode 100644 index 0000000..1b098cd --- /dev/null +++ b/Engine/Source/BlizzardCore/Source/Packages/Streaming/Tracker.h @@ -0,0 +1,47 @@ +#ifndef ENGINE_SOURCE_BLIZZARDCORE_SOURCE_PACKAGES_STREAMING_TRACKER_H +#define ENGINE_SOURCE_BLIZZARDCORE_SOURCE_PACKAGES_STREAMING_TRACKER_H + +#include +#include +#include "Engine/Source/BlizzardCore/Source/System/Lock/Lock.h" +#include "Engine/Source/BlizzardCore/Source/System/URL/URL.h" + +namespace Tracker { + +class TrackerHttpDataDownloadCallBack : public Blizzard::URL::DownloadCallback { + public: + /* 0004 */ std::string m_data; + /* 0020 */ uint32_t m_timeout; + /* 0024 */ Blizzard::Lock::Event m_event; + /* 0028 */ bool m_shouldBlock; + + ~TrackerHttpDataDownloadCallBack() override; + int32_t GetTimeout() override; + bool ShouldBlock() override; + bool ReceivedData(const void* data, int32_t size) override; + void Completed(Blizzard::URL::DownloadCallback::Status status) override; + virtual void SetTimeOutValue(uint32_t timeout); + + TrackerHttpDataDownloadCallBack(); +}; + +extern const char* trackerAddress; + +std::string ByteToHex(uint8_t byte); +std::string BytesToHex(const uint8_t* bytes, int32_t count); +char* GetKey(); +char* GetPeerID(); +const char* GetTrackerAddress(const char* locale); +std::string MakeTrackerURL(const char* address, const char* infoHash, int32_t event, int64_t downloaded, const char* stats); +std::string Quote(const char* str, uint32_t length); +void SendToTracker(const char* infoHash, int32_t event, int64_t downloaded, const char* stats); +void SetBuildnum(int32_t buildnum); +void SetLocale(const char* locale); + +} + +void StartupReportFrameCallback(); +void StartupReportSendTelemetry(bool start, bool unique); +void StartupReportSetSpeedTest(int32_t speedTest); + +#endif diff --git a/Engine/Source/BlizzardCore/Source/Packages/Streaming/Transport.h b/Engine/Source/BlizzardCore/Source/Packages/Streaming/Transport.h deleted file mode 100644 index e4f12a1..0000000 --- a/Engine/Source/BlizzardCore/Source/Packages/Streaming/Transport.h +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef ENGINE_SOURCE_BLIZZARDCORE_SOURCE_PACKAGES_STREAMING_TRANSPORT_H -#define ENGINE_SOURCE_BLIZZARDCORE_SOURCE_PACKAGES_STREAMING_TRANSPORT_H - -#include -#include - -namespace System_Streaming { -class HttpCallback { - public: - /* 0000 */ uint32_t unk_0000; - /* 0004 */ uint8_t unk_0004[20]; - /* 0018 */ uint32_t unk_0018; - /* 001C */ uint32_t unk_001C; - /* 0020 */ uint32_t unk_0020; - /* 0024 */ uint32_t unk_0024; - /* 0028 */ uint32_t unk_0028; - /* 002C */ uint32_t unk_002C; -}; -} - -#endif diff --git a/Engine/Source/BlizzardCore/Source/Packages/Streaming/Win32/Manifests.cpp b/Engine/Source/BlizzardCore/Source/Packages/Streaming/Win32/Manifests.cpp new file mode 100644 index 0000000..e43e83c --- /dev/null +++ b/Engine/Source/BlizzardCore/Source/Packages/Streaming/Win32/Manifests.cpp @@ -0,0 +1,224 @@ +#if defined(WOWDECOMP_ARCH_32) + +#include +#include +#include +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Manifests.h" +#include "Engine/Source/BlizzardCore/Source/System/File/File.h" +#include "Engine/Source/BlizzardCore/Source/System/String/String.h" + +// VERIFY: ef87a039 manual +// OFFSET: 0x0042E100 +void System_Streaming::HttpCallback::Completed(Blizzard::URL::DownloadCallback::Status status) { + this->m_status = status; + SetEvent(this->m_event); +} + +// VERIFY: 9a16da82 manual +// OFFSET: 0x00439ED0 +System_Streaming::HttpCallback::HttpCallback() { + this->m_data.reserve(1024); + this->m_data.erase(this->m_data.begin(), this->m_data.end()); + this->m_received = 0; + this->m_status = Blizzard::URL::DownloadCallback::DOWNLOAD_SUCCESS; + this->m_timeout = 3000; + this->m_event = CreateEventA(nullptr, FALSE, FALSE, nullptr); +} + +// VERIFY: 328f662c manual +// OFFSET: 0x00439F80 +System_Streaming::HttpCallback::~HttpCallback() { + CloseHandle(this->m_event); +} + +// VERIFY: 9abf951d manual +// OFFSET: 0x004567A0 +bool Blizzard::Streaming::FileManifest::ReadIndirectFile(const char* url) { + System_Streaming::HttpCallback* callback = new System_Streaming::HttpCallback(); + + bool result = false; + uint32_t attempt = 0; + + while (attempt < 5) { + result = Blizzard::URL::DownloadURL(url, callback); + + if (result) { + WaitForSingleObject(callback->m_event, INFINITE); + + if (callback->m_status) { + result = false; + } + } + + if (!result) { + callback->m_data.erase(callback->m_data.begin(), callback->m_data.end()); + callback->m_received = 0; + + if (callback->m_status == Blizzard::URL::DownloadCallback::DOWNLOAD_TIMEOUT) { + callback->SetTimeOutValue(2 * callback->GetTimeout()); + } + } + + attempt++; + + if (result) { + result = ReadDirectFileFromBuffer(const_cast(callback->m_data.c_str()), callback->m_data.size()); + delete callback; + return result; + } + } + + if (callback->m_status) { + Blizzard::File::AddToLastErrorStack(callback->m_status, Blizzard::String::QuickFormat<1024>("FileManifest::ReadIndirectFile - DownloadURL failed - %s", url).m_buffer, 20); + } else { + Blizzard::File::AddToLastErrorStack(0, "FileManifest::ReadIndirectFile - DownloadURL failed with no error", 20); + } + + delete callback; + return result; +} + +// VERIFY: f44bfac2 manual +// OFFSET: 0x00459050 +bool Blizzard::Streaming::Transport::ReadIndirectFile(const char* url) { + System_Streaming::HttpCallback* callback = new System_Streaming::HttpCallback(); + + bool result = false; + uint32_t attempt = 0; + + while (attempt < 5) { + result = Blizzard::URL::DownloadURL(url, callback); + + if (result) { + WaitForSingleObject(callback->m_event, INFINITE); + + if (callback->m_status) { + result = false; + } + } + + if (!result) { + callback->m_data.erase(callback->m_data.begin(), callback->m_data.end()); + callback->m_received = 0; + + if (callback->m_status == Blizzard::URL::DownloadCallback::DOWNLOAD_TIMEOUT) { + callback->SetTimeOutValue(2 * callback->GetTimeout()); + } + } + + attempt++; + + if (result) { + result = ReadDirectFileFromBuffer(const_cast(callback->m_data.c_str()), callback->m_data.size()); + delete callback; + return result; + } + } + + if (callback->m_status) { + Blizzard::File::AddToLastErrorStack(callback->m_status, Blizzard::String::QuickFormat<1024>("Transport::ReadIndirectFile - DownloadURL failed - %s", url).m_buffer, 20); + Blizzard::File::AddToLastErrorStack(callback->m_status, "Failed to load transport manifest.", 20); + } else { + Blizzard::File::AddToLastErrorStack(0, "Transport::ReadIndirectFile - DownloadURL failed", 20); + } + + delete callback; + return result; +} + +// VERIFY: dd085f48 manual +// OFFSET: 0x00459400 +bool Blizzard::Streaming::SourceManifest::ReadIndirectFile(const char* url) { + System_Streaming::HttpCallback* callback = new System_Streaming::HttpCallback(); + + bool result = false; + uint32_t attempt = 0; + + while (attempt < 5) { + result = Blizzard::URL::DownloadURL(url, callback); + + if (result) { + WaitForSingleObject(callback->m_event, INFINITE); + + if (callback->m_status) { + result = false; + } + } + + if (!result) { + callback->m_data.erase(callback->m_data.begin(), callback->m_data.end()); + callback->m_received = 0; + + if (callback->m_status == Blizzard::URL::DownloadCallback::DOWNLOAD_TIMEOUT) { + callback->SetTimeOutValue(2 * callback->GetTimeout()); + } + } + + attempt++; + + if (result) { + result = ReadDirectFileFromBuffer(const_cast(callback->m_data.c_str()), callback->m_data.size()); + delete callback; + return result; + } + } + + if (callback->m_status) { + Blizzard::File::AddToLastErrorStack(callback->m_status, Blizzard::String::QuickFormat<1024>("SourceManifest::ReadIndirectFile - DownloadURL failed - %s", url).m_buffer, 20); + Blizzard::File::AddToLastErrorStack(callback->m_status, "Failed to load source manifest.", 20); + } else { + Blizzard::File::AddToLastErrorStack(0, "SourceManifest::ReadIndirectFile - DownloadURL failed", 20); + } + + delete callback; + return result; +} + +// VERIFY: a9aeb481 manual +// OFFSET: 0x00461430 +bool Blizzard::Streaming::ManifestInfo::ReadIndirectFile(const char* url) { + System_Streaming::HttpCallback* callback = new System_Streaming::HttpCallback(); + + bool result = false; + uint32_t attempt = 0; + + while (attempt < 5) { + result = Blizzard::URL::DownloadURL(url, callback); + + if (result) { + WaitForSingleObject(callback->m_event, INFINITE); + + if (callback->m_status) { + result = false; + } + } + + if (!result) { + callback->m_data.erase(callback->m_data.begin(), callback->m_data.end()); + callback->m_received = 0; + + if (callback->m_status == Blizzard::URL::DownloadCallback::DOWNLOAD_TIMEOUT) { + callback->SetTimeOutValue(2 * callback->GetTimeout()); + } + } + + attempt++; + + if (result) { + result = this->ReadDirectFileFromBuffer(const_cast(callback->m_data.c_str()), callback->m_data.size()); + delete callback; + return result; + } + } + + if (callback->m_status) { + Blizzard::File::AddToLastErrorStack(callback->m_status, Blizzard::String::QuickFormat<1024>("FileManifest::ReadIndirectFile - DownloadURL failed - %s", url).m_buffer, 20); + } else { + Blizzard::File::AddToLastErrorStack(0, "FileManifest::ReadIndirectFile - DownloadURL failed with no error", 20); + } + + delete callback; + return result; +} + +#endif diff --git a/Engine/Source/BlizzardCore/Source/Packages/Streaming/Win32/Storage.cpp b/Engine/Source/BlizzardCore/Source/Packages/Streaming/Win32/Storage.cpp new file mode 100644 index 0000000..79e4804 --- /dev/null +++ b/Engine/Source/BlizzardCore/Source/Packages/Streaming/Win32/Storage.cpp @@ -0,0 +1,1276 @@ +#if defined(WOWDECOMP_ARCH_32) + +#include +#include +#include +#include +#include +#include +#include +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Storage.h" +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Streaming.h" +#include "Engine/Source/BlizzardCore/Source/System/File/File.h" +#include "Engine/Source/BlizzardCore/Source/System/File/Filestack.h" +#include "Engine/Source/BlizzardCore/Source/System/Log/Log.h" +#include "Engine/Source/BlizzardCore/Source/System/Memory/MemoryStorm.h" +#include "Engine/Source/BlizzardCore/Source/System/String/String.h" +#include "Engine/Source/BlizzardCore/Source/System/Thread/Thread.h" + +// STATIC: 0x00AB909F +bool Blizzard::Storage::s_usePartFiles = true; + +// STATIC: 0x00AB92BC +int32_t Blizzard::Storage::s_blockSize = 0x4000; + +// STATIC: 0x00AB93CC +std::string Blizzard::Storage::s_storagePath; + +// STATIC: 0x00B325C0 +Blizzard::Lock::Mutex Blizzard::Storage::s_storageLock; + +// STATIC: 0x00B325D8 +void* Blizzard::Storage::s_storageEvent; + +// STATIC: 0x00B38174 +std::map* Blizzard::Storage::s_storage; + +// STATIC: 0x00B38178 +Blizzard::File::StreamRecord* Blizzard::Storage::s_storageFile; + +// STATIC: 0x00B3817C +bool Blizzard::Storage::s_storageReady; + +// STATIC: 0x00B3817D +bool Blizzard::Storage::s_storageDirty; + +// STATIC: 0x00B3817E +volatile bool Blizzard::Storage::s_storageStop; + +// STATIC: 0x00B3817F +volatile bool Blizzard::Storage::s_storageStopped; + +// STATIC: 0x00B3834C +std::deque Blizzard::Storage::s_writeQueue; + +// VERIFY: f7b739ba manual +// OFFSET: 0x00427F50 +int32_t Blizzard::Storage::GetBlockLength(Blizzard::Streaming::StorageEntry* entry, int32_t block) { + int32_t blockSize = entry->m_blockSize; + + if (entry->m_size <= (block + 1LL) * blockSize) { + return static_cast(entry->m_size - static_cast(block) * blockSize); + } + + return entry->m_blockSize; +} + +// VERIFY: 0dc55920 manual +// OFFSET: 0x00427FB0 +int32_t Blizzard::Storage::CountRanges(Blizzard::Streaming::StorageEntry* entry, int64_t offset, int64_t size) { + return static_cast((size + offset) / entry->m_blockSize - offset / entry->m_blockSize + 4); +} + +// VERIFY: 7a1edb4d auto +// OFFSET: 0x0042CEF0 +bool Blizzard::Storage::ReadAt(Blizzard::File::Filesystem* fs, Blizzard::File::StreamRecord* file, void* buffer, int64_t offset, int32_t size) { + return Blizzard::File::Read(fs, file, buffer, offset, &size); +} + +// VERIFY: 93c137d2 auto +// OFFSET: 0x0042CF20 +bool Blizzard::Storage::WriteAt(Blizzard::File::StreamRecord* file, const void* buffer, int64_t offset, int32_t size) { + return Blizzard::File::Write(file, buffer, offset, &size); +} + +// VERIFY: 26ae7efd manual +// OFFSET: 0x0042D820 +bool Blizzard::Storage::IsComplete(Blizzard::Streaming::StorageEntry* entry) { + for (int32_t i = 0; i < static_cast(entry->m_blocks.size()); i++) { + if (entry->m_blocks[i].m_state != 3) { + return false; + } + } + + return true; +} + +// VERIFY: 5e4c6096 manual +// OFFSET: 0x0042D880 +int32_t Blizzard::Storage::BuildRanges(Blizzard::Streaming::StorageEntry* entry, int64_t offset, int32_t size, Blizzard::Streaming::LoadRange* ranges) { + int64_t position = offset; + uint32_t block = static_cast(offset / entry->m_blockSize); + int32_t count = 0; + + for (int32_t phase = 1; size && phase <= 3; phase++) { + if (phase == 2) { + int32_t full = entry->m_blockSize * (size / entry->m_blockSize); + + while (full >= entry->m_blockSize) { + int32_t state = entry->m_blocks[block].m_state; + Blizzard::Streaming::LoadRange& range = ranges[count]; + + switch (state) { + case 0: + case 1: + count++; + range.m_offset = position; + range.m_blockOffset = position; + range.m_size = entry->m_blockSize; + range.m_blockSize = entry->m_blockSize; + range.m_state = 3 - (state != 1); + break; + + case 2: + case 3: + case 4: + count++; + range.m_size = entry->m_blockSize; + range.m_offset = static_cast(block) * entry->m_blockSize; + range.m_blockOffset = 0; + range.m_blockSize = 0; + range.m_state = state == 4; + break; + } + + block++; + size -= entry->m_blockSize; + position += entry->m_blockSize; + full -= entry->m_blockSize; + } + + continue; + } + + int64_t blockStart = static_cast(block) * entry->m_blockSize; + + if (phase == 1 && position == blockStart) { + continue; + } + + int32_t inner = static_cast(position - blockStart); + int32_t length = GetBlockLength(entry, block); + int32_t state = entry->m_blocks[block].m_state; + int32_t available = length - inner; + int32_t take = size >= available ? available : size; + + switch (state) { + case 0: + case 1: { + Blizzard::Streaming::LoadRange& range = ranges[count++]; + size -= take; + range.m_offset = position; + range.m_blockOffset = blockStart; + range.m_size = take; + range.m_blockSize = length; + range.m_state = 3 - (state != 1); + break; + } + + case 2: + case 3: + case 4: { + Blizzard::Streaming::LoadRange& range = ranges[count++]; + range.m_offset = inner + entry->m_blockSize * static_cast(block); + size -= take; + range.m_size = take; + range.m_blockOffset = 0; + range.m_blockSize = 0; + range.m_state = state == 4; + break; + } + } + + block++; + position += entry->m_blockSize - inner; + } + + return count; +} + +// VERIFY: b2dea1aa manual +// OFFSET: 0x0042DB80 +int32_t Blizzard::Storage::BuildRangesFromStore(Blizzard::Streaming::StorageEntry* entry, int64_t offset, int32_t size, Blizzard::Streaming::LoadRange* ranges) { + int64_t start = entry->m_storeSize >= offset ? offset : entry->m_storeSize; + int32_t count = 0; + + if (start / entry->m_blockSize < offset / entry->m_blockSize) { + count = BuildRanges(entry, entry->m_storeSize, static_cast(offset / entry->m_blockSize * entry->m_blockSize - entry->m_storeSize), ranges); + + for (int32_t i = 0; i < count; i++) { + ranges[i].m_state = 4; + } + } + + return count + BuildRanges(entry, offset, size, ranges + count); +} + +// VERIFY: 66582138 manual +// OFFSET: 0x0042DC70 +int32_t Blizzard::Storage::BuildRangesWithHeader(Blizzard::Streaming::StorageEntry* entry, int64_t offset, int32_t size, Blizzard::Streaming::LoadRange* ranges) { + if (entry->m_blocks[0].m_state == 3) { + return BuildRanges(entry, offset, size, ranges); + } + + if (entry->m_blocks[0].m_state == 2) { + return BuildRanges(entry, offset, size, ranges); + } + + int32_t total = static_cast(entry->m_size / entry->m_blockSize + 1); + int32_t first = static_cast(offset / entry->m_blockSize); + int32_t head = 0; + + if (first > 0) { + head = first; + + for (int32_t i = 0; i < first; i++) { + Blizzard::Streaming::LoadRange& range = ranges[i]; + int32_t length = GetBlockLength(entry, i); + range.m_offset = 0; + range.m_size = 0; + range.m_blockOffset = static_cast(i) * entry->m_blockSize; + range.m_blockSize = length; + range.m_state = 4; + } + } + + int32_t count = BuildRanges(entry, offset, size, ranges + head) + head; + int32_t next = static_cast((offset + size - 1) / entry->m_blockSize + 1); + + if (next < total) { + Blizzard::Streaming::LoadRange* range = &ranges[count]; + count += total - next; + + for (; next < total; next++, range++) { + int64_t end = (next + 1LL) * entry->m_blockSize; + int32_t length = entry->m_size <= end ? static_cast(entry->m_size - static_cast(next) * entry->m_blockSize) : entry->m_blockSize; + + range->m_offset = 0; + range->m_size = 0; + range->m_blockOffset = static_cast(next) * entry->m_blockSize; + range->m_blockSize = length; + range->m_state = 4; + } + } + + return count; +} + +// VERIFY: bf328490 manual +// OFFSET: 0x0042DE70 +bool Blizzard::Storage::RequestRange(Blizzard::Streaming::StorageEntry* entry, int64_t offset, int32_t size, int32_t state) { + EnterCriticalSection(&s_storageLock); + + if (entry->m_closed) { + LeaveCriticalSection(&s_storageLock); + return false; + } + + int64_t blockSize = entry->m_blockSize; + int32_t last = static_cast((offset + size - 1) / blockSize); + + for (uint32_t block = static_cast(offset / blockSize); static_cast(block) <= last; block++) { + Blizzard::Streaming::StorageBlock& storageBlock = entry->m_blocks[block]; + + if (state != 1 || (storageBlock.m_state != 2 && storageBlock.m_state != 3)) { + storageBlock.m_state = state; + } + } + + LeaveCriticalSection(&s_storageLock); + return true; +} + +// VERIFY: 3a968ae6 manual +// OFFSET: 0x0042DF70 +void Blizzard::Storage::SetRangeAs(Blizzard::Streaming::StorageEntry* entry, int64_t offset, int32_t size, int32_t state) { + int32_t first = static_cast(offset / entry->m_blockSize); + int32_t last = size <= 0 ? first : static_cast((offset + size - 1) / entry->m_blockSize); + + EnterCriticalSection(&s_storageLock); + + for (uint32_t block = first; static_cast(block) <= last; block++) { + entry->m_blocks[block].m_state = state; + } + + LeaveCriticalSection(&s_storageLock); +} + +// VERIFY: 4073f769 manual +// OFFSET: 0x00432530 +Blizzard::Storage::StorageEntryRef::StorageEntryRef(Blizzard::Streaming::StorageEntry* entry) { + EnterCriticalSection(&s_storageLock); + + if (!entry || entry->m_released) { + LeaveCriticalSection(&s_storageLock); + this->m_entry = nullptr; + return; + } + + entry->m_refCount++; + LeaveCriticalSection(&s_storageLock); + this->m_entry = entry; +} + +// VERIFY: 702babd3 manual +// OFFSET: 0x004327D0 +bool Blizzard::Storage::WriteIndexEntry(Blizzard::Streaming::StorageEntry* entry, int32_t block, bool header) { + if (!s_storageReady) { + return false; + } + + if (entry->m_flags & 4) { + return true; + } + + if (!header) { + int32_t amount = 8; + Blizzard::File::Write(s_storageFile, &entry->m_storeSize, entry->m_headerOffset + 305, &amount); + + if (block >= 0 && block < static_cast(entry->m_blocks.size())) { + Blizzard::Streaming::StorageBlockRecord record; + record.m_state = entry->m_blocks[block].m_state; + record.m_offset = entry->m_blocks[block].m_offset; + record.m_storeOffset = entry->m_blocks[block].m_storeOffset; + record.m_size = entry->m_blocks[block].m_size; + + WriteAt(s_storageFile, &record, entry->m_headerOffset + 24LL * block + 321, 24); + } + + return true; + } + + int32_t version = 2; + Blizzard::File::SetPos(s_storageFile, 0, 0); + int32_t count = 4; + Blizzard::File::Write(s_storageFile, &version, &count); + + int32_t entries = static_cast(s_storage->size()); + count = 4; + Blizzard::File::Write(s_storageFile, &entries, &count); + + Blizzard::Streaming::StorageHeader storageHeader; + storageHeader.m_flags = entry->m_flags; + storageHeader.m_storeSize = entry->m_storeSize; + Blizzard::String::Copy(storageHeader.m_path, entry->m_path.c_str(), sizeof(storageHeader.m_path)); + Blizzard::String::Copy(storageHeader.m_version, entry->m_version.c_str(), sizeof(storageHeader.m_version)); + storageHeader.m_closed = entry->m_closed; + storageHeader.m_size = entry->m_size; + storageHeader.m_blockSize = entry->m_blockSize; + storageHeader.m_blockCount = static_cast(entry->m_blocks.size()); + + int32_t amount = sizeof(storageHeader); + Blizzard::File::Write(s_storageFile, &storageHeader, entry->m_headerOffset, &amount); + + amount = 24 * storageHeader.m_blockCount; + Blizzard::File::Write(s_storageFile, &entry->m_blocks[0], entry->m_headerOffset + 321, &amount); + + return true; +} + +// VERIFY: 21819d87 manual +// OFFSET: 0x00432A40 +Blizzard::Streaming::LoadRange* Blizzard::Storage::GetRange(Blizzard::Streaming::StorageEntry* entry, int64_t offset, int32_t size, int32_t* count, bool lock) { + int64_t zero = 0; + int64_t start = offset >= 0 ? offset : zero; + start = entry->m_size >= start ? start : entry->m_size; + + int64_t end = start + size; + zero = 0; + end = end >= 0 ? end : zero; + end = entry->m_size >= end ? end : entry->m_size; + + int32_t length = static_cast(end - start); + + if (end == start) { + *count = 0; + return nullptr; + } + + if (lock) { + EnterCriticalSection(&s_storageLock); + } + + Blizzard::Streaming::LoadRange* ranges; + + if (entry->m_flags & 2) { + ranges = static_cast(Blizzard::Memory::Allocate(sizeof(Blizzard::Streaming::LoadRange) * CountRanges(entry, 0, entry->m_size))); + *count = BuildRangesWithHeader(entry, start, length, ranges); + } else if (entry->m_flags & 1) { + zero = 0; + int64_t from = entry->m_storeSize >= 0 ? entry->m_storeSize : zero; + from = start >= from ? from : start; + ranges = static_cast(Blizzard::Memory::Allocate(sizeof(Blizzard::Streaming::LoadRange) * CountRanges(entry, from, start + length - from))); + *count = BuildRangesFromStore(entry, start, length, ranges); + } else { + ranges = static_cast(Blizzard::Memory::Allocate(sizeof(Blizzard::Streaming::LoadRange) * CountRanges(entry, start, length))); + *count = BuildRanges(entry, start, length, ranges); + } + + if (lock) { + LeaveCriticalSection(&s_storageLock); + } + + return ranges; +} + +// VERIFY: 9eae04c9 manual +// OFFSET: 0x00435A60 +int64_t Blizzard::Storage::GetNextHeaderOffset() { + int64_t offset = 8; + + for (std::map::iterator it = s_storage->begin(); it != s_storage->end(); ++it) { + if (it->second.m_flags & 4) { + continue; + } + + if (offset <= it->second.m_headerOffset) { + offset = it->second.m_headerOffset + static_cast(24 * static_cast(it->second.m_blocks.size())) + 321; + } + } + + return offset; +} + +// VERIFY: 66d08f5d manual +// OFFSET: 0x00439C40 +bool Blizzard::Storage::ReadLocal(Blizzard::File::Filesystem* fs, Blizzard::File::StreamRecord* file, Blizzard::Streaming::StorageEntry* entry, uint8_t* buffer, int64_t offset, int32_t size) { + EnterCriticalSection(&s_storageLock); + + bool result = false; + int32_t block = static_cast(offset / entry->m_blockSize); + Blizzard::Streaming::StorageBlock& storageBlock = entry->m_blocks[block]; + int64_t position = offset + storageBlock.m_storeOffset - static_cast(entry->m_blockSize) * block; + + if (entry->m_flags & 4) { + LeaveCriticalSection(&s_storageLock); + return false; + } + + if (storageBlock.m_state != 2) { + if (storageBlock.m_state == 3) { + int32_t amount = size; + result = Blizzard::File::Read(fs, file, buffer, position, &amount); + LeaveCriticalSection(&s_storageLock); + return result; + } + + if (storageBlock.m_state != 4) { + LeaveCriticalSection(&s_storageLock); + return false; + } + + LeaveCriticalSection(&s_storageLock); + + while (storageBlock.m_state == 4) { + Sleep(1); + } + + EnterCriticalSection(&s_storageLock); + + if (storageBlock.m_state == 3) { + result = ReadAt(fs, file, buffer, offset + storageBlock.m_storeOffset - static_cast(entry->m_blockSize) * block, size); + LeaveCriticalSection(&s_storageLock); + return result; + } + + result = false; + } + + int32_t count = static_cast(s_writeQueue.size()); + + for (int32_t i = 0; i < count; i++) { + Blizzard::Streaming::WriteRequest& request = s_writeQueue[i]; + + if (entry == request.m_entry && entry->m_blockSize * block == static_cast(request.m_offset)) { + Blizzard::String::MemCopy(buffer, request.m_data + offset - static_cast(block) * entry->m_blockSize, size); + result = true; + break; + } + } + + LeaveCriticalSection(&s_storageLock); + return result; +} + +// VERIFY: 6392bebc manual +// OFFSET: 0x004443E0 +bool Blizzard::Storage::QueueWrite(Blizzard::File::Filesystem* fs, Blizzard::File::StreamRecord* file, uint8_t* data, int64_t offset, int32_t size, bool owned) { + EnterCriticalSection(&s_storageLock); + + Blizzard::Streaming::StorageEntry* entry = file->m_streaming->m_entry; + Blizzard::Streaming::AddStreamed(size); + + uint32_t block = static_cast(offset / entry->m_blockSize); + Blizzard::Streaming::StorageBlock& storageBlock = entry->m_blocks[block]; + + if (!(entry->m_flags & 4)) { + if (!storageBlock.m_state || storageBlock.m_state == 1 || storageBlock.m_state == 4) { + Blizzard::Streaming::WriteRequest request; + request.m_fs = fs; + request.m_pending = 1; + request.m_file = file; + request.m_entry = entry; + request.m_offset = offset; + request.m_size = size; + + if (owned) { + request.m_data = data; + } else { + request.m_data = static_cast(Blizzard::Memory::Allocate(size)); + memmove(request.m_data, data, size); + } + + storageBlock.m_state = 2; + s_storageDirty = true; + s_writeQueue.push_back(request); + SetEvent(s_storageEvent); + } else if (owned) { + Blizzard::Memory::Free(data); + } + } + + LeaveCriticalSection(&s_storageLock); + return true; +} + +// VERIFY: 39a74cbc manual +// OFFSET: 0x00447BF0 +bool Blizzard::Storage::WriteIndex() { + if (!s_storageReady) { + return false; + } + + if (!s_storageDirty) { + return true; + } + + int32_t version = 2; + Blizzard::File::SetPos(s_storageFile, 0, 0); + int32_t count = 4; + Blizzard::File::Write(s_storageFile, &version, &count); + + int32_t entries = static_cast(s_storage->size()); + count = 4; + Blizzard::File::Write(s_storageFile, &entries, &count); + + std::vector records; + + for (std::map::iterator it = s_storage->begin(); it != s_storage->end(); ++it) { + Blizzard::Streaming::StorageEntry& entry = it->second; + + if (entry.m_flags & 4) { + continue; + } + + Blizzard::Streaming::StorageHeader header; + header.m_flags = entry.m_flags; + header.m_storeSize = entry.m_storeSize; + + const char* path = entry.m_path.c_str(); + + if (path) { + char* dst = header.m_path; + + do { + char c = *path++; + + if (!c) { + break; + } + + *dst++ = c; + } while (dst < &header.m_path[sizeof(header.m_path) - 1]); + + *dst = '\0'; + } else { + header.m_path[0] = '\0'; + } + + const char* version = entry.m_version.c_str(); + + if (version) { + char* dst = header.m_version; + + do { + char c = *version++; + + if (!c) { + break; + } + + *dst++ = c; + } while (dst < &header.m_version[sizeof(header.m_version) - 1]); + + *dst = '\0'; + } else { + header.m_version[0] = '\0'; + } + + header.m_size = entry.m_size; + header.m_closed = entry.m_closed; + header.m_blockSize = entry.m_blockSize; + header.m_blockCount = static_cast(entry.m_blocks.size()); + + int32_t amount = sizeof(header); + Blizzard::File::Write(s_storageFile, &header, &amount); + + records.resize(header.m_blockCount); + + for (int32_t i = 0; i < header.m_blockCount; i++) { + records[i].m_state = entry.m_blocks[i].m_state; + records[i].m_offset = entry.m_blocks[i].m_offset; + records[i].m_storeOffset = entry.m_blocks[i].m_storeOffset; + records[i].m_size = entry.m_blocks[i].m_size; + } + + amount = 24 * header.m_blockCount; + Blizzard::File::Write(s_storageFile, &records[0], -1LL, &amount); + } + + Blizzard::File::SetEOF(s_storageFile, 0, 1); + s_storageDirty = false; + + return true; +} + +// VERIFY: d17bd1fe manual +// OFFSET: 0x0044CB90 +bool Blizzard::Storage::Remove(const std::string& path) { + std::map::iterator it = s_storage->find(Blizzard::Streaming::ResolveFilePath(path)); + + if (it == s_storage->end()) { + return false; + } + + s_storage->erase(it); + return true; +} + +// VERIFY: bf3a0fcd manual +// OFFSET: 0x0044E580 +bool Blizzard::Storage::ReadStorageFile(const uint8_t* data, int32_t size) { + Blizzard::Streaming::StorageEntry entry; + + if (size < 4 || size - 4 < 4) { + return false; + } + + const uint8_t* cursor = data + 8; + int32_t left = size - 8; + int32_t count = *reinterpret_cast(data + 4); + + for (int32_t i = 0; i < count && left > 0; i++) { + if (left < 321) { + s_storage->clear(); + return false; + } + + const Blizzard::Streaming::StorageHeader* header = reinterpret_cast(cursor); + const uint8_t* blocks = cursor + 321; + left -= 321; + + entry.m_path.assign(header->m_path, strlen(header->m_path)); + entry.m_version.assign(header->m_version, strlen(header->m_version)); + entry.m_storeSize = header->m_storeSize; + entry.m_size = header->m_size; + entry.m_flags = header->m_flags; + entry.m_blockSize = header->m_blockSize; + entry.m_closed = header->m_closed; + entry.m_headerWritten = false; + entry.m_headerOffset = size - left - 321; + + if (!entry.m_blockSize || (entry.m_size + entry.m_blockSize - 1) / entry.m_blockSize != header->m_blockCount) { + s_storage->clear(); + return false; + } + + (*s_storage)[Blizzard::Streaming::ResolveFilePath(entry.m_path)] = entry; + Blizzard::Streaming::StorageEntry& stored = (*s_storage)[Blizzard::Streaming::ResolveFilePath(entry.m_path)]; + + int32_t bytes = 24 * header->m_blockCount; + + if (left < bytes) { + s_storage->clear(); + return false; + } + + std::vector records; + records.resize(header->m_blockCount); + Blizzard::String::MemCopy(&records[0], blocks, bytes); + + stored.m_blocks.resize(header->m_blockCount); + + for (int32_t j = 0; j < header->m_blockCount; j++) { + Blizzard::Streaming::StorageBlock& storageBlock = stored.m_blocks[j]; + storageBlock.m_offset = records[j].m_offset; + storageBlock.m_size = records[j].m_size; + storageBlock.m_storeOffset = records[j].m_storeOffset; + storageBlock.m_partOffset = records[j].m_storeOffset; + storageBlock.m_state = records[j].m_state; + } + + cursor = blocks + bytes; + left -= bytes; + } + + return true; +} + +// VERIFY: cb6770b1 manual +// OFFSET: 0x0044EA50 +Blizzard::Streaming::StorageEntry* Blizzard::Storage::PartialFile::CreateShared(const std::string& key, const char* path, int64_t size, const char* version, int32_t flags) { + Blizzard::Streaming::StorageEntry entry; + entry.m_path.assign(path, strlen(path)); + entry.m_version.assign(version, strlen(version)); + entry.m_flags = flags; + entry.m_closed = false; + entry.m_released = false; + entry.m_refCount = 0; + entry.m_size = size; + entry.m_storeSize = 0; + entry.m_blockSize = s_blockSize; + entry.m_headerWritten = true; + entry.m_file = nullptr; + entry.m_openCount = 0; + InitializeCriticalSection(&entry.m_lock); + + int32_t count = static_cast((size + entry.m_blockSize - 1) / entry.m_blockSize); + + if (s_usePartFiles) { + entry.m_blocks.resize(count, Blizzard::Streaming::StorageBlock()); + memset(&entry.m_blocks[0], 0, sizeof(Blizzard::Streaming::StorageBlock) * count); + (*s_storage)[key] = entry; + } else { + entry.m_blocks.resize(count, Blizzard::Streaming::StorageBlock()); + + int32_t left = static_cast(size); + + for (uint32_t i = 0; i < entry.m_blocks.size(); i++) { + Blizzard::Streaming::StorageBlock& block = entry.m_blocks[i]; + block.m_state = 0; + block.m_offset = static_cast(entry.m_blockSize) * i; + block.m_storeOffset = 0; + block.m_partOffset = 0; + block.m_size = i < entry.m_blocks.size() - 1 ? entry.m_blockSize : left; + left -= entry.m_blockSize; + } + + entry.m_headerOffset = GetNextHeaderOffset(); + (*s_storage)[key] = entry; + WriteIndexEntry(&entry, -1, true); + } + + return &(*s_storage)[key]; +} + +// VERIFY: ed165c96 manual +// OFFSET: 0x0044ED80 +Blizzard::Streaming::StorageEntry* Blizzard::Storage::Acquire(Blizzard::File::Filesystem* fs, const std::string& key, const char* path, int64_t size, const char* version, int32_t flags) { + if (!s_storage) { + return nullptr; + } + + if (!path) { + std::map::iterator it = s_storage->find(key); + + if (it == s_storage->end()) { + return nullptr; + } + + return &it->second; + } + + EnterCriticalSection(&s_storageLock); + + std::map::iterator it = s_storage->find(key); + + char partName[260]; + BuildVariantFileName(partName, sizeof(partName), path, "part"); + + if (it != s_storage->end()) { + Blizzard::File::FileInfo info; + + if (it->second.m_headerWritten || (Blizzard::File::GetFileInfo(fs, partName, &info) && info.m_size == it->second.m_storeSize && size == it->second.m_size && Blizzard::String::Equal(version, it->second.m_version.c_str()))) { + Blizzard::Streaming::StorageEntry* entry = &it->second; + LeaveCriticalSection(&s_storageLock); + return entry; + } + + Remove(it->second.m_path); + } + + if (!s_usePartFiles) { + Blizzard::File::Delete(partName); + } + + Blizzard::Streaming::StorageEntry* entry = PartialFile::CreateShared(key, path, size, version, flags); + LeaveCriticalSection(&s_storageLock); + return entry; +} + +// VERIFY: 02a9aee2 manual +// OFFSET: 0x004508B0 +void Blizzard::Storage::Shutdown() { + if (s_storageReady && s_storage) { + s_storageStop = true; + SetEvent(s_storageEvent); + + while (!s_storageStopped) { + Sleep(10); + } + + CloseHandle(s_storageEvent); + DeleteCriticalSection(&s_storageLock); + s_storageLock.DebugInfo = nullptr; + + if (s_storageFile) { + Blizzard::File::Close(s_storageFile); + } + } + + delete s_storage; + s_storage = nullptr; +} + +// VERIFY: 43918f20 manual +// OFFSET: 0x00456DE0 +bool Blizzard::Storage::PartialFile::RebuildHeader(Blizzard::File::Filesystem* fs, Blizzard::File::StreamRecord* file) { + Blizzard::Log::Printf(3, "Logs/Profiling_Storage_Initialization.log", "Reinitialized Part file '%s' started.\n", file->m_pathname); + + Blizzard::File::StreamingInfo* streaming = file->m_streaming; + + if (!streaming || !streaming->m_entry) { + return false; + } + + Blizzard::Streaming::StorageEntry* entry = streaming->m_entry; + + Blizzard::Streaming::PartFileHeader header; + header.m_magic = 2; + Blizzard::String::Copy(header.m_version, entry->m_version.c_str(), sizeof(header.m_version)); + header.m_flags = entry->m_flags; + header.m_size = entry->m_size; + header.m_blockSize = entry->m_blockSize; + + int32_t count = static_cast((header.m_size + header.m_blockSize - 1) / header.m_blockSize); + entry->m_blocks.resize(count); + memset(&entry->m_blocks[0], 0, sizeof(Blizzard::Streaming::StorageBlock) * count); + + int32_t amount = sizeof(header); + + if (!Blizzard::File::Write(file, &header, 0, &amount)) { + Blizzard::File::AddToLastErrorStack(0, "FileStack_Streaming::StreamingOpen - Failed to write .part header section", 20); + return false; + } + + amount = 20 * count; + + if (!Blizzard::File::Write(file, &entry->m_blocks[0], 52, &amount)) { + Blizzard::File::AddToLastErrorStack(0, "FileStack_Streaming::StreamingOpen - Failed to write .part storage section", 20); + return false; + } + + int64_t end = 20LL * count + 52; + entry->m_storeSize = end; + entry->m_headerWritten = true; + entry->m_closed = false; + entry->m_parsed = true; + Blizzard::File::SetEOF(file, end, 0); + + Blizzard::Log::Printf(3, "Logs/Profiling_Storage_Initialization.log", "Reinitialized Part file '%s' succeeded.\n", file->m_pathname); + return true; +} + +// VERIFY: d92a96a2 manual +// OFFSET: 0x00456F80 +bool Blizzard::Storage::PartialFile::ParseFile(Blizzard::File::Filesystem* fs, Blizzard::File::StreamRecord* file) { + Blizzard::File::StreamingInfo* streaming = file->m_streaming; + + if (!streaming || !streaming->m_entry) { + return false; + } + + Blizzard::Streaming::StorageEntry* entry = streaming->m_entry; + + if (entry->m_parsed) { + return true; + } + + if (streaming->m_info.m_size < 52) { + return RebuildHeader(fs, file); + } + + Blizzard::Streaming::PartFileHeader header; + int32_t amount = sizeof(header); + Blizzard::File::Read(fs, file, &header, 0, &amount); + + if (!header.m_blockSize || entry->m_version.compare(header.m_version) || header.m_size != file->m_info.m_size || header.m_magic != 2) { + return RebuildHeader(fs, file); + } + + entry->m_flags = header.m_flags; + entry->m_storeSize = file->m_streaming->m_info.m_size; + + int32_t count = static_cast((entry->m_blockSize + entry->m_size - 1) / entry->m_blockSize); + int32_t bytes = 20 * count; + uint8_t* raw = new uint8_t[bytes]; + + std::vector records; + records.resize(count); + + amount = bytes; + Blizzard::File::Read(fs, file, raw, 52, &amount); + + if (amount < bytes) { + delete[] raw; + return RebuildHeader(fs, file); + } + + Blizzard::String::MemCopy(&records[0], raw, amount); + delete[] raw; + + entry->m_blocks.resize(count); + + int32_t local = 0; + + for (int32_t i = 0; i < count; i++) { + Blizzard::Streaming::StorageBlock& block = entry->m_blocks[i]; + block.m_offset = 0; + block.m_size = entry->m_blockSize; + block.m_storeOffset = records[i].m_storeOffset; + block.m_partOffset = records[i].m_partOffset; + block.m_state = records[i].m_state != 0 ? 3 : 0; + + if (block.m_state == 3) { + if (block.m_storeOffset > entry->m_storeSize) { + return RebuildHeader(fs, file); + } + + local++; + } + } + + int64_t end = bytes + static_cast(local) * entry->m_blockSize + 52; + + if (entry->m_storeSize > end) { + Blizzard::File::SetEOF(file, end, 0); + entry->m_storeSize = end; + } else if (entry->m_storeSize < end) { + return RebuildHeader(fs, file); + } + + entry->m_parsed = true; + return true; +} + +// VERIFY: 47edb62c manual +// OFFSET: 0x004572C0 +bool Blizzard::Storage::WritePartBlockInfo(Blizzard::Streaming::StorageEntry* entry, Blizzard::File::StreamRecord* file, int32_t block) { + if (!s_storageReady) { + return false; + } + + if (entry->m_flags & 4) { + return true; + } + + bool result = true; + + if (block >= 0 && block < static_cast(entry->m_blocks.size())) { + Blizzard::Streaming::PartBlockRecord record; + record.m_storeOffset = entry->m_blocks[block].m_storeOffset; + record.m_state = entry->m_blocks[block].m_state; + record.m_partOffset = entry->m_blocks[block].m_partOffset; + + result = WriteAt(file, &record, 20LL * block + 52, sizeof(record)); + + if (!result) { + Blizzard::File::AddToLastErrorStack(0, "Failed to write storage information chunk", 20); + } + } + + return result; +} + +// VERIFY: 27d59f31 manual +// OFFSET: 0x00457390 +bool Blizzard::Storage::WriteBlock(Blizzard::Streaming::WriteRequest* request) { + Blizzard::Streaming::StorageEntry* entry = request->m_entry; + uint32_t block = static_cast(request->m_offset / entry->m_blockSize); + Blizzard::Streaming::StorageBlock& storageBlock = entry->m_blocks[block]; + int32_t state = storageBlock.m_state; + + if (state == 4 || (state != 3 && state != 2)) { + return state != 0; + } + + uint8_t* data = request->m_data; + bool allocated = false; + + if (block == entry->m_blocks.size() - 1 && request->m_size != entry->m_blockSize) { + allocated = true; + data = static_cast(Blizzard::Memory::Allocate(entry->m_blockSize)); + Blizzard::String::MemCopy(data, request->m_data, request->m_size); + } + + int64_t position = entry->m_storeSize; + bool existing = false; + + if (storageBlock.m_storeOffset) { + position = storageBlock.m_storeOffset; + existing = true; + } + + int32_t amount = entry->m_blockSize; + + if (!Blizzard::File::Write(request->m_file, data, position, &amount)) { + storageBlock.m_state = 0; + return false; + } + + if (allocated) { + Blizzard::Memory::Free(data); + } + + if (!existing) { + entry->m_blocks[block].m_storeOffset = position; + entry->m_storeSize += entry->m_blockSize; + } + + storageBlock.m_state = 3; + + bool result = s_usePartFiles ? WritePartBlockInfo(entry, request->m_file, block) : WriteIndexEntry(entry, block, false); + + if (!result) { + if (!existing) { + entry->m_blocks[block].m_storeOffset = 0; + entry->m_storeSize -= entry->m_blockSize; + } + + storageBlock.m_state = 0; + } + + return result; +} + +// VERIFY: 999e8cb7 manual +// OFFSET: 0x00457550 +bool Blizzard::Storage::FlushFile(Blizzard::File::Filesystem* fs, Blizzard::File::StreamRecord* file) { + EnterCriticalSection(&s_storageLock); + + int32_t count = static_cast(s_writeQueue.size()); + + for (int32_t i = 0; i < count; i++) { + Blizzard::Streaming::WriteRequest& request = s_writeQueue[i]; + + if (file == request.m_file) { + if (request.m_pending == 1) { + WriteBlock(&request); + request.m_pending = 0; + } + + if (request.m_data) { + Blizzard::Memory::Free(request.m_data); + request.m_data = nullptr; + } + } + } + + if (!s_usePartFiles) { + WriteIndex(); + } + + file->m_streaming->m_entry->m_released = true; + LeaveCriticalSection(&s_storageLock); + + while (file->m_streaming->m_entry->m_refCount > 0) { + Sleep(1); + } + + return true; +} + +// VERIFY: 4a7a69cc manual +// OFFSET: 0x00459660 +uint32_t Blizzard::Storage::StorageThread(void* param) { + if (s_storageStop) { + s_storageStopped = true; + return 1; + } + + do { + WaitForSingleObject(s_storageEvent, INFINITE); + + if (s_storageStop) { + break; + } + + for (;;) { + EnterCriticalSection(&s_storageLock); + + if (!s_writeQueue.size()) { + break; + } + + Blizzard::Streaming::WriteRequest& request = s_writeQueue.front(); + + if (request.m_pending == 1) { + WriteBlock(&request); + + if (request.m_data) { + Blizzard::Memory::Free(request.m_data); + request.m_data = nullptr; + } + } + + s_writeQueue.pop_front(); + LeaveCriticalSection(&s_storageLock); + + if (s_storageStop) { + s_storageStopped = true; + return 1; + } + } + + LeaveCriticalSection(&s_storageLock); + } while (!s_storageStop); + + s_storageStopped = true; + return 1; +} + +// VERIFY: 37d58904 manual +// OFFSET: 0x00459800 +bool Blizzard::Storage::Close(Blizzard::File::Filesystem* fs, Blizzard::File::StreamRecord* file, Blizzard::Streaming::StorageEntry* entry) { + if (entry->m_flags & 4) { + return true; + } + + EnterCriticalSection(&s_storageLock); + + if ((entry->m_flags & 1) && IsComplete(entry)) { + entry->m_closed = true; + LeaveCriticalSection(&s_storageLock); + return true; + } + + bool result = FlushFile(fs, file); + + for (std::vector::iterator it = entry->m_blocks.begin(); it != entry->m_blocks.end(); ++it) { + if (it->m_state != 3) { + it->m_state = 0; + } + } + + LeaveCriticalSection(&s_storageLock); + return result; +} + +// VERIFY: fd87d2fa manual +// OFFSET: 0x0045ADC0 +bool Blizzard::Storage::Initialize() { + s_usePartFiles = true; + + if (!s_storageReady) { + s_storage = new std::map(); + InitializeCriticalSection(&s_storageLock); + s_storageEvent = CreateEventA(nullptr, FALSE, FALSE, nullptr); + Blizzard::Thread::CreateDetached(StorageThread, nullptr, "Streaming Storage Thread"); + s_storageReady = true; + } + + return true; +} + +// VERIFY: 9d88e040 manual +// OFFSET: 0x0045AE90 +bool Blizzard::Storage::Initialize(const char* path, bool required) { + s_usePartFiles = false; + + if (s_storageReady) { + Blizzard::File::AddToLastErrorStack(0, "Storage::Initialize - s_storageReady said we've been here", 20); + return false; + } + + s_storage = new std::map(); + InitializeCriticalSection(&s_storageLock); + s_storageEvent = CreateEventA(nullptr, FALSE, FALSE, nullptr); + Blizzard::Thread::CreateDetached(StorageThread, nullptr, "Streaming Storage Thread"); + s_storageReady = true; + + void* data = nullptr; + uint32_t size = 0; + char absolute[260]; + + if (!path || !Blizzard::File::MakeAbsolutePath(path, absolute, sizeof(absolute), false)) { + Blizzard::File::AddToLastErrorStack(0, "Storage::Initialize - MakeAbsolutePath failed", 20); + return false; + } + + s_storagePath.assign(absolute, strlen(absolute)); + + bool found = false; + + for (int32_t i = 0; i < 25; i++) { + if (found) { + break; + } + + char name[260]; + BuildVariantFileName(name, sizeof(name), path, ""); + + if (!Blizzard::File::Exists(name)) { + break; + } + + if (Blizzard::File::Open(name, 4099, s_storageFile)) { + if (!System_File::LoadFile(s_storageFile, &data, &size)) { + break; + } + + found = true; + } else { + s_variantIndex++; + } + } + + if (!found) { + if (required) { + Blizzard::File::AddToLastErrorStack(0, "Storage::Initialize - Bad existing storage file", 20); + return false; + } + + if (s_storageFile) { + if (data) { + Blizzard::Memory::Free(data); + } + + Blizzard::File::Close(s_storageFile); + s_storageFile = nullptr; + Blizzard::File::Delete(path); + } + + s_usePartFiles = true; + return true; + } + + bool result = ReadStorageFile(static_cast(data), size); + Blizzard::Memory::Free(data); + + if (result) { + return true; + } + + if (required) { + Blizzard::File::AddToLastErrorStack(0, "Storage::Initialize - Bad existing storage file", 20); + return false; + } + + Blizzard::File::Close(s_storageFile); + s_storageFile = nullptr; + s_usePartFiles = true; + Blizzard::File::Delete(path); + return true; +} + +#endif diff --git a/Engine/Source/BlizzardCore/Source/Packages/Streaming/Win32/Streaming.cpp b/Engine/Source/BlizzardCore/Source/Packages/Streaming/Win32/Streaming.cpp index 7515d61..c1d09ba 100644 --- a/Engine/Source/BlizzardCore/Source/Packages/Streaming/Win32/Streaming.cpp +++ b/Engine/Source/BlizzardCore/Source/Packages/Streaming/Win32/Streaming.cpp @@ -1,77 +1,1181 @@ #if defined(WOWDECOMP_ARCH_32) +#include #include #include #include +#include +#include +#include #include +#include "Engine/Source/BlizzardCore/Include/Blizzard/Util/MD5.h" +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Manifests.h" +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Storage.h" #include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Streaming.h" +#include "Engine/Source/BlizzardCore/Source/System/Debug/ErrorStack.h" #include "Engine/Source/BlizzardCore/Source/System/File/File.h" +#include "Engine/Source/BlizzardCore/Source/System/File/Filestack.h" +#include "Engine/Source/BlizzardCore/Source/System/File/Filestack_Streaming.h" +#include "Engine/Source/BlizzardCore/Source/System/Log/Log.h" +#include "Engine/Source/BlizzardCore/Source/System/Memory/MemoryStorm.h" +#include "Engine/Source/BlizzardCore/Source/System/String/Path.h" +#include "Engine/Source/BlizzardCore/Source/System/String/String.h" +#include "Engine/Source/BlizzardCore/Source/System/Thread/Thread.h" + +// STATIC: 0x009E6204 +static const int32_t s_queueOrder[6] = { 0, 1, 0, 2, 0, 1 }; + +// STATIC: 0x009E621C +static const int32_t s_queueGroupBase[2] = { 0, 4 }; + +// STATIC: 0x00AB9344 +static bool s_useBackgroundQueues = true; + +// STATIC: 0x00AB9346 +static bool s_throttleProgress = true; // STATIC: 0x00B3252C -static HANDLE unk_B3252C; +static HANDLE s_throttleEvent; // STATIC: 0x00B32530 -static CRITICAL_SECTION unk_B32530; +static CRITICAL_SECTION s_queueLock; // STATIC: 0x00B32548 -static HANDLE unk_B32548[2]; +static HANDLE s_threadEvents[2]; // STATIC: 0x00B32550 -static HANDLE unk_B32550; +static HANDLE s_pauseEvent; // STATIC: 0x00B32554 -static Blizzard::Streaming::DownloadSlot* unk_B32554[2]; +static Blizzard::Streaming::FILE_THREAD_CMD* s_currentCommands[2]; // STATIC: 0x00B3255C -static std::deque* unk_B3255C[7]; +static std::deque* s_queues[7]; // STATIC: 0x00B325A0 -static CRITICAL_SECTION unk_B325A0; +static CRITICAL_SECTION s_pauseLock; // STATIC: 0x00B325B8 -static bool unk_B325B8; - -// STATIC: 0x00B325C0 -static CRITICAL_SECTION unk_B325C0; - -// STATIC: 0x00B325D8 -static HANDLE unk_B325D8; +static bool s_paused; // STATIC: 0x00B325DC -static HANDLE unk_B325DC; - -// STATIC: 0x00B38170 -static Blizzard::Streaming::SourceManifest* unk_B38170; - -// STATIC: 0x00B38174 -static Blizzard::Streaming::StorageEntryMap* unk_B38174; - -// STATIC: 0x00B38178 -static Blizzard::File::StreamRecord* unk_B38178; - -// STATIC: 0x00B3817C -static bool unk_B3817C; - -// STATIC: 0x00B3817E -static bool unk_B3817E; - -// STATIC: 0x00B3817F -static bool unk_B3817F; +static HANDLE s_queueEvent; // STATIC: 0x00B38182 -static bool unk_B38182; +static volatile bool s_stopThreads; // STATIC: 0x00B38184 -static int32_t unk_B38184; +static volatile int32_t s_threadMask; + +// STATIC: 0x00B38188 +static int32_t s_busyMask; // STATIC: 0x00B38294 -static Blizzard::Streaming::DigestStateMap* unk_B38294; +static Blizzard::Streaming::DigestStateMap* s_digestStates; // STATIC: 0x00B38298 -static Blizzard::Streaming::PathMap* unk_B38298; +static Blizzard::Streaming::PathMap* s_paths; + +// STATIC: 0x00B3829C +static int32_t s_commandsTaken; + +// STATIC: 0x00B382A0 +static int32_t s_commandsFreed; // STATIC: 0x00B386D0 -static Blizzard::Streaming::DownloadProgress unk_B386D0; +Blizzard::Streaming::DownloadProgress Blizzard::Streaming::s_progress; + +// STATIC: 0x00B38A54 +static int32_t s_queueRotation[2]; + +// VERIFY: ca557b86 auto +// OFFSET: 0x00428030 +int32_t Blizzard::Streaming::GetIdleThread() { + for (int32_t thread = 0; thread < 2; thread++) { + if (((1 << thread) & s_threadMask) && !((1 << thread) & s_busyMask)) { + return thread; + } + } + + return -1; +} + +// VERIFY: 7ce85334 manual +// OFFSET: 0x00428060 +void Blizzard::Streaming::DownloadProgress::Sample(uint32_t time) { + if (++this->m_index >= 51) { + this->m_index = 0; + } + + this->m_samples[this->m_index].m_time = 0; + this->m_samples[this->m_index].m_bytes = this->m_streamed; + this->m_samples[this->m_index].m_time = time; +} + +// VERIFY: c059fee6 manual +// OFFSET: 0x004280C0 +int32_t Blizzard::Streaming::DownloadProgress::GetRate() { + uint32_t last = this->m_index; + uint32_t first; + + if (last == 50) { + first = 0; + } else { + first = last + 1; + + if (!last) { + last = 51; + } + } + + uint32_t end = last - 1; + + while (!this->m_samples[first].m_time) { + if (first == end) { + break; + } + + if (++first > 50) { + first = 0; + } + } + + for (; !this->m_samples[end].m_time; end--) { + if (first == end) { + break; + } + + if (!end) { + end = 51; + } + } + + int64_t bytes = this->m_samples[end].m_bytes - this->m_samples[first].m_bytes; + int32_t time = this->m_samples[end].m_time - this->m_samples[first].m_time; + + if (first == end) { + uint32_t next = end + 1; + + if (next == 51) { + next = 0; + } + + if (this->m_samples[next].m_time) { + bytes = this->m_samples[next].m_bytes; + time = this->m_samples[next].m_time - this->m_lastTime; + } + } + + if (bytes > 0) { + return static_cast(1000 * (bytes / time)); + } + + return 0; +} + +// VERIFY: df0a8983 manual +// OFFSET: 0x0042E020 +void Blizzard::Streaming::HashFileName(Blizzard::Util::Digest<16>* digest, const char* name) { + char lower[260]; + memset(lower, 0, sizeof(lower)); + + if (name) { + char* dst = lower; + + do { + char c = *name++; + + if (!c) { + break; + } + + *dst++ = c; + } while (dst < &lower[259]); + + *dst = '\0'; + } else { + lower[0] = '\0'; + } + + for (char* cursor = lower; *cursor; cursor++) { + *cursor = tolower(*cursor); + } + + Blizzard::Util::HashString(digest->m_data, lower); +} + +// VERIFY: 1afaab41 auto +// OFFSET: 0x0042E0B0 +void Blizzard::Streaming::WaitForLoads() { + for (;;) { + EnterCriticalSection(&s_queueLock); + + bool busy = false; + + for (int32_t i = 0; i < 2; i++) { + if (s_currentCommands[i] && s_currentCommands[i]->m_type == 1) { + busy = true; + break; + } + } + + LeaveCriticalSection(&s_queueLock); + + if (!busy) { + return; + } + + Sleep(1); + } +} + +// VERIFY: 6c5c45f9 manual +// OFFSET: 0x00437ED0 +bool Blizzard::Streaming::CancelQueue(int32_t priority) { + EnterCriticalSection(&s_queueLock); + + std::deque& queue = *s_queues[priority]; + + for (std::deque::iterator it = queue.begin(); it != queue.end(); ++it) { + if (it->m_completion && it->m_type == 2) { + it->m_completion->m_result = static_cast(s_queues[priority]->size()); + it->m_completion->m_done = true; + SetEvent(*it->m_completion->m_event); + it->m_completion = nullptr; + } + + it->m_type = 0; + } + + for (DigestStateMap::iterator it = s_digestStates->begin(); it != s_digestStates->end(); ++it) { + if (it->second.m_state && it->second.m_priority == priority) { + it->second.m_state = 0; + } + } + + LeaveCriticalSection(&s_queueLock); + return true; +} + +// VERIFY: a2c311e9 manual +// OFFSET: 0x00438120 +bool Blizzard::Streaming::PopCommand(FILE_THREAD_CMD* command, int32_t queue) { + if (!s_queues[queue]->size()) { + return false; + } + + *command = s_queues[queue]->front(); + s_queues[queue]->pop_front(); + s_commandsTaken++; + + return true; +} + +// VERIFY: 004b23b3 auto +// OFFSET: 0x004381E0 +bool Blizzard::Streaming::SelectQueue(FILE_THREAD_CMD* command, int32_t group, int32_t* queue) { + if (group >= 1 && !s_useBackgroundQueues) { + return false; + } + + int32_t base = s_queueGroupBase[group]; + + for (int32_t i = 0; i < 6; i++) { + *queue = base + s_queueOrder[s_queueRotation[group]]; + s_queueRotation[group] = (s_queueRotation[group] + 1) % 6; + + if (PopCommand(command, *queue)) { + return true; + } + } + + return false; +} + +// VERIFY: d5dfe076 manual +// OFFSET: 0x00438260 +int32_t Blizzard::Streaming::GetNextCommand(FILE_THREAD_CMD** command, int32_t thread) { + FILE_THREAD_CMD* next = new FILE_THREAD_CMD(); + int32_t queue = 7; + + if (SelectQueue(next, 0, &queue) || (queue = 3, PopCommand(next, 3)) || SelectQueue(next, 1, &queue)) { + s_currentCommands[thread] = next; + *command = next; + return queue; + } + + delete next; + s_commandsFreed++; + return 7; +} + +// VERIFY: 7f6dac26 auto +// OFFSET: 0x00438360 +void Blizzard::Streaming::DownloadProgress::FireCallback() { + if (!this->m_enabled) { + return; + } + + if (s_throttleProgress && Blizzard::Time::Milliseconds() - this->m_lastTime < 5000) { + return; + } + + PROGRESSCALLBACK callback = this->m_callback; + + if (callback) { + callback(static_cast(this->m_total), static_cast(this->m_total >> 32), static_cast(this->m_downloaded), static_cast(this->m_downloaded >> 32), static_cast(this->m_streamed), static_cast(this->m_streamed >> 32), this->GetRate()); + } +} + +// VERIFY: 8977ceaf auto +// OFFSET: 0x00439E30 +void Blizzard::Streaming::AddDownloaded(int32_t size) { + s_progress.m_downloaded += size; + s_progress.FireCallback(); +} + +// VERIFY: 004ad102 manual +// OFFSET: 0x00439E50 +void Blizzard::Streaming::AddStreamed(int32_t size) { + s_progress.m_streamed += size; + + uint32_t now = static_cast(Blizzard::Time::Milliseconds()); + + if (now - s_progress.m_samples[s_progress.m_index].m_time > 100) { + s_progress.Sample(now); + s_progress.FireCallback(); + } +} + +// VERIFY: 7798fae9 manual +// OFFSET: 0x0043AF30 +bool Blizzard::Streaming::RemoveCompletion(Completion* completion, int32_t priority) { + if (!s_queues[priority]->size()) { + return false; + } + + EnterCriticalSection(&s_queueLock); + + std::deque& queue = *s_queues[priority]; + + for (std::deque::iterator it = queue.end(); it != queue.begin();) { + --it; + + if (it->m_completion == completion) { + it->m_completion = nullptr; + LeaveCriticalSection(&s_queueLock); + return true; + } + } + + LeaveCriticalSection(&s_queueLock); + return false; +} + +// VERIFY: dbe79009 manual +// OFFSET: 0x00444550 +bool Blizzard::Streaming::QueueLoad(Blizzard::File::StreamRecord* file, int32_t priority, LoadRange* range, Completion* completion) { + Blizzard::File::Filesystem* fs = System_File::Stacked::s_manager; + + while (fs && fs->m_original != &System_File::Stacked::s_streamstack) { + fs = fs->m_next; + } + + FILE_THREAD_CMD command; + command.m_fs = fs; + command.m_type = 1; + command.m_file = file; + command.m_range = static_cast(Blizzard::Memory::Allocate(sizeof(LoadRange))); + + if (range) { + memmove(command.m_range, range, sizeof(LoadRange)); + } + + command.m_completion = completion; + + EnterCriticalSection(&s_queueLock); + s_queues[priority]->push_back(command); + LeaveCriticalSection(&s_queueLock); + + return Blizzard::Storage::RequestRange(file->m_streaming->m_entry, range->m_blockOffset, range->m_blockSize, 1); +} + +// VERIFY: c895a955 manual +// OFFSET: 0x00444620 +bool Blizzard::Streaming::RequestRanges(Blizzard::File::StreamRecord* file, LoadRange* ranges, int32_t count) { + int32_t state = 0; + int32_t requests = 0; + int32_t blocks = 0; + std::vector completions; + + LoadRange current; + current.m_offset = 0; + current.m_size = 0; + current.m_state = 0; + + for (int32_t i = 0; i < count; i++) { + LoadRange& range = ranges[i]; + + if (range.m_state > 4) { + continue; + } + + if (!state) { + if (range.m_state < 2) { + continue; + } + + current.m_blockOffset = range.m_blockOffset; + current.m_blockSize = range.m_blockSize; + current.m_state = 2; + blocks++; + state = 2; + continue; + } + + if (current.m_blockOffset + current.m_blockSize != range.m_blockOffset) { + Completion* completion = new Completion(); + Blizzard::Lock::Event* event = new Blizzard::Lock::Event(); + completion->m_event = event; + *event = CreateEventA(nullptr, FALSE, FALSE, nullptr); + completions.push_back(completion); + + QueueLoad(file, 0, ¤t, completion); + SetEvent(s_throttleEvent); + SetEvent(s_queueEvent); + requests++; + + if (range.m_state < 2) { + state = 0; + } else { + current.m_blockOffset = range.m_blockOffset; + current.m_blockSize = range.m_blockSize; + state = range.m_state; + } + + current.m_state = state; + } else { + current.m_blockSize += range.m_blockSize; + blocks++; + } + } + + if (state) { + if (requests || blocks < 4) { + Completion* completion = new Completion(); + Blizzard::Lock::Event* event = new Blizzard::Lock::Event(); + completion->m_event = event; + *event = CreateEventA(nullptr, FALSE, FALSE, nullptr); + completions.push_back(completion); + QueueLoad(file, 0, ¤t, completion); + } else { + int32_t half = Blizzard::Storage::s_blockSize * (blocks - blocks / 2); + + LoadRange second; + second.m_offset = 0; + second.m_size = 0; + second.m_state = 2; + second.m_blockOffset = current.m_blockOffset + half; + second.m_blockSize = current.m_blockSize - half; + current.m_blockSize = half; + + Completion* completion = new Completion(); + Blizzard::Lock::Event* event = new Blizzard::Lock::Event(); + completion->m_event = event; + *event = CreateEventA(nullptr, FALSE, FALSE, nullptr); + completions.push_back(completion); + QueueLoad(file, 0, ¤t, completion); + + completion = new Completion(); + event = new Blizzard::Lock::Event(); + completion->m_event = event; + *event = CreateEventA(nullptr, FALSE, FALSE, nullptr); + completions.push_back(completion); + QueueLoad(file, 0, &second, completion); + } + } + + SetEvent(s_throttleEvent); + SetEvent(s_queueEvent); + + bool success = true; + + for (std::vector::iterator it = completions.begin(); it != completions.end(); ++it) { + WaitForSingleObject(*(*it)->m_event, INFINITE); + CloseHandle(*(*it)->m_event); + + if (!(*it)->m_success) { + success = false; + } + + delete (*it)->m_event; + (*it)->m_event = nullptr; + delete *it; + *it = nullptr; + } + + completions.erase(completions.begin(), completions.end()); + + return success; +} + +// VERIFY: c5eac1d5 auto +// OFFSET: 0x00444AA0 +bool Blizzard::Streaming::QueueCompletion(Completion* completion, int32_t priority) { + if (!s_queues[priority]->size()) { + completion->m_result = 0; + completion->m_done = false; + completion->m_success = false; + return false; + } + + FILE_THREAD_CMD command; + command.m_fs = nullptr; + command.m_type = 2; + command.m_file = nullptr; + command.m_range = nullptr; + command.m_completion = completion; + + EnterCriticalSection(&s_queueLock); + s_queues[priority]->push_back(command); + LeaveCriticalSection(&s_queueLock); + SetEvent(s_queueEvent); + + return true; +} + +// VERIFY: c29501bd manual +// OFFSET: 0x004480B0 +bool Blizzard::Streaming::MakeLocalAsync(Blizzard::File::StreamRecord* file, int64_t offset, int32_t size, int32_t priority, const char* name) { + if (!file->m_streaming || !file->m_streaming->m_entry) { + return false; + } + + Blizzard::Util::Digest<16> digest; + HashFileName(&digest, name); + + DigestStateMap::iterator it = s_digestStates->find(digest); + + if (it != s_digestStates->end()) { + if (it->second.m_state == 1) { + return true; + } + + if (it->second.m_state == 2 && it->second.m_priority <= priority) { + return true; + } + } + + StorageEntry* entry = file->m_streaming->m_entry; + + if (!entry) { + return false; + } + + int32_t count; + LoadRange* ranges = Blizzard::Storage::GetRange(entry, offset, size, &count, true); + + if (!ranges || !count) { + return false; + } + + bool queued = false; + + for (int32_t i = 0; i < count; i++) { + if (static_cast(ranges[i].m_state - 2) <= 2) { + QueueLoad(file, priority, &ranges[i], nullptr); + queued = true; + } + } + + if (queued) { + (*s_digestStates)[digest].m_state = 2; + (*s_digestStates)[digest].m_priority = priority; + + if (s_useBackgroundQueues) { + SetEvent(s_queueEvent); + } + } else { + (*s_digestStates)[digest].m_state = 1; + AddDownloaded(size); + } + + Blizzard::Memory::Free(ranges); + return true; +} + +// VERIFY: cb882196 manual +// OFFSET: 0x0044F120 +int32_t Blizzard::Streaming::CheckFileRange(const char* path, int64_t offset, int32_t size, const char* name, int32_t flags) { + Blizzard::Util::Digest<16> digest; + HashFileName(&digest, name); + + DigestStateMap::iterator it = s_digestStates->find(digest); + int32_t previous = 0; + + if (it != s_digestStates->end()) { + previous = it->second.m_state; + + if (previous == 1) { + return 1; + } + } + + if (!path) { + return -1; + } + + std::string key = ResolveFilePath(std::string(path)); + + if (!Blizzard::Storage::s_storage) { + return -1; + } + + std::map::iterator entry = Blizzard::Storage::s_storage->find(key); + + if (entry == Blizzard::Storage::s_storage->end()) { + return -1; + } + + int32_t count; + LoadRange* ranges = Blizzard::Storage::GetRange(&entry->second, offset, size, &count, false); + + if (!ranges || !count) { + return -1; + } + + int32_t result = 1; + + for (LoadRange* range = ranges; count > 0 && result; range++, count--) { + switch (range->m_state) { + case 1: + case 3: + if (result == 1) { + result = 2; + } + + break; + + case 2: + case 4: + result = 0; + break; + } + } + + Blizzard::Memory::Free(ranges); + + if (previous != result) { + (*s_digestStates)[digest].m_state = result; + } + + return result; +} + +// VERIFY: a3b69a54 manual +// OFFSET: 0x0044F370 +int32_t Blizzard::Streaming::GetIsLocalAmount(const char* path, int64_t offset, int32_t size, const char* name) { + Blizzard::Util::Digest<16> digest; + HashFileName(&digest, name); + + DigestStateMap::iterator it = s_digestStates->find(digest); + + if (it != s_digestStates->end() && it->second.m_state == 1) { + return size; + } + + std::string key = ResolveFilePath(std::string(path)); + + if (!Blizzard::Storage::s_storage) { + return size; + } + + std::map::iterator entry = Blizzard::Storage::s_storage->find(key); + + if (entry == Blizzard::Storage::s_storage->end()) { + return size; + } + + int32_t local = size; + int32_t count; + LoadRange* ranges = Blizzard::Storage::GetRange(&entry->second, offset, size, &count, false); + + if (ranges && count) { + local = 0; + + for (int32_t i = 0; i < count; i++) { + if (!ranges[i].m_state) { + local += ranges[i].m_size; + } + } + + Blizzard::Memory::Free(ranges); + } + + return local; +} + +// VERIFY: fcef87fc manual +// OFFSET: 0x0044F560 +bool Blizzard::Streaming::MakeLocalBlocking(Blizzard::File::StreamRecord* file, int64_t offset, int32_t size, int32_t priority, const char* name) { + Blizzard::Util::Digest<16> digest; + HashFileName(&digest, name); + + DigestStateMap::iterator it = s_digestStates->find(digest); + + if (it != s_digestStates->end() && it->second.m_state == 1) { + return true; + } + + std::string key = ResolveFilePath(std::string(file->m_pathname)); + + if (!Blizzard::Storage::s_storage) { + return false; + } + + std::map::iterator entry = Blizzard::Storage::s_storage->find(key); + + if (entry == Blizzard::Storage::s_storage->end()) { + return false; + } + + int32_t count; + LoadRange* ranges = Blizzard::Storage::GetRange(&entry->second, offset, size, &count, true); + + if (!ranges || !count) { + return false; + } + + std::vector completions; + bool queued = false; + + for (int32_t i = 0; i < count; i++) { + LoadRange& range = ranges[i]; + + if (static_cast(range.m_state - 2) > 2) { + continue; + } + + if (range.m_blockSize <= 0) { + Blizzard::Memory::Free(ranges); + return false; + } + + LoadRange request; + request.m_state = 2; + request.m_blockOffset = range.m_blockOffset; + request.m_blockSize = range.m_blockSize; + queued = true; + + Completion* completion = new Completion(); + Blizzard::Lock::Event* event = new Blizzard::Lock::Event(); + completion->m_event = event; + *event = CreateEventA(nullptr, FALSE, FALSE, nullptr); + completions.push_back(completion); + + QueueLoad(file, priority, &request, completion); + SetEvent(s_throttleEvent); + SetEvent(s_queueEvent); + } + + if (!queued) { + Blizzard::Memory::Free(ranges); + return true; + } + + SetEvent(s_throttleEvent); + SetEvent(s_queueEvent); + + bool success = true; + + for (std::vector::iterator it = completions.begin(); it != completions.end(); ++it) { + WaitForSingleObject(*(*it)->m_event, INFINITE); + CloseHandle(*(*it)->m_event); + + if (!(*it)->m_success) { + success = false; + } + + delete (*it)->m_event; + (*it)->m_event = nullptr; + delete *it; + *it = nullptr; + } + + completions.erase(completions.begin(), completions.end()); + Blizzard::Memory::Free(ranges); + + return success; +} + +// VERIFY: 7224c505 manual +// OFFSET: 0x00458A90 +bool System_File::Stacked::stream_flush(Blizzard::File::Filesystem* fs, FileParms* parms) { + Blizzard::File::StreamRecord* file = parms->m_stream; + + if (file->m_streaming && file->m_streaming->m_entry) { + EnterCriticalSection(&s_queueLock); + + for (int32_t i = 0; i < 7; i++) { + std::deque* queue = s_queues[i]; + + if (queue->size()) { + for (std::deque::iterator it = queue->begin(); it != queue->end(); ++it) { + if (file == it->m_file && it->m_type == 1) { + it->m_type = 0; + } + } + } + } + + for (int32_t i = 0; i < 2; i++) { + if (s_currentCommands[i] && file == s_currentCommands[i]->m_file && s_currentCommands[i]->m_type == 1) { + s_currentCommands[i]->m_type = 0; + } + } + + LeaveCriticalSection(&s_queueLock); + + if (!Blizzard::Storage::FlushFile(fs->m_next, file)) { + return false; + } + } + + if (!fs->m_next) { + return false; + } + + return (*reinterpret_cast(reinterpret_cast(fs->m_next) + parms->m_verb))(fs->m_next, parms); +} + +// VERIFY: 0872e772 manual +// OFFSET: 0x0045A8F0 +bool Blizzard::Streaming::LoadFile(Blizzard::File::Filesystem* fs, Blizzard::File::StreamRecord* file, LoadRange* range) { + Blizzard::Storage::StorageEntryRef ref(file->m_streaming->m_entry); + StorageEntry* entry = ref.m_entry; + + if (!entry) { + EnterCriticalSection(&Blizzard::Storage::s_storageLock); + LeaveCriticalSection(&Blizzard::Storage::s_storageLock); + return false; + } + + int32_t count = 0; + LoadRange* ranges = file->m_streaming ? Blizzard::Storage::GetRange(entry, range->m_blockOffset, range->m_blockSize, &count, true) : nullptr; + + if (!ranges || !count) { + EnterCriticalSection(&Blizzard::Storage::s_storageLock); + entry->m_refCount--; + LeaveCriticalSection(&Blizzard::Storage::s_storageLock); + return false; + } + + bool requested = false; + int32_t failState = 3; + + EnterCriticalSection(&Blizzard::Storage::s_storageLock); + + for (int32_t i = 0; i < count; i++) { + LoadRange& loadRange = ranges[i]; + + if (loadRange.m_state == 3) { + failState = 1; + Blizzard::Storage::RequestRange(entry, loadRange.m_blockOffset, loadRange.m_blockSize, 4); + requested = true; + } else if (loadRange.m_state == 2 || loadRange.m_state == 4) { + failState = 0; + Blizzard::Storage::RequestRange(entry, loadRange.m_blockOffset, loadRange.m_blockSize, 4); + requested = true; + } + } + + LeaveCriticalSection(&Blizzard::Storage::s_storageLock); + Blizzard::Memory::Free(ranges); + + if (!requested) { + Blizzard::Log::Printf(3, "Logs/Profiling_File_Defer_Cancelled.log", "%10lld, %10d - %s\n", range->m_blockOffset, range->m_blockSize, file->m_pathname); + EnterCriticalSection(&Blizzard::Storage::s_storageLock); + entry->m_refCount--; + LeaveCriticalSection(&Blizzard::Storage::s_storageLock); + return true; + } + + Blizzard::Log::Printf(3, "Logs/Profiling_File_Defer.log", "%10lld, %10d - %s\n", range->m_blockOffset, range->m_blockSize, file->m_pathname); + s_statBytesDownloaded += range->m_blockSize; + + uint8_t* data = static_cast(Blizzard::Memory::Allocate(range->m_blockSize)); + + std::string url; + url = ManifestInfo::GetRemotePath(file->m_streaming->m_path); + + Manifests::TransportItem* transport = ManifestInfo::GetTransportItem(file->m_streaming->m_path); + int32_t maxRetry = ManifestInfo::GetServerItemMaxRetry(std::string(url), file->m_streaming->m_path); + + bool result = Transport::Read(transport, std::string(url), maxRetry, data, file->m_info.m_size, range->m_blockOffset, range->m_blockSize); + + if (!result) { + ManifestInfo::DeactivateServer(std::string(url), file->m_streaming->m_path); + Blizzard::Memory::Free(data); + } else if (range->m_blockSize > Blizzard::Storage::s_blockSize) { + int32_t written = 0; + int32_t left = range->m_blockSize; + + while (left > 0) { + int32_t chunk = Blizzard::Storage::s_blockSize < left ? Blizzard::Storage::s_blockSize : left; + result &= Blizzard::Storage::QueueWrite(fs, file, &data[written], range->m_blockOffset + written, chunk, false); + written += chunk; + left -= chunk; + } + + Blizzard::Memory::Free(data); + } else { + result = Blizzard::Storage::QueueWrite(fs, file, data, range->m_blockOffset, range->m_blockSize, true); + } + + if (!result) { + Blizzard::Storage::SetRangeAs(entry, range->m_blockOffset, range->m_blockSize, failState); + } + + EnterCriticalSection(&Blizzard::Storage::s_storageLock); + entry->m_refCount--; + LeaveCriticalSection(&Blizzard::Storage::s_storageLock); + + return result; +} + +// VERIFY: 9e589b1a manual +// OFFSET: 0x0045B150 +uint32_t Blizzard::Streaming::DownloadThread(void* param) { + int32_t thread = *static_cast(param); + delete static_cast(param); + + EnterCriticalSection(&s_queueLock); + int32_t bit = 1 << thread; + s_threadMask |= bit; + LeaveCriticalSection(&s_queueLock); + + if (!s_stopThreads) { + for (;;) { + if (Blizzard::Lock::EventWait(100, s_queueEvent) || Blizzard::Lock::EventWait(5, s_threadEvents[thread])) { + while (!s_stopThreads) { + if (s_paused) { + WaitForSingleObject(s_pauseEvent, INFINITE); + SetEvent(s_pauseEvent); + } + + EnterCriticalSection(&s_queueLock); + s_busyMask |= bit; + + FILE_THREAD_CMD* command = nullptr; + int32_t queue = GetNextCommand(&command, thread); + + if (queue == 7) { + LeaveCriticalSection(&s_queueLock); + break; + } + + int32_t pending = 0; + + for (int32_t i = 0; i < 7; i++) { + pending += static_cast(s_queues[i]->size()); + } + + if (pending > 0) { + int32_t idle = GetIdleThread(); + + if (idle >= 0) { + SetEvent(s_threadEvents[idle]); + } + } + + LeaveCriticalSection(&s_queueLock); + + bool success = true; + bool requeue = false; + + if (!command->m_type) { + success = false; + } else if (command->m_type == 1) { + if (LoadFile(command->m_fs, command->m_file, command->m_range)) { + command->m_type = 0; + } else if (command->m_type && !command->m_completion) { + requeue = true; + success = false; + } + } else if (command->m_type == 2) { + command->m_type = 0; + + if (!pending) { + WaitForLoads(); + } + } + + if (command->m_completion) { + command->m_completion->m_result = static_cast(s_queues[queue]->size()); + command->m_completion->m_done = false; + command->m_completion->m_success = success; + SetEvent(*command->m_completion->m_event); + command->m_completion = nullptr; + } + + EnterCriticalSection(&s_queueLock); + + if (requeue) { + s_queues[queue]->push_front(*command); + AddStreamed(0); + } + + FILE_THREAD_CMD* current = s_currentCommands[thread]; + + if (current) { + s_currentCommands[thread] = nullptr; + Blizzard::Memory::Free(current->m_range); + delete current; + s_commandsFreed++; + } + + LeaveCriticalSection(&s_queueLock); + + System_File::FileError& error = System_File::s_error; + + if (error.m_errorStack) { + Blizzard::Debug::FreeErrorStack(error.m_errorStack); + } + + error.m_errorStack = nullptr; + + if (queue > 2) { + WaitForSingleObject(s_throttleEvent, FileManifest::GetBGPreloadSleep()); + } + } + } + + EnterCriticalSection(&s_queueLock); + s_busyMask &= ~bit; + LeaveCriticalSection(&s_queueLock); + + if (s_stopThreads) { + break; + } + } + } + + EnterCriticalSection(&s_queueLock); + s_threadMask &= ~bit; + LeaveCriticalSection(&s_queueLock); + + return 1; +} + +// VERIFY: 76b01508 manual +// OFFSET: 0x004616A0 +bool Blizzard::Streaming::InitializeStreaming(const char* manifest, const char* storagePath, const char* variant, const char* dataPath, bool required) { + if (s_streamingReady) { + return true; + } + + char cwd[260]; + cwd[0] = '\0'; + + if (!Blizzard::File::GetWorkingDirectory(cwd, sizeof(cwd))) { + Blizzard::File::AddToLastErrorStack(0, "InitializeStreaming - Failed to get working directory", 20); + return false; + } + + char root[260]; + + if (!manifest || Blizzard::String::EqualI(manifest, s_httpPrefix, s_httpPrefix ? strlen(s_httpPrefix) : 0)) { + Blizzard::String::Copy(root, cwd, sizeof(root)); + } else { + char absolute[260]; + + if (!Blizzard::File::MakeAbsolutePath(manifest, absolute, sizeof(absolute), false)) { + Blizzard::File::AddToLastErrorStack(0, "InitializeStreaming - Failed to make absolute manifest path", 20); + return false; + } + + int32_t length = static_cast(Blizzard::String::FindFilename(absolute) - absolute + 1); + Blizzard::String::Copy(root, absolute, length <= 260 ? length : 260); + } + + if (dataPath && (!Blizzard::File::MakeAbsolutePath(dataPath, root, sizeof(root), false) || !Blizzard::File::IsDirectory(dataPath))) { + Blizzard::File::AddToLastErrorStack(0, "InitializeStreaming - Invalid data path specified", 20); + } + + if (variant && *variant) { + Blizzard::String::Copy(Blizzard::Storage::s_variantName, variant, sizeof(Blizzard::Storage::s_variantName)); + } + + if (!Blizzard::File::SetWorkingDirectory(root)) { + Blizzard::File::AddToLastErrorStack(0, "InitializeStreaming - Failed to change working directory", 20); + return false; + } + + s_paths = new PathMap(); + + bool manifestLoaded = ManifestInfo::Initialize(manifest); + s_isStreamingTrial = FileManifest::GetIsStreamingTrial(); + + if (!manifestLoaded) { + Blizzard::File::SetWorkingDirectory(cwd); + Blizzard::File::AddToLastErrorStack(0, "InitializeStreaming - Could not load manifest", 20); + return false; + } + + bool storage = true; + + if (storagePath && *storagePath) { + if (!Blizzard::Storage::Initialize(storagePath, required)) { + if (required) { + storage = false; + } else { + storage = Blizzard::Storage::Initialize(); + Blizzard::File::Delete(storagePath); + } + } + } else { + storage = Blizzard::Storage::Initialize(); + } + + if (!storage) { + Blizzard::File::SetWorkingDirectory(cwd); + Blizzard::File::AddToLastErrorStack(0, "InitializeStreaming - Could not initialize storage", 20); + return false; + } + + s_digestStates = new DigestStateMap(); + + for (int32_t i = 0; i < 7; i++) { + s_queues[i] = new std::deque(); + } + + InitializeCriticalSection(&s_queueLock); + s_queueEvent = CreateEventA(nullptr, FALSE, FALSE, nullptr); + s_throttleEvent = CreateEventA(nullptr, FALSE, FALSE, nullptr); + + for (int32_t i = 0; i < 2; i++) { + s_currentCommands[i] = nullptr; + s_threadEvents[i] = CreateEventA(nullptr, FALSE, FALSE, nullptr); + + int32_t* thread = new int32_t; + *thread = i; + Blizzard::Thread::CreateDetached(DownloadThread, thread, Blizzard::String::QuickFormat<1024>("Stream BG DL %d", i).m_buffer); + } + + s_paused = false; + InitializeCriticalSection(&s_pauseLock); + s_pauseEvent = CreateEventA(nullptr, FALSE, FALSE, nullptr); + + System_File::Stacked::PushStreaming(); + s_streamingReady = true; + + if (Blizzard::File::SetWorkingDirectory(cwd)) { + return true; + } + + Blizzard::File::AddToLastErrorStack(0, "InitializeStreaming - Failed to restore working directory", 20); + return false; +} // VERIFY: 63d60986 auto // OFFSET: 0x004294C0 @@ -100,15 +1204,15 @@ char* GetComponentVersionData(uint32_t* size) { return data; } -// VERIFY: 59db56f0 manual +// VERIFY: 406a855d manual // OFFSET: 0x0044B570 std::string Blizzard::Streaming::ResolveFilePath(const std::string& path) { - if (!unk_B38298) { + if (!s_paths) { return std::string(); } - if ((*unk_B38298)[path].size()) { - return (*unk_B38298)[path]; + if ((*s_paths)[path].size()) { + return (*s_paths)[path]; } char absolute[260]; @@ -140,11 +1244,11 @@ std::string Blizzard::Streaming::ResolveFilePath(const std::string& path) { } StringToLower(normalized); - (*unk_B38298)[path].assign(normalized, strlen(normalized)); - return std::string((*unk_B38298)[path]); + (*s_paths)[path].assign(normalized, strlen(normalized)); + return std::string((*s_paths)[path]); } -// VERIFY: 745bac15 manual +// VERIFY: 7ff06267 manual // OFFSET: 0x0044EFB0 bool Blizzard::Streaming::IsStreamedFile(const char* path) { if (!Blizzard::Streaming::s_streamingReady || !path) { @@ -153,81 +1257,57 @@ bool Blizzard::Streaming::IsStreamedFile(const char* path) { std::string resolved = Blizzard::Streaming::ResolveFilePath(std::string(path)); - if (!unk_B38174) { + if (!Blizzard::Storage::s_storage) { return false; } - return unk_B38174->find(resolved) != unk_B38174->end(); + return Blizzard::Storage::s_storage->find(resolved) != Blizzard::Storage::s_storage->end(); } -// VERIFY: 5b965645 manual -// OFFSET: 0x004508B0 -static void StopThread() { - if (unk_B3817C && unk_B38174) { - unk_B3817E = true; - SetEvent(unk_B325D8); - - while (!unk_B3817F) { - Sleep(10); - } - - CloseHandle(unk_B325D8); - DeleteCriticalSection(&unk_B325C0); - unk_B325C0.DebugInfo = nullptr; - - if (unk_B38178) { - Blizzard::File::Close(unk_B38178); - } - } - - delete unk_B38174; - unk_B38174 = nullptr; -} - -// VERIFY: a9cb82c4 manual +// VERIFY: 81ccf08c manual // OFFSET: 0x00457680 void StopStreaming() { if (Blizzard::Streaming::s_streamingReady) { - unk_B386D0.FireCallback(); - unk_B38182 = true; - SetEvent(unk_B325DC); - SetEvent(unk_B3252C); - unk_B325B8 = false; - SetEvent(unk_B32550); + Blizzard::Streaming::s_progress.FireCallback(); + s_stopThreads = true; + SetEvent(s_queueEvent); + SetEvent(s_throttleEvent); + s_paused = false; + SetEvent(s_pauseEvent); - while (unk_B38184 > 0) { + while (s_threadMask > 0) { Sleep(10); } - CloseHandle(unk_B325DC); - CloseHandle(unk_B3252C); + CloseHandle(s_queueEvent); + CloseHandle(s_throttleEvent); - for (uint32_t i = 0; i < sizeof(unk_B32548) / sizeof(unk_B32548[0]); i++) { - CloseHandle(unk_B32548[i]); - delete unk_B32554[i]; + for (uint32_t i = 0; i < sizeof(s_threadEvents) / sizeof(s_threadEvents[0]); i++) { + CloseHandle(s_threadEvents[i]); + delete s_currentCommands[i]; } - DeleteCriticalSection(&unk_B32530); - unk_B32530.DebugInfo = nullptr; - CloseHandle(unk_B32550); - DeleteCriticalSection(&unk_B325A0); - unk_B325A0.DebugInfo = nullptr; + DeleteCriticalSection(&s_queueLock); + s_queueLock.DebugInfo = nullptr; + CloseHandle(s_pauseEvent); + DeleteCriticalSection(&s_pauseLock); + s_pauseLock.DebugInfo = nullptr; - delete unk_B38294; + delete s_digestStates; - for (uint32_t i = 0; i < sizeof(unk_B3255C) / sizeof(unk_B3255C[0]); i++) { - delete unk_B3255C[i]; + for (uint32_t i = 0; i < sizeof(s_queues) / sizeof(s_queues[0]); i++) { + delete s_queues[i]; } - delete unk_B38298; - unk_B38298 = nullptr; + delete s_paths; + s_paths = nullptr; Blizzard::Streaming::s_streamingReady = false; } - StopThread(); + Blizzard::Storage::Shutdown(); - delete unk_B38170; - unk_B38170 = nullptr; + delete Blizzard::Streaming::ManifestInfo::s_instance; + Blizzard::Streaming::ManifestInfo::s_instance = nullptr; } #endif diff --git a/Engine/Source/BlizzardCore/Source/Packages/Streaming/Win32/Transport.cpp b/Engine/Source/BlizzardCore/Source/Packages/Streaming/Win32/Transport.cpp new file mode 100644 index 0000000..3d03032 --- /dev/null +++ b/Engine/Source/BlizzardCore/Source/Packages/Streaming/Win32/Transport.cpp @@ -0,0 +1,583 @@ +#if defined(WOWDECOMP_ARCH_32) + +#include +#include +#include +#include +#include +#include +#include "Engine/Source/BlizzardCore/Include/Blizzard/Util/Digest.h" +#include "Engine/Source/BlizzardCore/Include/Blizzard/Util/MD5.h" +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Manifests.h" +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Streaming.h" +#include "Engine/Source/BlizzardCore/Source/System/Debug/ErrorStack.h" +#include "Engine/Source/BlizzardCore/Source/System/File/File.h" +#include "Engine/Source/BlizzardCore/Source/System/Log/Log.h" +#include "Engine/Source/BlizzardCore/Source/System/String/String.h" +#include "Engine/Source/BlizzardCore/Source/System/Time/Time.h" +#include "Engine/Source/BlizzardCore/Source/System/URL/URL.h" + +// STATIC: 0x00AB909E +static bool s_transportShouldBlock = true; + +// STATIC: 0x00AB91B8 +static double s_throttleScale = 0.0085; + +// STATIC: 0x00AB923C +static uint32_t s_transportTimeout = 10000; + +// STATIC: 0x00AB9390 +static std::string s_cookieName; + +// STATIC: 0x00AB93AC +static std::string s_cookieValue; + +// STATIC: 0x00B38028 +static int64_t s_throttleBias; + +// STATIC: 0x00B38030 +static int64_t s_throttleDebt; + +// VERIFY: 2d297ed5 auto +// OFFSET: 0x00427DE0 +int32_t Blizzard::Streaming::Transport::AdjustRange(int64_t* start, int64_t* end, int32_t md5Size, int64_t fileSize) { + int64_t alignedStart = *start - *start % md5Size; + int64_t alignedEnd = md5Size + *end - (md5Size + *end) % md5Size - 1; + int64_t firstChunk = alignedStart / md5Size; + int64_t lastChunk = (alignedEnd + 1) / md5Size - 1; + + if (alignedEnd > fileSize) { + alignedEnd = fileSize - 1; + } + + int32_t skip = static_cast(32 * firstChunk); + int64_t original = *start; + *start = skip + alignedStart; + *end = alignedEnd + 32 * (lastChunk + 1); + + return static_cast(skip + original - *start); +} + +// VERIFY: 94166980 manual +// OFFSET: 0x0042D650 +void Blizzard::Streaming::TransportHttpCallback::Completed(Blizzard::URL::DownloadCallback::Status status) { + this->m_status = status; + + switch (status) { + case Blizzard::URL::DownloadCallback::DOWNLOAD_SUCCESS: + case Blizzard::URL::DownloadCallback::DOWNLOAD_STOPPED: + this->m_success = true; + break; + + case Blizzard::URL::DownloadCallback::DOWNLOAD_FAILED: + case Blizzard::URL::DownloadCallback::DOWNLOAD_TIMEOUT: + case Blizzard::URL::DownloadCallback::DOWNLOAD_NOT_FOUND: + case Blizzard::URL::DownloadCallback::DOWNLOAD_NOT_MODIFIED: + case Blizzard::URL::DownloadCallback::DOWNLOAD_ABORTED: + case Blizzard::URL::DownloadCallback::DOWNLOAD_FORBIDDEN: + case Blizzard::URL::DownloadCallback::DOWNLOAD_NAME_NOT_RESOLVED: + case Blizzard::URL::DownloadCallback::DOWNLOAD_CANNOT_CONNECT: + case Blizzard::URL::DownloadCallback::DOWNLOAD_BAD_REQUEST: + case Blizzard::URL::DownloadCallback::DOWNLOAD_UNKNOWN_ERROR: + this->m_success = false; + break; + } + + SetEvent(this->m_event); +} + +// VERIFY: b569e14e manual +// OFFSET: 0x00437920 +void Blizzard::Streaming::Transport::THROTTLE::Wait() { + int64_t delta = s_throttleBias + this->m_start + static_cast(this->m_bytes * s_throttleScale) - Blizzard::Time::GetTimestamp(); + s_throttleDebt += delta; + + if (s_throttleDebt < 0 || s_throttleDebt <= 1000000) { + return; + } + + do { + Blizzard::Time::Timestamp start = Blizzard::Time::GetTimestamp(); + int64_t milliseconds = s_throttleDebt / 1000000; + int32_t sleep = milliseconds <= 100 ? static_cast(milliseconds) : 100; + + if (sleep > 0) { + Sleep(sleep); + } + + s_throttleDebt += start - Blizzard::Time::GetTimestamp(); + } while (s_throttleDebt > 1000000); +} + +// VERIFY: 06dc0fd3 manual +// OFFSET: 0x00437AD0 +Blizzard::Streaming::TransportHttpCallback::~TransportHttpCallback() { + CloseHandle(this->m_event); +} + +// VERIFY: 183aa510 manual +// OFFSET: 0x00437B50 +int32_t Blizzard::Streaming::TransportHttpCallback::GetTimeout() { + return this->m_timeout; +} + +// VERIFY: cc5e6cdc manual +// OFFSET: 0x00437B60 +Blizzard::URL::DownloadCallback::ByteRange Blizzard::Streaming::TransportHttpCallback::GetByteRange() { + ByteRange range; + range.m_start = this->m_rangeStart; + range.m_end = this->m_rangeEnd; + return range; +} + +// VERIFY: 13e9ae9f auto +// OFFSET: 0x00437B90 +bool Blizzard::Streaming::TransportHttpCallback::ShouldBlock() { + return s_transportShouldBlock; +} + +// VERIFY: 430f3437 manual +// OFFSET: 0x00437BA0 +void Blizzard::Streaming::TransportHttpCallback::SetByteRange(int64_t start, int64_t end) { + this->m_rangeStart = start; + this->m_rangeEnd = end; +} + +// VERIFY: 5cef936b manual +// OFFSET: 0x00437BC0 +void Blizzard::Streaming::TransportHttpCallback::SetTimeOutValue(uint32_t timeout) { + this->m_timeout = timeout; +} + +// VERIFY: b0731063 manual +// OFFSET: 0x00437BD0 +bool Blizzard::Streaming::TransportHttpCallback::Stop() { + return this->m_stop; +} + +// VERIFY: f43a911d manual +// OFFSET: 0x00437BE0 +Blizzard::URL::DownloadCallback::Cookie Blizzard::Streaming::TransportHttpCallback::GetCookie() { + Cookie cookie; + cookie.m_name = this->m_cookieName.c_str(); + cookie.m_value = this->m_cookieValue.c_str(); + return cookie; +} + +// VERIFY: 89b5f39c manual +// OFFSET: 0x00437C20 +bool Blizzard::Streaming::Transport::ReadFile(Manifests::TransportItem* transport, std::string url, int32_t maxRetry, void* data, int64_t fileSize, int64_t offset, int32_t size) { + Blizzard::File::StreamRecord* file; + + if (!Blizzard::File::Open(url.c_str() + 7, 4101, file)) { + return false; + } + + int32_t count = size; + + if (Blizzard::File::Read(file, data, offset, &count) && count == size) { + Blizzard::File::Close(file); + return true; + } + + Blizzard::File::Close(file); + return false; +} + +// VERIFY: d39315a5 manual +// OFFSET: 0x00439B20 +Blizzard::Streaming::TransportHttpCallback::TransportHttpCallback(uint32_t size) { + this->m_cookieName.erase(this->m_cookieName.begin(), this->m_cookieName.end()); + this->m_cookieValue.erase(this->m_cookieValue.begin(), this->m_cookieValue.end()); + this->m_data.reserve(size); + this->m_data.erase(this->m_data.begin(), this->m_data.end()); + this->m_received = 0; + this->m_rangeStart = 0; + this->m_rangeEnd = 0; + this->m_timeout = s_transportTimeout; + this->m_stop = false; + this->m_success = false; + this->m_event = CreateEventA(nullptr, FALSE, FALSE, nullptr); +} + +// VERIFY: 061834c0 manual +// OFFSET: 0x0043ABD0 +void Blizzard::Streaming::TransportHttpCallback::SetCookie(const char* name, const char* value) { + this->m_cookieName.assign(name, strlen(name)); + this->m_cookieValue.assign(value, strlen(value)); +} + +// VERIFY: 900064c1 manual +// OFFSET: 0x0043AC20 +bool Blizzard::Streaming::TransportHttpCallback::ReceivedData(const void* data, int32_t size) { + if (this->m_received >= this->m_rangeEnd - this->m_rangeStart + 1) { + this->m_stop = true; + } + + if (size <= 0) { + return true; + } + + int64_t left = this->m_rangeEnd - this->m_rangeStart - this->m_received + 1; + int32_t take = size >= left ? static_cast(left) : size; + + this->m_data.append(static_cast(data), take); + this->m_received += take; + + if (take != size) { + this->m_stop = true; + } + + return true; +} + +// VERIFY: 9c8ee2ca manual +// OFFSET: 0x0043D7B0 +Blizzard::Streaming::URL_INFO::URL_INFO(std::string url, int64_t start, int64_t end, int32_t size) { + this->m_start = start; + this->m_end = end; + this->m_size = size; + this->m_url = url; +} + +// VERIFY: f7a8aa98 manual +// OFFSET: 0x0043D840 +bool Blizzard::Streaming::Transport::MD5_Data(std::string* out, std::string* data, int32_t md5Size, int64_t start, int64_t end) { + bool result = false; + + std::string chunk; + chunk.reserve(static_cast(end - start + 1)); + + out->reserve(data->size()); + out->erase(out->begin(), out->end()); + + std::string hash; + hash.reserve(32); + + uint32_t position = 0; + uint32_t consumed = 0; + + if (data->size()) { + uint32_t hashOffset = 0; + uint32_t blockEnd = md5Size; + + for (;;) { + chunk.erase(chunk.begin(), chunk.end()); + + uint32_t length = md5Size; + uint32_t next = position + md5Size + 32; + + if (next > data->size()) { + length = data->size() - position - 32; + } + + chunk = data->substr(position, length); + consumed += length + 32; + out->append(chunk); + + hash.erase(hash.begin(), hash.end()); + + uint32_t hashPosition = blockEnd + hashOffset; + + if (blockEnd + hashOffset + 32 > data->size()) { + hashPosition = data->size() - 32; + } + + Blizzard::Util::Digest<16> expected; + expected.FromHexString(data->substr(hashPosition, 32).c_str()); + + Blizzard::Util::MD5 md5; + md5.Process(chunk.c_str(), chunk.size()); + + Blizzard::Util::Digest<16> actual; + md5.Finish(actual.m_data); + + result = actual == expected; + + if (!result) { + break; + } + + blockEnd += md5Size; + hashOffset += 32; + position = next; + + if (consumed >= data->size()) { + break; + } + } + } + + return result; +} + +// VERIFY: 1447d6ad manual +// OFFSET: 0x00452320 +void Blizzard::Streaming::Transport::GetSplitFileURL(const std::string& url, int64_t start, int64_t end, int32_t skip, int32_t splitSize, int32_t md5Size, int32_t size, std::vector* urls) { + if (md5Size) { + splitSize += 32 * (splitSize / md5Size); + } + + int64_t first = start / splitSize; + int64_t firstOffset = start % splitSize; + int64_t last = (end - 1) / splitSize; + int32_t previous = 0; + + if (first != last) { + Blizzard::Log::Printf(3, "Logs/Profiling_MPQSplit.log", "Got split %s, %d-d\n", url.c_str(), start, end); + } + + if (first > last) { + return; + } + + int64_t lastOffset = end % splitSize; + + for (int64_t chunk = first; chunk <= last; chunk++) { + int64_t chunkStart = chunk == first ? firstOffset : 0; + int64_t chunkEnd = lastOffset; + + if (lastOffset < chunkStart) { + chunkEnd = splitSize - 1; + } + + int64_t length = chunkEnd - chunkStart + 1; + int32_t blocks = static_cast(length / (md5Size + 32)); + + if (length % (md5Size + 32)) { + blocks++; + } + + int32_t chunkSize; + + if (chunk == first) { + chunkSize = static_cast(chunkEnd - 32 * blocks - chunkStart - skip + 1); + } else { + chunkSize = size - previous; + } + + previous = chunkSize; + + char number[260]; + sprintf(number, "%d", static_cast(chunk)); + + std::string chunkUrl = url; + chunkUrl.append(".", 1); + chunkUrl.append(number, strlen(number)); + + urls->push_back(URL_INFO(std::string(chunkUrl), chunkStart, chunkEnd, chunkSize)); + } +} + +// VERIFY: fc935412 manual +// OFFSET: 0x00455F10 +bool Blizzard::Streaming::Transport::ReadHttp(Manifests::TransportItem* transport, std::string url, int32_t maxRetry, void* data, int64_t fileSize, int64_t offset, int32_t size) { + int32_t error = 0; + + TransportHttpCallback* callback = new TransportHttpCallback(size); + + std::string baseUrl = url; + int64_t start = offset; + int64_t end = offset + size - 1; + int32_t skip = 0; + std::vector urls; + + if (transport) { + skip = AdjustRange(&start, &end, transport->m_md5Size, fileSize); + + if (skip) { + printf("offset is %d\n", skip); + } + + if (transport->m_splitSize > 0) { + GetSplitFileURL(baseUrl, start, end, skip, transport->m_splitSize, transport->m_md5Size, size, &urls); + } + } else { + urls.push_back(URL_INFO(std::string(baseUrl), offset, offset + size - 1, size)); + } + + bool result = false; + int32_t copied = 0; + + for (uint32_t i = 0; i < urls.size(); i++) { + result = false; + + std::string current = urls[i].m_url; + int64_t rangeStart = urls[i].m_start; + int64_t rangeEnd = urls[i].m_end; + int32_t rangeSize = urls[i].m_size; + + callback->m_data.erase(callback->m_data.begin(), callback->m_data.end()); + callback->m_received = 0; + callback->m_stop = false; + callback->m_success = false; + callback->SetByteRange(rangeStart, rangeEnd); + + if (s_cookieName.size() && s_cookieValue.size()) { + callback->SetCookie(s_cookieName.c_str(), s_cookieValue.c_str()); + } + + std::string checked; + + for (int32_t attempt = 0; attempt < maxRetry; attempt++) { + if (attempt) { + s_statRetries++; + } + + result = Blizzard::URL::DownloadURL(current.c_str(), callback); + + if (!result) { + error = 1; + Sleep(10); + } else { + WaitForSingleObject(callback->m_event, INFINITE); + result = callback->m_success; + + if (!result) { + error = 3; + Sleep(10); + } else if (rangeEnd - rangeStart + 1 != callback->m_data.size()) { + result = false; + error = 2; + } else { + result = true; + + if (transport) { + result = MD5_Data(&checked, &callback->m_data, transport->m_md5Size, rangeStart, rangeEnd); + + if (!result) { + error = 4; + } + } + } + } + + if (result) { + break; + } + + callback->m_data.erase(callback->m_data.begin(), callback->m_data.end()); + callback->m_received = 0; + callback->m_stop = false; + callback->m_success = false; + + if (callback->m_status == Blizzard::URL::DownloadCallback::DOWNLOAD_TIMEOUT) { + callback->SetTimeOutValue(2 * callback->GetTimeout()); + } + } + + if (!result) { + continue; + } + + if (transport) { + memmove(static_cast(data) + copied, checked.c_str() + skip, rangeSize); + } else { + memmove(data, callback->m_data.c_str(), size); + } + + copied += rangeSize; + } + + if (result && copied != size) { + error = 5; + result = false; + } + + if (!result) { + const char* message; + + switch (error) { + case 1: + message = "DownloadURL failed with no error"; + break; + + case 2: + message = "Downloaded smaller than expected"; + break; + + case 3: + if (callback->m_status == Blizzard::URL::DownloadCallback::DOWNLOAD_TIMEOUT) { + message = "DownloadURL failed - Timed out"; + } else if (callback->m_status == Blizzard::URL::DownloadCallback::DOWNLOAD_NOT_FOUND) { + message = "DownloadURL failed - File not found"; + } else { + message = "DownloadURL failed"; + } + + break; + + case 4: + message = "MD5 check failed"; + break; + + case 5: + message = "Copied smaller than expected"; + break; + + default: + message = "Unknown error"; + break; + } + + Blizzard::Log::Printf(3, "Logs/Streaming_Error.log", "%d - %s - %s\n", callback->m_status, message, url.c_str()); + + Blizzard::String::QuickFormat<1024> text("%s - %s", message, url.c_str()); + System_File::FileError& fileError = System_File::s_error; + Blizzard::Debug::ErrorStackRecord* stack = Blizzard::Debug::AddErrorToStack(fileError.m_errorStack, callback->m_status, text.m_buffer, 21); + + if (stack) { + System_File::FileError& current = System_File::s_error; + + if (current.m_errorStack != stack) { + Blizzard::Debug::FreeErrorStack(current.m_errorStack); + } + + current.m_errorStack = stack; + } + } + + if (callback) { + delete callback; + } + + return result; +} + +// VERIFY: 9f47312a manual +// OFFSET: 0x004592B0 +bool Blizzard::Streaming::Transport::Read(Manifests::TransportItem* transport, std::string url, int32_t maxRetry, void* data, int64_t fileSize, int64_t offset, int32_t size) { + struct Handler { + const char* m_prefix; + bool (*m_read)(Manifests::TransportItem*, std::string, int32_t, void*, int64_t, int64_t, int32_t); + }; + + Handler handlers[3] = { + { "file://", ReadFile }, + { "http://", ReadHttp }, + { nullptr, nullptr } + }; + + bool result = false; + + for (Handler* handler = handlers; handler->m_prefix; handler++) { + if (url.c_str() && !_strnicmp(url.c_str(), handler->m_prefix, strlen(handler->m_prefix))) { + THROTTLE throttle; + throttle.m_bytes = 0; + throttle.m_start = Blizzard::Time::GetTimestamp(); + + result = handler->m_read(transport, std::string(url), maxRetry, data, fileSize, offset, size); + + if (result) { + throttle.m_bytes = size; + } + + throttle.Wait(); + break; + } + } + + return result; +} + +#endif diff --git a/Engine/Source/BlizzardCore/Source/Packages/Streaming/Win64/Manifests.cpp b/Engine/Source/BlizzardCore/Source/Packages/Streaming/Win64/Manifests.cpp new file mode 100644 index 0000000..54c85d5 --- /dev/null +++ b/Engine/Source/BlizzardCore/Source/Packages/Streaming/Win64/Manifests.cpp @@ -0,0 +1,217 @@ +#if defined(WOWDECOMP_ARCH_64) + +#include +#include +#include +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Manifests.h" +#include "Engine/Source/BlizzardCore/Source/System/File/File.h" +#include "Engine/Source/BlizzardCore/Source/System/String/String.h" + +// OFFSET: 0x0042E100 +void System_Streaming::HttpCallback::Completed(Blizzard::URL::DownloadCallback::Status status) { + this->m_status = status; + SetEvent(this->m_event); +} + +// OFFSET: 0x00439ED0 +System_Streaming::HttpCallback::HttpCallback() { + this->m_data.reserve(1024); + this->m_data.erase(this->m_data.begin(), this->m_data.end()); + this->m_received = 0; + this->m_status = Blizzard::URL::DownloadCallback::DOWNLOAD_SUCCESS; + this->m_timeout = 3000; + this->m_event = CreateEventA(nullptr, FALSE, FALSE, nullptr); +} + +// OFFSET: 0x00439F80 +System_Streaming::HttpCallback::~HttpCallback() { + CloseHandle(this->m_event); +} + +// OFFSET: 0x004567A0 +bool Blizzard::Streaming::FileManifest::ReadIndirectFile(const char* url) { + System_Streaming::HttpCallback* callback = new System_Streaming::HttpCallback(); + + bool result = false; + uint32_t attempt = 0; + + while (attempt < 5) { + result = Blizzard::URL::DownloadURL(url, callback); + + if (result) { + WaitForSingleObject(callback->m_event, INFINITE); + + if (callback->m_status) { + result = false; + } + } + + if (!result) { + callback->m_data.erase(callback->m_data.begin(), callback->m_data.end()); + callback->m_received = 0; + + if (callback->m_status == Blizzard::URL::DownloadCallback::DOWNLOAD_TIMEOUT) { + callback->SetTimeOutValue(2 * callback->GetTimeout()); + } + } + + attempt++; + + if (result) { + result = ReadDirectFileFromBuffer(const_cast(callback->m_data.c_str()), callback->m_data.size()); + delete callback; + return result; + } + } + + if (callback->m_status) { + Blizzard::File::AddToLastErrorStack(callback->m_status, Blizzard::String::QuickFormat<1024>("FileManifest::ReadIndirectFile - DownloadURL failed - %s", url).m_buffer, 20); + } else { + Blizzard::File::AddToLastErrorStack(0, "FileManifest::ReadIndirectFile - DownloadURL failed with no error", 20); + } + + delete callback; + return result; +} + +// OFFSET: 0x00459050 +bool Blizzard::Streaming::Transport::ReadIndirectFile(const char* url) { + System_Streaming::HttpCallback* callback = new System_Streaming::HttpCallback(); + + bool result = false; + uint32_t attempt = 0; + + while (attempt < 5) { + result = Blizzard::URL::DownloadURL(url, callback); + + if (result) { + WaitForSingleObject(callback->m_event, INFINITE); + + if (callback->m_status) { + result = false; + } + } + + if (!result) { + callback->m_data.erase(callback->m_data.begin(), callback->m_data.end()); + callback->m_received = 0; + + if (callback->m_status == Blizzard::URL::DownloadCallback::DOWNLOAD_TIMEOUT) { + callback->SetTimeOutValue(2 * callback->GetTimeout()); + } + } + + attempt++; + + if (result) { + result = ReadDirectFileFromBuffer(const_cast(callback->m_data.c_str()), callback->m_data.size()); + delete callback; + return result; + } + } + + if (callback->m_status) { + Blizzard::File::AddToLastErrorStack(callback->m_status, Blizzard::String::QuickFormat<1024>("Transport::ReadIndirectFile - DownloadURL failed - %s", url).m_buffer, 20); + Blizzard::File::AddToLastErrorStack(callback->m_status, "Failed to load transport manifest.", 20); + } else { + Blizzard::File::AddToLastErrorStack(0, "Transport::ReadIndirectFile - DownloadURL failed", 20); + } + + delete callback; + return result; +} + +// OFFSET: 0x00459400 +bool Blizzard::Streaming::SourceManifest::ReadIndirectFile(const char* url) { + System_Streaming::HttpCallback* callback = new System_Streaming::HttpCallback(); + + bool result = false; + uint32_t attempt = 0; + + while (attempt < 5) { + result = Blizzard::URL::DownloadURL(url, callback); + + if (result) { + WaitForSingleObject(callback->m_event, INFINITE); + + if (callback->m_status) { + result = false; + } + } + + if (!result) { + callback->m_data.erase(callback->m_data.begin(), callback->m_data.end()); + callback->m_received = 0; + + if (callback->m_status == Blizzard::URL::DownloadCallback::DOWNLOAD_TIMEOUT) { + callback->SetTimeOutValue(2 * callback->GetTimeout()); + } + } + + attempt++; + + if (result) { + result = ReadDirectFileFromBuffer(const_cast(callback->m_data.c_str()), callback->m_data.size()); + delete callback; + return result; + } + } + + if (callback->m_status) { + Blizzard::File::AddToLastErrorStack(callback->m_status, Blizzard::String::QuickFormat<1024>("SourceManifest::ReadIndirectFile - DownloadURL failed - %s", url).m_buffer, 20); + Blizzard::File::AddToLastErrorStack(callback->m_status, "Failed to load source manifest.", 20); + } else { + Blizzard::File::AddToLastErrorStack(0, "SourceManifest::ReadIndirectFile - DownloadURL failed", 20); + } + + delete callback; + return result; +} + +// OFFSET: 0x00461430 +bool Blizzard::Streaming::ManifestInfo::ReadIndirectFile(const char* url) { + System_Streaming::HttpCallback* callback = new System_Streaming::HttpCallback(); + + bool result = false; + uint32_t attempt = 0; + + while (attempt < 5) { + result = Blizzard::URL::DownloadURL(url, callback); + + if (result) { + WaitForSingleObject(callback->m_event, INFINITE); + + if (callback->m_status) { + result = false; + } + } + + if (!result) { + callback->m_data.erase(callback->m_data.begin(), callback->m_data.end()); + callback->m_received = 0; + + if (callback->m_status == Blizzard::URL::DownloadCallback::DOWNLOAD_TIMEOUT) { + callback->SetTimeOutValue(2 * callback->GetTimeout()); + } + } + + attempt++; + + if (result) { + result = this->ReadDirectFileFromBuffer(const_cast(callback->m_data.c_str()), callback->m_data.size()); + delete callback; + return result; + } + } + + if (callback->m_status) { + Blizzard::File::AddToLastErrorStack(callback->m_status, Blizzard::String::QuickFormat<1024>("FileManifest::ReadIndirectFile - DownloadURL failed - %s", url).m_buffer, 20); + } else { + Blizzard::File::AddToLastErrorStack(0, "FileManifest::ReadIndirectFile - DownloadURL failed with no error", 20); + } + + delete callback; + return result; +} + +#endif diff --git a/Engine/Source/BlizzardCore/Source/Packages/Streaming/Win64/Storage.cpp b/Engine/Source/BlizzardCore/Source/Packages/Streaming/Win64/Storage.cpp new file mode 100644 index 0000000..6ef5eb4 --- /dev/null +++ b/Engine/Source/BlizzardCore/Source/Packages/Streaming/Win64/Storage.cpp @@ -0,0 +1,1245 @@ +#if defined(WOWDECOMP_ARCH_64) + +#include +#include +#include +#include +#include +#include +#include +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Storage.h" +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Streaming.h" +#include "Engine/Source/BlizzardCore/Source/System/File/File.h" +#include "Engine/Source/BlizzardCore/Source/System/File/Filestack.h" +#include "Engine/Source/BlizzardCore/Source/System/Log/Log.h" +#include "Engine/Source/BlizzardCore/Source/System/Memory/MemoryStorm.h" +#include "Engine/Source/BlizzardCore/Source/System/String/String.h" +#include "Engine/Source/BlizzardCore/Source/System/Thread/Thread.h" + +// STATIC: 0x00AB909F +bool Blizzard::Storage::s_usePartFiles = true; + +// STATIC: 0x00AB92BC +int32_t Blizzard::Storage::s_blockSize = 0x4000; + +// STATIC: 0x00AB93CC +std::string Blizzard::Storage::s_storagePath; + +// STATIC: 0x00B325C0 +Blizzard::Lock::Mutex Blizzard::Storage::s_storageLock; + +// STATIC: 0x00B325D8 +void* Blizzard::Storage::s_storageEvent; + +// STATIC: 0x00B38174 +std::map* Blizzard::Storage::s_storage; + +// STATIC: 0x00B38178 +Blizzard::File::StreamRecord* Blizzard::Storage::s_storageFile; + +// STATIC: 0x00B3817C +bool Blizzard::Storage::s_storageReady; + +// STATIC: 0x00B3817D +bool Blizzard::Storage::s_storageDirty; + +// STATIC: 0x00B3817E +volatile bool Blizzard::Storage::s_storageStop; + +// STATIC: 0x00B3817F +volatile bool Blizzard::Storage::s_storageStopped; + +// STATIC: 0x00B3834C +std::deque Blizzard::Storage::s_writeQueue; + +// OFFSET: 0x00427F50 +int32_t Blizzard::Storage::GetBlockLength(Blizzard::Streaming::StorageEntry* entry, int32_t block) { + int32_t blockSize = entry->m_blockSize; + + if (entry->m_size <= (block + 1LL) * blockSize) { + return static_cast(entry->m_size - static_cast(block) * blockSize); + } + + return entry->m_blockSize; +} + +// OFFSET: 0x00427FB0 +int32_t Blizzard::Storage::CountRanges(Blizzard::Streaming::StorageEntry* entry, int64_t offset, int64_t size) { + return static_cast((size + offset) / entry->m_blockSize - offset / entry->m_blockSize + 4); +} + +// OFFSET: 0x0042CEF0 +bool Blizzard::Storage::ReadAt(Blizzard::File::Filesystem* fs, Blizzard::File::StreamRecord* file, void* buffer, int64_t offset, int32_t size) { + return Blizzard::File::Read(fs, file, buffer, offset, &size); +} + +// OFFSET: 0x0042CF20 +bool Blizzard::Storage::WriteAt(Blizzard::File::StreamRecord* file, const void* buffer, int64_t offset, int32_t size) { + return Blizzard::File::Write(file, buffer, offset, &size); +} + +// OFFSET: 0x0042D820 +bool Blizzard::Storage::IsComplete(Blizzard::Streaming::StorageEntry* entry) { + for (int32_t i = 0; i < static_cast(entry->m_blocks.size()); i++) { + if (entry->m_blocks[i].m_state != 3) { + return false; + } + } + + return true; +} + +// OFFSET: 0x0042D880 +int32_t Blizzard::Storage::BuildRanges(Blizzard::Streaming::StorageEntry* entry, int64_t offset, int32_t size, Blizzard::Streaming::LoadRange* ranges) { + int64_t position = offset; + uint32_t block = static_cast(offset / entry->m_blockSize); + int32_t count = 0; + + for (int32_t phase = 1; size && phase <= 3; phase++) { + if (phase == 2) { + int32_t full = entry->m_blockSize * (size / entry->m_blockSize); + + while (full >= entry->m_blockSize) { + int32_t state = entry->m_blocks[block].m_state; + Blizzard::Streaming::LoadRange& range = ranges[count]; + + switch (state) { + case 0: + case 1: + count++; + range.m_offset = position; + range.m_blockOffset = position; + range.m_size = entry->m_blockSize; + range.m_blockSize = entry->m_blockSize; + range.m_state = 3 - (state != 1); + break; + + case 2: + case 3: + case 4: + count++; + range.m_size = entry->m_blockSize; + range.m_offset = static_cast(block) * entry->m_blockSize; + range.m_blockOffset = 0; + range.m_blockSize = 0; + range.m_state = state == 4; + break; + } + + block++; + size -= entry->m_blockSize; + position += entry->m_blockSize; + full -= entry->m_blockSize; + } + + continue; + } + + int64_t blockStart = static_cast(block) * entry->m_blockSize; + + if (phase == 1 && position == blockStart) { + continue; + } + + int32_t inner = static_cast(position - blockStart); + int32_t length = GetBlockLength(entry, block); + int32_t state = entry->m_blocks[block].m_state; + int32_t available = length - inner; + int32_t take = size >= available ? available : size; + + switch (state) { + case 0: + case 1: { + Blizzard::Streaming::LoadRange& range = ranges[count++]; + size -= take; + range.m_offset = position; + range.m_blockOffset = blockStart; + range.m_size = take; + range.m_blockSize = length; + range.m_state = 3 - (state != 1); + break; + } + + case 2: + case 3: + case 4: { + Blizzard::Streaming::LoadRange& range = ranges[count++]; + range.m_offset = inner + entry->m_blockSize * static_cast(block); + size -= take; + range.m_size = take; + range.m_blockOffset = 0; + range.m_blockSize = 0; + range.m_state = state == 4; + break; + } + } + + block++; + position += entry->m_blockSize - inner; + } + + return count; +} + +// OFFSET: 0x0042DB80 +int32_t Blizzard::Storage::BuildRangesFromStore(Blizzard::Streaming::StorageEntry* entry, int64_t offset, int32_t size, Blizzard::Streaming::LoadRange* ranges) { + int64_t start = entry->m_storeSize >= offset ? offset : entry->m_storeSize; + int32_t count = 0; + + if (start / entry->m_blockSize < offset / entry->m_blockSize) { + count = BuildRanges(entry, entry->m_storeSize, static_cast(offset / entry->m_blockSize * entry->m_blockSize - entry->m_storeSize), ranges); + + for (int32_t i = 0; i < count; i++) { + ranges[i].m_state = 4; + } + } + + return count + BuildRanges(entry, offset, size, ranges + count); +} + +// OFFSET: 0x0042DC70 +int32_t Blizzard::Storage::BuildRangesWithHeader(Blizzard::Streaming::StorageEntry* entry, int64_t offset, int32_t size, Blizzard::Streaming::LoadRange* ranges) { + if (entry->m_blocks[0].m_state == 3) { + return BuildRanges(entry, offset, size, ranges); + } + + if (entry->m_blocks[0].m_state == 2) { + return BuildRanges(entry, offset, size, ranges); + } + + int32_t total = static_cast(entry->m_size / entry->m_blockSize + 1); + int32_t first = static_cast(offset / entry->m_blockSize); + int32_t head = 0; + + if (first > 0) { + head = first; + + for (int32_t i = 0; i < first; i++) { + Blizzard::Streaming::LoadRange& range = ranges[i]; + int32_t length = GetBlockLength(entry, i); + range.m_offset = 0; + range.m_size = 0; + range.m_blockOffset = static_cast(i) * entry->m_blockSize; + range.m_blockSize = length; + range.m_state = 4; + } + } + + int32_t count = BuildRanges(entry, offset, size, ranges + head) + head; + int32_t next = static_cast((offset + size - 1) / entry->m_blockSize + 1); + + if (next < total) { + Blizzard::Streaming::LoadRange* range = &ranges[count]; + count += total - next; + + for (; next < total; next++, range++) { + int64_t end = (next + 1LL) * entry->m_blockSize; + int32_t length = entry->m_size <= end ? static_cast(entry->m_size - static_cast(next) * entry->m_blockSize) : entry->m_blockSize; + + range->m_offset = 0; + range->m_size = 0; + range->m_blockOffset = static_cast(next) * entry->m_blockSize; + range->m_blockSize = length; + range->m_state = 4; + } + } + + return count; +} + +// OFFSET: 0x0042DE70 +bool Blizzard::Storage::RequestRange(Blizzard::Streaming::StorageEntry* entry, int64_t offset, int32_t size, int32_t state) { + EnterCriticalSection(&s_storageLock); + + if (entry->m_closed) { + LeaveCriticalSection(&s_storageLock); + return false; + } + + int64_t blockSize = entry->m_blockSize; + int32_t last = static_cast((offset + size - 1) / blockSize); + + for (uint32_t block = static_cast(offset / blockSize); static_cast(block) <= last; block++) { + Blizzard::Streaming::StorageBlock& storageBlock = entry->m_blocks[block]; + + if (state != 1 || (storageBlock.m_state != 2 && storageBlock.m_state != 3)) { + storageBlock.m_state = state; + } + } + + LeaveCriticalSection(&s_storageLock); + return true; +} + +// OFFSET: 0x0042DF70 +void Blizzard::Storage::SetRangeAs(Blizzard::Streaming::StorageEntry* entry, int64_t offset, int32_t size, int32_t state) { + int32_t first = static_cast(offset / entry->m_blockSize); + int32_t last = size <= 0 ? first : static_cast((offset + size - 1) / entry->m_blockSize); + + EnterCriticalSection(&s_storageLock); + + for (uint32_t block = first; static_cast(block) <= last; block++) { + entry->m_blocks[block].m_state = state; + } + + LeaveCriticalSection(&s_storageLock); +} + +// OFFSET: 0x00432530 +Blizzard::Storage::StorageEntryRef::StorageEntryRef(Blizzard::Streaming::StorageEntry* entry) { + EnterCriticalSection(&s_storageLock); + + if (!entry || entry->m_released) { + LeaveCriticalSection(&s_storageLock); + this->m_entry = nullptr; + return; + } + + entry->m_refCount++; + LeaveCriticalSection(&s_storageLock); + this->m_entry = entry; +} + +// OFFSET: 0x004327D0 +bool Blizzard::Storage::WriteIndexEntry(Blizzard::Streaming::StorageEntry* entry, int32_t block, bool header) { + if (!s_storageReady) { + return false; + } + + if (entry->m_flags & 4) { + return true; + } + + if (!header) { + int32_t amount = 8; + Blizzard::File::Write(s_storageFile, &entry->m_storeSize, entry->m_headerOffset + 305, &amount); + + if (block >= 0 && block < static_cast(entry->m_blocks.size())) { + Blizzard::Streaming::StorageBlockRecord record; + record.m_state = entry->m_blocks[block].m_state; + record.m_offset = entry->m_blocks[block].m_offset; + record.m_storeOffset = entry->m_blocks[block].m_storeOffset; + record.m_size = entry->m_blocks[block].m_size; + + WriteAt(s_storageFile, &record, entry->m_headerOffset + 24LL * block + 321, 24); + } + + return true; + } + + int32_t version = 2; + Blizzard::File::SetPos(s_storageFile, 0, 0); + int32_t count = 4; + Blizzard::File::Write(s_storageFile, &version, &count); + + int32_t entries = static_cast(s_storage->size()); + count = 4; + Blizzard::File::Write(s_storageFile, &entries, &count); + + Blizzard::Streaming::StorageHeader storageHeader; + storageHeader.m_flags = entry->m_flags; + storageHeader.m_storeSize = entry->m_storeSize; + Blizzard::String::Copy(storageHeader.m_path, entry->m_path.c_str(), sizeof(storageHeader.m_path)); + Blizzard::String::Copy(storageHeader.m_version, entry->m_version.c_str(), sizeof(storageHeader.m_version)); + storageHeader.m_closed = entry->m_closed; + storageHeader.m_size = entry->m_size; + storageHeader.m_blockSize = entry->m_blockSize; + storageHeader.m_blockCount = static_cast(entry->m_blocks.size()); + + int32_t amount = sizeof(storageHeader); + Blizzard::File::Write(s_storageFile, &storageHeader, entry->m_headerOffset, &amount); + + amount = 24 * storageHeader.m_blockCount; + Blizzard::File::Write(s_storageFile, &entry->m_blocks[0], entry->m_headerOffset + 321, &amount); + + return true; +} + +// OFFSET: 0x00432A40 +Blizzard::Streaming::LoadRange* Blizzard::Storage::GetRange(Blizzard::Streaming::StorageEntry* entry, int64_t offset, int32_t size, int32_t* count, bool lock) { + int64_t zero = 0; + int64_t start = offset >= 0 ? offset : zero; + start = entry->m_size >= start ? start : entry->m_size; + + int64_t end = start + size; + zero = 0; + end = end >= 0 ? end : zero; + end = entry->m_size >= end ? end : entry->m_size; + + int32_t length = static_cast(end - start); + + if (end == start) { + *count = 0; + return nullptr; + } + + if (lock) { + EnterCriticalSection(&s_storageLock); + } + + Blizzard::Streaming::LoadRange* ranges; + + if (entry->m_flags & 2) { + ranges = static_cast(Blizzard::Memory::Allocate(sizeof(Blizzard::Streaming::LoadRange) * CountRanges(entry, 0, entry->m_size))); + *count = BuildRangesWithHeader(entry, start, length, ranges); + } else if (entry->m_flags & 1) { + zero = 0; + int64_t from = entry->m_storeSize >= 0 ? entry->m_storeSize : zero; + from = start >= from ? from : start; + ranges = static_cast(Blizzard::Memory::Allocate(sizeof(Blizzard::Streaming::LoadRange) * CountRanges(entry, from, start + length - from))); + *count = BuildRangesFromStore(entry, start, length, ranges); + } else { + ranges = static_cast(Blizzard::Memory::Allocate(sizeof(Blizzard::Streaming::LoadRange) * CountRanges(entry, start, length))); + *count = BuildRanges(entry, start, length, ranges); + } + + if (lock) { + LeaveCriticalSection(&s_storageLock); + } + + return ranges; +} + +// OFFSET: 0x00435A60 +int64_t Blizzard::Storage::GetNextHeaderOffset() { + int64_t offset = 8; + + for (std::map::iterator it = s_storage->begin(); it != s_storage->end(); ++it) { + if (it->second.m_flags & 4) { + continue; + } + + if (offset <= it->second.m_headerOffset) { + offset = it->second.m_headerOffset + static_cast(24 * static_cast(it->second.m_blocks.size())) + 321; + } + } + + return offset; +} + +// OFFSET: 0x00439C40 +bool Blizzard::Storage::ReadLocal(Blizzard::File::Filesystem* fs, Blizzard::File::StreamRecord* file, Blizzard::Streaming::StorageEntry* entry, uint8_t* buffer, int64_t offset, int32_t size) { + EnterCriticalSection(&s_storageLock); + + bool result = false; + int32_t block = static_cast(offset / entry->m_blockSize); + Blizzard::Streaming::StorageBlock& storageBlock = entry->m_blocks[block]; + int64_t position = offset + storageBlock.m_storeOffset - static_cast(entry->m_blockSize) * block; + + if (entry->m_flags & 4) { + LeaveCriticalSection(&s_storageLock); + return false; + } + + if (storageBlock.m_state != 2) { + if (storageBlock.m_state == 3) { + int32_t amount = size; + result = Blizzard::File::Read(fs, file, buffer, position, &amount); + LeaveCriticalSection(&s_storageLock); + return result; + } + + if (storageBlock.m_state != 4) { + LeaveCriticalSection(&s_storageLock); + return false; + } + + LeaveCriticalSection(&s_storageLock); + + while (storageBlock.m_state == 4) { + Sleep(1); + } + + EnterCriticalSection(&s_storageLock); + + if (storageBlock.m_state == 3) { + result = ReadAt(fs, file, buffer, offset + storageBlock.m_storeOffset - static_cast(entry->m_blockSize) * block, size); + LeaveCriticalSection(&s_storageLock); + return result; + } + + result = false; + } + + int32_t count = static_cast(s_writeQueue.size()); + + for (int32_t i = 0; i < count; i++) { + Blizzard::Streaming::WriteRequest& request = s_writeQueue[i]; + + if (entry == request.m_entry && entry->m_blockSize * block == static_cast(request.m_offset)) { + Blizzard::String::MemCopy(buffer, request.m_data + offset - static_cast(block) * entry->m_blockSize, size); + result = true; + break; + } + } + + LeaveCriticalSection(&s_storageLock); + return result; +} + +// OFFSET: 0x004443E0 +bool Blizzard::Storage::QueueWrite(Blizzard::File::Filesystem* fs, Blizzard::File::StreamRecord* file, uint8_t* data, int64_t offset, int32_t size, bool owned) { + EnterCriticalSection(&s_storageLock); + + Blizzard::Streaming::StorageEntry* entry = file->m_streaming->m_entry; + Blizzard::Streaming::AddStreamed(size); + + uint32_t block = static_cast(offset / entry->m_blockSize); + Blizzard::Streaming::StorageBlock& storageBlock = entry->m_blocks[block]; + + if (!(entry->m_flags & 4)) { + if (!storageBlock.m_state || storageBlock.m_state == 1 || storageBlock.m_state == 4) { + Blizzard::Streaming::WriteRequest request; + request.m_fs = fs; + request.m_pending = 1; + request.m_file = file; + request.m_entry = entry; + request.m_offset = offset; + request.m_size = size; + + if (owned) { + request.m_data = data; + } else { + request.m_data = static_cast(Blizzard::Memory::Allocate(size)); + memmove(request.m_data, data, size); + } + + storageBlock.m_state = 2; + s_storageDirty = true; + s_writeQueue.push_back(request); + SetEvent(s_storageEvent); + } else if (owned) { + Blizzard::Memory::Free(data); + } + } + + LeaveCriticalSection(&s_storageLock); + return true; +} + +// OFFSET: 0x00447BF0 +bool Blizzard::Storage::WriteIndex() { + if (!s_storageReady) { + return false; + } + + if (!s_storageDirty) { + return true; + } + + int32_t version = 2; + Blizzard::File::SetPos(s_storageFile, 0, 0); + int32_t count = 4; + Blizzard::File::Write(s_storageFile, &version, &count); + + int32_t entries = static_cast(s_storage->size()); + count = 4; + Blizzard::File::Write(s_storageFile, &entries, &count); + + std::vector records; + + for (std::map::iterator it = s_storage->begin(); it != s_storage->end(); ++it) { + Blizzard::Streaming::StorageEntry& entry = it->second; + + if (entry.m_flags & 4) { + continue; + } + + Blizzard::Streaming::StorageHeader header; + header.m_flags = entry.m_flags; + header.m_storeSize = entry.m_storeSize; + + const char* path = entry.m_path.c_str(); + + if (path) { + char* dst = header.m_path; + + do { + char c = *path++; + + if (!c) { + break; + } + + *dst++ = c; + } while (dst < &header.m_path[sizeof(header.m_path) - 1]); + + *dst = '\0'; + } else { + header.m_path[0] = '\0'; + } + + const char* version = entry.m_version.c_str(); + + if (version) { + char* dst = header.m_version; + + do { + char c = *version++; + + if (!c) { + break; + } + + *dst++ = c; + } while (dst < &header.m_version[sizeof(header.m_version) - 1]); + + *dst = '\0'; + } else { + header.m_version[0] = '\0'; + } + + header.m_size = entry.m_size; + header.m_closed = entry.m_closed; + header.m_blockSize = entry.m_blockSize; + header.m_blockCount = static_cast(entry.m_blocks.size()); + + int32_t amount = sizeof(header); + Blizzard::File::Write(s_storageFile, &header, &amount); + + records.resize(header.m_blockCount); + + for (int32_t i = 0; i < header.m_blockCount; i++) { + records[i].m_state = entry.m_blocks[i].m_state; + records[i].m_offset = entry.m_blocks[i].m_offset; + records[i].m_storeOffset = entry.m_blocks[i].m_storeOffset; + records[i].m_size = entry.m_blocks[i].m_size; + } + + amount = 24 * header.m_blockCount; + Blizzard::File::Write(s_storageFile, &records[0], -1LL, &amount); + } + + Blizzard::File::SetEOF(s_storageFile, 0, 1); + s_storageDirty = false; + + return true; +} + +// OFFSET: 0x0044CB90 +bool Blizzard::Storage::Remove(const std::string& path) { + std::map::iterator it = s_storage->find(Blizzard::Streaming::ResolveFilePath(path)); + + if (it == s_storage->end()) { + return false; + } + + s_storage->erase(it); + return true; +} + +// OFFSET: 0x0044E580 +bool Blizzard::Storage::ReadStorageFile(const uint8_t* data, int32_t size) { + Blizzard::Streaming::StorageEntry entry; + + if (size < 4 || size - 4 < 4) { + return false; + } + + const uint8_t* cursor = data + 8; + int32_t left = size - 8; + int32_t count = *reinterpret_cast(data + 4); + + for (int32_t i = 0; i < count && left > 0; i++) { + if (left < 321) { + s_storage->clear(); + return false; + } + + const Blizzard::Streaming::StorageHeader* header = reinterpret_cast(cursor); + const uint8_t* blocks = cursor + 321; + left -= 321; + + entry.m_path.assign(header->m_path, strlen(header->m_path)); + entry.m_version.assign(header->m_version, strlen(header->m_version)); + entry.m_storeSize = header->m_storeSize; + entry.m_size = header->m_size; + entry.m_flags = header->m_flags; + entry.m_blockSize = header->m_blockSize; + entry.m_closed = header->m_closed; + entry.m_headerWritten = false; + entry.m_headerOffset = size - left - 321; + + if (!entry.m_blockSize || (entry.m_size + entry.m_blockSize - 1) / entry.m_blockSize != header->m_blockCount) { + s_storage->clear(); + return false; + } + + (*s_storage)[Blizzard::Streaming::ResolveFilePath(entry.m_path)] = entry; + Blizzard::Streaming::StorageEntry& stored = (*s_storage)[Blizzard::Streaming::ResolveFilePath(entry.m_path)]; + + int32_t bytes = 24 * header->m_blockCount; + + if (left < bytes) { + s_storage->clear(); + return false; + } + + std::vector records; + records.resize(header->m_blockCount); + Blizzard::String::MemCopy(&records[0], blocks, bytes); + + stored.m_blocks.resize(header->m_blockCount); + + for (int32_t j = 0; j < header->m_blockCount; j++) { + Blizzard::Streaming::StorageBlock& storageBlock = stored.m_blocks[j]; + storageBlock.m_offset = records[j].m_offset; + storageBlock.m_size = records[j].m_size; + storageBlock.m_storeOffset = records[j].m_storeOffset; + storageBlock.m_partOffset = records[j].m_storeOffset; + storageBlock.m_state = records[j].m_state; + } + + cursor = blocks + bytes; + left -= bytes; + } + + return true; +} + +// OFFSET: 0x0044EA50 +Blizzard::Streaming::StorageEntry* Blizzard::Storage::PartialFile::CreateShared(const std::string& key, const char* path, int64_t size, const char* version, int32_t flags) { + Blizzard::Streaming::StorageEntry entry; + entry.m_path.assign(path, strlen(path)); + entry.m_version.assign(version, strlen(version)); + entry.m_flags = flags; + entry.m_closed = false; + entry.m_released = false; + entry.m_refCount = 0; + entry.m_size = size; + entry.m_storeSize = 0; + entry.m_blockSize = s_blockSize; + entry.m_headerWritten = true; + entry.m_file = nullptr; + entry.m_openCount = 0; + InitializeCriticalSection(&entry.m_lock); + + int32_t count = static_cast((size + entry.m_blockSize - 1) / entry.m_blockSize); + + if (s_usePartFiles) { + entry.m_blocks.resize(count, Blizzard::Streaming::StorageBlock()); + memset(&entry.m_blocks[0], 0, sizeof(Blizzard::Streaming::StorageBlock) * count); + (*s_storage)[key] = entry; + } else { + entry.m_blocks.resize(count, Blizzard::Streaming::StorageBlock()); + + int32_t left = static_cast(size); + + for (uint32_t i = 0; i < entry.m_blocks.size(); i++) { + Blizzard::Streaming::StorageBlock& block = entry.m_blocks[i]; + block.m_state = 0; + block.m_offset = static_cast(entry.m_blockSize) * i; + block.m_storeOffset = 0; + block.m_partOffset = 0; + block.m_size = i < entry.m_blocks.size() - 1 ? entry.m_blockSize : left; + left -= entry.m_blockSize; + } + + entry.m_headerOffset = GetNextHeaderOffset(); + (*s_storage)[key] = entry; + WriteIndexEntry(&entry, -1, true); + } + + return &(*s_storage)[key]; +} + +// OFFSET: 0x0044ED80 +Blizzard::Streaming::StorageEntry* Blizzard::Storage::Acquire(Blizzard::File::Filesystem* fs, const std::string& key, const char* path, int64_t size, const char* version, int32_t flags) { + if (!s_storage) { + return nullptr; + } + + if (!path) { + std::map::iterator it = s_storage->find(key); + + if (it == s_storage->end()) { + return nullptr; + } + + return &it->second; + } + + EnterCriticalSection(&s_storageLock); + + std::map::iterator it = s_storage->find(key); + + char partName[260]; + BuildVariantFileName(partName, sizeof(partName), path, "part"); + + if (it != s_storage->end()) { + Blizzard::File::FileInfo info; + + if (it->second.m_headerWritten || (Blizzard::File::GetFileInfo(fs, partName, &info) && info.m_size == it->second.m_storeSize && size == it->second.m_size && Blizzard::String::Equal(version, it->second.m_version.c_str()))) { + Blizzard::Streaming::StorageEntry* entry = &it->second; + LeaveCriticalSection(&s_storageLock); + return entry; + } + + Remove(it->second.m_path); + } + + if (!s_usePartFiles) { + Blizzard::File::Delete(partName); + } + + Blizzard::Streaming::StorageEntry* entry = PartialFile::CreateShared(key, path, size, version, flags); + LeaveCriticalSection(&s_storageLock); + return entry; +} + +// OFFSET: 0x004508B0 +void Blizzard::Storage::Shutdown() { + if (s_storageReady && s_storage) { + s_storageStop = true; + SetEvent(s_storageEvent); + + while (!s_storageStopped) { + Sleep(10); + } + + CloseHandle(s_storageEvent); + DeleteCriticalSection(&s_storageLock); + s_storageLock.DebugInfo = nullptr; + + if (s_storageFile) { + Blizzard::File::Close(s_storageFile); + } + } + + delete s_storage; + s_storage = nullptr; +} + +// OFFSET: 0x00456DE0 +bool Blizzard::Storage::PartialFile::RebuildHeader(Blizzard::File::Filesystem* fs, Blizzard::File::StreamRecord* file) { + Blizzard::Log::Printf(3, "Logs/Profiling_Storage_Initialization.log", "Reinitialized Part file '%s' started.\n", file->m_pathname); + + Blizzard::File::StreamingInfo* streaming = file->m_streaming; + + if (!streaming || !streaming->m_entry) { + return false; + } + + Blizzard::Streaming::StorageEntry* entry = streaming->m_entry; + + Blizzard::Streaming::PartFileHeader header; + header.m_magic = 2; + Blizzard::String::Copy(header.m_version, entry->m_version.c_str(), sizeof(header.m_version)); + header.m_flags = entry->m_flags; + header.m_size = entry->m_size; + header.m_blockSize = entry->m_blockSize; + + int32_t count = static_cast((header.m_size + header.m_blockSize - 1) / header.m_blockSize); + entry->m_blocks.resize(count); + memset(&entry->m_blocks[0], 0, sizeof(Blizzard::Streaming::StorageBlock) * count); + + int32_t amount = sizeof(header); + + if (!Blizzard::File::Write(file, &header, 0, &amount)) { + Blizzard::File::AddToLastErrorStack(0, "FileStack_Streaming::StreamingOpen - Failed to write .part header section", 20); + return false; + } + + amount = 20 * count; + + if (!Blizzard::File::Write(file, &entry->m_blocks[0], 52, &amount)) { + Blizzard::File::AddToLastErrorStack(0, "FileStack_Streaming::StreamingOpen - Failed to write .part storage section", 20); + return false; + } + + int64_t end = 20LL * count + 52; + entry->m_storeSize = end; + entry->m_headerWritten = true; + entry->m_closed = false; + entry->m_parsed = true; + Blizzard::File::SetEOF(file, end, 0); + + Blizzard::Log::Printf(3, "Logs/Profiling_Storage_Initialization.log", "Reinitialized Part file '%s' succeeded.\n", file->m_pathname); + return true; +} + +// OFFSET: 0x00456F80 +bool Blizzard::Storage::PartialFile::ParseFile(Blizzard::File::Filesystem* fs, Blizzard::File::StreamRecord* file) { + Blizzard::File::StreamingInfo* streaming = file->m_streaming; + + if (!streaming || !streaming->m_entry) { + return false; + } + + Blizzard::Streaming::StorageEntry* entry = streaming->m_entry; + + if (entry->m_parsed) { + return true; + } + + if (streaming->m_info.m_size < 52) { + return RebuildHeader(fs, file); + } + + Blizzard::Streaming::PartFileHeader header; + int32_t amount = sizeof(header); + Blizzard::File::Read(fs, file, &header, 0, &amount); + + if (!header.m_blockSize || entry->m_version.compare(header.m_version) || header.m_size != file->m_info.m_size || header.m_magic != 2) { + return RebuildHeader(fs, file); + } + + entry->m_flags = header.m_flags; + entry->m_storeSize = file->m_streaming->m_info.m_size; + + int32_t count = static_cast((entry->m_blockSize + entry->m_size - 1) / entry->m_blockSize); + int32_t bytes = 20 * count; + uint8_t* raw = new uint8_t[bytes]; + + std::vector records; + records.resize(count); + + amount = bytes; + Blizzard::File::Read(fs, file, raw, 52, &amount); + + if (amount < bytes) { + delete[] raw; + return RebuildHeader(fs, file); + } + + Blizzard::String::MemCopy(&records[0], raw, amount); + delete[] raw; + + entry->m_blocks.resize(count); + + int32_t local = 0; + + for (int32_t i = 0; i < count; i++) { + Blizzard::Streaming::StorageBlock& block = entry->m_blocks[i]; + block.m_offset = 0; + block.m_size = entry->m_blockSize; + block.m_storeOffset = records[i].m_storeOffset; + block.m_partOffset = records[i].m_partOffset; + block.m_state = records[i].m_state != 0 ? 3 : 0; + + if (block.m_state == 3) { + if (block.m_storeOffset > entry->m_storeSize) { + return RebuildHeader(fs, file); + } + + local++; + } + } + + int64_t end = bytes + static_cast(local) * entry->m_blockSize + 52; + + if (entry->m_storeSize > end) { + Blizzard::File::SetEOF(file, end, 0); + entry->m_storeSize = end; + } else if (entry->m_storeSize < end) { + return RebuildHeader(fs, file); + } + + entry->m_parsed = true; + return true; +} + +// OFFSET: 0x004572C0 +bool Blizzard::Storage::WritePartBlockInfo(Blizzard::Streaming::StorageEntry* entry, Blizzard::File::StreamRecord* file, int32_t block) { + if (!s_storageReady) { + return false; + } + + if (entry->m_flags & 4) { + return true; + } + + bool result = true; + + if (block >= 0 && block < static_cast(entry->m_blocks.size())) { + Blizzard::Streaming::PartBlockRecord record; + record.m_storeOffset = entry->m_blocks[block].m_storeOffset; + record.m_state = entry->m_blocks[block].m_state; + record.m_partOffset = entry->m_blocks[block].m_partOffset; + + result = WriteAt(file, &record, 20LL * block + 52, sizeof(record)); + + if (!result) { + Blizzard::File::AddToLastErrorStack(0, "Failed to write storage information chunk", 20); + } + } + + return result; +} + +// OFFSET: 0x00457390 +bool Blizzard::Storage::WriteBlock(Blizzard::Streaming::WriteRequest* request) { + Blizzard::Streaming::StorageEntry* entry = request->m_entry; + uint32_t block = static_cast(request->m_offset / entry->m_blockSize); + Blizzard::Streaming::StorageBlock& storageBlock = entry->m_blocks[block]; + int32_t state = storageBlock.m_state; + + if (state == 4 || (state != 3 && state != 2)) { + return state != 0; + } + + uint8_t* data = request->m_data; + bool allocated = false; + + if (block == entry->m_blocks.size() - 1 && request->m_size != entry->m_blockSize) { + allocated = true; + data = static_cast(Blizzard::Memory::Allocate(entry->m_blockSize)); + Blizzard::String::MemCopy(data, request->m_data, request->m_size); + } + + int64_t position = entry->m_storeSize; + bool existing = false; + + if (storageBlock.m_storeOffset) { + position = storageBlock.m_storeOffset; + existing = true; + } + + int32_t amount = entry->m_blockSize; + + if (!Blizzard::File::Write(request->m_file, data, position, &amount)) { + storageBlock.m_state = 0; + return false; + } + + if (allocated) { + Blizzard::Memory::Free(data); + } + + if (!existing) { + entry->m_blocks[block].m_storeOffset = position; + entry->m_storeSize += entry->m_blockSize; + } + + storageBlock.m_state = 3; + + bool result = s_usePartFiles ? WritePartBlockInfo(entry, request->m_file, block) : WriteIndexEntry(entry, block, false); + + if (!result) { + if (!existing) { + entry->m_blocks[block].m_storeOffset = 0; + entry->m_storeSize -= entry->m_blockSize; + } + + storageBlock.m_state = 0; + } + + return result; +} + +// OFFSET: 0x00457550 +bool Blizzard::Storage::FlushFile(Blizzard::File::Filesystem* fs, Blizzard::File::StreamRecord* file) { + EnterCriticalSection(&s_storageLock); + + int32_t count = static_cast(s_writeQueue.size()); + + for (int32_t i = 0; i < count; i++) { + Blizzard::Streaming::WriteRequest& request = s_writeQueue[i]; + + if (file == request.m_file) { + if (request.m_pending == 1) { + WriteBlock(&request); + request.m_pending = 0; + } + + if (request.m_data) { + Blizzard::Memory::Free(request.m_data); + request.m_data = nullptr; + } + } + } + + if (!s_usePartFiles) { + WriteIndex(); + } + + file->m_streaming->m_entry->m_released = true; + LeaveCriticalSection(&s_storageLock); + + while (file->m_streaming->m_entry->m_refCount > 0) { + Sleep(1); + } + + return true; +} + +// OFFSET: 0x00459660 +uint32_t Blizzard::Storage::StorageThread(void* param) { + if (s_storageStop) { + s_storageStopped = true; + return 1; + } + + do { + WaitForSingleObject(s_storageEvent, INFINITE); + + if (s_storageStop) { + break; + } + + for (;;) { + EnterCriticalSection(&s_storageLock); + + if (!s_writeQueue.size()) { + break; + } + + Blizzard::Streaming::WriteRequest& request = s_writeQueue.front(); + + if (request.m_pending == 1) { + WriteBlock(&request); + + if (request.m_data) { + Blizzard::Memory::Free(request.m_data); + request.m_data = nullptr; + } + } + + s_writeQueue.pop_front(); + LeaveCriticalSection(&s_storageLock); + + if (s_storageStop) { + s_storageStopped = true; + return 1; + } + } + + LeaveCriticalSection(&s_storageLock); + } while (!s_storageStop); + + s_storageStopped = true; + return 1; +} + +// OFFSET: 0x00459800 +bool Blizzard::Storage::Close(Blizzard::File::Filesystem* fs, Blizzard::File::StreamRecord* file, Blizzard::Streaming::StorageEntry* entry) { + if (entry->m_flags & 4) { + return true; + } + + EnterCriticalSection(&s_storageLock); + + if ((entry->m_flags & 1) && IsComplete(entry)) { + entry->m_closed = true; + LeaveCriticalSection(&s_storageLock); + return true; + } + + bool result = FlushFile(fs, file); + + for (std::vector::iterator it = entry->m_blocks.begin(); it != entry->m_blocks.end(); ++it) { + if (it->m_state != 3) { + it->m_state = 0; + } + } + + LeaveCriticalSection(&s_storageLock); + return result; +} + +// OFFSET: 0x0045ADC0 +bool Blizzard::Storage::Initialize() { + s_usePartFiles = true; + + if (!s_storageReady) { + s_storage = new std::map(); + InitializeCriticalSection(&s_storageLock); + s_storageEvent = CreateEventA(nullptr, FALSE, FALSE, nullptr); + Blizzard::Thread::CreateDetached(StorageThread, nullptr, "Streaming Storage Thread"); + s_storageReady = true; + } + + return true; +} + +// OFFSET: 0x0045AE90 +bool Blizzard::Storage::Initialize(const char* path, bool required) { + s_usePartFiles = false; + + if (s_storageReady) { + Blizzard::File::AddToLastErrorStack(0, "Storage::Initialize - s_storageReady said we've been here", 20); + return false; + } + + s_storage = new std::map(); + InitializeCriticalSection(&s_storageLock); + s_storageEvent = CreateEventA(nullptr, FALSE, FALSE, nullptr); + Blizzard::Thread::CreateDetached(StorageThread, nullptr, "Streaming Storage Thread"); + s_storageReady = true; + + void* data = nullptr; + uint32_t size = 0; + char absolute[260]; + + if (!path || !Blizzard::File::MakeAbsolutePath(path, absolute, sizeof(absolute), false)) { + Blizzard::File::AddToLastErrorStack(0, "Storage::Initialize - MakeAbsolutePath failed", 20); + return false; + } + + s_storagePath.assign(absolute, strlen(absolute)); + + bool found = false; + + for (int32_t i = 0; i < 25; i++) { + if (found) { + break; + } + + char name[260]; + BuildVariantFileName(name, sizeof(name), path, ""); + + if (!Blizzard::File::Exists(name)) { + break; + } + + if (Blizzard::File::Open(name, 4099, s_storageFile)) { + if (!System_File::LoadFile(s_storageFile, &data, &size)) { + break; + } + + found = true; + } else { + s_variantIndex++; + } + } + + if (!found) { + if (required) { + Blizzard::File::AddToLastErrorStack(0, "Storage::Initialize - Bad existing storage file", 20); + return false; + } + + if (s_storageFile) { + if (data) { + Blizzard::Memory::Free(data); + } + + Blizzard::File::Close(s_storageFile); + s_storageFile = nullptr; + Blizzard::File::Delete(path); + } + + s_usePartFiles = true; + return true; + } + + bool result = ReadStorageFile(static_cast(data), size); + Blizzard::Memory::Free(data); + + if (result) { + return true; + } + + if (required) { + Blizzard::File::AddToLastErrorStack(0, "Storage::Initialize - Bad existing storage file", 20); + return false; + } + + Blizzard::File::Close(s_storageFile); + s_storageFile = nullptr; + s_usePartFiles = true; + Blizzard::File::Delete(path); + return true; +} + +#endif diff --git a/Engine/Source/BlizzardCore/Source/Packages/Streaming/Win64/Streaming.cpp b/Engine/Source/BlizzardCore/Source/Packages/Streaming/Win64/Streaming.cpp index 57f4860..568c6cd 100644 --- a/Engine/Source/BlizzardCore/Source/Packages/Streaming/Win64/Streaming.cpp +++ b/Engine/Source/BlizzardCore/Source/Packages/Streaming/Win64/Streaming.cpp @@ -1,77 +1,1157 @@ #if defined(WOWDECOMP_ARCH_64) +#include #include #include #include +#include +#include +#include #include +#include "Engine/Source/BlizzardCore/Include/Blizzard/Util/MD5.h" +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Manifests.h" +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Storage.h" #include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Streaming.h" +#include "Engine/Source/BlizzardCore/Source/System/Debug/ErrorStack.h" #include "Engine/Source/BlizzardCore/Source/System/File/File.h" +#include "Engine/Source/BlizzardCore/Source/System/File/Filestack.h" +#include "Engine/Source/BlizzardCore/Source/System/File/Filestack_Streaming.h" +#include "Engine/Source/BlizzardCore/Source/System/Log/Log.h" +#include "Engine/Source/BlizzardCore/Source/System/Memory/MemoryStorm.h" +#include "Engine/Source/BlizzardCore/Source/System/String/Path.h" +#include "Engine/Source/BlizzardCore/Source/System/String/String.h" +#include "Engine/Source/BlizzardCore/Source/System/Thread/Thread.h" + +// STATIC: 0x009E6204 +static const int32_t s_queueOrder[6] = { 0, 1, 0, 2, 0, 1 }; + +// STATIC: 0x009E621C +static const int32_t s_queueGroupBase[2] = { 0, 4 }; + +// STATIC: 0x00AB9344 +static bool s_useBackgroundQueues = true; + +// STATIC: 0x00AB9346 +static bool s_throttleProgress = true; // STATIC: 0x00B3252C -static HANDLE unk_B3252C; +static HANDLE s_throttleEvent; // STATIC: 0x00B32530 -static CRITICAL_SECTION unk_B32530; +static CRITICAL_SECTION s_queueLock; // STATIC: 0x00B32548 -static HANDLE unk_B32548[2]; +static HANDLE s_threadEvents[2]; // STATIC: 0x00B32550 -static HANDLE unk_B32550; +static HANDLE s_pauseEvent; // STATIC: 0x00B32554 -static Blizzard::Streaming::DownloadSlot* unk_B32554[2]; +static Blizzard::Streaming::FILE_THREAD_CMD* s_currentCommands[2]; // STATIC: 0x00B3255C -static std::deque* unk_B3255C[7]; +static std::deque* s_queues[7]; // STATIC: 0x00B325A0 -static CRITICAL_SECTION unk_B325A0; +static CRITICAL_SECTION s_pauseLock; // STATIC: 0x00B325B8 -static bool unk_B325B8; - -// STATIC: 0x00B325C0 -static CRITICAL_SECTION unk_B325C0; - -// STATIC: 0x00B325D8 -static HANDLE unk_B325D8; +static bool s_paused; // STATIC: 0x00B325DC -static HANDLE unk_B325DC; - -// STATIC: 0x00B38170 -static Blizzard::Streaming::SourceManifest* unk_B38170; - -// STATIC: 0x00B38174 -static Blizzard::Streaming::StorageEntryMap* unk_B38174; - -// STATIC: 0x00B38178 -static Blizzard::File::StreamRecord* unk_B38178; - -// STATIC: 0x00B3817C -static bool unk_B3817C; - -// STATIC: 0x00B3817E -static bool unk_B3817E; - -// STATIC: 0x00B3817F -static bool unk_B3817F; +static HANDLE s_queueEvent; // STATIC: 0x00B38182 -static bool unk_B38182; +static volatile bool s_stopThreads; // STATIC: 0x00B38184 -static int32_t unk_B38184; +static volatile int32_t s_threadMask; + +// STATIC: 0x00B38188 +static int32_t s_busyMask; // STATIC: 0x00B38294 -static Blizzard::Streaming::DigestStateMap* unk_B38294; +static Blizzard::Streaming::DigestStateMap* s_digestStates; // STATIC: 0x00B38298 -static Blizzard::Streaming::PathMap* unk_B38298; +static Blizzard::Streaming::PathMap* s_paths; + +// STATIC: 0x00B3829C +static int32_t s_commandsTaken; + +// STATIC: 0x00B382A0 +static int32_t s_commandsFreed; // STATIC: 0x00B386D0 -static Blizzard::Streaming::DownloadProgress unk_B386D0; +Blizzard::Streaming::DownloadProgress Blizzard::Streaming::s_progress; + +// STATIC: 0x00B38A54 +static int32_t s_queueRotation[2]; + +// OFFSET: 0x00428030 +int32_t Blizzard::Streaming::GetIdleThread() { + for (int32_t thread = 0; thread < 2; thread++) { + if (((1 << thread) & s_threadMask) && !((1 << thread) & s_busyMask)) { + return thread; + } + } + + return -1; +} + +// OFFSET: 0x00428060 +void Blizzard::Streaming::DownloadProgress::Sample(uint32_t time) { + if (++this->m_index >= 51) { + this->m_index = 0; + } + + this->m_samples[this->m_index].m_time = 0; + this->m_samples[this->m_index].m_bytes = this->m_streamed; + this->m_samples[this->m_index].m_time = time; +} + +// OFFSET: 0x004280C0 +int32_t Blizzard::Streaming::DownloadProgress::GetRate() { + uint32_t last = this->m_index; + uint32_t first; + + if (last == 50) { + first = 0; + } else { + first = last + 1; + + if (!last) { + last = 51; + } + } + + uint32_t end = last - 1; + + while (!this->m_samples[first].m_time) { + if (first == end) { + break; + } + + if (++first > 50) { + first = 0; + } + } + + for (; !this->m_samples[end].m_time; end--) { + if (first == end) { + break; + } + + if (!end) { + end = 51; + } + } + + int64_t bytes = this->m_samples[end].m_bytes - this->m_samples[first].m_bytes; + int32_t time = this->m_samples[end].m_time - this->m_samples[first].m_time; + + if (first == end) { + uint32_t next = end + 1; + + if (next == 51) { + next = 0; + } + + if (this->m_samples[next].m_time) { + bytes = this->m_samples[next].m_bytes; + time = this->m_samples[next].m_time - this->m_lastTime; + } + } + + if (bytes > 0) { + return static_cast(1000 * (bytes / time)); + } + + return 0; +} + +// OFFSET: 0x0042E020 +void Blizzard::Streaming::HashFileName(Blizzard::Util::Digest<16>* digest, const char* name) { + char lower[260]; + memset(lower, 0, sizeof(lower)); + + if (name) { + char* dst = lower; + + do { + char c = *name++; + + if (!c) { + break; + } + + *dst++ = c; + } while (dst < &lower[259]); + + *dst = '\0'; + } else { + lower[0] = '\0'; + } + + for (char* cursor = lower; *cursor; cursor++) { + *cursor = tolower(*cursor); + } + + Blizzard::Util::HashString(digest->m_data, lower); +} + +// OFFSET: 0x0042E0B0 +void Blizzard::Streaming::WaitForLoads() { + for (;;) { + EnterCriticalSection(&s_queueLock); + + bool busy = false; + + for (int32_t i = 0; i < 2; i++) { + if (s_currentCommands[i] && s_currentCommands[i]->m_type == 1) { + busy = true; + break; + } + } + + LeaveCriticalSection(&s_queueLock); + + if (!busy) { + return; + } + + Sleep(1); + } +} + +// OFFSET: 0x00437ED0 +bool Blizzard::Streaming::CancelQueue(int32_t priority) { + EnterCriticalSection(&s_queueLock); + + std::deque& queue = *s_queues[priority]; + + for (std::deque::iterator it = queue.begin(); it != queue.end(); ++it) { + if (it->m_completion && it->m_type == 2) { + it->m_completion->m_result = static_cast(s_queues[priority]->size()); + it->m_completion->m_done = true; + SetEvent(*it->m_completion->m_event); + it->m_completion = nullptr; + } + + it->m_type = 0; + } + + for (DigestStateMap::iterator it = s_digestStates->begin(); it != s_digestStates->end(); ++it) { + if (it->second.m_state && it->second.m_priority == priority) { + it->second.m_state = 0; + } + } + + LeaveCriticalSection(&s_queueLock); + return true; +} + +// OFFSET: 0x00438120 +bool Blizzard::Streaming::PopCommand(FILE_THREAD_CMD* command, int32_t queue) { + if (!s_queues[queue]->size()) { + return false; + } + + *command = s_queues[queue]->front(); + s_queues[queue]->pop_front(); + s_commandsTaken++; + + return true; +} + +// OFFSET: 0x004381E0 +bool Blizzard::Streaming::SelectQueue(FILE_THREAD_CMD* command, int32_t group, int32_t* queue) { + if (group >= 1 && !s_useBackgroundQueues) { + return false; + } + + int32_t base = s_queueGroupBase[group]; + + for (int32_t i = 0; i < 6; i++) { + *queue = base + s_queueOrder[s_queueRotation[group]]; + s_queueRotation[group] = (s_queueRotation[group] + 1) % 6; + + if (PopCommand(command, *queue)) { + return true; + } + } + + return false; +} + +// OFFSET: 0x00438260 +int32_t Blizzard::Streaming::GetNextCommand(FILE_THREAD_CMD** command, int32_t thread) { + FILE_THREAD_CMD* next = new FILE_THREAD_CMD(); + int32_t queue = 7; + + if (SelectQueue(next, 0, &queue) || (queue = 3, PopCommand(next, 3)) || SelectQueue(next, 1, &queue)) { + s_currentCommands[thread] = next; + *command = next; + return queue; + } + + delete next; + s_commandsFreed++; + return 7; +} + +// OFFSET: 0x00438360 +void Blizzard::Streaming::DownloadProgress::FireCallback() { + if (!this->m_enabled) { + return; + } + + if (s_throttleProgress && Blizzard::Time::Milliseconds() - this->m_lastTime < 5000) { + return; + } + + PROGRESSCALLBACK callback = this->m_callback; + + if (callback) { + callback(static_cast(this->m_total), static_cast(this->m_total >> 32), static_cast(this->m_downloaded), static_cast(this->m_downloaded >> 32), static_cast(this->m_streamed), static_cast(this->m_streamed >> 32), this->GetRate()); + } +} + +// OFFSET: 0x00439E30 +void Blizzard::Streaming::AddDownloaded(int32_t size) { + s_progress.m_downloaded += size; + s_progress.FireCallback(); +} + +// OFFSET: 0x00439E50 +void Blizzard::Streaming::AddStreamed(int32_t size) { + s_progress.m_streamed += size; + + uint32_t now = static_cast(Blizzard::Time::Milliseconds()); + + if (now - s_progress.m_samples[s_progress.m_index].m_time > 100) { + s_progress.Sample(now); + s_progress.FireCallback(); + } +} + +// OFFSET: 0x0043AF30 +bool Blizzard::Streaming::RemoveCompletion(Completion* completion, int32_t priority) { + if (!s_queues[priority]->size()) { + return false; + } + + EnterCriticalSection(&s_queueLock); + + std::deque& queue = *s_queues[priority]; + + for (std::deque::iterator it = queue.end(); it != queue.begin();) { + --it; + + if (it->m_completion == completion) { + it->m_completion = nullptr; + LeaveCriticalSection(&s_queueLock); + return true; + } + } + + LeaveCriticalSection(&s_queueLock); + return false; +} + +// OFFSET: 0x00444550 +bool Blizzard::Streaming::QueueLoad(Blizzard::File::StreamRecord* file, int32_t priority, LoadRange* range, Completion* completion) { + Blizzard::File::Filesystem* fs = System_File::Stacked::s_manager; + + while (fs && fs->m_original != &System_File::Stacked::s_streamstack) { + fs = fs->m_next; + } + + FILE_THREAD_CMD command; + command.m_fs = fs; + command.m_type = 1; + command.m_file = file; + command.m_range = static_cast(Blizzard::Memory::Allocate(sizeof(LoadRange))); + + if (range) { + memmove(command.m_range, range, sizeof(LoadRange)); + } + + command.m_completion = completion; + + EnterCriticalSection(&s_queueLock); + s_queues[priority]->push_back(command); + LeaveCriticalSection(&s_queueLock); + + return Blizzard::Storage::RequestRange(file->m_streaming->m_entry, range->m_blockOffset, range->m_blockSize, 1); +} + +// OFFSET: 0x00444620 +bool Blizzard::Streaming::RequestRanges(Blizzard::File::StreamRecord* file, LoadRange* ranges, int32_t count) { + int32_t state = 0; + int32_t requests = 0; + int32_t blocks = 0; + std::vector completions; + + LoadRange current; + current.m_offset = 0; + current.m_size = 0; + current.m_state = 0; + + for (int32_t i = 0; i < count; i++) { + LoadRange& range = ranges[i]; + + if (range.m_state > 4) { + continue; + } + + if (!state) { + if (range.m_state < 2) { + continue; + } + + current.m_blockOffset = range.m_blockOffset; + current.m_blockSize = range.m_blockSize; + current.m_state = 2; + blocks++; + state = 2; + continue; + } + + if (current.m_blockOffset + current.m_blockSize != range.m_blockOffset) { + Completion* completion = new Completion(); + Blizzard::Lock::Event* event = new Blizzard::Lock::Event(); + completion->m_event = event; + *event = CreateEventA(nullptr, FALSE, FALSE, nullptr); + completions.push_back(completion); + + QueueLoad(file, 0, ¤t, completion); + SetEvent(s_throttleEvent); + SetEvent(s_queueEvent); + requests++; + + if (range.m_state < 2) { + state = 0; + } else { + current.m_blockOffset = range.m_blockOffset; + current.m_blockSize = range.m_blockSize; + state = range.m_state; + } + + current.m_state = state; + } else { + current.m_blockSize += range.m_blockSize; + blocks++; + } + } + + if (state) { + if (requests || blocks < 4) { + Completion* completion = new Completion(); + Blizzard::Lock::Event* event = new Blizzard::Lock::Event(); + completion->m_event = event; + *event = CreateEventA(nullptr, FALSE, FALSE, nullptr); + completions.push_back(completion); + QueueLoad(file, 0, ¤t, completion); + } else { + int32_t half = Blizzard::Storage::s_blockSize * (blocks - blocks / 2); + + LoadRange second; + second.m_offset = 0; + second.m_size = 0; + second.m_state = 2; + second.m_blockOffset = current.m_blockOffset + half; + second.m_blockSize = current.m_blockSize - half; + current.m_blockSize = half; + + Completion* completion = new Completion(); + Blizzard::Lock::Event* event = new Blizzard::Lock::Event(); + completion->m_event = event; + *event = CreateEventA(nullptr, FALSE, FALSE, nullptr); + completions.push_back(completion); + QueueLoad(file, 0, ¤t, completion); + + completion = new Completion(); + event = new Blizzard::Lock::Event(); + completion->m_event = event; + *event = CreateEventA(nullptr, FALSE, FALSE, nullptr); + completions.push_back(completion); + QueueLoad(file, 0, &second, completion); + } + } + + SetEvent(s_throttleEvent); + SetEvent(s_queueEvent); + + bool success = true; + + for (std::vector::iterator it = completions.begin(); it != completions.end(); ++it) { + WaitForSingleObject(*(*it)->m_event, INFINITE); + CloseHandle(*(*it)->m_event); + + if (!(*it)->m_success) { + success = false; + } + + delete (*it)->m_event; + (*it)->m_event = nullptr; + delete *it; + *it = nullptr; + } + + completions.erase(completions.begin(), completions.end()); + + return success; +} + +// OFFSET: 0x00444AA0 +bool Blizzard::Streaming::QueueCompletion(Completion* completion, int32_t priority) { + if (!s_queues[priority]->size()) { + completion->m_result = 0; + completion->m_done = false; + completion->m_success = false; + return false; + } + + FILE_THREAD_CMD command; + command.m_fs = nullptr; + command.m_type = 2; + command.m_file = nullptr; + command.m_range = nullptr; + command.m_completion = completion; + + EnterCriticalSection(&s_queueLock); + s_queues[priority]->push_back(command); + LeaveCriticalSection(&s_queueLock); + SetEvent(s_queueEvent); + + return true; +} + +// OFFSET: 0x004480B0 +bool Blizzard::Streaming::MakeLocalAsync(Blizzard::File::StreamRecord* file, int64_t offset, int32_t size, int32_t priority, const char* name) { + if (!file->m_streaming || !file->m_streaming->m_entry) { + return false; + } + + Blizzard::Util::Digest<16> digest; + HashFileName(&digest, name); + + DigestStateMap::iterator it = s_digestStates->find(digest); + + if (it != s_digestStates->end()) { + if (it->second.m_state == 1) { + return true; + } + + if (it->second.m_state == 2 && it->second.m_priority <= priority) { + return true; + } + } + + StorageEntry* entry = file->m_streaming->m_entry; + + if (!entry) { + return false; + } + + int32_t count; + LoadRange* ranges = Blizzard::Storage::GetRange(entry, offset, size, &count, true); + + if (!ranges || !count) { + return false; + } + + bool queued = false; + + for (int32_t i = 0; i < count; i++) { + if (static_cast(ranges[i].m_state - 2) <= 2) { + QueueLoad(file, priority, &ranges[i], nullptr); + queued = true; + } + } + + if (queued) { + (*s_digestStates)[digest].m_state = 2; + (*s_digestStates)[digest].m_priority = priority; + + if (s_useBackgroundQueues) { + SetEvent(s_queueEvent); + } + } else { + (*s_digestStates)[digest].m_state = 1; + AddDownloaded(size); + } + + Blizzard::Memory::Free(ranges); + return true; +} + +// OFFSET: 0x0044F120 +int32_t Blizzard::Streaming::CheckFileRange(const char* path, int64_t offset, int32_t size, const char* name, int32_t flags) { + Blizzard::Util::Digest<16> digest; + HashFileName(&digest, name); + + DigestStateMap::iterator it = s_digestStates->find(digest); + int32_t previous = 0; + + if (it != s_digestStates->end()) { + previous = it->second.m_state; + + if (previous == 1) { + return 1; + } + } + + if (!path) { + return -1; + } + + std::string key = ResolveFilePath(std::string(path)); + + if (!Blizzard::Storage::s_storage) { + return -1; + } + + std::map::iterator entry = Blizzard::Storage::s_storage->find(key); + + if (entry == Blizzard::Storage::s_storage->end()) { + return -1; + } + + int32_t count; + LoadRange* ranges = Blizzard::Storage::GetRange(&entry->second, offset, size, &count, false); + + if (!ranges || !count) { + return -1; + } + + int32_t result = 1; + + for (LoadRange* range = ranges; count > 0 && result; range++, count--) { + switch (range->m_state) { + case 1: + case 3: + if (result == 1) { + result = 2; + } + + break; + + case 2: + case 4: + result = 0; + break; + } + } + + Blizzard::Memory::Free(ranges); + + if (previous != result) { + (*s_digestStates)[digest].m_state = result; + } + + return result; +} + +// OFFSET: 0x0044F370 +int32_t Blizzard::Streaming::GetIsLocalAmount(const char* path, int64_t offset, int32_t size, const char* name) { + Blizzard::Util::Digest<16> digest; + HashFileName(&digest, name); + + DigestStateMap::iterator it = s_digestStates->find(digest); + + if (it != s_digestStates->end() && it->second.m_state == 1) { + return size; + } + + std::string key = ResolveFilePath(std::string(path)); + + if (!Blizzard::Storage::s_storage) { + return size; + } + + std::map::iterator entry = Blizzard::Storage::s_storage->find(key); + + if (entry == Blizzard::Storage::s_storage->end()) { + return size; + } + + int32_t local = size; + int32_t count; + LoadRange* ranges = Blizzard::Storage::GetRange(&entry->second, offset, size, &count, false); + + if (ranges && count) { + local = 0; + + for (int32_t i = 0; i < count; i++) { + if (!ranges[i].m_state) { + local += ranges[i].m_size; + } + } + + Blizzard::Memory::Free(ranges); + } + + return local; +} + +// OFFSET: 0x0044F560 +bool Blizzard::Streaming::MakeLocalBlocking(Blizzard::File::StreamRecord* file, int64_t offset, int32_t size, int32_t priority, const char* name) { + Blizzard::Util::Digest<16> digest; + HashFileName(&digest, name); + + DigestStateMap::iterator it = s_digestStates->find(digest); + + if (it != s_digestStates->end() && it->second.m_state == 1) { + return true; + } + + std::string key = ResolveFilePath(std::string(file->m_pathname)); + + if (!Blizzard::Storage::s_storage) { + return false; + } + + std::map::iterator entry = Blizzard::Storage::s_storage->find(key); + + if (entry == Blizzard::Storage::s_storage->end()) { + return false; + } + + int32_t count; + LoadRange* ranges = Blizzard::Storage::GetRange(&entry->second, offset, size, &count, true); + + if (!ranges || !count) { + return false; + } + + std::vector completions; + bool queued = false; + + for (int32_t i = 0; i < count; i++) { + LoadRange& range = ranges[i]; + + if (static_cast(range.m_state - 2) > 2) { + continue; + } + + if (range.m_blockSize <= 0) { + Blizzard::Memory::Free(ranges); + return false; + } + + LoadRange request; + request.m_state = 2; + request.m_blockOffset = range.m_blockOffset; + request.m_blockSize = range.m_blockSize; + queued = true; + + Completion* completion = new Completion(); + Blizzard::Lock::Event* event = new Blizzard::Lock::Event(); + completion->m_event = event; + *event = CreateEventA(nullptr, FALSE, FALSE, nullptr); + completions.push_back(completion); + + QueueLoad(file, priority, &request, completion); + SetEvent(s_throttleEvent); + SetEvent(s_queueEvent); + } + + if (!queued) { + Blizzard::Memory::Free(ranges); + return true; + } + + SetEvent(s_throttleEvent); + SetEvent(s_queueEvent); + + bool success = true; + + for (std::vector::iterator it = completions.begin(); it != completions.end(); ++it) { + WaitForSingleObject(*(*it)->m_event, INFINITE); + CloseHandle(*(*it)->m_event); + + if (!(*it)->m_success) { + success = false; + } + + delete (*it)->m_event; + (*it)->m_event = nullptr; + delete *it; + *it = nullptr; + } + + completions.erase(completions.begin(), completions.end()); + Blizzard::Memory::Free(ranges); + + return success; +} + +// OFFSET: 0x00458A90 +bool System_File::Stacked::stream_flush(Blizzard::File::Filesystem* fs, FileParms* parms) { + Blizzard::File::StreamRecord* file = parms->m_stream; + + if (file->m_streaming && file->m_streaming->m_entry) { + EnterCriticalSection(&s_queueLock); + + for (int32_t i = 0; i < 7; i++) { + std::deque* queue = s_queues[i]; + + if (queue->size()) { + for (std::deque::iterator it = queue->begin(); it != queue->end(); ++it) { + if (file == it->m_file && it->m_type == 1) { + it->m_type = 0; + } + } + } + } + + for (int32_t i = 0; i < 2; i++) { + if (s_currentCommands[i] && file == s_currentCommands[i]->m_file && s_currentCommands[i]->m_type == 1) { + s_currentCommands[i]->m_type = 0; + } + } + + LeaveCriticalSection(&s_queueLock); + + if (!Blizzard::Storage::FlushFile(fs->m_next, file)) { + return false; + } + } + + if (!fs->m_next) { + return false; + } + + return (*reinterpret_cast(reinterpret_cast(fs->m_next) + parms->m_verb))(fs->m_next, parms); +} + +// OFFSET: 0x0045A8F0 +bool Blizzard::Streaming::LoadFile(Blizzard::File::Filesystem* fs, Blizzard::File::StreamRecord* file, LoadRange* range) { + Blizzard::Storage::StorageEntryRef ref(file->m_streaming->m_entry); + StorageEntry* entry = ref.m_entry; + + if (!entry) { + EnterCriticalSection(&Blizzard::Storage::s_storageLock); + LeaveCriticalSection(&Blizzard::Storage::s_storageLock); + return false; + } + + int32_t count = 0; + LoadRange* ranges = file->m_streaming ? Blizzard::Storage::GetRange(entry, range->m_blockOffset, range->m_blockSize, &count, true) : nullptr; + + if (!ranges || !count) { + EnterCriticalSection(&Blizzard::Storage::s_storageLock); + entry->m_refCount--; + LeaveCriticalSection(&Blizzard::Storage::s_storageLock); + return false; + } + + bool requested = false; + int32_t failState = 3; + + EnterCriticalSection(&Blizzard::Storage::s_storageLock); + + for (int32_t i = 0; i < count; i++) { + LoadRange& loadRange = ranges[i]; + + if (loadRange.m_state == 3) { + failState = 1; + Blizzard::Storage::RequestRange(entry, loadRange.m_blockOffset, loadRange.m_blockSize, 4); + requested = true; + } else if (loadRange.m_state == 2 || loadRange.m_state == 4) { + failState = 0; + Blizzard::Storage::RequestRange(entry, loadRange.m_blockOffset, loadRange.m_blockSize, 4); + requested = true; + } + } + + LeaveCriticalSection(&Blizzard::Storage::s_storageLock); + Blizzard::Memory::Free(ranges); + + if (!requested) { + Blizzard::Log::Printf(3, "Logs/Profiling_File_Defer_Cancelled.log", "%10lld, %10d - %s\n", range->m_blockOffset, range->m_blockSize, file->m_pathname); + EnterCriticalSection(&Blizzard::Storage::s_storageLock); + entry->m_refCount--; + LeaveCriticalSection(&Blizzard::Storage::s_storageLock); + return true; + } + + Blizzard::Log::Printf(3, "Logs/Profiling_File_Defer.log", "%10lld, %10d - %s\n", range->m_blockOffset, range->m_blockSize, file->m_pathname); + s_statBytesDownloaded += range->m_blockSize; + + uint8_t* data = static_cast(Blizzard::Memory::Allocate(range->m_blockSize)); + + std::string url; + url = ManifestInfo::GetRemotePath(file->m_streaming->m_path); + + Manifests::TransportItem* transport = ManifestInfo::GetTransportItem(file->m_streaming->m_path); + int32_t maxRetry = ManifestInfo::GetServerItemMaxRetry(std::string(url), file->m_streaming->m_path); + + bool result = Transport::Read(transport, std::string(url), maxRetry, data, file->m_info.m_size, range->m_blockOffset, range->m_blockSize); + + if (!result) { + ManifestInfo::DeactivateServer(std::string(url), file->m_streaming->m_path); + Blizzard::Memory::Free(data); + } else if (range->m_blockSize > Blizzard::Storage::s_blockSize) { + int32_t written = 0; + int32_t left = range->m_blockSize; + + while (left > 0) { + int32_t chunk = Blizzard::Storage::s_blockSize < left ? Blizzard::Storage::s_blockSize : left; + result &= Blizzard::Storage::QueueWrite(fs, file, &data[written], range->m_blockOffset + written, chunk, false); + written += chunk; + left -= chunk; + } + + Blizzard::Memory::Free(data); + } else { + result = Blizzard::Storage::QueueWrite(fs, file, data, range->m_blockOffset, range->m_blockSize, true); + } + + if (!result) { + Blizzard::Storage::SetRangeAs(entry, range->m_blockOffset, range->m_blockSize, failState); + } + + EnterCriticalSection(&Blizzard::Storage::s_storageLock); + entry->m_refCount--; + LeaveCriticalSection(&Blizzard::Storage::s_storageLock); + + return result; +} + +// OFFSET: 0x0045B150 +uint32_t Blizzard::Streaming::DownloadThread(void* param) { + int32_t thread = *static_cast(param); + delete static_cast(param); + + EnterCriticalSection(&s_queueLock); + int32_t bit = 1 << thread; + s_threadMask |= bit; + LeaveCriticalSection(&s_queueLock); + + if (!s_stopThreads) { + for (;;) { + if (Blizzard::Lock::EventWait(100, s_queueEvent) || Blizzard::Lock::EventWait(5, s_threadEvents[thread])) { + while (!s_stopThreads) { + if (s_paused) { + WaitForSingleObject(s_pauseEvent, INFINITE); + SetEvent(s_pauseEvent); + } + + EnterCriticalSection(&s_queueLock); + s_busyMask |= bit; + + FILE_THREAD_CMD* command = nullptr; + int32_t queue = GetNextCommand(&command, thread); + + if (queue == 7) { + LeaveCriticalSection(&s_queueLock); + break; + } + + int32_t pending = 0; + + for (int32_t i = 0; i < 7; i++) { + pending += static_cast(s_queues[i]->size()); + } + + if (pending > 0) { + int32_t idle = GetIdleThread(); + + if (idle >= 0) { + SetEvent(s_threadEvents[idle]); + } + } + + LeaveCriticalSection(&s_queueLock); + + bool success = true; + bool requeue = false; + + if (!command->m_type) { + success = false; + } else if (command->m_type == 1) { + if (LoadFile(command->m_fs, command->m_file, command->m_range)) { + command->m_type = 0; + } else if (command->m_type && !command->m_completion) { + requeue = true; + success = false; + } + } else if (command->m_type == 2) { + command->m_type = 0; + + if (!pending) { + WaitForLoads(); + } + } + + if (command->m_completion) { + command->m_completion->m_result = static_cast(s_queues[queue]->size()); + command->m_completion->m_done = false; + command->m_completion->m_success = success; + SetEvent(*command->m_completion->m_event); + command->m_completion = nullptr; + } + + EnterCriticalSection(&s_queueLock); + + if (requeue) { + s_queues[queue]->push_front(*command); + AddStreamed(0); + } + + FILE_THREAD_CMD* current = s_currentCommands[thread]; + + if (current) { + s_currentCommands[thread] = nullptr; + Blizzard::Memory::Free(current->m_range); + delete current; + s_commandsFreed++; + } + + LeaveCriticalSection(&s_queueLock); + + System_File::FileError& error = System_File::s_error; + + if (error.m_errorStack) { + Blizzard::Debug::FreeErrorStack(error.m_errorStack); + } + + error.m_errorStack = nullptr; + + if (queue > 2) { + WaitForSingleObject(s_throttleEvent, FileManifest::GetBGPreloadSleep()); + } + } + } + + EnterCriticalSection(&s_queueLock); + s_busyMask &= ~bit; + LeaveCriticalSection(&s_queueLock); + + if (s_stopThreads) { + break; + } + } + } + + EnterCriticalSection(&s_queueLock); + s_threadMask &= ~bit; + LeaveCriticalSection(&s_queueLock); + + return 1; +} + +// OFFSET: 0x004616A0 +bool Blizzard::Streaming::InitializeStreaming(const char* manifest, const char* storagePath, const char* variant, const char* dataPath, bool required) { + if (s_streamingReady) { + return true; + } + + char cwd[260]; + cwd[0] = '\0'; + + if (!Blizzard::File::GetWorkingDirectory(cwd, sizeof(cwd))) { + Blizzard::File::AddToLastErrorStack(0, "InitializeStreaming - Failed to get working directory", 20); + return false; + } + + char root[260]; + + if (!manifest || Blizzard::String::EqualI(manifest, s_httpPrefix, s_httpPrefix ? strlen(s_httpPrefix) : 0)) { + Blizzard::String::Copy(root, cwd, sizeof(root)); + } else { + char absolute[260]; + + if (!Blizzard::File::MakeAbsolutePath(manifest, absolute, sizeof(absolute), false)) { + Blizzard::File::AddToLastErrorStack(0, "InitializeStreaming - Failed to make absolute manifest path", 20); + return false; + } + + int32_t length = static_cast(Blizzard::String::FindFilename(absolute) - absolute + 1); + Blizzard::String::Copy(root, absolute, length <= 260 ? length : 260); + } + + if (dataPath && (!Blizzard::File::MakeAbsolutePath(dataPath, root, sizeof(root), false) || !Blizzard::File::IsDirectory(dataPath))) { + Blizzard::File::AddToLastErrorStack(0, "InitializeStreaming - Invalid data path specified", 20); + } + + if (variant && *variant) { + Blizzard::String::Copy(Blizzard::Storage::s_variantName, variant, sizeof(Blizzard::Storage::s_variantName)); + } + + if (!Blizzard::File::SetWorkingDirectory(root)) { + Blizzard::File::AddToLastErrorStack(0, "InitializeStreaming - Failed to change working directory", 20); + return false; + } + + s_paths = new PathMap(); + + bool manifestLoaded = ManifestInfo::Initialize(manifest); + s_isStreamingTrial = FileManifest::GetIsStreamingTrial(); + + if (!manifestLoaded) { + Blizzard::File::SetWorkingDirectory(cwd); + Blizzard::File::AddToLastErrorStack(0, "InitializeStreaming - Could not load manifest", 20); + return false; + } + + bool storage = true; + + if (storagePath && *storagePath) { + if (!Blizzard::Storage::Initialize(storagePath, required)) { + if (required) { + storage = false; + } else { + storage = Blizzard::Storage::Initialize(); + Blizzard::File::Delete(storagePath); + } + } + } else { + storage = Blizzard::Storage::Initialize(); + } + + if (!storage) { + Blizzard::File::SetWorkingDirectory(cwd); + Blizzard::File::AddToLastErrorStack(0, "InitializeStreaming - Could not initialize storage", 20); + return false; + } + + s_digestStates = new DigestStateMap(); + + for (int32_t i = 0; i < 7; i++) { + s_queues[i] = new std::deque(); + } + + InitializeCriticalSection(&s_queueLock); + s_queueEvent = CreateEventA(nullptr, FALSE, FALSE, nullptr); + s_throttleEvent = CreateEventA(nullptr, FALSE, FALSE, nullptr); + + for (int32_t i = 0; i < 2; i++) { + s_currentCommands[i] = nullptr; + s_threadEvents[i] = CreateEventA(nullptr, FALSE, FALSE, nullptr); + + int32_t* thread = new int32_t; + *thread = i; + Blizzard::Thread::CreateDetached(DownloadThread, thread, Blizzard::String::QuickFormat<1024>("Stream BG DL %d", i).m_buffer); + } + + s_paused = false; + InitializeCriticalSection(&s_pauseLock); + s_pauseEvent = CreateEventA(nullptr, FALSE, FALSE, nullptr); + + System_File::Stacked::PushStreaming(); + s_streamingReady = true; + + if (Blizzard::File::SetWorkingDirectory(cwd)) { + return true; + } + + Blizzard::File::AddToLastErrorStack(0, "InitializeStreaming - Failed to restore working directory", 20); + return false; +} // OFFSET: 0x004294C0 char* GetComponentVersionData(uint32_t* size) { @@ -101,12 +1181,12 @@ char* GetComponentVersionData(uint32_t* size) { // OFFSET: 0x0044B570 std::string Blizzard::Streaming::ResolveFilePath(const std::string& path) { - if (!unk_B38298) { + if (!s_paths) { return std::string(); } - if ((*unk_B38298)[path].size()) { - return (*unk_B38298)[path]; + if ((*s_paths)[path].size()) { + return (*s_paths)[path]; } char absolute[260]; @@ -138,8 +1218,8 @@ std::string Blizzard::Streaming::ResolveFilePath(const std::string& path) { } StringToLower(normalized); - (*unk_B38298)[path].assign(normalized, strlen(normalized)); - return std::string((*unk_B38298)[path]); + (*s_paths)[path].assign(normalized, strlen(normalized)); + return std::string((*s_paths)[path]); } // OFFSET: 0x0044EFB0 @@ -150,79 +1230,56 @@ bool Blizzard::Streaming::IsStreamedFile(const char* path) { std::string resolved = Blizzard::Streaming::ResolveFilePath(std::string(path)); - if (!unk_B38174) { + if (!Blizzard::Storage::s_storage) { return false; } - return unk_B38174->find(resolved) != unk_B38174->end(); -} - -// OFFSET: 0x004508B0 -static void StopThread() { - if (unk_B3817C && unk_B38174) { - unk_B3817E = true; - SetEvent(unk_B325D8); - - while (!unk_B3817F) { - Sleep(10); - } - - CloseHandle(unk_B325D8); - DeleteCriticalSection(&unk_B325C0); - unk_B325C0.DebugInfo = nullptr; - - if (unk_B38178) { - Blizzard::File::Close(unk_B38178); - } - } - - delete unk_B38174; - unk_B38174 = nullptr; + return Blizzard::Storage::s_storage->find(resolved) != Blizzard::Storage::s_storage->end(); } // OFFSET: 0x00457680 void StopStreaming() { if (Blizzard::Streaming::s_streamingReady) { - unk_B386D0.FireCallback(); - unk_B38182 = true; - SetEvent(unk_B325DC); - SetEvent(unk_B3252C); - unk_B325B8 = false; - SetEvent(unk_B32550); + Blizzard::Streaming::s_progress.FireCallback(); + s_stopThreads = true; + SetEvent(s_queueEvent); + SetEvent(s_throttleEvent); + s_paused = false; + SetEvent(s_pauseEvent); - while (unk_B38184 > 0) { + while (s_threadMask > 0) { Sleep(10); } - CloseHandle(unk_B325DC); - CloseHandle(unk_B3252C); + CloseHandle(s_queueEvent); + CloseHandle(s_throttleEvent); - for (uint32_t i = 0; i < sizeof(unk_B32548) / sizeof(unk_B32548[0]); i++) { - CloseHandle(unk_B32548[i]); - delete unk_B32554[i]; + for (uint32_t i = 0; i < sizeof(s_threadEvents) / sizeof(s_threadEvents[0]); i++) { + CloseHandle(s_threadEvents[i]); + delete s_currentCommands[i]; } - DeleteCriticalSection(&unk_B32530); - unk_B32530.DebugInfo = nullptr; - CloseHandle(unk_B32550); - DeleteCriticalSection(&unk_B325A0); - unk_B325A0.DebugInfo = nullptr; + DeleteCriticalSection(&s_queueLock); + s_queueLock.DebugInfo = nullptr; + CloseHandle(s_pauseEvent); + DeleteCriticalSection(&s_pauseLock); + s_pauseLock.DebugInfo = nullptr; - delete unk_B38294; + delete s_digestStates; - for (uint32_t i = 0; i < sizeof(unk_B3255C) / sizeof(unk_B3255C[0]); i++) { - delete unk_B3255C[i]; + for (uint32_t i = 0; i < sizeof(s_queues) / sizeof(s_queues[0]); i++) { + delete s_queues[i]; } - delete unk_B38298; - unk_B38298 = nullptr; + delete s_paths; + s_paths = nullptr; Blizzard::Streaming::s_streamingReady = false; } - StopThread(); + Blizzard::Storage::Shutdown(); - delete unk_B38170; - unk_B38170 = nullptr; + delete Blizzard::Streaming::ManifestInfo::s_instance; + Blizzard::Streaming::ManifestInfo::s_instance = nullptr; } #endif diff --git a/Engine/Source/BlizzardCore/Source/Packages/Streaming/Win64/Transport.cpp b/Engine/Source/BlizzardCore/Source/Packages/Streaming/Win64/Transport.cpp new file mode 100644 index 0000000..24965cf --- /dev/null +++ b/Engine/Source/BlizzardCore/Source/Packages/Streaming/Win64/Transport.cpp @@ -0,0 +1,563 @@ +#if defined(WOWDECOMP_ARCH_64) + +#include +#include +#include +#include +#include +#include +#include "Engine/Source/BlizzardCore/Include/Blizzard/Util/Digest.h" +#include "Engine/Source/BlizzardCore/Include/Blizzard/Util/MD5.h" +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Manifests.h" +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Streaming.h" +#include "Engine/Source/BlizzardCore/Source/System/Debug/ErrorStack.h" +#include "Engine/Source/BlizzardCore/Source/System/File/File.h" +#include "Engine/Source/BlizzardCore/Source/System/Log/Log.h" +#include "Engine/Source/BlizzardCore/Source/System/String/String.h" +#include "Engine/Source/BlizzardCore/Source/System/Time/Time.h" +#include "Engine/Source/BlizzardCore/Source/System/URL/URL.h" + +// STATIC: 0x00AB909E +static bool s_transportShouldBlock = true; + +// STATIC: 0x00AB91B8 +static double s_throttleScale = 0.0085; + +// STATIC: 0x00AB923C +static uint32_t s_transportTimeout = 10000; + +// STATIC: 0x00AB9390 +static std::string s_cookieName; + +// STATIC: 0x00AB93AC +static std::string s_cookieValue; + +// STATIC: 0x00B38028 +static int64_t s_throttleBias; + +// STATIC: 0x00B38030 +static int64_t s_throttleDebt; + +// OFFSET: 0x00427DE0 +int32_t Blizzard::Streaming::Transport::AdjustRange(int64_t* start, int64_t* end, int32_t md5Size, int64_t fileSize) { + int64_t alignedStart = *start - *start % md5Size; + int64_t alignedEnd = md5Size + *end - (md5Size + *end) % md5Size - 1; + int64_t firstChunk = alignedStart / md5Size; + int64_t lastChunk = (alignedEnd + 1) / md5Size - 1; + + if (alignedEnd > fileSize) { + alignedEnd = fileSize - 1; + } + + int32_t skip = static_cast(32 * firstChunk); + int64_t original = *start; + *start = skip + alignedStart; + *end = alignedEnd + 32 * (lastChunk + 1); + + return static_cast(skip + original - *start); +} + +// OFFSET: 0x0042D650 +void Blizzard::Streaming::TransportHttpCallback::Completed(Blizzard::URL::DownloadCallback::Status status) { + this->m_status = status; + + switch (status) { + case Blizzard::URL::DownloadCallback::DOWNLOAD_SUCCESS: + case Blizzard::URL::DownloadCallback::DOWNLOAD_STOPPED: + this->m_success = true; + break; + + case Blizzard::URL::DownloadCallback::DOWNLOAD_FAILED: + case Blizzard::URL::DownloadCallback::DOWNLOAD_TIMEOUT: + case Blizzard::URL::DownloadCallback::DOWNLOAD_NOT_FOUND: + case Blizzard::URL::DownloadCallback::DOWNLOAD_NOT_MODIFIED: + case Blizzard::URL::DownloadCallback::DOWNLOAD_ABORTED: + case Blizzard::URL::DownloadCallback::DOWNLOAD_FORBIDDEN: + case Blizzard::URL::DownloadCallback::DOWNLOAD_NAME_NOT_RESOLVED: + case Blizzard::URL::DownloadCallback::DOWNLOAD_CANNOT_CONNECT: + case Blizzard::URL::DownloadCallback::DOWNLOAD_BAD_REQUEST: + case Blizzard::URL::DownloadCallback::DOWNLOAD_UNKNOWN_ERROR: + this->m_success = false; + break; + } + + SetEvent(this->m_event); +} + +// OFFSET: 0x00437920 +void Blizzard::Streaming::Transport::THROTTLE::Wait() { + int64_t delta = s_throttleBias + this->m_start + static_cast(this->m_bytes * s_throttleScale) - Blizzard::Time::GetTimestamp(); + s_throttleDebt += delta; + + if (s_throttleDebt < 0 || s_throttleDebt <= 1000000) { + return; + } + + do { + Blizzard::Time::Timestamp start = Blizzard::Time::GetTimestamp(); + int64_t milliseconds = s_throttleDebt / 1000000; + int32_t sleep = milliseconds <= 100 ? static_cast(milliseconds) : 100; + + if (sleep > 0) { + Sleep(sleep); + } + + s_throttleDebt += start - Blizzard::Time::GetTimestamp(); + } while (s_throttleDebt > 1000000); +} + +// OFFSET: 0x00437AD0 +Blizzard::Streaming::TransportHttpCallback::~TransportHttpCallback() { + CloseHandle(this->m_event); +} + +// OFFSET: 0x00437B50 +int32_t Blizzard::Streaming::TransportHttpCallback::GetTimeout() { + return this->m_timeout; +} + +// OFFSET: 0x00437B60 +Blizzard::URL::DownloadCallback::ByteRange Blizzard::Streaming::TransportHttpCallback::GetByteRange() { + ByteRange range; + range.m_start = this->m_rangeStart; + range.m_end = this->m_rangeEnd; + return range; +} + +// OFFSET: 0x00437B90 +bool Blizzard::Streaming::TransportHttpCallback::ShouldBlock() { + return s_transportShouldBlock; +} + +// OFFSET: 0x00437BA0 +void Blizzard::Streaming::TransportHttpCallback::SetByteRange(int64_t start, int64_t end) { + this->m_rangeStart = start; + this->m_rangeEnd = end; +} + +// OFFSET: 0x00437BC0 +void Blizzard::Streaming::TransportHttpCallback::SetTimeOutValue(uint32_t timeout) { + this->m_timeout = timeout; +} + +// OFFSET: 0x00437BD0 +bool Blizzard::Streaming::TransportHttpCallback::Stop() { + return this->m_stop; +} + +// OFFSET: 0x00437BE0 +Blizzard::URL::DownloadCallback::Cookie Blizzard::Streaming::TransportHttpCallback::GetCookie() { + Cookie cookie; + cookie.m_name = this->m_cookieName.c_str(); + cookie.m_value = this->m_cookieValue.c_str(); + return cookie; +} + +// OFFSET: 0x00437C20 +bool Blizzard::Streaming::Transport::ReadFile(Manifests::TransportItem* transport, std::string url, int32_t maxRetry, void* data, int64_t fileSize, int64_t offset, int32_t size) { + Blizzard::File::StreamRecord* file; + + if (!Blizzard::File::Open(url.c_str() + 7, 4101, file)) { + return false; + } + + int32_t count = size; + + if (Blizzard::File::Read(file, data, offset, &count) && count == size) { + Blizzard::File::Close(file); + return true; + } + + Blizzard::File::Close(file); + return false; +} + +// OFFSET: 0x00439B20 +Blizzard::Streaming::TransportHttpCallback::TransportHttpCallback(uint32_t size) { + this->m_cookieName.erase(this->m_cookieName.begin(), this->m_cookieName.end()); + this->m_cookieValue.erase(this->m_cookieValue.begin(), this->m_cookieValue.end()); + this->m_data.reserve(size); + this->m_data.erase(this->m_data.begin(), this->m_data.end()); + this->m_received = 0; + this->m_rangeStart = 0; + this->m_rangeEnd = 0; + this->m_timeout = s_transportTimeout; + this->m_stop = false; + this->m_success = false; + this->m_event = CreateEventA(nullptr, FALSE, FALSE, nullptr); +} + +// OFFSET: 0x0043ABD0 +void Blizzard::Streaming::TransportHttpCallback::SetCookie(const char* name, const char* value) { + this->m_cookieName.assign(name, strlen(name)); + this->m_cookieValue.assign(value, strlen(value)); +} + +// OFFSET: 0x0043AC20 +bool Blizzard::Streaming::TransportHttpCallback::ReceivedData(const void* data, int32_t size) { + if (this->m_received >= this->m_rangeEnd - this->m_rangeStart + 1) { + this->m_stop = true; + } + + if (size <= 0) { + return true; + } + + int64_t left = this->m_rangeEnd - this->m_rangeStart - this->m_received + 1; + int32_t take = size >= left ? static_cast(left) : size; + + this->m_data.append(static_cast(data), take); + this->m_received += take; + + if (take != size) { + this->m_stop = true; + } + + return true; +} + +// OFFSET: 0x0043D7B0 +Blizzard::Streaming::URL_INFO::URL_INFO(std::string url, int64_t start, int64_t end, int32_t size) { + this->m_start = start; + this->m_end = end; + this->m_size = size; + this->m_url = url; +} + +// OFFSET: 0x0043D840 +bool Blizzard::Streaming::Transport::MD5_Data(std::string* out, std::string* data, int32_t md5Size, int64_t start, int64_t end) { + bool result = false; + + std::string chunk; + chunk.reserve(static_cast(end - start + 1)); + + out->reserve(data->size()); + out->erase(out->begin(), out->end()); + + std::string hash; + hash.reserve(32); + + uint32_t position = 0; + uint32_t consumed = 0; + + if (data->size()) { + uint32_t hashOffset = 0; + uint32_t blockEnd = md5Size; + + for (;;) { + chunk.erase(chunk.begin(), chunk.end()); + + uint32_t length = md5Size; + uint32_t next = position + md5Size + 32; + + if (next > data->size()) { + length = data->size() - position - 32; + } + + chunk = data->substr(position, length); + consumed += length + 32; + out->append(chunk); + + hash.erase(hash.begin(), hash.end()); + + uint32_t hashPosition = blockEnd + hashOffset; + + if (blockEnd + hashOffset + 32 > data->size()) { + hashPosition = data->size() - 32; + } + + Blizzard::Util::Digest<16> expected; + expected.FromHexString(data->substr(hashPosition, 32).c_str()); + + Blizzard::Util::MD5 md5; + md5.Process(chunk.c_str(), chunk.size()); + + Blizzard::Util::Digest<16> actual; + md5.Finish(actual.m_data); + + result = actual == expected; + + if (!result) { + break; + } + + blockEnd += md5Size; + hashOffset += 32; + position = next; + + if (consumed >= data->size()) { + break; + } + } + } + + return result; +} + +// OFFSET: 0x00452320 +void Blizzard::Streaming::Transport::GetSplitFileURL(const std::string& url, int64_t start, int64_t end, int32_t skip, int32_t splitSize, int32_t md5Size, int32_t size, std::vector* urls) { + if (md5Size) { + splitSize += 32 * (splitSize / md5Size); + } + + int64_t first = start / splitSize; + int64_t firstOffset = start % splitSize; + int64_t last = (end - 1) / splitSize; + int32_t previous = 0; + + if (first != last) { + Blizzard::Log::Printf(3, "Logs/Profiling_MPQSplit.log", "Got split %s, %d-d\n", url.c_str(), start, end); + } + + if (first > last) { + return; + } + + int64_t lastOffset = end % splitSize; + + for (int64_t chunk = first; chunk <= last; chunk++) { + int64_t chunkStart = chunk == first ? firstOffset : 0; + int64_t chunkEnd = lastOffset; + + if (lastOffset < chunkStart) { + chunkEnd = splitSize - 1; + } + + int64_t length = chunkEnd - chunkStart + 1; + int32_t blocks = static_cast(length / (md5Size + 32)); + + if (length % (md5Size + 32)) { + blocks++; + } + + int32_t chunkSize; + + if (chunk == first) { + chunkSize = static_cast(chunkEnd - 32 * blocks - chunkStart - skip + 1); + } else { + chunkSize = size - previous; + } + + previous = chunkSize; + + char number[260]; + sprintf(number, "%d", static_cast(chunk)); + + std::string chunkUrl = url; + chunkUrl.append(".", 1); + chunkUrl.append(number, strlen(number)); + + urls->push_back(URL_INFO(std::string(chunkUrl), chunkStart, chunkEnd, chunkSize)); + } +} + +// OFFSET: 0x00455F10 +bool Blizzard::Streaming::Transport::ReadHttp(Manifests::TransportItem* transport, std::string url, int32_t maxRetry, void* data, int64_t fileSize, int64_t offset, int32_t size) { + int32_t error = 0; + + TransportHttpCallback* callback = new TransportHttpCallback(size); + + std::string baseUrl = url; + int64_t start = offset; + int64_t end = offset + size - 1; + int32_t skip = 0; + std::vector urls; + + if (transport) { + skip = AdjustRange(&start, &end, transport->m_md5Size, fileSize); + + if (skip) { + printf("offset is %d\n", skip); + } + + if (transport->m_splitSize > 0) { + GetSplitFileURL(baseUrl, start, end, skip, transport->m_splitSize, transport->m_md5Size, size, &urls); + } + } else { + urls.push_back(URL_INFO(std::string(baseUrl), offset, offset + size - 1, size)); + } + + bool result = false; + int32_t copied = 0; + + for (uint32_t i = 0; i < urls.size(); i++) { + result = false; + + std::string current = urls[i].m_url; + int64_t rangeStart = urls[i].m_start; + int64_t rangeEnd = urls[i].m_end; + int32_t rangeSize = urls[i].m_size; + + callback->m_data.erase(callback->m_data.begin(), callback->m_data.end()); + callback->m_received = 0; + callback->m_stop = false; + callback->m_success = false; + callback->SetByteRange(rangeStart, rangeEnd); + + if (s_cookieName.size() && s_cookieValue.size()) { + callback->SetCookie(s_cookieName.c_str(), s_cookieValue.c_str()); + } + + std::string checked; + + for (int32_t attempt = 0; attempt < maxRetry; attempt++) { + if (attempt) { + s_statRetries++; + } + + result = Blizzard::URL::DownloadURL(current.c_str(), callback); + + if (!result) { + error = 1; + Sleep(10); + } else { + WaitForSingleObject(callback->m_event, INFINITE); + result = callback->m_success; + + if (!result) { + error = 3; + Sleep(10); + } else if (rangeEnd - rangeStart + 1 != callback->m_data.size()) { + result = false; + error = 2; + } else { + result = true; + + if (transport) { + result = MD5_Data(&checked, &callback->m_data, transport->m_md5Size, rangeStart, rangeEnd); + + if (!result) { + error = 4; + } + } + } + } + + if (result) { + break; + } + + callback->m_data.erase(callback->m_data.begin(), callback->m_data.end()); + callback->m_received = 0; + callback->m_stop = false; + callback->m_success = false; + + if (callback->m_status == Blizzard::URL::DownloadCallback::DOWNLOAD_TIMEOUT) { + callback->SetTimeOutValue(2 * callback->GetTimeout()); + } + } + + if (!result) { + continue; + } + + if (transport) { + memmove(static_cast(data) + copied, checked.c_str() + skip, rangeSize); + } else { + memmove(data, callback->m_data.c_str(), size); + } + + copied += rangeSize; + } + + if (result && copied != size) { + error = 5; + result = false; + } + + if (!result) { + const char* message; + + switch (error) { + case 1: + message = "DownloadURL failed with no error"; + break; + + case 2: + message = "Downloaded smaller than expected"; + break; + + case 3: + if (callback->m_status == Blizzard::URL::DownloadCallback::DOWNLOAD_TIMEOUT) { + message = "DownloadURL failed - Timed out"; + } else if (callback->m_status == Blizzard::URL::DownloadCallback::DOWNLOAD_NOT_FOUND) { + message = "DownloadURL failed - File not found"; + } else { + message = "DownloadURL failed"; + } + + break; + + case 4: + message = "MD5 check failed"; + break; + + case 5: + message = "Copied smaller than expected"; + break; + + default: + message = "Unknown error"; + break; + } + + Blizzard::Log::Printf(3, "Logs/Streaming_Error.log", "%d - %s - %s\n", callback->m_status, message, url.c_str()); + + Blizzard::String::QuickFormat<1024> text("%s - %s", message, url.c_str()); + System_File::FileError& fileError = System_File::s_error; + Blizzard::Debug::ErrorStackRecord* stack = Blizzard::Debug::AddErrorToStack(fileError.m_errorStack, callback->m_status, text.m_buffer, 21); + + if (stack) { + System_File::FileError& current = System_File::s_error; + + if (current.m_errorStack != stack) { + Blizzard::Debug::FreeErrorStack(current.m_errorStack); + } + + current.m_errorStack = stack; + } + } + + if (callback) { + delete callback; + } + + return result; +} + +// OFFSET: 0x004592B0 +bool Blizzard::Streaming::Transport::Read(Manifests::TransportItem* transport, std::string url, int32_t maxRetry, void* data, int64_t fileSize, int64_t offset, int32_t size) { + struct Handler { + const char* m_prefix; + bool (*m_read)(Manifests::TransportItem*, std::string, int32_t, void*, int64_t, int64_t, int32_t); + }; + + Handler handlers[3] = { + { "file://", ReadFile }, + { "http://", ReadHttp }, + { nullptr, nullptr } + }; + + bool result = false; + + for (Handler* handler = handlers; handler->m_prefix; handler++) { + if (url.c_str() && !_strnicmp(url.c_str(), handler->m_prefix, strlen(handler->m_prefix))) { + THROTTLE throttle; + throttle.m_bytes = 0; + throttle.m_start = Blizzard::Time::GetTimestamp(); + + result = handler->m_read(transport, std::string(url), maxRetry, data, fileSize, offset, size); + + if (result) { + throttle.m_bytes = size; + } + + throttle.Wait(); + break; + } + } + + return result; +} + +#endif diff --git a/Engine/Source/BlizzardCore/Source/Packages/Util/MD5.cpp b/Engine/Source/BlizzardCore/Source/Packages/Util/MD5.cpp index a3727f9..b8ac76c 100644 --- a/Engine/Source/BlizzardCore/Source/Packages/Util/MD5.cpp +++ b/Engine/Source/BlizzardCore/Source/Packages/Util/MD5.cpp @@ -1,5 +1,6 @@ #include #include +#include "Engine/Source/BlizzardCore/Include/Blizzard/Util/Digest.h" #include "Engine/Source/BlizzardCore/Include/Blizzard/Util/MD5.h" #define MD5_ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n)))) @@ -9,6 +10,26 @@ #define MD5_I(x, y, z) ((y) ^ ((x) | ~(z))) #define MD5_STEP(f, a, b, c, d, k, s, ti) t = a + f(b, c, d) + x[k] + (ti); a = MD5_ROTATE_LEFT(t, s) + b +// STATIC: 0x009E54A0 +const uint8_t Blizzard::Util::s_hexDigits[256] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +}; + // STATIC: 0x00A505D8 static const uint8_t s_padding[64] = { 0x80 }; @@ -171,3 +192,11 @@ void Blizzard::Util::MD5::Process(const void* data, uint32_t size) { memcpy(this->m_buffer, p, left); } } + +// VERIFY: c43394ea manual +// OFFSET: 0x0042B320 +void Blizzard::Util::HashString(uint8_t* digest, const char* str) { + MD5 md5; + md5.Process(str, str ? static_cast(strlen(str)) : 0); + md5.Finish(digest); +} diff --git a/Engine/Source/BlizzardCore/Source/Packages/Util/SBig.cpp b/Engine/Source/BlizzardCore/Source/Packages/Util/SBig.cpp new file mode 100644 index 0000000..55081a5 --- /dev/null +++ b/Engine/Source/BlizzardCore/Source/Packages/Util/SBig.cpp @@ -0,0 +1,670 @@ +#include "SBig.h" +#include +#include +#include +#include + +// INLINED +inline uint32_t ExtractLowPart(uint64_t& value) { + uint32_t low = static_cast(value); + value >>= 32; + return low; +} + +// INLINED +inline uint32_t ExtractLowPartSx(uint64_t& value) { + uint32_t low = static_cast(value); + value >>= 32; + + if (value >= 0x80000000) { + value |= 0xFFFFFFFF00000000ULL; + } + + return low; +} + +// INLINED +inline uint32_t ExtractLowPartLargeSum(uint64_t& value, uint64_t add) { + value += add; + uint32_t carry = value < add; + uint32_t low = ExtractLowPart(value); + value += static_cast(carry) << 32; + return low; +} + +// INLINED +inline void InsertLowPart(uint64_t& value, uint32_t low) { + value = (value << 32) + low; +} + +// INLINED +inline uint64_t MakeLarge(uint32_t low, uint32_t high) { + return low + (static_cast(high) << 32); +} + +// VERIFY: 1f93de79 manual +// OFFSET: 0x00443D30 +Blizzard::BigBuffer::BigBuffer() { + this->m_offset = 0; +} + +// VERIFY: f4f2b38e manual +// OFFSET: 0x00446260 +uint32_t& Blizzard::BigBuffer::operator[](uint32_t index) { + this->GrowToFit(index); + return this->m_data[index + this->m_offset]; +} + +// VERIFY: e08d76c1 manual +// OFFSET: 0x00431060 +uint32_t Blizzard::BigBuffer::operator[](uint32_t index) const { + return this->IsUsed(index) ? this->m_data[index + this->m_offset] : 0; +} + +// INLINED +inline void Blizzard::BigBuffer::Clear() { + this->m_data.resize(this->m_offset, 0); +} + +// VERIFY: e1bff0cb manual +// OFFSET: 0x0042BBA0 +uint32_t Blizzard::BigBuffer::Count() const { + return static_cast(this->m_data.size()) - this->m_offset; +} + +// INLINED +inline void Blizzard::BigBuffer::GrowToFit(uint32_t index) { + uint32_t count = index + this->m_offset + 1; + uint32_t size = static_cast(this->m_data.size()); + this->m_data.resize(count < size ? size : count, 0); +} + +// INLINED +inline int32_t Blizzard::BigBuffer::IsUsed(uint32_t index) const { + return index + this->m_offset < this->m_data.size(); +} + +// INLINED +inline void Blizzard::BigBuffer::SetCount(uint32_t count) { + this->m_data.resize(count + this->m_offset, 0); +} + +// INLINED +inline void Blizzard::BigBuffer::SetOffset(uint32_t offset) { + this->m_offset = offset; + + if (offset) { + this->GrowToFit(0xFFFFFFFF); + } +} + +// VERIFY: e1005b4f manual +// OFFSET: 0x004395D0 +void Blizzard::BigBuffer::Trim() const { + while (this->Count() && !this->m_data.back()) { + this->m_data.pop_back(); + } +} + +// INLINED +inline Blizzard::BigStack::BigStack() { + this->m_used = 0; +} + +// INLINED +inline Blizzard::BigStack::~BigStack() { +} + +// INLINED +inline Blizzard::BigBuffer& Blizzard::BigStack::Alloc(uint32_t* count) { + if (count) { + ++*count; + } + + return this->m_buffer[this->m_used++]; +} + +// INLINED +inline void Blizzard::BigStack::Free(uint32_t count) { + this->m_used -= count; +} + +// INLINED +inline Blizzard::BigBuffer& Blizzard::BigStack::MakeDistinct(BigBuffer& orig, int32_t required) { + return required ? this->Alloc(nullptr) : orig; +} + +// INLINED +inline void Blizzard::BigStack::UnmakeDistinct(BigBuffer& orig, BigBuffer& distinct) { + if (&orig != &distinct) { + orig = distinct; + this->Free(1); + } +} + +// INLINED +inline std::vector& Blizzard::BigData::Output() const { + return this->m_output; +} + +// INLINED +inline Blizzard::BigBuffer& Blizzard::BigData::Primary() { + return this->m_primary; +} + +// INLINED +inline const Blizzard::BigBuffer& Blizzard::BigData::Primary() const { + return this->m_primary; +} + +// INLINED +inline Blizzard::BigStack& Blizzard::BigData::Stack() const { + return this->m_stack; +} + +// VERIFY: 693c6ebe manual +// OFFSET: 0x004310B0 +static int32_t Compare(const Blizzard::BigBuffer& a, const Blizzard::BigBuffer& b) { + int32_t result = 0; + + for (uint32_t i = 0; a.IsUsed(i) || b.IsUsed(i); ++i) { + if (a[i] != b[i]) { + result = b[i] < a[i] ? 1 : -1; + } + } + + return result; +} + +// VERIFY: cb9622bc manual +// OFFSET: 0x00431220 +static uint32_t HighBitPos(const Blizzard::BigBuffer& a) { + uint32_t index = a.Count(); + + while (index) { + --index; + + if (a[index]) { + uint32_t mask = 0x80000000; + + for (uint32_t bit = 32; bit; mask >>= 1) { + --bit; + + if (a[index] & mask) { + return bit + 32 * index; + } + } + } + } + + return 0; +} + +// VERIFY: 4e76115e manual +// OFFSET: 0x004462D0 +static void Div(Blizzard::BigBuffer& a, uint32_t* b, const Blizzard::BigBuffer& c, uint64_t d) { + a.SetCount(c.Count()); + + uint64_t data = 0; + uint32_t i = c.Count(); + + while (i) { + --i; + InsertLowPart(data, c[i]); + a[i] = static_cast(data / d); + data %= d; + } + + a.Trim(); + *b = static_cast(data); +} + +// VERIFY: 93bc6b11 manual +// OFFSET: 0x00446420 +static void Mul(Blizzard::BigBuffer& a, const Blizzard::BigBuffer& b, uint64_t c) { + uint64_t carry = 0; + uint32_t i = 0; + + for (; carry || b.IsUsed(i); ++i) { + carry += b[i] * c; + a[i] = ExtractLowPart(carry); + } + + a.SetCount(i); +} + +// VERIFY: 82495513 manual +// OFFSET: 0x004464F0 +static void Mul(Blizzard::BigBuffer& a, const Blizzard::BigBuffer& b, const Blizzard::BigBuffer& c, Blizzard::BigStack& stack) { + Blizzard::BigBuffer& aa = stack.MakeDistinct(a, &a == &b || &a == &c); + aa.Clear(); + + for (uint32_t bIndex = 0; b.IsUsed(bIndex); ++bIndex) { + uint64_t carry = 0; + uint32_t cIndex = 0; + + for (; c.IsUsed(cIndex); ++cIndex) { + carry += aa[bIndex + cIndex] + static_cast(b[bIndex]) * c[cIndex]; + aa[bIndex + cIndex] = ExtractLowPart(carry); + } + + aa[bIndex + cIndex] = ExtractLowPart(carry); + } + + stack.UnmakeDistinct(a, aa); +} + +// VERIFY: d5fbc759 manual +// OFFSET: 0x004467B0 +static void Shl(Blizzard::BigBuffer& a, const Blizzard::BigBuffer& b, uint32_t c) { + uint32_t cWords = c >> 5; + uint32_t cBits = c & 0x1F; + uint32_t aCount = b.Count() + cWords + 1; + uint32_t aIndex = aCount; + + while (aIndex) { + --aIndex; + uint32_t value = 0; + + if (aIndex >= cWords) { + value = b[aIndex - cWords] << cBits; + + if (aIndex > cWords) { + if (cBits) { + value += b[aIndex - cWords - 1] >> (32 - cBits); + } + } + } + + a[aIndex] = value; + } + + a.SetCount(aCount); + a.Trim(); +} + +// VERIFY: 69d2980e manual +// OFFSET: 0x00446940 +static void Shr(Blizzard::BigBuffer& a, const Blizzard::BigBuffer& b, uint32_t c) { + uint32_t cWords = c >> 5; + uint32_t cBits = c & 0x1F; + uint32_t i = 0; + + for (; b.IsUsed(i + cWords); ++i) { + uint32_t value = b[i + cWords] >> cBits; + + if (cBits) { + value += b[i + cWords + 1] << (32 - cBits); + } + + a[i] = value; + } + + a.SetCount(i); +} + +// VERIFY: 4b844ac8 manual +// OFFSET: 0x00446A40 +static void Square(Blizzard::BigBuffer& a, const Blizzard::BigBuffer& b, Blizzard::BigStack& stack) { + Blizzard::BigBuffer& aa = stack.MakeDistinct(a, &a == &b); + aa.Clear(); + + for (uint32_t i = 0; b.IsUsed(i); ++i) { + uint64_t carry = 0; + uint32_t j = 0; + + for (; j <= i; ++j) { + uint64_t mul = static_cast(b[i]) * b[j]; + uint64_t add = mul + aa[i + j]; + + if (j < i) { + carry += mul; + } + + aa[i + j] = ExtractLowPartLargeSum(carry, add); + } + + aa[i + j] = ExtractLowPart(carry); + } + + stack.UnmakeDistinct(a, aa); +} + +// VERIFY: 0d85ba57 manual +// OFFSET: 0x00446D00 +static void Sub(Blizzard::BigBuffer& a, const Blizzard::BigBuffer& b, const Blizzard::BigBuffer& c) { + uint64_t borrow = 0; + uint32_t i = 0; + + for (; b.IsUsed(i) || c.IsUsed(i); ++i) { + borrow += b[i] - static_cast(c[i]); + a[i] = ExtractLowPartSx(borrow); + } + + a.SetCount(i); +} + +// INLINED +inline void SetZero(Blizzard::BigBuffer& a) { + a.Clear(); +} + +// INLINED +inline void SetOne(Blizzard::BigBuffer& a) { + a.SetCount(1); + a[0] = 1; +} + +// VERIFY: 3076dfa4 auto +// OFFSET: 0x00446E30 +static void FromBinary(Blizzard::BigBuffer& a, const void* data, uint32_t bytes) { + a.Clear(); + + for (uint32_t i = 0; i < bytes; ++i) { + uint32_t byte = static_cast(data)[i]; + a[i >> 2] = ((i & 3) ? a[i >> 2] : 0) + (byte << (8 * (i & 3))); + } +} + +// VERIFY: 2972bf63 manual +// OFFSET: 0x00443D50 +static void ToBinaryAppend(std::vector& output, const Blizzard::BigBuffer& a) { + for (uint32_t i = 0; i < 4 * a.Count(); ++i) { + uint32_t value = a[i >> 2] >> (8 * (i & 3)); + + if (value || (i >> 2) + 1 < a.Count()) { + output.push_back(static_cast(value)); + } + } +} + +// INLINED +inline void ToBinary(std::vector& output, const Blizzard::BigBuffer& a) { + output.clear(); + ToBinaryAppend(output, a); +} + +// VERIFY: a5083fc6 manual +// OFFSET: 0x004494A0 +static void Div(Blizzard::BigBuffer& a, Blizzard::BigBuffer& b, const Blizzard::BigBuffer& c, const Blizzard::BigBuffer& d, Blizzard::BigStack& stack) { + c.Trim(); + d.Trim(); + + uint32_t cCount = c.Count(); + uint32_t dCount = d.Count(); + + if (dCount > cCount) { + b = c; + SetZero(a); + return; + } + + if (dCount <= 1) { + Div(a, &b[0], c, d[0]); + b.SetCount(1); + return; + } + + uint32_t allocCount = 0; + Blizzard::BigBuffer& cc = stack.Alloc(&allocCount); + Blizzard::BigBuffer& dd = stack.Alloc(&allocCount); + Blizzard::BigBuffer& work = stack.Alloc(&allocCount); + + uint32_t shift = 31 - (HighBitPos(d) & 0x1F); + Shl(cc, c, shift); + Shl(dd, d, shift); + + uint32_t t = dd[dCount - 1] + 1; + uint32_t index = cCount - dCount + 1; + a.SetCount(index); + + while (index) { + --index; + a.SetOffset(index); + cc.SetOffset(index); + + if (t) { + a[0] = static_cast(MakeLarge(cc[dCount - 1], cc[dCount]) / t); + } else { + a[0] = cc[dCount]; + } + + if (a[0]) { + Mul(work, dd, a[0]); + Sub(cc, cc, work); + } + + while (cc[dCount] || Compare(cc, dd) >= 0) { + ++a[0]; + Sub(cc, cc, dd); + } + } + + Shr(b, cc, shift); + b.Trim(); + stack.Free(allocCount); +} + +// INLINED +inline void MulMod(Blizzard::BigBuffer& a, const Blizzard::BigBuffer& b, const Blizzard::BigBuffer& c, const Blizzard::BigBuffer& d, Blizzard::BigStack& stack) { + uint32_t allocCount = 0; + Blizzard::BigBuffer& temp = stack.Alloc(&allocCount); + Mul(temp, b, c, stack); + Div(temp, a, temp, d, stack); + stack.Free(allocCount); +} + +// VERIFY: 49fdfca5 manual +// OFFSET: 0x00449820 +static void PowMod(Blizzard::BigBuffer& a, const Blizzard::BigBuffer& b, const Blizzard::BigBuffer& c, const Blizzard::BigBuffer& d, Blizzard::BigStack& stack) { + c.Trim(); + + if (!c.Count()) { + SetOne(a); + return; + } + + uint32_t allocCount = 0; + Blizzard::BigBuffer& temp = stack.Alloc(&allocCount); + Blizzard::BigBuffer& b2 = stack.Alloc(&allocCount); + Blizzard::BigBuffer& b3 = stack.Alloc(&allocCount); + Blizzard::BigBuffer& aa = stack.MakeDistinct(a, &a == &b || &a == &c || &a == &d); + + MulMod(b2, b, b, d, stack); + MulMod(b3, b2, b, d, stack); + + const Blizzard::BigBuffer* bPower[3] = { &b, &b2, &b3 }; + SetOne(aa); + + uint32_t cIndex = c.Count(); + + while (cIndex) { + --cIndex; + uint32_t ci = c[cIndex]; + uint32_t ciBits = 32; + + if (cIndex + 1 == c.Count()) { + while (!(ci & 0xC0000000)) { + ci <<= 2; + ciBits -= 2; + } + } + + for (uint32_t bit = 0; bit < ciBits; bit += 2) { + Square(aa, aa, stack); + Div(temp, aa, aa, d, stack); + Square(aa, aa, stack); + Div(temp, aa, aa, d, stack); + + if (ci >> 30) { + MulMod(aa, aa, *bPower[(ci >> 30) - 1], d, stack); + } + + ci <<= 2; + } + } + + stack.UnmakeDistinct(a, aa); + stack.Free(allocCount); +} + +// INLINED +inline void Blizzard::SBigDel(BigData* num) { + delete num; +} + +// INLINED +inline void Blizzard::SBigFromBinary(BigData* num, const void* data, uint32_t bytes) { + FromBinary(num->Primary(), data, bytes); +} + +// VERIFY: 78e6fe12 manual +// OFFSET: 0x00446EB0 +void Blizzard::SBigNew(BigData** num) { + *num = new BigData; +} + +// INLINED +inline void Blizzard::SBigPowMod(BigData* a, const BigData* b, const BigData* c, const BigData* d) { + PowMod(a->Primary(), b->Primary(), c->Primary(), d->Primary(), a->Stack()); +} + +// VERIFY: 38a8ab58 manual +// OFFSET: 0x00446F20 +void Blizzard::SBigToBinaryBuffer(const BigData* num, void* data, uint32_t maxBytes, uint32_t* bytes) { + std::vector& output = num->Output(); + ToBinary(output, num->Primary()); + + uint32_t count = maxBytes; + + if (output.size() < maxBytes) { + count = static_cast(output.size()); + } + + memcpy(data, output.data(), count); + + if (bytes) { + *bytes = count; + } +} + +// INLINED +inline Blizzard::BigNum::BigNum() { + SBigNew(&this->m_data); +} + +// INLINED +inline Blizzard::BigNum::~BigNum() { + SBigDel(this->m_data); +} + +// INLINED +inline void Blizzard::BigNum::FromBinary(const void* data, uint32_t bytes) { + SBigFromBinary(this->m_data, data, bytes); +} + +// INLINED +inline Blizzard::BigNum& Blizzard::BigNum::PowMod(const BigNum& b, const BigNum& c, const BigNum& d) { + SBigPowMod(this->m_data, b.m_data, c.m_data, d.m_data); + return *this; +} + +// INLINED +inline void* Blizzard::BigNum::ToBinaryBuffer(void* data, uint32_t bytes) const { + uint32_t written; + SBigToBinaryBuffer(this->m_data, data, bytes, &written); + + if (written < bytes) { + memset(static_cast(data) + written, 0, bytes - written); + } + + return data; +} + +// INLINED +inline void Blizzard::Crypt::RSA::Prepare(const void* modulus, uint32_t mLength, const void* exponent, uint32_t eLength) { + this->m_modulus.FromBinary(modulus, mLength); + this->m_exponent.FromBinary(exponent, eLength); +} + +// VERIFY: ce01fdce manual +// OFFSET: 0x0044B0E0 +void Blizzard::Crypt::RSA::Process(uint8_t* data, uint32_t length) { + BigNum src; + src.FromBinary(data, length); + BigNum dst; + dst.PowMod(src, this->m_exponent, this->m_modulus); + dst.ToBinaryBuffer(data, length); +} + +// VERIFY: 518d5063 manual +// OFFSET: 0x00435430 +void Blizzard::SSignatureVerifyStream_Begin(SSignatureData** token, uint32_t modulusSize, uint32_t pubExponentSize) { + *token = new SSignatureData; + (*token)->modulusSize = modulusSize; + (*token)->pubExponentSize = pubExponentSize; + (*token)->magicBufferUsed = 0; + (*token)->magicBufferSize = modulusSize + 4; + (*token)->magicBuffer.SetCount((*token)->magicBufferSize); + memset((*token)->magicBuffer.m_data, 0, (*token)->magicBufferSize); + (*token)->sha.Prepare(); +} + +// VERIFY: fb9a0f93 auto +// OFFSET: 0x0042C950 +void Blizzard::SSignatureVerifyStream_ProvideData(SSignatureData* token, const uint8_t* data, uint32_t size) { + int32_t excess = size - token->magicBufferSize; + + if (excess >= 0) { + if (token->magicBufferUsed) { + token->sha.Process(token->magicBuffer.m_data, token->magicBufferUsed); + } + + if (excess > 0) { + token->sha.Process(data, excess); + } + + memcpy(token->magicBuffer.m_data, data + excess, token->magicBufferSize); + token->magicBufferUsed = token->magicBufferSize; + } else { + int32_t flush = size + token->magicBufferUsed - token->magicBufferSize; + + if (flush > 0) { + token->sha.Process(token->magicBuffer.m_data, flush); + token->magicBufferUsed -= flush; + memmove(token->magicBuffer.m_data, token->magicBuffer.m_data + flush, token->magicBufferUsed); + } + + memcpy(token->magicBuffer.m_data + token->magicBufferUsed, data, size); + token->magicBufferUsed += size; + } +} + +// VERIFY: 75edd647 manual +// OFFSET: 0x0044B2B0 +bool Blizzard::SSignatureVerifyStream_Finish(SSignatureData* token, const uint8_t* modulus, const uint8_t* pubExponent) { + bool result = false; + + if (token->magicBufferUsed == token->magicBufferSize && *reinterpret_cast(token->magicBuffer.m_data) == 'SIGN') { + uint8_t* generated = static_cast(alloca(token->modulusSize)); + memset(generated, 0xBB, token->modulusSize); + generated[token->modulusSize - 1] = 0x0B; + token->sha.Finish(*reinterpret_cast(generated)); + + uint8_t* stored = static_cast(alloca(token->modulusSize)); + memcpy(stored, token->magicBuffer.m_data + 4, token->modulusSize); + + Crypt::RSA decoder; + decoder.Prepare(modulus, token->modulusSize, pubExponent, token->pubExponentSize); + decoder.Process(stored, token->modulusSize); + result = memcmp(stored, generated, token->modulusSize) == 0; + } + + if (token->magicBuffer.m_data) { + delete[] token->magicBuffer.m_data; + } + + delete token; + + return result; +} diff --git a/Engine/Source/BlizzardCore/Source/Packages/Util/SBig.h b/Engine/Source/BlizzardCore/Source/Packages/Util/SBig.h new file mode 100644 index 0000000..23aa84a --- /dev/null +++ b/Engine/Source/BlizzardCore/Source/Packages/Util/SBig.h @@ -0,0 +1,143 @@ +#ifndef ENGINE_SOURCE_BLIZZARDCORE_SOURCE_PACKAGES_UTIL_SBIG_H +#define ENGINE_SOURCE_BLIZZARDCORE_SOURCE_PACKAGES_UTIL_SBIG_H + +#include +#include +#include "_Triage/SHA1.h" + +namespace Blizzard { + +class BigBuffer { + public: + /* 0000 */ mutable std::vector m_data; + /* 0010 */ uint32_t m_offset; + + BigBuffer(); + uint32_t& operator[](uint32_t index); + uint32_t operator[](uint32_t index) const; + void Clear(); + uint32_t Count() const; + int32_t IsUsed(uint32_t index) const; + void SetCount(uint32_t count); + void SetOffset(uint32_t offset); + void Trim() const; + + private: + void GrowToFit(uint32_t index); +}; + +class BigStack { + public: + /* 0000 */ BigBuffer m_buffer[16]; + /* 0140 */ uint32_t m_used; + + BigStack(); + ~BigStack(); + BigBuffer& Alloc(uint32_t* count); + void Free(uint32_t count); + BigBuffer& MakeDistinct(BigBuffer& orig, int32_t required); + void UnmakeDistinct(BigBuffer& orig, BigBuffer& distinct); +}; + +class BigData { + public: + /* 0000 */ BigBuffer m_primary; + /* 0014 */ mutable BigStack m_stack; + /* 0158 */ mutable std::vector m_output; + + std::vector& Output() const; + BigBuffer& Primary(); + const BigBuffer& Primary() const; + BigStack& Stack() const; +}; + +class BigNum { + public: + /* 0000 */ BigData* m_data; + + BigNum(); + ~BigNum(); + void FromBinary(const void* data, uint32_t bytes); + BigNum& PowMod(const BigNum& b, const BigNum& c, const BigNum& d); + void* ToBinaryBuffer(void* data, uint32_t bytes) const; +}; + +namespace Crypt { +class RSA { + public: + /* 0000 */ BigNum m_modulus; + /* 0004 */ BigNum m_exponent; + + void Prepare(const void* modulus, uint32_t mLength, const void* exponent, uint32_t eLength); + void Process(uint8_t* data, uint32_t length); +}; +} + +namespace Util { +template +class Array { + public: + /* 0000 */ uint32_t m_count; + /* 0004 */ T* m_data; + + Array(); + void SetCount(uint32_t count); +}; +} + +struct SSignatureData { + /* 0000 */ uint32_t modulusSize; + /* 0004 */ uint32_t pubExponentSize; + /* 0008 */ uint32_t magicBufferUsed; + /* 000C */ uint32_t magicBufferSize; + /* 0010 */ Util::Array magicBuffer; + /* 0018 */ SHA1 sha; +}; + +void SBigDel(BigData* num); +void SBigFromBinary(BigData* num, const void* data, uint32_t bytes); +void SBigNew(BigData** num); +void SBigPowMod(BigData* a, const BigData* b, const BigData* c, const BigData* d); +void SBigToBinaryBuffer(const BigData* num, void* data, uint32_t maxBytes, uint32_t* bytes); + +void SSignatureVerifyStream_Begin(SSignatureData** token, uint32_t modulusSize, uint32_t pubExponentSize); +bool SSignatureVerifyStream_Finish(SSignatureData* token, const uint8_t* modulus, const uint8_t* pubExponent); +void SSignatureVerifyStream_ProvideData(SSignatureData* token, const uint8_t* data, uint32_t size); + +} + +// INLINED +template +Blizzard::Util::Array::Array() { + this->m_data = nullptr; + this->m_count = 0; +} + +// VERIFY: e1586fec manual +// OFFSET: 0x0042EA40 +template +void Blizzard::Util::Array::SetCount(uint32_t count) { + if (count) { + if (count != this->m_count) { + T* data = new T[count]; + uint32_t keep = this->m_count < count ? this->m_count : count; + + for (uint32_t i = 0; i < keep; i++) { + data[i] = this->m_data[i]; + } + + if (this->m_data) { + delete[] this->m_data; + } + + this->m_data = data; + } + } else if (this->m_data) { + delete[] this->m_data; + this->m_data = nullptr; + } + + this->m_count = count; +} + +#endif diff --git a/Engine/Source/BlizzardCore/Source/Packages/iounit/IOFileUnit.cpp b/Engine/Source/BlizzardCore/Source/Packages/iounit/IOFileUnit.cpp index fd26278..5f842e8 100644 --- a/Engine/Source/BlizzardCore/Source/Packages/iounit/IOFileUnit.cpp +++ b/Engine/Source/BlizzardCore/Source/Packages/iounit/IOFileUnit.cpp @@ -42,14 +42,14 @@ uint32_t IOFileUnit::GetType() { return 'file'; } -// VERIFY: e1defcb9 manual +// VERIFY: 50aaf91c manual // OFFSET: 0x00453860 bool IOFileUnit::Read(void* buffer, int64_t offset, uint32_t count, uint32_t* bytesRead) { if (static_cast(System_SFile::s_rawReadInfo).m_retryNative) { const char* path = Blizzard::File::GetFileInfo(this->m_stream)->m_path; Blizzard::File::StreamingInfo* streaming = this->m_stream->m_streaming; - if (!streaming || !streaming->m_storagehandle.m_mNode || Blizzard::Streaming::CheckFileRange(path, offset, count, path, 5) == 1) { + if (!streaming || !streaming->m_entry || Blizzard::Streaming::CheckFileRange(path, offset, count, path, 5) == 1) { return this->ReadNative(static_cast(offset), path, buffer, count, bytesRead); } } diff --git a/Engine/Source/BlizzardCore/Source/System/Debug/Debug.h b/Engine/Source/BlizzardCore/Source/System/Debug/Debug.h index f6037f1..7cdad76 100644 --- a/Engine/Source/BlizzardCore/Source/System/Debug/Debug.h +++ b/Engine/Source/BlizzardCore/Source/System/Debug/Debug.h @@ -8,6 +8,7 @@ namespace Debug { typedef void (*AssertCallback)(const char* expression, const char* message, const char* fileName, uint32_t lineNumber); +void Breakpoint(); char* CanonicalStr(const char* src, char* dst, uint32_t maxchars); void DefaultCallback(const char* expression, const char* message, const char* fileName, uint32_t lineNumber); void Printf(void (*output)(const char*), const char* format, ...); diff --git a/Engine/Source/BlizzardCore/Source/System/Debug/Win32/Debug.cpp b/Engine/Source/BlizzardCore/Source/System/Debug/Win32/Debug.cpp new file mode 100644 index 0000000..96ddc06 --- /dev/null +++ b/Engine/Source/BlizzardCore/Source/System/Debug/Win32/Debug.cpp @@ -0,0 +1,60 @@ +#if defined(WOWDECOMP_ARCH_32) + +#include +#include +#include +#include +#include "Engine/Source/BlizzardCore/Source/System/Debug/Debug.h" +#include "Engine/Source/BlizzardCore/Source/System/File/File.h" +#include "Engine/Source/BlizzardCore/Source/System/Process/Process.h" +#include "Engine/Source/BlizzardCore/Source/System/String/Path.h" +#include "Engine/Source/BlizzardCore/Source/System/String/String.h" +#include "Engine/Source/BlizzardCore/Source/System/Time/Time.h" + +// STATIC: 0x00B325BB +static bool s_continueAfterAssert; + +// VERIFY: bafff304 manual +// OFFSET: 0x00427010 +void Blizzard::Debug::Breakpoint() { + __try { + __debugbreak(); + } __except (EXCEPTION_EXECUTE_HANDLER) { + } +} + +// VERIFY: 608ef70b manual +// OFFSET: 0x00439880 +void Blizzard::Debug::DefaultCallback(const char* expression, const char* message, const char* fileName, uint32_t lineNumber) { + char text[2048]; + char path[512]; + char canonical[256]; + char directory[512]; + Blizzard::Time::TimeRec rec; + + Blizzard::Time::BreakTime(Blizzard::Time::GetTimestamp(), rec); + Blizzard::String::Format(text, sizeof(text), "%04d/%02d/%02d %02d:%02d:%02d %s(%d) : Assertion failed: %s \"%s\"\n", rec.year, rec.month, rec.day, rec.hour, rec.minute, rec.second, CanonicalStr(fileName, canonical, sizeof(canonical)), lineNumber, expression, message); + fprintf(stderr, "%s", text); + + Blizzard::Process::GetProcessDirectory(directory, sizeof(directory)); + Blizzard::String::Append(directory, "Errors", sizeof(directory)); + Blizzard::File::CreateDirectory(directory, true); + Blizzard::String::Append(directory, "/Assert.log", sizeof(directory)); + Blizzard::String::MakeBackslashPath(directory, path, sizeof(path)); + + FILE* stream = nullptr; + fopen_s(&stream, path, "a"); + + if (stream) { + fprintf(stream, "%s", text); + fclose(stream); + } + + Breakpoint(); + + if (!s_continueAfterAssert) { + abort(); + } +} + +#endif diff --git a/Engine/Source/BlizzardCore/Source/System/Debug/Win64/Debug.cpp b/Engine/Source/BlizzardCore/Source/System/Debug/Win64/Debug.cpp new file mode 100644 index 0000000..10f2330 --- /dev/null +++ b/Engine/Source/BlizzardCore/Source/System/Debug/Win64/Debug.cpp @@ -0,0 +1,58 @@ +#if defined(WOWDECOMP_ARCH_64) + +#include +#include +#include +#include +#include "Engine/Source/BlizzardCore/Source/System/Debug/Debug.h" +#include "Engine/Source/BlizzardCore/Source/System/File/File.h" +#include "Engine/Source/BlizzardCore/Source/System/Process/Process.h" +#include "Engine/Source/BlizzardCore/Source/System/String/Path.h" +#include "Engine/Source/BlizzardCore/Source/System/String/String.h" +#include "Engine/Source/BlizzardCore/Source/System/Time/Time.h" + +// STATIC: 0x00B325BB +static bool s_continueAfterAssert; + +// OFFSET: 0x00427010 +void Blizzard::Debug::Breakpoint() { + __try { + __debugbreak(); + } __except (EXCEPTION_EXECUTE_HANDLER) { + } +} + +// OFFSET: 0x00439880 +void Blizzard::Debug::DefaultCallback(const char* expression, const char* message, const char* fileName, uint32_t lineNumber) { + char text[2048]; + char path[512]; + char canonical[256]; + char directory[512]; + Blizzard::Time::TimeRec rec; + + Blizzard::Time::BreakTime(Blizzard::Time::GetTimestamp(), rec); + Blizzard::String::Format(text, sizeof(text), "%04d/%02d/%02d %02d:%02d:%02d %s(%d) : Assertion failed: %s \"%s\"\n", rec.year, rec.month, rec.day, rec.hour, rec.minute, rec.second, CanonicalStr(fileName, canonical, sizeof(canonical)), lineNumber, expression, message); + fprintf(stderr, "%s", text); + + Blizzard::Process::GetProcessDirectory(directory, sizeof(directory)); + Blizzard::String::Append(directory, "Errors", sizeof(directory)); + Blizzard::File::CreateDirectory(directory, true); + Blizzard::String::Append(directory, "/Assert.log", sizeof(directory)); + Blizzard::String::MakeBackslashPath(directory, path, sizeof(path)); + + FILE* stream = nullptr; + fopen_s(&stream, path, "a"); + + if (stream) { + fprintf(stream, "%s", text); + fclose(stream); + } + + Breakpoint(); + + if (!s_continueAfterAssert) { + abort(); + } +} + +#endif diff --git a/Engine/Source/BlizzardCore/Source/System/File/Filestack_Streaming.cpp b/Engine/Source/BlizzardCore/Source/System/File/Filestack_Streaming.cpp index c99c3b7..fabe7aa 100644 --- a/Engine/Source/BlizzardCore/Source/System/File/Filestack_Streaming.cpp +++ b/Engine/Source/BlizzardCore/Source/System/File/Filestack_Streaming.cpp @@ -1,13 +1,382 @@ +#include #include +#include +#include +#include +#include +#include +#include +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Manifests.h" +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Storage.h" +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Streaming.h" #include "Engine/Source/BlizzardCore/Source/System/File/File.h" #include "Engine/Source/BlizzardCore/Source/System/File/Filestack_Streaming.h" +#include "Engine/Source/BlizzardCore/Source/System/Log/Log.h" +#include "Engine/Source/BlizzardCore/Source/System/Memory/MemoryStorm.h" +#include "Engine/Source/BlizzardCore/Source/System/String/String.h" +#include "Engine/Source/BlizzardCore/Source/System/Unicode/Unicode.h" -// VERIFY: 149f4945 manual +// STATIC: 0x00AB9240 +Blizzard::File::Filesystem System_File::Stacked::s_streamstack = { + &System_File::Stacked::s_streamstack, + nullptr, + { + System_File::Stacked::PassThrough, + System_File::Stacked::stream_close, + System_File::Stacked::PassThrough, + System_File::Stacked::PassThrough, + System_File::Stacked::stream_dirwalk, + System_File::Stacked::stream_exists, + System_File::Stacked::stream_flush, + System_File::Stacked::stream_getfileinfo, + System_File::Stacked::PassThrough, + System_File::Stacked::PassThrough, + System_File::Stacked::PassThrough, + System_File::Stacked::PassThrough, + System_File::Stacked::PassThrough, + System_File::Stacked::PassThrough, + System_File::Stacked::PassThrough, + System_File::Stacked::PassThrough, + System_File::Stacked::PassThrough, + System_File::Stacked::stream_open, + System_File::Stacked::stream_read, + System_File::Stacked::stream_readp, + System_File::Stacked::PassThrough, + System_File::Stacked::PassThrough, + System_File::Stacked::PassThrough, + System_File::Stacked::PassThrough, + System_File::Stacked::PassThrough, + System_File::Stacked::PassThrough, + System_File::Stacked::PassThrough, + System_File::Stacked::PassThrough, + System_File::Stacked::stream_shutdown + } +}; + +// VERIFY: d80e4dd6 manual +// OFFSET: 0x00427AD0 +int32_t STORMAPI System_File::Stacked::ExistsAt(Blizzard::File::Filesystem* fs, const char* path) { + FileParms parms; + parms.m_path = const_cast(path); + parms.m_verb = offsetof(Blizzard::File::Filesystem, m_verbs.m_exists); + parms.m_info = &parms.m_info2; + + if (!fs || !fs->m_verbs.m_exists(fs, &parms)) { + return 0; + } + + return parms.m_info->m_existence; +} + +// VERIFY: c29b39e1 manual +// OFFSET: 0x00427B30 +Blizzard::File::StreamRecord* STORMAPI System_File::Stacked::OpenAt(Blizzard::File::Filesystem* fs, Blizzard::File::StreamRecord* file, const char* path, int32_t mode) { + FileParms parms; + parms.m_stream = file; + parms.m_verb = offsetof(Blizzard::File::Filesystem, m_verbs.m_open); + parms.m_path = const_cast(path); + parms.m_mode = mode; + + if (!fs || !fs->m_verbs.m_open(fs, &parms)) { + return nullptr; + } + + return parms.m_stream; +} + +// VERIFY: 71a6dd7e manual +// OFFSET: 0x00427B90 +bool STORMAPI System_File::Stacked::CloseAt(Blizzard::File::Filesystem* fs, Blizzard::File::StreamRecord* file) { + FileParms parms; + parms.m_stream = file; + parms.m_verb = offsetof(Blizzard::File::Filesystem, m_verbs.m_close); + + if (!fs) { + return false; + } + + return fs->m_verbs.m_close(fs, &parms); +} + +// VERIFY: 9a01a8e1 manual // OFFSET: 0x00427BE0 bool System_File::Stacked::stream_read(Blizzard::File::Filesystem* fs, FileParms* parms) { Blizzard::File::StreamingInfo* streaming = parms->m_stream->m_streaming; - if ((streaming && streaming->m_storagehandle.m_mNode) || !fs->m_next) { + if ((streaming && streaming->m_entry) || !fs->m_next) { + return false; + } + + return (*reinterpret_cast(reinterpret_cast(fs->m_next) + parms->m_verb))(fs->m_next, parms); +} + +// VERIFY: 74024bbf manual +// OFFSET: 0x0042D5C0 +void System_File::Stacked::PushStreaming() { + Blizzard::File::Filesystem* fs = static_cast(malloc(sizeof(Blizzard::File::Filesystem))); + Blizzard::String::MemCopy(fs, &s_streamstack, sizeof(Blizzard::File::Filesystem)); + fs->m_next = s_manager; + s_manager = fs; + HoistAll(); +} + +// VERIFY: 4816cb8b manual +// OFFSET: 0x004354C0 +bool STORMAPI System_File::Stacked::CreatePartFile(Blizzard::File::Filesystem* fs, FileParms* parms) { + char name[260]; + Blizzard::Storage::BuildVariantFileName(name, sizeof(name), parms->m_path, "part"); + + FileParms create; + create.m_verb = offsetof(Blizzard::File::Filesystem, m_verbs.m_open); + create.m_stream = nullptr; + create.m_path = name; + create.m_mode = 0x403; + + if (!fs->m_next || !fs->m_next->m_verbs.m_open(fs->m_next, &create) || !create.m_stream) { + return false; + } + + create.m_verb = offsetof(Blizzard::File::Filesystem, m_verbs.m_close); + + if (fs->m_next) { + fs->m_next->m_verbs.m_close(fs->m_next, &create); + } + + return true; +} + +// VERIFY: 78534a15 manual +// OFFSET: 0x00439AA0 +Blizzard::File::StreamRecord* STORMAPI System_File::Stacked::AllocStreamingRecord(const char* path) { + uint32_t length = path ? strlen(path) : 0; + + Blizzard::File::StreamRecord* record = static_cast(Blizzard::Memory::Allocate(sizeof(Blizzard::File::StreamRecord) + sizeof(Blizzard::File::StreamingInfo) + length + 1, 8, __FILE__, __LINE__)); + record->m_streaming = reinterpret_cast(record + 1); + record->m_pathname = reinterpret_cast(record->m_streaming + 1); + new (record->m_streaming) Blizzard::File::StreamingInfo; + Blizzard::String::Copy(record->m_pathname, path, length + 1); + + return record; +} + +// VERIFY: 03e5c89b manual +// OFFSET: 0x0043D710 +Blizzard::File::StreamRecord* FileStack_Streaming::InitRecord(Blizzard::File::StreamRecord* record) { + Blizzard::String::MemCopy(&record->m_streaming->m_info, &record->m_info, sizeof(Blizzard::File::FileInfo)); + record->m_info.m_path = record->m_pathname; + record->m_info.m_size = m_file->m_size; + record->m_info.m_regularFile = true; + record->m_infoValid = true; + record->m_info.m_createTime = 0; + record->m_info.m_modTime = 0; + record->m_info.m_accessTime = 0; + record->m_info.m_attributes = 32; + record->m_streaming->m_entry = m_entry; + record->m_streaming->m_path = m_key; + + return record; +} + +// VERIFY: 5c9f211d manual +// OFFSET: 0x00449CD0 +bool StreamDirWalk::Callback(const Blizzard::File::ProcessDirParms& parms) { + static_cast(parms.m_cookie)->m_files[std::string(parms.m_filename)] = parms.m_isDir; + return true; +} + +// VERIFY: 206882ea manual +// OFFSET: 0x00452190 +bool System_File::Stacked::stream_readp(Blizzard::File::Filesystem* fs, FileParms* parms) { + Blizzard::File::StreamRecord* file = parms->m_stream; + + if (!file->m_streaming || !file->m_streaming->m_entry) { + if (!fs->m_next) { + return false; + } + + return (*reinterpret_cast(reinterpret_cast(fs->m_next) + parms->m_verb))(fs->m_next, parms); + } + + uint8_t* start = static_cast(parms->m_buffer); + int32_t count; + Blizzard::Streaming::LoadRange* ranges = Blizzard::Storage::GetRange(file->m_streaming->m_entry, parms->m_pos, parms->m_amount, &count, true); + + if (!ranges || !count) { + parms->m_amount = 0; + return false; + } + + for (int32_t i = 0; i < count; i++) { + if (static_cast(ranges[i].m_state) >= 2) { + if (!Blizzard::Streaming::RequestRanges(file, ranges, count)) { + Blizzard::Memory::Free(ranges); + parms->m_amount = 0; + return false; + } + + break; + } + } + + uint8_t* buffer = start; + bool result = true; + + for (Blizzard::Streaming::LoadRange* range = ranges; count > 0 && result; count--, range++) { + if (Blizzard::Storage::ReadLocal(fs->m_next, file, file->m_streaming->m_entry, buffer, range->m_offset, range->m_size)) { + buffer += range->m_size; + } else { + result = false; + } + + if (!range->m_state) { + Blizzard::Log::Printf(3, "Logs/Profiling_File_Local.log", "%10lld, %10d - %s\n", range->m_offset, range->m_size, file->m_pathname); + Blizzard::Streaming::s_statBytesLocal += range->m_size; + } + } + + parms->m_amount = static_cast(buffer - start); + Blizzard::Memory::Free(ranges); + + return result; +} + +// VERIFY: 563da2f5 manual +// OFFSET: 0x004542B0 +bool StreamDirWalk::Walk(Blizzard::File::Filesystem* fs, System_File::Stacked::FileParms* parms) { + char buffer[1024]; + + System_File::Stacked::FileParms walk = *parms; + walk.m_cookie = this; + walk.m_dircallback = Callback; + + if (!fs->m_next || !(*reinterpret_cast(reinterpret_cast(fs->m_next) + walk.m_verb))(fs->m_next, &walk)) { + return false; + } + + std::vector files = Blizzard::Streaming::FileManifest::GetFileList(parms->m_path); + + for (std::vector::iterator it = files.begin(); it != files.end(); ++it) { + if (m_files.find(*it) == m_files.end()) { + m_files[*it] = false; + } + } + + Blizzard::File::ProcessDirParms dir; + dir.m_pathRoot = parms->m_path; + dir.m_cookie = parms->m_cookie; + + for (std::map::iterator it = m_files.begin(); it != m_files.end(); ++it) { + System_File::FromNativeName(buffer, sizeof(buffer), Blizzard::StringConversion_CodepageToUTF8::ToNative(it->first.c_str()).m_data); + dir.m_filename = buffer; + dir.m_isDir = it->second; + + if (!parms->m_dircallback(dir)) { + return false; + } + } + + return true; +} + +// VERIFY: ba20daaa manual +// OFFSET: 0x00454540 +bool System_File::Stacked::stream_exists(Blizzard::File::Filesystem* fs, FileParms* parms) { + if (!parms->m_path) { + parms->m_info->m_existence = 0; + return true; + } + + std::string key = Blizzard::Streaming::ResolveFilePath(std::string(parms->m_path)); + Blizzard::Streaming::Manifests::FileItem* item = Blizzard::Streaming::ManifestInfo::GetFileItem(key); + + if (item) { + parms->m_info->m_existence = item->m_size ? 1 : 2; + return true; + } + + if (!fs->m_next) { + return false; + } + + return (*reinterpret_cast(reinterpret_cast(fs->m_next) + parms->m_verb))(fs->m_next, parms); +} + +// VERIFY: 8fa7cb2e manual +// OFFSET: 0x00454680 +bool System_File::Stacked::stream_getfileinfo(Blizzard::File::Filesystem* fs, FileParms* parms) { + if (!parms->m_path) { + if (parms->m_stream) { + Blizzard::Streaming::Manifests::FileItem* item = nullptr; + + if (parms->m_stream->m_streaming) { + item = Blizzard::Streaming::ManifestInfo::GetFileItem(parms->m_stream->m_streaming->m_path); + } + + if (!fs->m_next || !(*reinterpret_cast(reinterpret_cast(fs->m_next) + parms->m_verb))(fs->m_next, parms)) { + return false; + } + + if (item) { + parms->m_info->m_size = item->m_size; + } + } + + return true; + } + + std::string key = Blizzard::Streaming::ResolveFilePath(std::string(parms->m_path)); + Blizzard::Streaming::Manifests::FileItem* item = Blizzard::Streaming::ManifestInfo::GetFileItem(key); + + if (item) { + parms->m_info->m_size = item->m_size; + parms->m_info->m_path = parms->m_path; + parms->m_info->m_createTime = 0; + parms->m_info->m_modTime = 0; + parms->m_info->m_accessTime = 0; + parms->m_info->m_regularFile = true; + parms->m_info->m_existence = item->m_size > 0 ? 1 : 2; + parms->m_info->m_attributes = 32; + return true; + } + + if (!fs->m_next) { + return false; + } + + return (*reinterpret_cast(reinterpret_cast(fs->m_next) + parms->m_verb))(fs->m_next, parms); +} + +// VERIFY: 07b05e40 manual +// OFFSET: 0x004589F0 +bool System_File::Stacked::stream_dirwalk(Blizzard::File::Filesystem* fs, FileParms* parms) { + StreamDirWalk walk; + return walk.Walk(fs, parms); +} + +// VERIFY: e830e690 manual +// OFFSET: 0x00459020 +bool System_File::Stacked::stream_shutdown(Blizzard::File::Filesystem* fs, FileParms* parms) { + StopStreaming(); + + if (!fs->m_next) { + return false; + } + + return (*reinterpret_cast(reinterpret_cast(fs->m_next) + parms->m_verb))(fs->m_next, parms); +} + +// VERIFY: 23df52d2 manual +// OFFSET: 0x0045A830 +bool System_File::Stacked::stream_open(Blizzard::File::Filesystem* fs, FileParms* parms) { + FileStack_Streaming stack; + Blizzard::File::StreamRecord* file = stack.StreamingOpen(fs, parms); + + if (file) { + parms->m_stream = file; + return true; + } + + if (!fs->m_next) { return false; } diff --git a/Engine/Source/BlizzardCore/Source/System/File/Filestack_Streaming.h b/Engine/Source/BlizzardCore/Source/System/File/Filestack_Streaming.h index 1f7cf54..39a9869 100644 --- a/Engine/Source/BlizzardCore/Source/System/File/Filestack_Streaming.h +++ b/Engine/Source/BlizzardCore/Source/System/File/Filestack_Streaming.h @@ -1,4 +1,61 @@ #ifndef ENGINE_SOURCE_BLIZZARDCORE_SOURCE_SYSTEM_FILE_FILESTACK_STREAMING_H #define ENGINE_SOURCE_BLIZZARDCORE_SOURCE_SYSTEM_FILE_FILESTACK_STREAMING_H +#include +#include +#include +#include "Engine/Source/BlizzardCore/Source/System/File/Filestack.h" +#include "Engine/Source/BlizzardCore/Source/System/File/Types.h" +#include "Engine/Source/Storm/H/Types.h" + +namespace Blizzard { +namespace Streaming { +namespace Manifests { +class FileItem; +} +} +} + +class FileStack_Streaming { + public: + /* 0000 */ std::string m_key; + /* 001C */ Blizzard::Streaming::Manifests::FileItem* m_file; + /* 0020 */ Blizzard::Streaming::StorageEntry* m_entry; + + Blizzard::File::StreamRecord* InitRecord(Blizzard::File::StreamRecord* record); + Blizzard::File::StreamRecord* StreamingOpen(Blizzard::File::Filesystem* fs, System_File::Stacked::FileParms* parms); +}; + +class StreamDirWalk { + public: + static bool Callback(const Blizzard::File::ProcessDirParms& parms); + + /* 0000 */ std::map m_files; + + bool Walk(Blizzard::File::Filesystem* fs, System_File::Stacked::FileParms* parms); +}; + +namespace System_File { +namespace Stacked { + +extern Blizzard::File::Filesystem s_streamstack; + +Blizzard::File::StreamRecord* STORMAPI AllocStreamingRecord(const char* path); +bool STORMAPI CloseAt(Blizzard::File::Filesystem* fs, Blizzard::File::StreamRecord* file); +bool STORMAPI CreatePartFile(Blizzard::File::Filesystem* fs, FileParms* parms); +int32_t STORMAPI ExistsAt(Blizzard::File::Filesystem* fs, const char* path); +Blizzard::File::StreamRecord* STORMAPI OpenAt(Blizzard::File::Filesystem* fs, Blizzard::File::StreamRecord* file, const char* path, int32_t mode); +void PushStreaming(); +bool stream_close(Blizzard::File::Filesystem* fs, FileParms* parms); +bool stream_dirwalk(Blizzard::File::Filesystem* fs, FileParms* parms); +bool stream_exists(Blizzard::File::Filesystem* fs, FileParms* parms); +bool stream_flush(Blizzard::File::Filesystem* fs, FileParms* parms); +bool stream_getfileinfo(Blizzard::File::Filesystem* fs, FileParms* parms); +bool stream_open(Blizzard::File::Filesystem* fs, FileParms* parms); +bool stream_readp(Blizzard::File::Filesystem* fs, FileParms* parms); +bool stream_shutdown(Blizzard::File::Filesystem* fs, FileParms* parms); + +} +} + #endif diff --git a/Engine/Source/BlizzardCore/Source/System/File/Types.h b/Engine/Source/BlizzardCore/Source/System/File/Types.h index 5b4e526..8ad82d2 100644 --- a/Engine/Source/BlizzardCore/Source/System/File/Types.h +++ b/Engine/Source/BlizzardCore/Source/System/File/Types.h @@ -3,10 +3,12 @@ #include #include +#include #include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Storage.h" #include "Engine/Source/BlizzardCore/Source/System/Time/Types.h" namespace Blizzard { namespace File { struct Filesystem; }} +namespace Blizzard { namespace Streaming { struct StorageEntry; }} namespace Blizzard { namespace File { struct ProcessDirParms; }} namespace Blizzard { namespace File { struct StreamRecord; }} namespace Blizzard { namespace File { struct StreamingInfo; }} @@ -146,10 +148,9 @@ struct ProcessDirParms { namespace Blizzard { namespace File { struct StreamingInfo { - /* 0000 */ Blizzard::Storage::StorageUnitHandle m_storagehandle; - /* 0008 */ Blizzard::File::INODE m_inode; - /* 000C */ uint32_t m_streamRefCount; - /* 0010 */ Blizzard::File::FileInfo m_streaminginfo; + /* 0000 */ Blizzard::Streaming::StorageEntry* m_entry; + /* 0004 */ std::string m_path; + /* 0020 */ Blizzard::File::FileInfo m_info; }; } } diff --git a/Engine/Source/BlizzardCore/Source/System/File/Win32/Filestack.cpp b/Engine/Source/BlizzardCore/Source/System/File/Win32/Filestack.cpp index c0c2818..d333d16 100644 --- a/Engine/Source/BlizzardCore/Source/System/File/Win32/Filestack.cpp +++ b/Engine/Source/BlizzardCore/Source/System/File/Win32/Filestack.cpp @@ -190,7 +190,7 @@ bool System_File::GetRootChars(Blizzard::File::Filesystem* fs, System_File::Stac return true; } -// VERIFY: 372926fe manual +// VERIFY: d09f7f0d manual // OFFSET: 0x00435580 void System_File::GetFileInfoByFile(Blizzard::File::StreamRecord* file) { if (file->m_infoValid) { @@ -205,7 +205,7 @@ void System_File::GetFileInfoByFile(Blizzard::File::StreamRecord* file) { return; } - if (!file->m_streaming || !file->m_streaming->m_storagehandle.m_mNode) { + if (!file->m_streaming || !file->m_streaming->m_entry) { file->m_info.m_size = (static_cast(sizeHigh) << 32) | sizeLow; } diff --git a/Engine/Source/BlizzardCore/Source/System/File/Win32/Filestack_Streaming.cpp b/Engine/Source/BlizzardCore/Source/System/File/Win32/Filestack_Streaming.cpp new file mode 100644 index 0000000..9d9a2ed --- /dev/null +++ b/Engine/Source/BlizzardCore/Source/System/File/Win32/Filestack_Streaming.cpp @@ -0,0 +1,143 @@ +#if defined(WOWDECOMP_ARCH_32) + +#include +#include +#include +#include +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Manifests.h" +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Storage.h" +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Streaming.h" +#include "Engine/Source/BlizzardCore/Source/System/File/File.h" +#include "Engine/Source/BlizzardCore/Source/System/File/Filestack_Streaming.h" +#include "Engine/Source/BlizzardCore/Source/System/Memory/MemoryStorm.h" + +// STATIC: 0x00AB9345 +static bool s_stackedClose = true; + +// VERIFY: 0c3f778a manual +// OFFSET: 0x00458C50 +Blizzard::File::StreamRecord* FileStack_Streaming::StreamingOpen(Blizzard::File::Filesystem* fs, System_File::Stacked::FileParms* parms) { + m_key = Blizzard::Streaming::ResolveFilePath(std::string(parms->m_path)); + m_file = Blizzard::Streaming::ManifestInfo::GetFileItem(m_key); + + if (!m_file) { + return nullptr; + } + + Blizzard::File::FileInfo info; + + if (System_File::Stacked::ExistsAt(fs->m_next, parms->m_path) && Blizzard::File::GetFileInfo(fs->m_next, parms->m_path, &info) && info.m_size == m_file->m_size) { + return nullptr; + } + + if (m_file->m_flags & 4) { + Blizzard::File::StreamRecord* record = System_File::Stacked::AllocStreamingRecord(parms->m_path); + record->m_fileHandle = nullptr; + record->m_mode = parms->m_mode; + return InitRecord(record); + } + + m_entry = Blizzard::Storage::Acquire(fs->m_next, m_key, parms->m_path, m_file->m_size, m_file->m_fileVersion.c_str(), m_file->m_flags); + + if (!m_entry) { + return nullptr; + } + + Blizzard::File::StreamRecord* file = nullptr; + + EnterCriticalSection(&m_entry->m_lock); + + if (m_entry->m_openCount > 0) { + m_entry->m_openCount++; + Blizzard::File::StreamRecord* shared = m_entry->m_file; + LeaveCriticalSection(&m_entry->m_lock); + return shared; + } + + int32_t mode = parms->m_mode & 0xFFFFFFF0 | 3; + Blizzard::File::StreamRecord* record = System_File::Stacked::AllocStreamingRecord(parms->m_path); + char name[260]; + + if (Blizzard::Storage::s_usePartFiles) { + for (int32_t attempt = 0; !file;) { + Blizzard::Storage::BuildVariantFileName(name, sizeof(name), parms->m_path, "part"); + + if ((!System_File::Stacked::ExistsAt(fs->m_next, name) && !System_File::Stacked::CreatePartFile(fs, parms)) || !(file = System_File::Stacked::OpenAt(fs->m_next, record, name, mode))) { + Blizzard::Storage::s_variantIndex++; + } + + if (++attempt >= 25) { + break; + } + } + } else { + Blizzard::Storage::BuildVariantFileName(name, sizeof(name), parms->m_path, "part"); + + if (System_File::Stacked::ExistsAt(fs->m_next, name) || System_File::Stacked::CreatePartFile(fs, parms)) { + file = System_File::Stacked::OpenAt(fs->m_next, record, name, mode); + } + } + + if (!file) { + Blizzard::Memory::Free(record); + Blizzard::File::AddToLastErrorStack(0, "FileStack_Streaming::StreamingOpen - Unable to open a unique instance of the .part file", 20); + LeaveCriticalSection(&m_entry->m_lock); + return nullptr; + } + + file = InitRecord(file); + + if (Blizzard::Storage::s_usePartFiles && !Blizzard::Storage::PartialFile::ParseFile(fs->m_next, file)) { + Blizzard::File::AddToLastErrorStack(0, "FileStack_Streaming::StreamingOpen - Failed to parse .part file", 20); + System_File::Stacked::CloseAt(fs->m_next, file); + LeaveCriticalSection(&m_entry->m_lock); + return nullptr; + } + + m_entry->m_openCount++; + m_entry->m_file = file; + LeaveCriticalSection(&m_entry->m_lock); + + return file; +} + +// VERIFY: 3810c62d manual +// OFFSET: 0x0045A6F0 +bool System_File::Stacked::stream_close(Blizzard::File::Filesystem* fs, FileParms* parms) { + Blizzard::File::StreamRecord* file = parms->m_stream; + + if (s_stackedClose) { + FileParms flush; + flush.m_verb = offsetof(Blizzard::File::Filesystem, m_verbs.m_flush); + flush.m_stream = file; + + if (s_manager) { + s_manager->m_verbs.m_flush(s_manager, &flush); + } + } + + if (file->m_streaming && file->m_streaming->m_entry) { + EnterCriticalSection(&file->m_streaming->m_entry->m_lock); + file->m_streaming->m_entry->m_openCount--; + + if (file->m_streaming->m_entry->m_openCount > 0) { + LeaveCriticalSection(&file->m_streaming->m_entry->m_lock); + return true; + } + + file->m_streaming->m_entry->m_file = nullptr; + LeaveCriticalSection(&file->m_streaming->m_entry->m_lock); + } + + bool result = !file->m_streaming || Blizzard::Storage::Close(fs->m_next, file, file->m_streaming->m_entry); + + if (file->m_streaming) { + file->m_streaming->~StreamingInfo(); + } + + bool passed = fs->m_next ? (*reinterpret_cast(reinterpret_cast(fs->m_next) + parms->m_verb))(fs->m_next, parms) : false; + + return result && passed; +} + +#endif diff --git a/Engine/Source/BlizzardCore/Source/System/File/Win64/Filestack.cpp b/Engine/Source/BlizzardCore/Source/System/File/Win64/Filestack.cpp index 9989c58..f7b478d 100644 --- a/Engine/Source/BlizzardCore/Source/System/File/Win64/Filestack.cpp +++ b/Engine/Source/BlizzardCore/Source/System/File/Win64/Filestack.cpp @@ -198,7 +198,7 @@ void System_File::GetFileInfoByFile(Blizzard::File::StreamRecord* file) { return; } - if (!file->m_streaming || !file->m_streaming->m_storagehandle.m_mNode) { + if (!file->m_streaming || !file->m_streaming->m_entry) { file->m_info.m_size = (static_cast(sizeHigh) << 32) | sizeLow; } diff --git a/Engine/Source/BlizzardCore/Source/System/File/Win64/Filestack_Streaming.cpp b/Engine/Source/BlizzardCore/Source/System/File/Win64/Filestack_Streaming.cpp new file mode 100644 index 0000000..be8713a --- /dev/null +++ b/Engine/Source/BlizzardCore/Source/System/File/Win64/Filestack_Streaming.cpp @@ -0,0 +1,141 @@ +#if defined(WOWDECOMP_ARCH_64) + +#include +#include +#include +#include +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Manifests.h" +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Storage.h" +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Streaming.h" +#include "Engine/Source/BlizzardCore/Source/System/File/File.h" +#include "Engine/Source/BlizzardCore/Source/System/File/Filestack_Streaming.h" +#include "Engine/Source/BlizzardCore/Source/System/Memory/MemoryStorm.h" + +// STATIC: 0x00AB9345 +static bool s_stackedClose = true; + +// OFFSET: 0x00458C50 +Blizzard::File::StreamRecord* FileStack_Streaming::StreamingOpen(Blizzard::File::Filesystem* fs, System_File::Stacked::FileParms* parms) { + m_key = Blizzard::Streaming::ResolveFilePath(std::string(parms->m_path)); + m_file = Blizzard::Streaming::ManifestInfo::GetFileItem(m_key); + + if (!m_file) { + return nullptr; + } + + Blizzard::File::FileInfo info; + + if (System_File::Stacked::ExistsAt(fs->m_next, parms->m_path) && Blizzard::File::GetFileInfo(fs->m_next, parms->m_path, &info) && info.m_size == m_file->m_size) { + return nullptr; + } + + if (m_file->m_flags & 4) { + Blizzard::File::StreamRecord* record = System_File::Stacked::AllocStreamingRecord(parms->m_path); + record->m_fileHandle = nullptr; + record->m_mode = parms->m_mode; + return InitRecord(record); + } + + m_entry = Blizzard::Storage::Acquire(fs->m_next, m_key, parms->m_path, m_file->m_size, m_file->m_fileVersion.c_str(), m_file->m_flags); + + if (!m_entry) { + return nullptr; + } + + Blizzard::File::StreamRecord* file = nullptr; + + EnterCriticalSection(&m_entry->m_lock); + + if (m_entry->m_openCount > 0) { + m_entry->m_openCount++; + Blizzard::File::StreamRecord* shared = m_entry->m_file; + LeaveCriticalSection(&m_entry->m_lock); + return shared; + } + + int32_t mode = parms->m_mode & 0xFFFFFFF0 | 3; + Blizzard::File::StreamRecord* record = System_File::Stacked::AllocStreamingRecord(parms->m_path); + char name[260]; + + if (Blizzard::Storage::s_usePartFiles) { + for (int32_t attempt = 0; !file;) { + Blizzard::Storage::BuildVariantFileName(name, sizeof(name), parms->m_path, "part"); + + if ((!System_File::Stacked::ExistsAt(fs->m_next, name) && !System_File::Stacked::CreatePartFile(fs, parms)) || !(file = System_File::Stacked::OpenAt(fs->m_next, record, name, mode))) { + Blizzard::Storage::s_variantIndex++; + } + + if (++attempt >= 25) { + break; + } + } + } else { + Blizzard::Storage::BuildVariantFileName(name, sizeof(name), parms->m_path, "part"); + + if (System_File::Stacked::ExistsAt(fs->m_next, name) || System_File::Stacked::CreatePartFile(fs, parms)) { + file = System_File::Stacked::OpenAt(fs->m_next, record, name, mode); + } + } + + if (!file) { + Blizzard::Memory::Free(record); + Blizzard::File::AddToLastErrorStack(0, "FileStack_Streaming::StreamingOpen - Unable to open a unique instance of the .part file", 20); + LeaveCriticalSection(&m_entry->m_lock); + return nullptr; + } + + file = InitRecord(file); + + if (Blizzard::Storage::s_usePartFiles && !Blizzard::Storage::PartialFile::ParseFile(fs->m_next, file)) { + Blizzard::File::AddToLastErrorStack(0, "FileStack_Streaming::StreamingOpen - Failed to parse .part file", 20); + System_File::Stacked::CloseAt(fs->m_next, file); + LeaveCriticalSection(&m_entry->m_lock); + return nullptr; + } + + m_entry->m_openCount++; + m_entry->m_file = file; + LeaveCriticalSection(&m_entry->m_lock); + + return file; +} + +// OFFSET: 0x0045A6F0 +bool System_File::Stacked::stream_close(Blizzard::File::Filesystem* fs, FileParms* parms) { + Blizzard::File::StreamRecord* file = parms->m_stream; + + if (s_stackedClose) { + FileParms flush; + flush.m_verb = offsetof(Blizzard::File::Filesystem, m_verbs.m_flush); + flush.m_stream = file; + + if (s_manager) { + s_manager->m_verbs.m_flush(s_manager, &flush); + } + } + + if (file->m_streaming && file->m_streaming->m_entry) { + EnterCriticalSection(&file->m_streaming->m_entry->m_lock); + file->m_streaming->m_entry->m_openCount--; + + if (file->m_streaming->m_entry->m_openCount > 0) { + LeaveCriticalSection(&file->m_streaming->m_entry->m_lock); + return true; + } + + file->m_streaming->m_entry->m_file = nullptr; + LeaveCriticalSection(&file->m_streaming->m_entry->m_lock); + } + + bool result = !file->m_streaming || Blizzard::Storage::Close(fs->m_next, file, file->m_streaming->m_entry); + + if (file->m_streaming) { + file->m_streaming->~StreamingInfo(); + } + + bool passed = fs->m_next ? (*reinterpret_cast(reinterpret_cast(fs->m_next) + parms->m_verb))(fs->m_next, parms) : false; + + return result && passed; +} + +#endif diff --git a/Engine/Source/BlizzardCore/Source/System/Lock/Lock.h b/Engine/Source/BlizzardCore/Source/System/Lock/Lock.h index 0107871..cab86bc 100644 --- a/Engine/Source/BlizzardCore/Source/System/Lock/Lock.h +++ b/Engine/Source/BlizzardCore/Source/System/Lock/Lock.h @@ -57,6 +57,7 @@ class ScopedMutex { ~ScopedMutex(); }; +void EventCreate(Event& event); void EventDestroy(Event& event); void EventSet(Event& event); Event* EventWait(uint32_t timeout, Event& event); diff --git a/Engine/Source/BlizzardCore/Source/System/Lock/Win32/Event.cpp b/Engine/Source/BlizzardCore/Source/System/Lock/Win32/Event.cpp index 5c5d7e4..1f98cd3 100644 --- a/Engine/Source/BlizzardCore/Source/System/Lock/Win32/Event.cpp +++ b/Engine/Source/BlizzardCore/Source/System/Lock/Win32/Event.cpp @@ -4,6 +4,12 @@ #include #include "Engine/Source/BlizzardCore/Source/System/Lock/Lock.h" +// VERIFY: aa3fb77e auto +// OFFSET: 0x00435C00 +void Blizzard::Lock::EventCreate(Event& event) { + event = CreateEventA(nullptr, FALSE, FALSE, nullptr); +} + // VERIFY: 3018692c auto // OFFSET: 0x00428320 void Blizzard::Lock::EventDestroy(Event& event) { diff --git a/Engine/Source/BlizzardCore/Source/System/Lock/Win64/Event.cpp b/Engine/Source/BlizzardCore/Source/System/Lock/Win64/Event.cpp index 4c5dcd9..bffffcf 100644 --- a/Engine/Source/BlizzardCore/Source/System/Lock/Win64/Event.cpp +++ b/Engine/Source/BlizzardCore/Source/System/Lock/Win64/Event.cpp @@ -4,6 +4,11 @@ #include #include "Engine/Source/BlizzardCore/Source/System/Lock/Lock.h" +// OFFSET: 0x00435C00 +void Blizzard::Lock::EventCreate(Event& event) { + event = CreateEventA(nullptr, FALSE, FALSE, nullptr); +} + // OFFSET: 0x00428320 void Blizzard::Lock::EventDestroy(Event& event) { CloseHandle(event); diff --git a/Engine/Source/BlizzardCore/Source/System/Memory/TempBuffer.h b/Engine/Source/BlizzardCore/Source/System/Memory/TempBuffer.h index eecc5a4..d47361d 100644 --- a/Engine/Source/BlizzardCore/Source/System/Memory/TempBuffer.h +++ b/Engine/Source/BlizzardCore/Source/System/Memory/TempBuffer.h @@ -21,7 +21,8 @@ class TempBuffer { } } -// INLINED +// VERIFY: cf4c642a manual +// OFFSET: 0x0042EBB0 template Blizzard::Memory::TempBuffer::TempBuffer(uint32_t count) { this->m_count = count; @@ -38,7 +39,7 @@ Blizzard::Memory::TempBuffer::~TempBuffer() { } // VERIFY: 019cc2c0 manual -// OFFSET: [0x0042EC20, 0x0042EAF0] +// OFFSET: [0x0042EC20, 0x0042EAF0, 0x0041D200] template void Blizzard::Memory::TempBuffer::Resize(uint32_t count) { if (count > N) { diff --git a/Engine/Source/BlizzardCore/Source/System/Process/Process.h b/Engine/Source/BlizzardCore/Source/System/Process/Process.h index af358f7..a797fc1 100644 --- a/Engine/Source/BlizzardCore/Source/System/Process/Process.h +++ b/Engine/Source/BlizzardCore/Source/System/Process/Process.h @@ -8,6 +8,7 @@ namespace Process { bool GetProcessDirectory(char* buffer, int32_t buffersize); bool GetProcessPath(char* buffer, int32_t buffersize); +bool LaunchChildProcessWithArguments(const char* path, const char* arguments, void (*callback)(void*), void* param); void Sleep(uint32_t milliseconds); } diff --git a/Engine/Source/BlizzardCore/Source/System/Process/Win32/Process.cpp b/Engine/Source/BlizzardCore/Source/System/Process/Win32/Process.cpp index 13ec3bc..405c304 100644 --- a/Engine/Source/BlizzardCore/Source/System/Process/Win32/Process.cpp +++ b/Engine/Source/BlizzardCore/Source/System/Process/Win32/Process.cpp @@ -2,12 +2,48 @@ #include #include +#include +#include +#include #include #include "Engine/Source/BlizzardCore/Source/System/File/File.h" #include "Engine/Source/BlizzardCore/Source/System/Memory/TempBuffer.h" #include "Engine/Source/BlizzardCore/Source/System/Process/Process.h" #include "Engine/Source/BlizzardCore/Source/System/String/Path.h" #include "Engine/Source/BlizzardCore/Source/System/String/String.h" +#include "Engine/Source/BlizzardCore/Source/System/Unicode/Unicode.h" + +struct ChildProcess { + /* 0000 */ HANDLE m_process; + /* 0004 */ void (*m_callback)(void*); + /* 0008 */ void* m_param; +}; + +// STATIC: 0x00B33FF4 +static UINT_PTR s_timer; + +// STATIC: 0x00B38310 +static std::set s_childProcesses; + +// VERIFY: a7ca143a manual +// OFFSET: 0x0043DEC0 +static void CALLBACK TimerFunc(HWND hwnd, UINT message, UINT_PTR id, DWORD time) { + for (std::set::iterator it = s_childProcesses.begin(); it != s_childProcesses.end();) { + std::set::iterator current = it++; + ChildProcess* child = *current; + + if (!WaitForSingleObjectEx(child->m_process, 0, FALSE)) { + child->m_callback(child->m_param); + s_childProcesses.erase(current); + delete child; + } + } + + if (!s_childProcesses.size()) { + KillTimer(nullptr, s_timer); + s_timer = 0; + } +} // VERIFY: 17c9a893 manual // OFFSET: 0x00435C20 @@ -45,6 +81,77 @@ bool Blizzard::Process::GetProcessDirectory(char* buffer, int32_t buffersize) { return true; } +// VERIFY: d3087926 manual +// OFFSET: 0x00440D80 +bool Blizzard::Process::LaunchChildProcessWithArguments(const char* path, const char* arguments, void (*callback)(void*), void* param) { + if (!arguments) { + arguments = ""; + } + + std::string command; + command.push_back('"'); + command.append(path); + command.push_back('"'); + + while (*arguments) { + size_t length = strcspn(arguments, "\n"); + command.push_back(' '); + + bool quote = Blizzard::String::FindFirstOf(arguments, "\t ", static_cast(length)) != nullptr; + + if (quote) { + command.push_back('"'); + } + + command.append(std::string(arguments, length)); + + if (quote) { + command.push_back('"'); + } + + arguments += length; + arguments += strspn(arguments, "\n"); + } + + STARTUPINFOA startup; + PROCESS_INFORMATION info; + memset(&startup, 0, sizeof(startup)); + memset(&info, 0, sizeof(info)); + startup.cb = sizeof(startup); + + BOOL created; + + { + Blizzard::StringConversion_CodepageToUTF8::ToNative nativeCommand(command.c_str()); + Blizzard::StringConversion_CodepageToUTF8::ToNative nativePath(path); + created = CreateProcessA(nativePath.m_data, nativeCommand.m_data, nullptr, nullptr, FALSE, 0, nullptr, nullptr, &startup, &info); + } + + if (!created) { + return false; + } + + if (!callback) { + return true; + } + + if (WaitForInputIdle(info.hProcess, 10000)) { + return false; + } + + ChildProcess* child = new ChildProcess; + child->m_process = info.hProcess; + child->m_callback = callback; + child->m_param = param; + s_childProcesses.insert(child); + + if (!s_timer) { + s_timer = SetTimer(nullptr, 0, 250, TimerFunc); + } + + return true; +} + // INLINED void Blizzard::Process::Sleep(uint32_t milliseconds) { ::Sleep(milliseconds); diff --git a/Engine/Source/BlizzardCore/Source/System/Process/Win64/Process.cpp b/Engine/Source/BlizzardCore/Source/System/Process/Win64/Process.cpp index e88374d..d6a947d 100644 --- a/Engine/Source/BlizzardCore/Source/System/Process/Win64/Process.cpp +++ b/Engine/Source/BlizzardCore/Source/System/Process/Win64/Process.cpp @@ -2,12 +2,47 @@ #include #include +#include +#include +#include #include #include "Engine/Source/BlizzardCore/Source/System/File/File.h" #include "Engine/Source/BlizzardCore/Source/System/Memory/TempBuffer.h" #include "Engine/Source/BlizzardCore/Source/System/Process/Process.h" #include "Engine/Source/BlizzardCore/Source/System/String/Path.h" #include "Engine/Source/BlizzardCore/Source/System/String/String.h" +#include "Engine/Source/BlizzardCore/Source/System/Unicode/Unicode.h" + +struct ChildProcess { + /* 0000 */ HANDLE m_process; + /* 0004 */ void (*m_callback)(void*); + /* 0008 */ void* m_param; +}; + +// STATIC: 0x00B33FF4 +static UINT_PTR s_timer; + +// STATIC: 0x00B38310 +static std::set s_childProcesses; + +// OFFSET: 0x0043DEC0 +static void CALLBACK TimerFunc(HWND hwnd, UINT message, UINT_PTR id, DWORD time) { + for (std::set::iterator it = s_childProcesses.begin(); it != s_childProcesses.end();) { + std::set::iterator current = it++; + ChildProcess* child = *current; + + if (!WaitForSingleObjectEx(child->m_process, 0, FALSE)) { + child->m_callback(child->m_param); + s_childProcesses.erase(current); + delete child; + } + } + + if (!s_childProcesses.size()) { + KillTimer(nullptr, s_timer); + s_timer = 0; + } +} // OFFSET: 0x00435C20 bool Blizzard::Process::GetProcessPath(char* buffer, int32_t buffersize) { @@ -43,6 +78,76 @@ bool Blizzard::Process::GetProcessDirectory(char* buffer, int32_t buffersize) { return true; } +// OFFSET: 0x00440D80 +bool Blizzard::Process::LaunchChildProcessWithArguments(const char* path, const char* arguments, void (*callback)(void*), void* param) { + if (!arguments) { + arguments = ""; + } + + std::string command; + command.push_back('"'); + command.append(path); + command.push_back('"'); + + while (*arguments) { + size_t length = strcspn(arguments, "\n"); + command.push_back(' '); + + bool quote = Blizzard::String::FindFirstOf(arguments, "\t ", static_cast(length)) != nullptr; + + if (quote) { + command.push_back('"'); + } + + command.append(std::string(arguments, length)); + + if (quote) { + command.push_back('"'); + } + + arguments += length; + arguments += strspn(arguments, "\n"); + } + + STARTUPINFOA startup; + PROCESS_INFORMATION info; + memset(&startup, 0, sizeof(startup)); + memset(&info, 0, sizeof(info)); + startup.cb = sizeof(startup); + + BOOL created; + + { + Blizzard::StringConversion_CodepageToUTF8::ToNative nativeCommand(command.c_str()); + Blizzard::StringConversion_CodepageToUTF8::ToNative nativePath(path); + created = CreateProcessA(nativePath.m_data, nativeCommand.m_data, nullptr, nullptr, FALSE, 0, nullptr, nullptr, &startup, &info); + } + + if (!created) { + return false; + } + + if (!callback) { + return true; + } + + if (WaitForInputIdle(info.hProcess, 10000)) { + return false; + } + + ChildProcess* child = new ChildProcess; + child->m_process = info.hProcess; + child->m_callback = callback; + child->m_param = param; + s_childProcesses.insert(child); + + if (!s_timer) { + s_timer = SetTimer(nullptr, 0, 250, TimerFunc); + } + + return true; +} + // INLINED void Blizzard::Process::Sleep(uint32_t milliseconds) { ::Sleep(milliseconds); diff --git a/Engine/Source/BlizzardCore/Source/System/String/String.cpp b/Engine/Source/BlizzardCore/Source/System/String/String.cpp index a9f8d29..797dee6 100644 --- a/Engine/Source/BlizzardCore/Source/System/String/String.cpp +++ b/Engine/Source/BlizzardCore/Source/System/String/String.cpp @@ -69,6 +69,26 @@ uint32_t Blizzard::String::Append(char* dst, const char* src, uint32_t maxchars) return static_cast(p - dst); } +// VERIFY: 109c466e auto +// OFFSET: 0x00428830 +const char* Blizzard::String::FindFirstOf(const char* str, const char* chars, int32_t maxchars) { + if (!str || !chars || !*chars || maxchars < 1 || !*str) { + return nullptr; + } + + const char* end = str + maxchars; + + for (const char* p = str; p < end && *p; p++) { + for (const char* c = chars; *c; c++) { + if (*p == *c) { + return p; + } + } + } + + return nullptr; +} + // VERIFY: a95efa1a auto // OFFSET: 0x004288A0 int32_t Blizzard::String::VFormat(char* dst, uint32_t maxchars, const char* format, va_list args) { @@ -242,6 +262,12 @@ bool Blizzard::String::EqualI(const char* str1, const char* str2) { return str1 && str2 && !_stricmp(str1, str2); } +// VERIFY: ea6a1355 auto +// OFFSET: 0x004287B0 +bool Blizzard::String::EqualI(const char* str1, const char* str2, uint32_t count) { + return str1 && str2 && !_strnicmp(str1, str2, count); +} + // VERIFY: 87af17bb manual // OFFSET: 0x004287E0 uint32_t Blizzard::String::Length(const char* str) { diff --git a/Engine/Source/BlizzardCore/Source/System/String/String.h b/Engine/Source/BlizzardCore/Source/System/String/String.h index 2c7bcbe..b27e1a8 100644 --- a/Engine/Source/BlizzardCore/Source/System/String/String.h +++ b/Engine/Source/BlizzardCore/Source/System/String/String.h @@ -30,7 +30,9 @@ uint32_t Copy(char* dst, const char* src, uint32_t maxchars); char* Duplicate(const char* str); bool Equal(const char* str1, const char* str2); bool EqualI(const char* str1, const char* str2); +bool EqualI(const char* str1, const char* str2, uint32_t count); const char* Find(const char* str, const char* substr, uint32_t maxchars); +const char* FindFirstOf(const char* str, const char* chars, int32_t maxchars); const char* FindI(const char* str, const char* substr, uint32_t maxchars); const char* FindReverse(const char* str, char c, uint32_t maxchars); int32_t Format(char* dst, uint32_t maxchars, const char* format, ...); diff --git a/Engine/Source/BlizzardCore/Source/System/Thread/Thread.h b/Engine/Source/BlizzardCore/Source/System/Thread/Thread.h index cdc8e31..d1d1518 100644 --- a/Engine/Source/BlizzardCore/Source/System/Thread/Thread.h +++ b/Engine/Source/BlizzardCore/Source/System/Thread/Thread.h @@ -52,6 +52,8 @@ bool Create(uint32_t (*function)(void*), void* param, ThreadRecord** thread, con bool CreateDetached(uint32_t (*function)(void*), void* param, const char* name); bool CreateDetachedFromPool(ThreadPoolRecord* pool, uint32_t (*function)(void*), void* param, int32_t flags, int32_t stackSize); bool CreateFromPool(ThreadPoolRecord* pool, uint32_t (*function)(void*), void* param, ThreadRecord** thread, int32_t flags, int32_t stackSize); +bool IsRunning(ThreadRecord* thread); +bool Sleep(uint32_t milliseconds); bool WaitForever(ThreadRecord* thread); } diff --git a/Engine/Source/BlizzardCore/Source/System/Thread/Win32/Thread.cpp b/Engine/Source/BlizzardCore/Source/System/Thread/Win32/Thread.cpp index aac2174..7e1beec 100644 --- a/Engine/Source/BlizzardCore/Source/System/Thread/Win32/Thread.cpp +++ b/Engine/Source/BlizzardCore/Source/System/Thread/Win32/Thread.cpp @@ -40,6 +40,19 @@ System_Thread::ExternalTLSRecord System_Thread::s_externalTLS[32]; // STATIC: 0x00B382B0 int32_t System_Thread::s_externalTLSCount; +// VERIFY: 4fe82795 auto +// OFFSET: 0x004284E0 +bool Blizzard::Thread::Sleep(uint32_t milliseconds) { + ::Sleep(milliseconds); + return true; +} + +// VERIFY: 05d69120 manual +// OFFSET: 0x00428CA0 +bool Blizzard::Thread::IsRunning(ThreadRecord* thread) { + return thread->m_state >= 0; +} + // VERIFY: e6b687dc manual // OFFSET: 0x00428CB0 bool System_Thread::SetPriorityLevel(Blizzard::Thread::ThreadRecord* thread, int32_t level) { diff --git a/Engine/Source/BlizzardCore/Source/System/Thread/Win64/Thread.cpp b/Engine/Source/BlizzardCore/Source/System/Thread/Win64/Thread.cpp index 86f9a6d..7045533 100644 --- a/Engine/Source/BlizzardCore/Source/System/Thread/Win64/Thread.cpp +++ b/Engine/Source/BlizzardCore/Source/System/Thread/Win64/Thread.cpp @@ -40,6 +40,17 @@ System_Thread::ExternalTLSRecord System_Thread::s_externalTLS[32]; // STATIC: 0x00B382B0 int32_t System_Thread::s_externalTLSCount; +// OFFSET: 0x004284E0 +bool Blizzard::Thread::Sleep(uint32_t milliseconds) { + ::Sleep(milliseconds); + return true; +} + +// OFFSET: 0x00428CA0 +bool Blizzard::Thread::IsRunning(ThreadRecord* thread) { + return thread->m_state >= 0; +} + // OFFSET: 0x00428CB0 bool System_Thread::SetPriorityLevel(Blizzard::Thread::ThreadRecord* thread, int32_t level) { switch (level) { diff --git a/Engine/Source/BlizzardCore/Source/System/URL/URL.cpp b/Engine/Source/BlizzardCore/Source/System/URL/URL.cpp new file mode 100644 index 0000000..7b143e6 --- /dev/null +++ b/Engine/Source/BlizzardCore/Source/System/URL/URL.cpp @@ -0,0 +1,87 @@ +#include "URL.h" +#include + +// VERIFY: b4a4f159 auto +// OFFSET: 0x00426DF0 +Blizzard::URL::DownloadCallback::~DownloadCallback() { +} + +// VERIFY: 0376006c auto +// OFFSET: 0x008E5250 +const char* Blizzard::URL::DownloadCallback::WantIfModifiedSince() { + return nullptr; +} + +// VERIFY: 9ebe0d4f auto +// OFFSET: 0x008A1420 +bool Blizzard::URL::DownloadCallback::WantData() { + return true; +} + +// VERIFY: deafea3c auto +// OFFSET: 0x00632050 +void Blizzard::URL::DownloadCallback::GetLastModified(const char* lastModified) { +} + +// VERIFY: 21209c1c auto +// OFFSET: 0x00653A10 +void Blizzard::URL::DownloadCallback::GetContentLength(int64_t length) { +} + +// VERIFY: 1d4642d1 auto +// OFFSET: 0x005EEB70 +void Blizzard::URL::DownloadCallback::ConnectedOK() { +} + +// VERIFY: abe175a0 auto +// OFFSET: 0x00632050 +void Blizzard::URL::DownloadCallback::GetHTTPStatusCode(int32_t code) { +} + +// VERIFY: acf356a7 auto +// OFFSET: 0x00426DA0 +int32_t Blizzard::URL::DownloadCallback::GetTimeout() { + return 60000; +} + +// VERIFY: 206d184f auto +// OFFSET: 0x00426DB0 +Blizzard::URL::DownloadCallback::ByteRange Blizzard::URL::DownloadCallback::GetByteRange() { + ByteRange range; + range.m_start = -1; + range.m_end = -1; + return range; +} + +// VERIFY: 845a2a0f auto +// OFFSET: 0x00427A90 +bool Blizzard::URL::DownloadCallback::Stop() { + return false; +} + +// VERIFY: 4f923f93 auto +// OFFSET: 0x00427A90 +bool Blizzard::URL::DownloadCallback::ShouldBlock() { + return false; +} + +// VERIFY: d002f513 auto +// OFFSET: 0x008E5250 +const char* Blizzard::URL::DownloadCallback::GetPostData() { + return nullptr; +} + +// VERIFY: 320609ee auto +// OFFSET: 0x008E5250 +const char* Blizzard::URL::DownloadCallback::GetPostContentType() { + return nullptr; +} + +// VERIFY: 514fdb0b auto +// OFFSET: 0x00426DD0 +Blizzard::URL::DownloadCallback::Cookie Blizzard::URL::DownloadCallback::GetCookie() { + Cookie cookie; + cookie.m_name = nullptr; + cookie.m_value = nullptr; + return cookie; +} diff --git a/Engine/Source/BlizzardCore/Source/System/URL/URL.h b/Engine/Source/BlizzardCore/Source/System/URL/URL.h new file mode 100644 index 0000000..0ed2cfe --- /dev/null +++ b/Engine/Source/BlizzardCore/Source/System/URL/URL.h @@ -0,0 +1,79 @@ +#ifndef ENGINE_SOURCE_BLIZZARDCORE_SOURCE_SYSTEM_URL_URL_H +#define ENGINE_SOURCE_BLIZZARDCORE_SOURCE_SYSTEM_URL_URL_H + +#include + +namespace Blizzard { +namespace URL { + +class DownloadCallback { + public: + enum Status { + DOWNLOAD_SUCCESS = 0, + DOWNLOAD_FAILED = 1, + DOWNLOAD_TIMEOUT = 2, + DOWNLOAD_NOT_FOUND = 3, + DOWNLOAD_NOT_MODIFIED = 4, + DOWNLOAD_ABORTED = 5, + DOWNLOAD_FORBIDDEN = 6, + DOWNLOAD_NAME_NOT_RESOLVED = 7, + DOWNLOAD_CANNOT_CONNECT = 8, + DOWNLOAD_STOPPED = 9, + DOWNLOAD_BAD_REQUEST = 10, + DOWNLOAD_UNKNOWN_ERROR = 11, + }; + + struct ByteRange { + /* 0000 */ int64_t m_start; + /* 0008 */ int64_t m_end; + }; + + struct Cookie { + /* 0000 */ const char* m_name; + /* 0004 */ const char* m_value; + }; + + virtual ~DownloadCallback(); + virtual const char* WantIfModifiedSince(); + virtual bool WantData(); + virtual void GetLastModified(const char* lastModified); + virtual void GetContentLength(int64_t length); + virtual void ConnectedOK(); + virtual void GetHTTPStatusCode(int32_t code); + virtual int32_t GetTimeout(); + virtual ByteRange GetByteRange(); + virtual bool Stop(); + virtual bool ShouldBlock(); + virtual const char* GetPostData(); + virtual const char* GetPostContentType(); + virtual Cookie GetCookie(); + virtual bool ReceivedData(const void* data, int32_t size) = 0; + virtual void Completed(Status status) = 0; +}; + +class HttpRequest { + public: + /* 0000 */ void* m_session; + /* 0004 */ void* m_connect; + /* 0008 */ void* m_request; + /* 000C */ void* m_connectEvent; + /* 0010 */ void* m_requestEvent; + /* 0014 */ void* m_completeEvent; + /* 0018 */ void* m_dataEvent; + /* 001C */ int32_t m_state; + /* 0020 */ bool m_done; + /* 0021 */ bool m_connected; + /* 0024 */ uint32_t m_error; + /* 0028 */ DownloadCallback::Status m_status; + /* 002C */ DownloadCallback* m_callback; + + HttpRequest(); + ~HttpRequest(); +}; + +bool DownloadURL(const char* url, DownloadCallback* callback); + +} +} + +#endif diff --git a/Engine/Source/BlizzardCore/Source/System/URL/Win32/URL.cpp b/Engine/Source/BlizzardCore/Source/System/URL/Win32/URL.cpp new file mode 100644 index 0000000..7fe6a03 --- /dev/null +++ b/Engine/Source/BlizzardCore/Source/System/URL/Win32/URL.cpp @@ -0,0 +1,386 @@ +#if defined(WOWDECOMP_ARCH_32) + +#include +#include +#include +#include +#include +#include "Engine/Source/BlizzardCore/Source/System/URL/URL.h" +#include "Engine/Source/BlizzardCore/Source/System/String/String.h" +#include "Engine/Source/BlizzardCore/Source/System/Thread/Thread.h" +#include "Engine/Source/BlizzardCore/Source/System/Unicode/Unicode.h" + +// STATIC: 0x00B38010 +static HINTERNET s_session; + +// VERIFY: 5941dae3 manual +// OFFSET: 0x0042CA00 +static uint32_t ReadResponseData(void* param) { + Blizzard::URL::HttpRequest* request = static_cast(param); + + if (request->m_error) { + switch (request->m_error) { + case ERROR_INTERNET_TIMEOUT: + request->m_status = Blizzard::URL::DownloadCallback::DOWNLOAD_TIMEOUT; + break; + + case ERROR_INTERNET_NAME_NOT_RESOLVED: + request->m_status = Blizzard::URL::DownloadCallback::DOWNLOAD_NAME_NOT_RESOLVED; + break; + + case ERROR_INTERNET_CANNOT_CONNECT: + request->m_status = Blizzard::URL::DownloadCallback::DOWNLOAD_CANNOT_CONNECT; + break; + + default: + request->m_status = Blizzard::URL::DownloadCallback::DOWNLOAD_FAILED; + break; + } + + InternetCloseHandle(request->m_connect); + return 0; + } + + char contentType[256]; + DWORD contentTypeLength = sizeof(contentType); + HttpQueryInfoA(request->m_request, HTTP_QUERY_CONTENT_TYPE, contentType, &contentTypeLength, nullptr); + + DWORD statusCode; + DWORD statusCodeLength = sizeof(statusCode); + if (!HttpQueryInfoA(request->m_request, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &statusCode, &statusCodeLength, nullptr)) { + statusCode = 0; + } + + request->m_callback->GetHTTPStatusCode(statusCode); + + if (statusCode >= HTTP_STATUS_OK && statusCode < HTTP_STATUS_AMBIGUOUS) { + char lastModified[256]; + DWORD lastModifiedLength = sizeof(lastModified); + if (HttpQueryInfoA(request->m_request, HTTP_QUERY_LAST_MODIFIED, lastModified, &lastModifiedLength, nullptr)) { + request->m_callback->GetLastModified(lastModified); + } + + char contentLength[256]; + DWORD contentLengthLength = sizeof(contentLength); + if (HttpQueryInfoA(request->m_request, HTTP_QUERY_CONTENT_LENGTH, contentLength, &contentLengthLength, nullptr)) { + request->m_callback->GetContentLength(static_cast(atol(contentLength))); + } + + if (!request->m_callback->WantData()) { + request->m_done = true; + InternetCloseHandle(request->m_connect); + return 0; + } + + char data[16384]; + + do { + INTERNET_BUFFERSA buffers; + memset(&buffers, 0, sizeof(buffers)); + buffers.dwStructSize = sizeof(buffers); + buffers.lpvBuffer = data; + buffers.dwBufferLength = sizeof(data); + + if (!InternetReadFileExA(request->m_request, &buffers, 0, reinterpret_cast(request))) { + if (GetLastError() != ERROR_IO_PENDING) { + break; + } + + WaitForSingleObject(request->m_completeEvent, INFINITE); + } + + if (!request->m_done) { + if (!buffers.dwBufferLength) { + request->m_done = true; + continue; + } + + WaitForSingleObject(request->m_dataEvent, INFINITE); + } + + if (buffers.dwBufferLength) { + if (!request->m_callback->ReceivedData(data, buffers.dwBufferLength)) { + request->m_status = Blizzard::URL::DownloadCallback::DOWNLOAD_ABORTED; + request->m_done = true; + } + + if (request->m_callback->Stop()) { + request->m_status = Blizzard::URL::DownloadCallback::DOWNLOAD_STOPPED; + request->m_done = true; + } + } + } while (!request->m_done); + + InternetCloseHandle(request->m_connect); + return 0; + } + + switch (statusCode) { + case HTTP_STATUS_NOT_MODIFIED: + request->m_status = Blizzard::URL::DownloadCallback::DOWNLOAD_NOT_MODIFIED; + break; + + case HTTP_STATUS_BAD_REQUEST: + request->m_status = Blizzard::URL::DownloadCallback::DOWNLOAD_BAD_REQUEST; + break; + + case HTTP_STATUS_FORBIDDEN: + request->m_status = Blizzard::URL::DownloadCallback::DOWNLOAD_FORBIDDEN; + break; + + case HTTP_STATUS_NOT_FOUND: + request->m_status = Blizzard::URL::DownloadCallback::DOWNLOAD_NOT_FOUND; + break; + + default: + request->m_status = Blizzard::URL::DownloadCallback::DOWNLOAD_FAILED; + break; + } + + InternetCloseHandle(request->m_connect); + return 0; +} + +// VERIFY: 811239fc manual +// OFFSET: 0x0042CD80 +Blizzard::URL::HttpRequest::~HttpRequest() { + CloseHandle(this->m_dataEvent); + CloseHandle(this->m_completeEvent); + CloseHandle(this->m_requestEvent); + CloseHandle(this->m_connectEvent); +} + +// VERIFY: d40a5d30 auto +// OFFSET: 0x0042CDC0 +static HINTERNET ConnectServer(Blizzard::URL::HttpRequest* request, const char* serverName, INTERNET_PORT serverPort) { + request->m_state = 0; + + HINTERNET connect = InternetConnectA(request->m_session, serverName, serverPort, nullptr, nullptr, INTERNET_SERVICE_HTTP, 0, reinterpret_cast(request)); + + if (!connect) { + if (GetLastError() != ERROR_IO_PENDING) { + return nullptr; + } + + WaitForSingleObject(request->m_connectEvent, INFINITE); + } + + DWORD timeout = request->m_callback->GetTimeout(); + InternetSetOptionA(connect, INTERNET_OPTION_CONNECT_TIMEOUT, &timeout, sizeof(timeout)); + InternetSetOptionA(connect, INTERNET_OPTION_RECEIVE_TIMEOUT, &timeout, sizeof(timeout)); + + return connect; +} + +// VERIFY: 9517de1d manual +// OFFSET: 0x00437840 +Blizzard::URL::HttpRequest::HttpRequest() { + this->m_connectEvent = CreateEventA(nullptr, FALSE, FALSE, nullptr); + this->m_requestEvent = CreateEventA(nullptr, FALSE, FALSE, nullptr); + this->m_completeEvent = CreateEventA(nullptr, FALSE, FALSE, nullptr); + this->m_dataEvent = CreateEventA(nullptr, FALSE, FALSE, nullptr); + this->m_session = nullptr; + this->m_connect = nullptr; + this->m_request = nullptr; + this->m_state = 0; + this->m_done = false; + this->m_connected = false; + this->m_callback = nullptr; + this->m_error = 0; + this->m_status = Blizzard::URL::DownloadCallback::DOWNLOAD_SUCCESS; +} + +// VERIFY: e68b8917 manual +// OFFSET: 0x00451290 +static void CALLBACK InternetCallback(HINTERNET internet, DWORD_PTR context, DWORD internetStatus, LPVOID statusInformation, DWORD statusInformationLength) { + Blizzard::URL::HttpRequest* request = reinterpret_cast(context); + + if (!request->m_state) { + if (internetStatus == INTERNET_STATUS_HANDLE_CREATED) { + request->m_connect = reinterpret_cast(static_cast(statusInformation)->dwResult); + SetEvent(request->m_connectEvent); + } else if (internetStatus == INTERNET_STATUS_HANDLE_CLOSING && internet == request->m_connect) { + request->m_done = true; + } + + return; + } + + switch (internetStatus) { + case INTERNET_STATUS_RECEIVING_RESPONSE: + if (!request->m_connected) { + request->m_callback->ConnectedOK(); + request->m_connected = true; + } + + break; + + case INTERNET_STATUS_RESPONSE_RECEIVED: + SetEvent(request->m_dataEvent); + + if (!*static_cast(statusInformation)) { + request->m_done = true; + } + + break; + + case INTERNET_STATUS_HANDLE_CREATED: + request->m_request = reinterpret_cast(static_cast(statusInformation)->dwResult); + SetEvent(request->m_requestEvent); + break; + + case INTERNET_STATUS_HANDLE_CLOSING: + if (internet == request->m_connect) { + SetEvent(request->m_dataEvent); + SetEvent(request->m_completeEvent); + request->m_callback->Completed(request->m_status); + delete request; + } + + break; + + case INTERNET_STATUS_REQUEST_COMPLETE: + if (request->m_state == 2) { + SetEvent(request->m_completeEvent); + } else { + request->m_state = 2; + request->m_error = static_cast(statusInformation)->dwError; + Blizzard::Thread::CreateDetachedFromPool(nullptr, ReadResponseData, request, 0, 0); + } + + break; + } +} + +// VERIFY: 280c8c87 auto +// OFFSET: 0x00451420 +static HINTERNET GetSession() { + if (!s_session) { + s_session = InternetOpenA("Blizzard Web Client", INTERNET_OPEN_TYPE_PRECONFIG, nullptr, nullptr, INTERNET_FLAG_ASYNC); + + if (s_session) { + if (InternetSetStatusCallbackA(s_session, InternetCallback) == INTERNET_INVALID_STATUS_CALLBACK) { + s_session = nullptr; + return nullptr; + } + + return s_session; + } + } + + return s_session; +} + +// VERIFY: 20cc9fca manual +// OFFSET: 0x00451470 +bool Blizzard::URL::DownloadURL(const char* url, DownloadCallback* callback) { + char hostName[1024]; + char urlPath[1024]; + + URL_COMPONENTSA components; + memset(&components, 0, sizeof(components)); + components.dwStructSize = sizeof(components); + components.lpszHostName = hostName; + components.dwHostNameLength = sizeof(hostName); + components.lpszUrlPath = urlPath; + components.dwUrlPathLength = sizeof(urlPath); + + if (!InternetCrackUrlA(url, 0, 0, &components)) { + return false; + } + + INTERNET_PORT port = components.nPort; + + HttpRequest* request = new HttpRequest(); + + if (!request) { + return false; + } + + request->m_callback = callback; + request->m_session = GetSession(); + + if (!request->m_session) { + delete request; + return false; + } + + request->m_connect = ConnectServer(request, hostName, port); + + if (!request->m_connect) { + delete request; + return false; + } + + const char* verb; + if (callback->GetPostData()) { + verb = "POST"; + } else if (callback->WantData()) { + verb = "GET"; + } else { + verb = "HEAD"; + } + + request->m_state = 1; + request->m_request = HttpOpenRequestA(request->m_connect, verb, urlPath, nullptr, nullptr, nullptr, (components.nScheme == INTERNET_SCHEME_HTTPS ? INTERNET_FLAG_SECURE : 0) | INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_UI, reinterpret_cast(request)); + + if (!request->m_request) { + if (GetLastError() != ERROR_IO_PENDING) { + delete request; + return false; + } + + WaitForSingleObject(request->m_requestEvent, INFINITE); + } + + char headers[1024]; + memset(headers, 0, sizeof(headers)); + + char header[1024]; + + const char* postData = callback->GetPostData(); + DWORD postDataLength = 0; + + if (postData) { + if (callback->GetPostContentType()) { + Blizzard::String::Format(header, sizeof(header), "Content-Type: %s\n\n", callback->GetPostContentType()); + } else { + Blizzard::String::Format(header, sizeof(header), "Content-Type: text/html\n\n"); + } + + Blizzard::String::Append(headers, header, sizeof(headers)); + + postDataLength = Blizzard::String::Length(postData); + Blizzard::String::Format(header, sizeof(header), "Content-Length: %d\n", postDataLength); + Blizzard::String::Append(headers, header, sizeof(headers)); + } + + const char* ifModifiedSince = callback->WantIfModifiedSince(); + + if (ifModifiedSince) { + Blizzard::String::Format(header, sizeof(header), "If-Modified-Since: %s\n", ifModifiedSince); + Blizzard::String::Append(headers, header, sizeof(headers)); + } + + DownloadCallback::ByteRange range = callback->GetByteRange(); + + if (range.m_start != -1 || range.m_end != -1) { + Blizzard::String::Format(header, sizeof(header), "Range: bytes=%lld-%lld\n", range.m_start, range.m_end); + Blizzard::String::Append(headers, header, sizeof(headers)); + } + + DownloadCallback::Cookie cookie = callback->GetCookie(); + + if (cookie.m_name && *cookie.m_name && cookie.m_value) { + InternetSetCookieA(Blizzard::StringConversion_CodepageToUTF8::ToNative(url).m_data, Blizzard::StringConversion_CodepageToUTF8::ToNative(cookie.m_name).m_data, Blizzard::StringConversion_CodepageToUTF8::ToNative(cookie.m_value).m_data); + } + + if (!HttpSendRequestA(request->m_request, headers, static_cast(-1), const_cast(postData), postDataLength) && GetLastError() != ERROR_IO_PENDING) { + delete request; + return false; + } + + return true; +} + +#endif diff --git a/Engine/Source/BlizzardCore/Source/System/URL/Win64/URL.cpp b/Engine/Source/BlizzardCore/Source/System/URL/Win64/URL.cpp new file mode 100644 index 0000000..fcb240b --- /dev/null +++ b/Engine/Source/BlizzardCore/Source/System/URL/Win64/URL.cpp @@ -0,0 +1,379 @@ +#if defined(WOWDECOMP_ARCH_64) + +#include +#include +#include +#include +#include +#include "Engine/Source/BlizzardCore/Source/System/URL/URL.h" +#include "Engine/Source/BlizzardCore/Source/System/String/String.h" +#include "Engine/Source/BlizzardCore/Source/System/Thread/Thread.h" +#include "Engine/Source/BlizzardCore/Source/System/Unicode/Unicode.h" + +// STATIC: 0x00B38010 +static HINTERNET s_session; + +// OFFSET: 0x0042CA00 +static uint32_t ReadResponseData(void* param) { + Blizzard::URL::HttpRequest* request = static_cast(param); + + if (request->m_error) { + switch (request->m_error) { + case ERROR_INTERNET_TIMEOUT: + request->m_status = Blizzard::URL::DownloadCallback::DOWNLOAD_TIMEOUT; + break; + + case ERROR_INTERNET_NAME_NOT_RESOLVED: + request->m_status = Blizzard::URL::DownloadCallback::DOWNLOAD_NAME_NOT_RESOLVED; + break; + + case ERROR_INTERNET_CANNOT_CONNECT: + request->m_status = Blizzard::URL::DownloadCallback::DOWNLOAD_CANNOT_CONNECT; + break; + + default: + request->m_status = Blizzard::URL::DownloadCallback::DOWNLOAD_FAILED; + break; + } + + InternetCloseHandle(request->m_connect); + return 0; + } + + char contentType[256]; + DWORD contentTypeLength = sizeof(contentType); + HttpQueryInfoA(request->m_request, HTTP_QUERY_CONTENT_TYPE, contentType, &contentTypeLength, nullptr); + + DWORD statusCode; + DWORD statusCodeLength = sizeof(statusCode); + if (!HttpQueryInfoA(request->m_request, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &statusCode, &statusCodeLength, nullptr)) { + statusCode = 0; + } + + request->m_callback->GetHTTPStatusCode(statusCode); + + if (statusCode >= HTTP_STATUS_OK && statusCode < HTTP_STATUS_AMBIGUOUS) { + char lastModified[256]; + DWORD lastModifiedLength = sizeof(lastModified); + if (HttpQueryInfoA(request->m_request, HTTP_QUERY_LAST_MODIFIED, lastModified, &lastModifiedLength, nullptr)) { + request->m_callback->GetLastModified(lastModified); + } + + char contentLength[256]; + DWORD contentLengthLength = sizeof(contentLength); + if (HttpQueryInfoA(request->m_request, HTTP_QUERY_CONTENT_LENGTH, contentLength, &contentLengthLength, nullptr)) { + request->m_callback->GetContentLength(static_cast(atol(contentLength))); + } + + if (!request->m_callback->WantData()) { + request->m_done = true; + InternetCloseHandle(request->m_connect); + return 0; + } + + char data[16384]; + + do { + INTERNET_BUFFERSA buffers; + memset(&buffers, 0, sizeof(buffers)); + buffers.dwStructSize = sizeof(buffers); + buffers.lpvBuffer = data; + buffers.dwBufferLength = sizeof(data); + + if (!InternetReadFileExA(request->m_request, &buffers, 0, reinterpret_cast(request))) { + if (GetLastError() != ERROR_IO_PENDING) { + break; + } + + WaitForSingleObject(request->m_completeEvent, INFINITE); + } + + if (!request->m_done) { + if (!buffers.dwBufferLength) { + request->m_done = true; + continue; + } + + WaitForSingleObject(request->m_dataEvent, INFINITE); + } + + if (buffers.dwBufferLength) { + if (!request->m_callback->ReceivedData(data, buffers.dwBufferLength)) { + request->m_status = Blizzard::URL::DownloadCallback::DOWNLOAD_ABORTED; + request->m_done = true; + } + + if (request->m_callback->Stop()) { + request->m_status = Blizzard::URL::DownloadCallback::DOWNLOAD_STOPPED; + request->m_done = true; + } + } + } while (!request->m_done); + + InternetCloseHandle(request->m_connect); + return 0; + } + + switch (statusCode) { + case HTTP_STATUS_NOT_MODIFIED: + request->m_status = Blizzard::URL::DownloadCallback::DOWNLOAD_NOT_MODIFIED; + break; + + case HTTP_STATUS_BAD_REQUEST: + request->m_status = Blizzard::URL::DownloadCallback::DOWNLOAD_BAD_REQUEST; + break; + + case HTTP_STATUS_FORBIDDEN: + request->m_status = Blizzard::URL::DownloadCallback::DOWNLOAD_FORBIDDEN; + break; + + case HTTP_STATUS_NOT_FOUND: + request->m_status = Blizzard::URL::DownloadCallback::DOWNLOAD_NOT_FOUND; + break; + + default: + request->m_status = Blizzard::URL::DownloadCallback::DOWNLOAD_FAILED; + break; + } + + InternetCloseHandle(request->m_connect); + return 0; +} + +// OFFSET: 0x0042CD80 +Blizzard::URL::HttpRequest::~HttpRequest() { + CloseHandle(this->m_dataEvent); + CloseHandle(this->m_completeEvent); + CloseHandle(this->m_requestEvent); + CloseHandle(this->m_connectEvent); +} + +// OFFSET: 0x0042CDC0 +static HINTERNET ConnectServer(Blizzard::URL::HttpRequest* request, const char* serverName, INTERNET_PORT serverPort) { + request->m_state = 0; + + HINTERNET connect = InternetConnectA(request->m_session, serverName, serverPort, nullptr, nullptr, INTERNET_SERVICE_HTTP, 0, reinterpret_cast(request)); + + if (!connect) { + if (GetLastError() != ERROR_IO_PENDING) { + return nullptr; + } + + WaitForSingleObject(request->m_connectEvent, INFINITE); + } + + DWORD timeout = request->m_callback->GetTimeout(); + InternetSetOptionA(connect, INTERNET_OPTION_CONNECT_TIMEOUT, &timeout, sizeof(timeout)); + InternetSetOptionA(connect, INTERNET_OPTION_RECEIVE_TIMEOUT, &timeout, sizeof(timeout)); + + return connect; +} + +// OFFSET: 0x00437840 +Blizzard::URL::HttpRequest::HttpRequest() { + this->m_connectEvent = CreateEventA(nullptr, FALSE, FALSE, nullptr); + this->m_requestEvent = CreateEventA(nullptr, FALSE, FALSE, nullptr); + this->m_completeEvent = CreateEventA(nullptr, FALSE, FALSE, nullptr); + this->m_dataEvent = CreateEventA(nullptr, FALSE, FALSE, nullptr); + this->m_session = nullptr; + this->m_connect = nullptr; + this->m_request = nullptr; + this->m_state = 0; + this->m_done = false; + this->m_connected = false; + this->m_callback = nullptr; + this->m_error = 0; + this->m_status = Blizzard::URL::DownloadCallback::DOWNLOAD_SUCCESS; +} + +// OFFSET: 0x00451290 +static void CALLBACK InternetCallback(HINTERNET internet, DWORD_PTR context, DWORD internetStatus, LPVOID statusInformation, DWORD statusInformationLength) { + Blizzard::URL::HttpRequest* request = reinterpret_cast(context); + + if (!request->m_state) { + if (internetStatus == INTERNET_STATUS_HANDLE_CREATED) { + request->m_connect = reinterpret_cast(static_cast(statusInformation)->dwResult); + SetEvent(request->m_connectEvent); + } else if (internetStatus == INTERNET_STATUS_HANDLE_CLOSING && internet == request->m_connect) { + request->m_done = true; + } + + return; + } + + switch (internetStatus) { + case INTERNET_STATUS_RECEIVING_RESPONSE: + if (!request->m_connected) { + request->m_callback->ConnectedOK(); + request->m_connected = true; + } + + break; + + case INTERNET_STATUS_RESPONSE_RECEIVED: + SetEvent(request->m_dataEvent); + + if (!*static_cast(statusInformation)) { + request->m_done = true; + } + + break; + + case INTERNET_STATUS_HANDLE_CREATED: + request->m_request = reinterpret_cast(static_cast(statusInformation)->dwResult); + SetEvent(request->m_requestEvent); + break; + + case INTERNET_STATUS_HANDLE_CLOSING: + if (internet == request->m_connect) { + SetEvent(request->m_dataEvent); + SetEvent(request->m_completeEvent); + request->m_callback->Completed(request->m_status); + delete request; + } + + break; + + case INTERNET_STATUS_REQUEST_COMPLETE: + if (request->m_state == 2) { + SetEvent(request->m_completeEvent); + } else { + request->m_state = 2; + request->m_error = static_cast(statusInformation)->dwError; + Blizzard::Thread::CreateDetachedFromPool(nullptr, ReadResponseData, request, 0, 0); + } + + break; + } +} + +// OFFSET: 0x00451420 +static HINTERNET GetSession() { + if (!s_session) { + s_session = InternetOpenA("Blizzard Web Client", INTERNET_OPEN_TYPE_PRECONFIG, nullptr, nullptr, INTERNET_FLAG_ASYNC); + + if (s_session) { + if (InternetSetStatusCallbackA(s_session, InternetCallback) == INTERNET_INVALID_STATUS_CALLBACK) { + s_session = nullptr; + return nullptr; + } + + return s_session; + } + } + + return s_session; +} + +// OFFSET: 0x00451470 +bool Blizzard::URL::DownloadURL(const char* url, DownloadCallback* callback) { + char hostName[1024]; + char urlPath[1024]; + + URL_COMPONENTSA components; + memset(&components, 0, sizeof(components)); + components.dwStructSize = sizeof(components); + components.lpszHostName = hostName; + components.dwHostNameLength = sizeof(hostName); + components.lpszUrlPath = urlPath; + components.dwUrlPathLength = sizeof(urlPath); + + if (!InternetCrackUrlA(url, 0, 0, &components)) { + return false; + } + + INTERNET_PORT port = components.nPort; + + HttpRequest* request = new HttpRequest(); + + if (!request) { + return false; + } + + request->m_callback = callback; + request->m_session = GetSession(); + + if (!request->m_session) { + delete request; + return false; + } + + request->m_connect = ConnectServer(request, hostName, port); + + if (!request->m_connect) { + delete request; + return false; + } + + const char* verb; + if (callback->GetPostData()) { + verb = "POST"; + } else if (callback->WantData()) { + verb = "GET"; + } else { + verb = "HEAD"; + } + + request->m_state = 1; + request->m_request = HttpOpenRequestA(request->m_connect, verb, urlPath, nullptr, nullptr, nullptr, (components.nScheme == INTERNET_SCHEME_HTTPS ? INTERNET_FLAG_SECURE : 0) | INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_UI, reinterpret_cast(request)); + + if (!request->m_request) { + if (GetLastError() != ERROR_IO_PENDING) { + delete request; + return false; + } + + WaitForSingleObject(request->m_requestEvent, INFINITE); + } + + char headers[1024]; + memset(headers, 0, sizeof(headers)); + + char header[1024]; + + const char* postData = callback->GetPostData(); + DWORD postDataLength = 0; + + if (postData) { + if (callback->GetPostContentType()) { + Blizzard::String::Format(header, sizeof(header), "Content-Type: %s\n\n", callback->GetPostContentType()); + } else { + Blizzard::String::Format(header, sizeof(header), "Content-Type: text/html\n\n"); + } + + Blizzard::String::Append(headers, header, sizeof(headers)); + + postDataLength = Blizzard::String::Length(postData); + Blizzard::String::Format(header, sizeof(header), "Content-Length: %d\n", postDataLength); + Blizzard::String::Append(headers, header, sizeof(headers)); + } + + const char* ifModifiedSince = callback->WantIfModifiedSince(); + + if (ifModifiedSince) { + Blizzard::String::Format(header, sizeof(header), "If-Modified-Since: %s\n", ifModifiedSince); + Blizzard::String::Append(headers, header, sizeof(headers)); + } + + DownloadCallback::ByteRange range = callback->GetByteRange(); + + if (range.m_start != -1 || range.m_end != -1) { + Blizzard::String::Format(header, sizeof(header), "Range: bytes=%lld-%lld\n", range.m_start, range.m_end); + Blizzard::String::Append(headers, header, sizeof(headers)); + } + + DownloadCallback::Cookie cookie = callback->GetCookie(); + + if (cookie.m_name && *cookie.m_name && cookie.m_value) { + InternetSetCookieA(Blizzard::StringConversion_CodepageToUTF8::ToNative(url).m_data, Blizzard::StringConversion_CodepageToUTF8::ToNative(cookie.m_name).m_data, Blizzard::StringConversion_CodepageToUTF8::ToNative(cookie.m_value).m_data); + } + + if (!HttpSendRequestA(request->m_request, headers, static_cast(-1), const_cast(postData), postDataLength) && GetLastError() != ERROR_IO_PENDING) { + delete request; + return false; + } + + return true; +} + +#endif diff --git a/Engine/Source/BlizzardCore/Source/System/Version/Version.h b/Engine/Source/BlizzardCore/Source/System/Version/Version.h new file mode 100644 index 0000000..f0eb415 --- /dev/null +++ b/Engine/Source/BlizzardCore/Source/System/Version/Version.h @@ -0,0 +1,21 @@ +#ifndef ENGINE_SOURCE_BLIZZARDCORE_SOURCE_SYSTEM_VERSION_VERSION_H +#define ENGINE_SOURCE_BLIZZARDCORE_SOURCE_SYSTEM_VERSION_VERSION_H + +#include + +namespace Blizzard { +namespace Version { + +struct FileVersion { + /* 0000 */ uint32_t m_major; + /* 0004 */ uint32_t m_minor; + /* 0008 */ uint32_t m_build; + /* 000C */ uint32_t m_revision; +}; + +bool GetFileVersion(const char* path, FileVersion& version); + +} +} + +#endif diff --git a/Engine/Source/BlizzardCore/Source/System/Version/Win32/Version.cpp b/Engine/Source/BlizzardCore/Source/System/Version/Win32/Version.cpp new file mode 100644 index 0000000..0628e61 --- /dev/null +++ b/Engine/Source/BlizzardCore/Source/System/Version/Win32/Version.cpp @@ -0,0 +1,145 @@ +#if defined(WOWDECOMP_ARCH_32) + +#include +#include +#include "Engine/Source/BlizzardCore/Source/System/File/File.h" +#include "Engine/Source/BlizzardCore/Source/System/Unicode/Unicode.h" +#include "Engine/Source/BlizzardCore/Source/System/Version/Version.h" + +typedef DWORD (WINAPI* GETFILEVERSIONINFOSIZEAPROC)(LPCSTR filename, LPDWORD handle); +typedef BOOL (WINAPI* GETFILEVERSIONINFOAPROC)(LPCSTR filename, DWORD handle, DWORD size, LPVOID data); +typedef BOOL (WINAPI* VERQUERYVALUEAPROC)(LPCVOID block, LPCSTR subBlock, LPVOID* buffer, PUINT length); + +// VERIFY: b9f2ec32 auto +// OFFSET: 0x00429380 +DWORD OsGetFileVersionInfoSizeA(LPCSTR filename, LPDWORD handle) { + HMODULE module = LoadLibraryA("version.dll"); + + if (!module) { + return 0; + } + + DWORD result = 0; + GETFILEVERSIONINFOSIZEAPROC proc = reinterpret_cast(GetProcAddress(module, "GetFileVersionInfoSizeA")); + + if (proc) { + result = proc(filename, handle); + } else { + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + } + + FreeLibrary(module); + return result; +} + +// VERIFY: 56107495 auto +// OFFSET: 0x004293E0 +BOOL OsGetFileVersionInfoA(LPCSTR filename, DWORD handle, DWORD size, LPVOID data) { + HMODULE module = LoadLibraryA("version.dll"); + + if (!module) { + return FALSE; + } + + BOOL result = FALSE; + GETFILEVERSIONINFOAPROC proc = reinterpret_cast(GetProcAddress(module, "GetFileVersionInfoA")); + + if (proc) { + result = proc(filename, handle, size, data); + } else { + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + } + + FreeLibrary(module); + return result; +} + +// VERIFY: 7100bec3 auto +// OFFSET: 0x00429450 +BOOL OsVerQueryValueA(LPCVOID block, LPCSTR subBlock, LPVOID* buffer, PUINT length) { + HMODULE module = LoadLibraryA("version.dll"); + + if (!module) { + return FALSE; + } + + BOOL result = FALSE; + VERQUERYVALUEAPROC proc = reinterpret_cast(GetProcAddress(module, "VerQueryValueA")); + + if (proc) { + result = proc(block, subBlock, buffer, length); + } else { + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + } + + FreeLibrary(module); + return result; +} + +// VERIFY: 6874300b manual +// OFFSET: 0x004338F0 +static bool GetVersionInfo(const char* path, Blizzard::Version::FileVersion& version, int32_t type) { + version.m_major = 0; + version.m_minor = 0; + version.m_build = 0; + version.m_revision = 0; + + if (Blizzard::File::Exists(path) != 1) { + return false; + } + + Blizzard::StringConversion_CodepageToUTF8::ToNative nativePath(path); + + DWORD handle; + DWORD size = OsGetFileVersionInfoSizeA(nativePath.m_data, &handle); + uint8_t* data = nullptr; + + if (size) { + data = new uint8_t[size]; + } + + if (!OsGetFileVersionInfoA(nativePath.m_data, 0, size, data)) { + if (data) { + delete[] data; + } + + return false; + } + + VS_FIXEDFILEINFO* info; + UINT length; + + if (!OsVerQueryValueA(data, "\\", reinterpret_cast(&info), &length) || length < sizeof(VS_FIXEDFILEINFO)) { + if (data) { + delete[] data; + } + + return false; + } + + if (type == 0) { + version.m_major = HIWORD(info->dwProductVersionMS); + version.m_minor = LOWORD(info->dwProductVersionMS); + version.m_build = HIWORD(info->dwProductVersionLS); + version.m_revision = LOWORD(info->dwProductVersionLS); + } else if (type == 1) { + version.m_major = HIWORD(info->dwFileVersionMS); + version.m_minor = LOWORD(info->dwFileVersionMS); + version.m_build = HIWORD(info->dwFileVersionLS); + version.m_revision = LOWORD(info->dwFileVersionLS); + } + + if (data) { + delete[] data; + } + + return true; +} + +// VERIFY: f37c4489 auto +// OFFSET: 0x00433A90 +bool Blizzard::Version::GetFileVersion(const char* path, FileVersion& version) { + return GetVersionInfo(path, version, 1); +} + +#endif diff --git a/Engine/Source/BlizzardCore/Source/System/Version/Win64/Version.cpp b/Engine/Source/BlizzardCore/Source/System/Version/Win64/Version.cpp new file mode 100644 index 0000000..b2fc8ae --- /dev/null +++ b/Engine/Source/BlizzardCore/Source/System/Version/Win64/Version.cpp @@ -0,0 +1,140 @@ +#if defined(WOWDECOMP_ARCH_64) + +#include +#include +#include "Engine/Source/BlizzardCore/Source/System/File/File.h" +#include "Engine/Source/BlizzardCore/Source/System/Unicode/Unicode.h" +#include "Engine/Source/BlizzardCore/Source/System/Version/Version.h" + +typedef DWORD (WINAPI* GETFILEVERSIONINFOSIZEAPROC)(LPCSTR filename, LPDWORD handle); +typedef BOOL (WINAPI* GETFILEVERSIONINFOAPROC)(LPCSTR filename, DWORD handle, DWORD size, LPVOID data); +typedef BOOL (WINAPI* VERQUERYVALUEAPROC)(LPCVOID block, LPCSTR subBlock, LPVOID* buffer, PUINT length); + +// OFFSET: 0x00429380 +DWORD OsGetFileVersionInfoSizeA(LPCSTR filename, LPDWORD handle) { + HMODULE module = LoadLibraryA("version.dll"); + + if (!module) { + return 0; + } + + DWORD result = 0; + GETFILEVERSIONINFOSIZEAPROC proc = reinterpret_cast(GetProcAddress(module, "GetFileVersionInfoSizeA")); + + if (proc) { + result = proc(filename, handle); + } else { + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + } + + FreeLibrary(module); + return result; +} + +// OFFSET: 0x004293E0 +BOOL OsGetFileVersionInfoA(LPCSTR filename, DWORD handle, DWORD size, LPVOID data) { + HMODULE module = LoadLibraryA("version.dll"); + + if (!module) { + return FALSE; + } + + BOOL result = FALSE; + GETFILEVERSIONINFOAPROC proc = reinterpret_cast(GetProcAddress(module, "GetFileVersionInfoA")); + + if (proc) { + result = proc(filename, handle, size, data); + } else { + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + } + + FreeLibrary(module); + return result; +} + +// OFFSET: 0x00429450 +BOOL OsVerQueryValueA(LPCVOID block, LPCSTR subBlock, LPVOID* buffer, PUINT length) { + HMODULE module = LoadLibraryA("version.dll"); + + if (!module) { + return FALSE; + } + + BOOL result = FALSE; + VERQUERYVALUEAPROC proc = reinterpret_cast(GetProcAddress(module, "VerQueryValueA")); + + if (proc) { + result = proc(block, subBlock, buffer, length); + } else { + SetLastError(ERROR_CALL_NOT_IMPLEMENTED); + } + + FreeLibrary(module); + return result; +} + +// OFFSET: 0x004338F0 +static bool GetVersionInfo(const char* path, Blizzard::Version::FileVersion& version, int32_t type) { + version.m_major = 0; + version.m_minor = 0; + version.m_build = 0; + version.m_revision = 0; + + if (Blizzard::File::Exists(path) != 1) { + return false; + } + + Blizzard::StringConversion_CodepageToUTF8::ToNative nativePath(path); + + DWORD handle; + DWORD size = OsGetFileVersionInfoSizeA(nativePath.m_data, &handle); + uint8_t* data = nullptr; + + if (size) { + data = new uint8_t[size]; + } + + if (!OsGetFileVersionInfoA(nativePath.m_data, 0, size, data)) { + if (data) { + delete[] data; + } + + return false; + } + + VS_FIXEDFILEINFO* info; + UINT length; + + if (!OsVerQueryValueA(data, "\\", reinterpret_cast(&info), &length) || length < sizeof(VS_FIXEDFILEINFO)) { + if (data) { + delete[] data; + } + + return false; + } + + if (type == 0) { + version.m_major = HIWORD(info->dwProductVersionMS); + version.m_minor = LOWORD(info->dwProductVersionMS); + version.m_build = HIWORD(info->dwProductVersionLS); + version.m_revision = LOWORD(info->dwProductVersionLS); + } else if (type == 1) { + version.m_major = HIWORD(info->dwFileVersionMS); + version.m_minor = LOWORD(info->dwFileVersionMS); + version.m_build = HIWORD(info->dwFileVersionLS); + version.m_revision = LOWORD(info->dwFileVersionLS); + } + + if (data) { + delete[] data; + } + + return true; +} + +// OFFSET: 0x00433A90 +bool Blizzard::Version::GetFileVersion(const char* path, FileVersion& version) { + return GetVersionInfo(path, version, 1); +} + +#endif diff --git a/Engine/Source/ComSat/ComSatAllocator.h b/Engine/Source/ComSat/ComSatAllocator.h new file mode 100644 index 0000000..8b59fc3 --- /dev/null +++ b/Engine/Source/ComSat/ComSatAllocator.h @@ -0,0 +1,22 @@ +#ifndef ENGINE_SOURCE_COMSAT_COMSATALLOCATOR_H +#define ENGINE_SOURCE_COMSAT_COMSATALLOCATOR_H + +#include +#include +#include "Engine/Source/ComSat/ComSatInterface.h" + +namespace ComSat { + +template +void Delete(Allocator& allocator, T* object); + +} + +// INLINED +template +void ComSat::Delete(ComSat::Allocator& allocator, T* object) { + object->~T(); + allocator.Free(object); +} + +#endif diff --git a/Engine/Source/ComSat/ComSatBitPacker.cpp b/Engine/Source/ComSat/ComSatBitPacker.cpp new file mode 100644 index 0000000..27d4098 --- /dev/null +++ b/Engine/Source/ComSat/ComSatBitPacker.cpp @@ -0,0 +1,119 @@ +#include "Engine/Source/ComSat/ComSatBitPacker.h" +#include + +// VERIFY: 09242d98 auto +// OFFSET: 0x00885730 +ComSat::BitPacker::BitPacker(uint8_t* buffer, uint32_t bitLength) { + this->m_buffer = buffer; + this->m_bitLength = bitLength; + this->m_byteOffset = 0; + this->m_bitOffset = 0; +} + +// VERIFY: 4151e984 auto +// OFFSET: 0x00885760 +ComSat::BitPacker::~BitPacker() { +} + +// VERIFY: 2517a981 auto +// OFFSET: 0x008858E0 +uint32_t ComSat::BitPacker::Finalize() { + if (this->m_bitOffset) { + this->m_buffer[this->m_byteOffset] &= (1 << this->m_bitOffset) - 1; + this->m_byteOffset++; + this->m_bitOffset = 0; + } + return this->m_byteOffset; +} + +// VERIFY: c6ad9043 manual +// OFFSET: 0x00885770 +bool ComSat::BitPacker::PackBits(const uint8_t* data, uint32_t bits) { + if (this->m_bitLength < bits + this->m_bitOffset + 8 * this->m_byteOffset) { + return false; + } + int32_t bytes = bits >> 3; + uint32_t remainder = bits & 7; + int32_t i; + if (this->m_bitOffset) { + for (i = 0; i < bytes; i++) { + this->m_buffer[this->m_byteOffset] &= (1 << this->m_bitOffset) - 1; + this->m_buffer[this->m_byteOffset] |= data[i] << this->m_bitOffset; + this->m_buffer[this->m_byteOffset + 1] &= -1 << this->m_bitOffset; + this->m_buffer[this->m_byteOffset + 1] |= data[i] >> (8 - this->m_bitOffset); + this->m_byteOffset++; + } + } else { + memcpy(&this->m_buffer[this->m_byteOffset], data, bytes); + this->m_byteOffset += bytes; + i = bytes; + } + if (remainder) { + uint8_t value = data[i] & ((1 << remainder) - 1); + this->m_buffer[this->m_byteOffset] &= (0xFF >> (8 - this->m_bitOffset)) | (-1 << (this->m_bitOffset + remainder)); + this->m_buffer[this->m_byteOffset] |= value << this->m_bitOffset; + if (this->m_bitOffset + remainder >= 8) { + this->m_buffer[this->m_byteOffset + 1] &= -1 << this->m_bitOffset; + this->m_buffer[this->m_byteOffset + 1] |= value >> (8 - this->m_bitOffset); + this->m_byteOffset++; + this->m_bitOffset += remainder - 8; + return true; + } + this->m_bitOffset += remainder; + } + return true; +} + +// VERIFY: 670e65cb auto +// OFFSET: 0x00885730 +ComSat::BitUnpacker::BitUnpacker(const uint8_t* buffer, uint32_t bitLength) { + this->m_buffer = buffer; + this->m_bitLength = bitLength; + this->m_byteOffset = 0; + this->m_bitOffset = 0; +} + +// VERIFY: aaf78467 auto +// OFFSET: 0x00885760 +ComSat::BitUnpacker::~BitUnpacker() { +} + +// VERIFY: 6ca95947 manual +// OFFSET: 0x00885910 +bool ComSat::BitUnpacker::UnpackBits(uint8_t* data, uint32_t bits) { + if (this->m_bitLength < this->m_bitOffset + bits + 8 * this->m_byteOffset) { + return false; + } + int32_t bytes = bits >> 3; + int32_t remainder = bits & 7; + memset(data, 0, remainder ? bytes + 1 : bytes); + int32_t i; + if (this->m_bitOffset) { + for (i = 0; i < bytes; i++) { + data[i] = this->m_buffer[this->m_byteOffset] >> this->m_bitOffset; + data[i] |= (((1 << this->m_bitOffset) - 1) & this->m_buffer[this->m_byteOffset++ + 1]) << (8 - this->m_bitOffset); + } + } else { + memcpy(data, &this->m_buffer[this->m_byteOffset], bytes); + this->m_byteOffset += bytes; + i = bytes; + } + if (remainder) { + if (!this->m_bitOffset) { + data[i] = ((1 << remainder) - 1) & this->m_buffer[this->m_byteOffset]; + this->m_bitOffset = remainder; + return true; + } + if (remainder > static_cast(8 - this->m_bitOffset)) { + data[i] = this->m_buffer[this->m_byteOffset] >> this->m_bitOffset; + this->m_byteOffset++; + int32_t bitOffset = remainder + this->m_bitOffset - 8; + data[i] |= (((1 << bitOffset) - 1) & this->m_buffer[this->m_byteOffset]) << (8 - this->m_bitOffset); + this->m_bitOffset = bitOffset; + return true; + } + data[i] = ((1 << remainder) - 1) & (this->m_buffer[this->m_byteOffset] >> this->m_bitOffset); + this->m_bitOffset = (remainder + this->m_bitOffset) & 7; + } + return true; +} diff --git a/Engine/Source/ComSat/ComSatBitPacker.h b/Engine/Source/ComSat/ComSatBitPacker.h new file mode 100644 index 0000000..bb38dc5 --- /dev/null +++ b/Engine/Source/ComSat/ComSatBitPacker.h @@ -0,0 +1,38 @@ +#ifndef ENGINE_SOURCE_COMSAT_COMSATBITPACKER_H +#define ENGINE_SOURCE_COMSAT_COMSATBITPACKER_H + +#include +#include + +namespace ComSat { + +class BitPacker { + public: + /* 0004 */ uint8_t* m_buffer; + /* 0008 */ uint32_t m_bitLength; + /* 000C */ uint32_t m_byteOffset; + /* 0010 */ uint32_t m_bitOffset; + + virtual ~BitPacker(); + + BitPacker(uint8_t* buffer, uint32_t bitLength); + uint32_t Finalize(); + bool PackBits(const uint8_t* data, uint32_t bits); +}; + +class BitUnpacker { + public: + /* 0004 */ const uint8_t* m_buffer; + /* 0008 */ uint32_t m_bitLength; + /* 000C */ uint32_t m_byteOffset; + /* 0010 */ uint32_t m_bitOffset; + + virtual ~BitUnpacker(); + + BitUnpacker(const uint8_t* buffer, uint32_t bitLength); + bool UnpackBits(uint8_t* data, uint32_t bits); +}; + +} + +#endif diff --git a/Engine/Source/ComSat/ComSatHash.cpp b/Engine/Source/ComSat/ComSatHash.cpp new file mode 100644 index 0000000..ca0f615 --- /dev/null +++ b/Engine/Source/ComSat/ComSatHash.cpp @@ -0,0 +1,13 @@ +#include "Engine/Source/ComSat/ComSatHash.h" + +// VERIFY: a913c4f0 auto +// OFFSET: 0x00887330 +uint32_t ComSat::Hash32(const void* data, uint32_t length, uint32_t seed) { + const uint8_t* bytes = static_cast(data); + uint32_t hash = seed; + for (; length; length--) { + hash = (hash ^ *bytes) * 0x1000193; + bytes++; + } + return hash; +} diff --git a/Engine/Source/ComSat/ComSatHash.h b/Engine/Source/ComSat/ComSatHash.h new file mode 100644 index 0000000..b7156f9 --- /dev/null +++ b/Engine/Source/ComSat/ComSatHash.h @@ -0,0 +1,13 @@ +#ifndef ENGINE_SOURCE_COMSAT_COMSATHASH_H +#define ENGINE_SOURCE_COMSAT_COMSATHASH_H + +#include +#include + +namespace ComSat { + +uint32_t Hash32(const void* data, uint32_t length, uint32_t seed); + +} + +#endif diff --git a/Engine/Source/ComSat/ComSatInterface.cpp b/Engine/Source/ComSat/ComSatInterface.cpp index 04d1b15..d127ef2 100644 --- a/Engine/Source/ComSat/ComSatInterface.cpp +++ b/Engine/Source/ComSat/ComSatInterface.cpp @@ -1,17 +1,20 @@ -#include "ComSatInterface.h" -#include "Engine/Source/ComSat/ComSatSoundIOSoundEngine.h" +#include "Engine/Source/ComSat/ComSatInterface.h" +#include "Engine/Source/ComSat/ComSatManager.h" +#include "Engine/Source/ComSat/ComSatNetwork.h" +#include "Engine/Source/ComSat/ComSatSoundManager.h" +#include // STATIC: 0x00D43988 -static ComSat::Sound::Manager* unk_D43988; +static ComSat::Sound::Manager* s_soundManager; // STATIC: 0x00D4398C -static ComSat::Network::Manager* unk_D4398C; +static ComSat::Network::Manager* s_networkManager; // INLINED ComSat::Allocator::~Allocator() { } -// VERIFY: d03c9b46 auto +// VERIFY: 452c7806 auto // OFFSET: 0x00880B30 void ComSat::Interface::Destroy(ComSat::Interface* comsat, ComSat::Allocator& allocator) { if (comsat) { @@ -19,17 +22,25 @@ void ComSat::Interface::Destroy(ComSat::Interface* comsat, ComSat::Allocator& al allocator.Free(comsat); } - if (unk_D43988) { - ComSat::Sound::Manager* soundManager = unk_D43988; + if (s_soundManager) { + ComSat::Sound::Manager* soundManager = s_soundManager; soundManager->~Manager(); allocator.Free(soundManager); - unk_D43988 = nullptr; + s_soundManager = nullptr; } - if (unk_D4398C) { - ComSat::Network::Manager* networkManager = unk_D4398C; + if (s_networkManager) { + ComSat::Network::Manager* networkManager = s_networkManager; networkManager->~Manager(); allocator.Free(networkManager); - unk_D4398C = nullptr; + s_networkManager = nullptr; } } + +// VERIFY: 5430b1ec manual +// OFFSET: 0x00880F30 +ComSat::Interface* ComSat::Interface::Create(const ComSat::Initialization& init, ComSat::Allocator& allocator) { + s_soundManager = new (allocator.Alloc(sizeof(ComSat::Sound::Manager))) ComSat::Sound::Manager(init, allocator); + s_networkManager = new (allocator.Alloc(sizeof(ComSat::Network::Manager))) ComSat::Network::Manager(init, allocator); + return new (allocator.Alloc(sizeof(ComSat::Manager))) ComSat::Manager(*s_soundManager, *s_networkManager, init, allocator); +} diff --git a/Engine/Source/ComSat/ComSatInterface.h b/Engine/Source/ComSat/ComSatInterface.h index 671606b..c28fb85 100644 --- a/Engine/Source/ComSat/ComSatInterface.h +++ b/Engine/Source/ComSat/ComSatInterface.h @@ -3,6 +3,7 @@ #include #include +#include "Engine/Source/ComSat/Types.h" namespace ComSat { @@ -17,13 +18,29 @@ struct DeviceInfo { /* 0000 */ char m_name[256]; }; -enum MuteSetting { +struct Initialization { + /* 0000 */ uint32_t m_maxLocalPlayers; + /* 0004 */ uint32_t unk_0004; + /* 0008 */ uint32_t unk_0008; + /* 000C */ uint16_t m_port; + /* 0010 */ uint32_t m_time; + /* 0014 */ uint32_t m_maxChannels; }; class Interface { public: - class Callback; + class Callback { + public: + virtual ~Callback(); + virtual void NotifyLocalTalkerStart(uint8_t localTalker) = 0; + virtual void NotifyLocalTalkerStop(uint8_t localTalker) = 0; + virtual void NotifyTalkerStart(uint8_t localTalker, uint64_t session, uint64_t talker) = 0; + virtual void NotifyTalkerStop(uint8_t localTalker, uint64_t session, uint64_t talker) = 0; + virtual void NotifyLocalTalkerVoiceLevel(uint8_t localTalker, float level, bool talking) = 0; + virtual void NotifyDeviceError(uint8_t localTalker) = 0; + }; + static Interface* Create(const Initialization& init, Allocator& allocator); static void Destroy(Interface* comsat, Allocator& allocator); virtual ~Interface(); @@ -32,50 +49,41 @@ class Interface { virtual int32_t EnumerateCaptureDevices(DeviceInfo* devices, int32_t maxDevices) = 0; virtual void CallbackSet(Interface::Callback& callback) = 0; virtual void CallbackClear() = 0; - virtual int32_t SessionCreate(uint64_t session) = 0; - virtual void SessionDestroy(uint64_t session) = 0; - virtual void SessionSetNetworkId(uint64_t session, uint16_t networkId) = 0; - virtual int32_t SessionAddLocal(uint64_t session, uint8_t localTalker, uint64_t talker) = 0; - virtual int32_t SessionAddRemote(uint64_t session, uint64_t talker, uint8_t priority, const uint8_t (&key)[16], const char* address) = 0; - virtual void SessionSetTalkerNetworkIdLocal(uint64_t session, uint64_t talker, uint8_t networkId) = 0; - virtual void SessionSetTalkerNetworkIdRemote(uint64_t session, uint64_t talker, uint8_t networkId) = 0; - virtual void SessionRemove(uint64_t session, uint64_t talker) = 0; + virtual bool SessionCreate(uint64_t session) = 0; + virtual bool SessionDestroy(uint64_t session) = 0; + virtual bool SessionSetNetworkId(uint64_t session, uint16_t networkId) = 0; + virtual bool SessionAddLocal(uint64_t session, uint8_t localTalker, uint64_t talker) = 0; + virtual bool SessionAddRemote(uint64_t session, uint64_t talker, uint8_t networkId, const uint8_t (&key)[16], const char* address) = 0; + virtual bool SessionSetTalkerNetworkIdLocal(uint64_t session, uint64_t talker, uint8_t networkId) = 0; + virtual bool SessionSetTalkerNetworkIdRemote(uint64_t session, uint64_t talker, uint8_t networkId) = 0; + virtual bool SessionRemove(uint64_t session, uint64_t talker) = 0; virtual int32_t SessionNumMembers(uint64_t session) = 0; - virtual int32_t SessionGetTalkerByIndex(uint64_t session, int32_t index, uint64_t& talker, uint8_t& flags) = 0; - virtual void SessionSetTalkerPriority(uint64_t session, uint64_t talker, uint8_t priority) = 0; - virtual int32_t LocalTalkerCreate(uint8_t localTalker, uint64_t talker, float threshold, int32_t outputDevice, int32_t captureDevice) = 0; - virtual void LocalTalkerDestroy(uint8_t localTalker) = 0; - virtual void LocalTalkerChangeOutputDevice(uint8_t localTalker, int32_t device) = 0; - virtual void LocalTalkerChangeCaptureDevice(uint8_t localTalker, int32_t device) = 0; + virtual bool SessionGetTalkerByIndex(uint64_t session, int32_t index, uint64_t& talker, uint8_t& localTalker) = 0; + virtual bool SessionSetTalkerPriority(uint64_t session, uint64_t talker, uint8_t priority) = 0; + virtual bool LocalTalkerCreate(uint8_t localTalker, uint64_t talker, float threshold, int32_t outputDevice, int32_t captureDevice) = 0; + virtual bool LocalTalkerDestroy(uint8_t localTalker) = 0; + virtual bool LocalTalkerChangeOutputDevice(uint8_t localTalker, int32_t device) = 0; + virtual bool LocalTalkerChangeCaptureDevice(uint8_t localTalker, int32_t device) = 0; virtual int32_t LocalTalkerGetCurrentOutputDeviceIndex(uint8_t localTalker) = 0; virtual int32_t LocalTalkerGetCurrentCaptureDeviceIndex(uint8_t localTalker) = 0; - virtual void LocalTalkerEnable(uint8_t localTalker, bool enable) = 0; - virtual void LocalTalkerThreshold(uint8_t localTalker, float threshold) = 0; - virtual void LocalTalkerEnableVoiceLevelCallback(uint8_t localTalker, bool enable) = 0; - virtual void LocalTalkerSelectSession(uint8_t localTalker, uint64_t session) = 0; - virtual void LocalTalkerSetSessionPriority(uint8_t localTalker, uint64_t session, uint8_t priority) = 0; - virtual void LocalTalkerSetRemoteTalkerVolume(uint8_t localTalker, uint64_t talker, float volume) = 0; - virtual void LocalTalkerSetSessionVolume(uint8_t localTalker, uint64_t session, float volume) = 0; - virtual void MuteTalker(uint8_t localTalker, uint64_t talker, MuteSetting setting) = 0; - virtual int32_t IsTalkerMuted(uint8_t localTalker, uint64_t talker) = 0; - virtual void MuteSession(uint8_t localTalker, uint64_t session, MuteSetting setting) = 0; - virtual int32_t IsSessionMuted(uint8_t localTalker, uint64_t session) = 0; - virtual int32_t IsTalkerTalkingInSession(uint64_t talker, uint8_t localTalker, uint64_t session) = 0; - virtual int32_t DoesTalkerHaveHeadset(uint64_t talker) = 0; - virtual int32_t DoesLocalPlayerHaveHeadset(uint8_t localTalker) = 0; + virtual bool LocalTalkerEnable(uint8_t localTalker, bool enable) = 0; + virtual bool LocalTalkerThreshold(uint8_t localTalker, float threshold) = 0; + virtual bool LocalTalkerEnableVoiceLevelCallback(uint8_t localTalker, bool enable) = 0; + virtual bool LocalTalkerSelectSession(uint8_t localTalker, uint64_t session) = 0; + virtual bool LocalTalkerSetSessionPriority(uint8_t localTalker, uint64_t session, uint8_t priority) = 0; + virtual bool LocalTalkerSetRemoteTalkerVolume(uint8_t localTalker, uint64_t talker, float volume) = 0; + virtual bool LocalTalkerSetSessionVolume(uint8_t localTalker, uint64_t session, float volume) = 0; + virtual bool MuteTalker(uint8_t localTalker, uint64_t talker, MuteSetting setting) = 0; + virtual bool IsTalkerMuted(uint8_t localTalker, uint64_t talker) = 0; + virtual bool MuteSession(uint8_t localTalker, uint64_t session, MuteSetting setting) = 0; + virtual bool IsSessionMuted(uint8_t localTalker, uint64_t session) = 0; + virtual bool IsTalkerTalkingInSession(uint64_t session, uint8_t localTalker, uint64_t talker) = 0; + virtual bool DoesTalkerHaveHeadset(uint64_t talker) = 0; + virtual bool DoesLocalPlayerHaveHeadset(uint8_t localTalker) = 0; virtual void DebugSetSequenceDelay(int32_t delay) = 0; virtual void DebugSetSoundOutputDelay(uint8_t localTalker, int32_t delay) = 0; }; -namespace Network { - -class Manager { - public: - ~Manager(); -}; - -} - } #endif diff --git a/Engine/Source/ComSat/ComSatMD5.cpp b/Engine/Source/ComSat/ComSatMD5.cpp new file mode 100644 index 0000000..2d763c9 --- /dev/null +++ b/Engine/Source/ComSat/ComSatMD5.cpp @@ -0,0 +1,166 @@ +#include "Engine/Source/ComSat/ComSatMD5.h" +#include + +#define MD5_ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n)))) +#define MD5_F(x, y, z) (((x) & (y)) | (~(x) & (z))) +#define MD5_G(x, y, z) (((x) & (z)) | ((y) & ~(z))) +#define MD5_H(x, y, z) ((x) ^ (y) ^ (z)) +#define MD5_I(x, y, z) ((y) ^ ((x) | ~(z))) +#define MD5_STEP(f, a, b, c, d, k, s, ti) t = a + f(b, c, d) + x[k] + (ti); a = MD5_ROTATE_LEFT(t, s) + b + +// STATIC: 0x00A505D8 +static const uint8_t s_padding[64] = { 0x80 }; + +// VERIFY: 19a62d29 manual +// OFFSET: 0x00887EA0 +void ComSat::MD5::ProcessBlock(const uint8_t* block) { + uint32_t a = this->m_state[0]; + uint32_t b = this->m_state[1]; + uint32_t c = this->m_state[2]; + uint32_t d = this->m_state[3]; + uint32_t t; + const uint32_t* x; + uint32_t buffer[16]; + + if (!(reinterpret_cast(block) & 3)) { + x = reinterpret_cast(block); + } else { + memcpy(buffer, block, sizeof(buffer)); + x = buffer; + } + + MD5_STEP(MD5_F, a, b, c, d, 0, 7, 0xD76AA478); + MD5_STEP(MD5_F, d, a, b, c, 1, 12, 0xE8C7B756); + MD5_STEP(MD5_F, c, d, a, b, 2, 17, 0x242070DB); + MD5_STEP(MD5_F, b, c, d, a, 3, 22, 0xC1BDCEEE); + MD5_STEP(MD5_F, a, b, c, d, 4, 7, 0xF57C0FAF); + MD5_STEP(MD5_F, d, a, b, c, 5, 12, 0x4787C62A); + MD5_STEP(MD5_F, c, d, a, b, 6, 17, 0xA8304613); + MD5_STEP(MD5_F, b, c, d, a, 7, 22, 0xFD469501); + MD5_STEP(MD5_F, a, b, c, d, 8, 7, 0x698098D8); + MD5_STEP(MD5_F, d, a, b, c, 9, 12, 0x8B44F7AF); + MD5_STEP(MD5_F, c, d, a, b, 10, 17, 0xFFFF5BB1); + MD5_STEP(MD5_F, b, c, d, a, 11, 22, 0x895CD7BE); + MD5_STEP(MD5_F, a, b, c, d, 12, 7, 0x6B901122); + MD5_STEP(MD5_F, d, a, b, c, 13, 12, 0xFD987193); + MD5_STEP(MD5_F, c, d, a, b, 14, 17, 0xA679438E); + MD5_STEP(MD5_F, b, c, d, a, 15, 22, 0x49B40821); + + MD5_STEP(MD5_G, a, b, c, d, 1, 5, 0xF61E2562); + MD5_STEP(MD5_G, d, a, b, c, 6, 9, 0xC040B340); + MD5_STEP(MD5_G, c, d, a, b, 11, 14, 0x265E5A51); + MD5_STEP(MD5_G, b, c, d, a, 0, 20, 0xE9B6C7AA); + MD5_STEP(MD5_G, a, b, c, d, 5, 5, 0xD62F105D); + MD5_STEP(MD5_G, d, a, b, c, 10, 9, 0x02441453); + MD5_STEP(MD5_G, c, d, a, b, 15, 14, 0xD8A1E681); + MD5_STEP(MD5_G, b, c, d, a, 4, 20, 0xE7D3FBC8); + MD5_STEP(MD5_G, a, b, c, d, 9, 5, 0x21E1CDE6); + MD5_STEP(MD5_G, d, a, b, c, 14, 9, 0xC33707D6); + MD5_STEP(MD5_G, c, d, a, b, 3, 14, 0xF4D50D87); + MD5_STEP(MD5_G, b, c, d, a, 8, 20, 0x455A14ED); + MD5_STEP(MD5_G, a, b, c, d, 13, 5, 0xA9E3E905); + MD5_STEP(MD5_G, d, a, b, c, 2, 9, 0xFCEFA3F8); + MD5_STEP(MD5_G, c, d, a, b, 7, 14, 0x676F02D9); + MD5_STEP(MD5_G, b, c, d, a, 12, 20, 0x8D2A4C8A); + + MD5_STEP(MD5_H, a, b, c, d, 5, 4, 0xFFFA3942); + MD5_STEP(MD5_H, d, a, b, c, 8, 11, 0x8771F681); + MD5_STEP(MD5_H, c, d, a, b, 11, 16, 0x6D9D6122); + MD5_STEP(MD5_H, b, c, d, a, 14, 23, 0xFDE5380C); + MD5_STEP(MD5_H, a, b, c, d, 1, 4, 0xA4BEEA44); + MD5_STEP(MD5_H, d, a, b, c, 4, 11, 0x4BDECFA9); + MD5_STEP(MD5_H, c, d, a, b, 7, 16, 0xF6BB4B60); + MD5_STEP(MD5_H, b, c, d, a, 10, 23, 0xBEBFBC70); + MD5_STEP(MD5_H, a, b, c, d, 13, 4, 0x289B7EC6); + MD5_STEP(MD5_H, d, a, b, c, 0, 11, 0xEAA127FA); + MD5_STEP(MD5_H, c, d, a, b, 3, 16, 0xD4EF3085); + MD5_STEP(MD5_H, b, c, d, a, 6, 23, 0x04881D05); + MD5_STEP(MD5_H, a, b, c, d, 9, 4, 0xD9D4D039); + MD5_STEP(MD5_H, d, a, b, c, 12, 11, 0xE6DB99E5); + MD5_STEP(MD5_H, c, d, a, b, 15, 16, 0x1FA27CF8); + MD5_STEP(MD5_H, b, c, d, a, 2, 23, 0xC4AC5665); + + MD5_STEP(MD5_I, a, b, c, d, 0, 6, 0xF4292244); + MD5_STEP(MD5_I, d, a, b, c, 7, 10, 0x432AFF97); + MD5_STEP(MD5_I, c, d, a, b, 14, 15, 0xAB9423A7); + MD5_STEP(MD5_I, b, c, d, a, 5, 21, 0xFC93A039); + MD5_STEP(MD5_I, a, b, c, d, 12, 6, 0x655B59C3); + MD5_STEP(MD5_I, d, a, b, c, 3, 10, 0x8F0CCC92); + MD5_STEP(MD5_I, c, d, a, b, 10, 15, 0xFFEFF47D); + MD5_STEP(MD5_I, b, c, d, a, 1, 21, 0x85845DD1); + MD5_STEP(MD5_I, a, b, c, d, 8, 6, 0x6FA87E4F); + MD5_STEP(MD5_I, d, a, b, c, 15, 10, 0xFE2CE6E0); + MD5_STEP(MD5_I, c, d, a, b, 6, 15, 0xA3014314); + MD5_STEP(MD5_I, b, c, d, a, 13, 21, 0x4E0811A1); + MD5_STEP(MD5_I, a, b, c, d, 4, 6, 0xF7537E82); + MD5_STEP(MD5_I, d, a, b, c, 11, 10, 0xBD3AF235); + MD5_STEP(MD5_I, c, d, a, b, 2, 15, 0x2AD7D2BB); + MD5_STEP(MD5_I, b, c, d, a, 9, 21, 0xEB86D391); + + this->m_state[0] += a; + this->m_state[1] += b; + this->m_state[2] += c; + this->m_state[3] += d; +} + +// VERIFY: fadbeeaa auto +// OFFSET: 0x008885D0 +void ComSat::MD5::Prepare() { + this->m_count[1] = 0; + this->m_count[0] = 0; + this->m_state[0] = 0x67452301; + this->m_state[1] = 0xEFCDAB89; + this->m_state[2] = 0x98BADCFE; + this->m_state[3] = 0x10325476; +} + +// VERIFY: 5a665437 manual +// OFFSET: 0x00888600 +void ComSat::MD5::Process(const void* data, uint32_t size) { + const uint8_t* p = static_cast(data); + uint32_t index = (this->m_count[0] >> 3) & 0x3F; + uint32_t bits = 8 * size; + if (!size) { + return; + } + this->m_count[0] += bits; + this->m_count[1] += size >> 29; + if (this->m_count[0] < bits) { + this->m_count[1]++; + } + if (index) { + uint32_t part = index + size <= 64 ? size : 64 - index; + memcpy(&this->m_buffer[index], p, part); + if (part + index < 64) { + return; + } + size -= part; + p += part; + this->ProcessBlock(this->m_buffer); + } + if (size >= 64) { + uint32_t blocks = size >> 6; + size -= 64 * blocks; + do { + this->ProcessBlock(p); + p += 64; + } while (--blocks); + } + if (size) { + memcpy(this->m_buffer, p, size); + } +} + +// VERIFY: 14ebee61 manual +// OFFSET: 0x008886E0 +void ComSat::MD5::Finish(uint8_t (&digest)[16]) { + uint8_t length[8]; + for (int32_t i = 0; i < 8; i++) { + length[i] = static_cast(this->m_count[i >> 2] >> ((i & 3) << 3)); + } + this->Process(s_padding, ((55 - (this->m_count[0] >> 3)) & 63) + 1); + this->Process(length, 8); + for (uint32_t i = 0; i < 16; i++) { + digest[i] = static_cast(this->m_state[i >> 2] >> ((i & 3) << 3)); + } +} diff --git a/Engine/Source/ComSat/ComSatMD5.h b/Engine/Source/ComSat/ComSatMD5.h new file mode 100644 index 0000000..941ae0a --- /dev/null +++ b/Engine/Source/ComSat/ComSatMD5.h @@ -0,0 +1,23 @@ +#ifndef ENGINE_SOURCE_COMSAT_COMSATMD5_H +#define ENGINE_SOURCE_COMSAT_COMSATMD5_H + +#include +#include + +namespace ComSat { + +class MD5 { + public: + /* 0000 */ uint32_t m_count[2]; + /* 0008 */ uint32_t m_state[4]; + /* 0018 */ uint8_t m_buffer[64]; + + void Finish(uint8_t (&digest)[16]); + void Prepare(); + void Process(const void* data, uint32_t size); + void ProcessBlock(const uint8_t* block); +}; + +} + +#endif diff --git a/Engine/Source/ComSat/ComSatManager.cpp b/Engine/Source/ComSat/ComSatManager.cpp new file mode 100644 index 0000000..d5e8aab --- /dev/null +++ b/Engine/Source/ComSat/ComSatManager.cpp @@ -0,0 +1,808 @@ +#include "Engine/Source/ComSat/ComSatManager.h" +#include "Engine/Source/ComSat/ComSatAllocator.h" +#include "Engine/Source/ComSat/ComSatBitPacker.h" +#include +#include + +// VERIFY: daaf90f8 auto +// OFFSET: 0x0087F900 +ComSat::Interface::~Interface() { +} + +// INLINED +ComSat::Manager::LocalTalker::LocalTalker(ComSat::Allocator& allocator) : m_guid(0), m_session(nullptr), m_sessions(allocator) { +} + +// VERIFY: 03a47a69 auto +// OFFSET: 0x0087F990 +void ComSat::Manager::Work(uint32_t elapsed) { + this->m_networkManager->Work(elapsed); + this->m_soundManager->Work(elapsed); +} + +// VERIFY: 36e8ca55 auto +// OFFSET: 0x0087F9C0 +void ComSat::Manager::CallbackClear() { + this->m_callback = nullptr; +} + +// VERIFY: 814c3774 auto +// OFFSET: 0x0095BE50 +void ComSat::Manager::CallbackSet(ComSat::Interface::Callback& callback) { + this->m_callback = &callback; +} + +// VERIFY: e4968ea4 auto +// OFFSET: 0x0087F9D0 +bool ComSat::Manager::LocalTalkerChangeOutputDevice(uint8_t localTalker, int32_t device) { + return this->m_soundManager->LocalTalkerChangeOutputDevice(localTalker, device); +} + +// VERIFY: c0eb6067 auto +// OFFSET: 0x0087F9E0 +bool ComSat::Manager::LocalTalkerChangeCaptureDevice(uint8_t localTalker, int32_t device) { + return this->m_soundManager->LocalTalkerChangeCaptureDevice(localTalker, device); +} + +// VERIFY: 2b33b977 auto +// OFFSET: 0x0087F9F0 +int32_t ComSat::Manager::LocalTalkerGetCurrentOutputDeviceIndex(uint8_t localTalker) { + return this->m_soundManager->LocalTalkerGetCurrentOutputDeviceIndex(localTalker); +} + +// VERIFY: 6fedd7b9 auto +// OFFSET: 0x0087FA00 +int32_t ComSat::Manager::LocalTalkerGetCurrentCaptureDeviceIndex(uint8_t localTalker) { + return this->m_soundManager->LocalTalkerGetCurrentCaptureDeviceIndex(localTalker); +} + +// VERIFY: 87fe7308 auto +// OFFSET: 0x0087FA10 +bool ComSat::Manager::LocalTalkerEnable(uint8_t localTalker, bool enable) { + return this->m_soundManager->LocalTalkerEnable(localTalker, enable); +} + +// VERIFY: 030f3ac2 auto +// OFFSET: 0x0087FA20 +bool ComSat::Manager::LocalTalkerThreshold(uint8_t localTalker, float threshold) { + if (threshold < 0.0f || threshold > 1.0f) { + return false; + } + return this->m_soundManager->LocalTalkerThreshold(localTalker, threshold); +} + +// VERIFY: fc07e902 auto +// OFFSET: 0x0087FA60 +bool ComSat::Manager::LocalTalkerEnableVoiceLevelCallback(uint8_t localTalker, bool enable) { + if (localTalker >= this->m_maxLocalPlayers) { + return false; + } + this->m_soundManager->LocalTalkerEnableVoiceLevelCallback(localTalker, enable); + return true; +} + +// VERIFY: 6ed3bdce auto +// OFFSET: 0x0087FA90 +bool ComSat::Manager::LocalTalkerSetRemoteTalkerVolume(uint8_t localTalker, uint64_t talker, float volume) { + return this->m_soundManager->LocalTalkerSetRemoteTalkerVolume(localTalker, talker, volume); +} + +// VERIFY: 6d300b56 auto +// OFFSET: 0x0087FAC0 +bool ComSat::Manager::LocalTalkerSetSessionVolume(uint8_t localTalker, uint64_t session, float volume) { + return this->m_soundManager->LocalTalkerSetSessionVolume(localTalker, session, volume); +} + +// VERIFY: ff4b4a0e auto +// OFFSET: 0x0087FAF0 +int32_t ComSat::Manager::SessionNumMembers(uint64_t session) { + return this->m_soundManager->SessionNumMembers(session); +} + +// VERIFY: 9e7d64e0 auto +// OFFSET: 0x0087FB10 +bool ComSat::Manager::SessionGetTalkerByIndex(uint64_t session, int32_t index, uint64_t& talker, uint8_t& localTalker) { + if (!this->m_soundManager->SessionGetTalkerByIndex(session, index, talker, localTalker)) { + return false; + } + if (localTalker != 0xFF) { + if (localTalker >= this->m_maxLocalPlayers) { + return false; + } + uint64_t guid = this->m_localTalkers[localTalker]->m_guid; + if (!guid) { + return false; + } + talker = guid; + } + return true; +} + +// VERIFY: b46ff538 auto +// OFFSET: 0x0087FB70 +bool ComSat::Manager::SessionSetTalkerPriority(uint64_t session, uint64_t talker, uint8_t priority) { + return this->m_soundManager->SetPlaybackPriorityForPlayerInSession(session, talker, priority); +} + +// VERIFY: 1b462178 auto +// OFFSET: 0x0087FBA0 +bool ComSat::Manager::LocalTalkerSetSessionPriority(uint8_t localTalker, uint64_t session, uint8_t priority) { + return this->m_soundManager->SetPlaybackPriorityForSession(session, localTalker, priority); +} + +// VERIFY: 3b40d07f manual +// OFFSET: 0x0087FBC0 +bool ComSat::Manager::IsTalkerMuted(uint8_t localTalker, uint64_t talker) { + if (localTalker < this->m_maxLocalPlayers) { + return this->m_soundManager->IsRemoteTalkerMuted(localTalker, talker); + } + return false; +} + +// VERIFY: d7c8ef33 auto +// OFFSET: 0x0087FBF0 +bool ComSat::Manager::MuteTalker(uint8_t localTalker, uint64_t talker, ComSat::MuteSetting setting) { + return this->m_soundManager->SetTalkerMuted(localTalker, talker, setting); +} + +// VERIFY: ed19ad38 auto +// OFFSET: 0x0087FC10 +bool ComSat::Manager::MuteSession(uint8_t localTalker, uint64_t session, ComSat::MuteSetting setting) { + if (localTalker < this->m_maxLocalPlayers && this->m_localTalkers[localTalker]->m_guid) { + return this->m_soundManager->SetSessionMuted(localTalker, session, setting); + } + return false; +} + +// VERIFY: 9f29457b auto +// OFFSET: 0x0087FC50 +bool ComSat::Manager::IsSessionMuted(uint8_t localTalker, uint64_t session) { + return this->m_soundManager->IsSessionMuted(localTalker, session); +} + +// VERIFY: cfd75ff0 manual +// OFFSET: 0x0087FC70 +uint8_t ComSat::Manager::GetLocalTalkerIndex(uint64_t talker) { + for (uint32_t i = 0; i < this->m_maxLocalPlayers; i++) { + if (this->m_localTalkers[i]->m_guid == talker) { + return i; + } + } + return 0xFF; +} + +// VERIFY: baa2befb auto +// OFFSET: 0x0087FCB0 +bool ComSat::Manager::IsTalkerTalkingInSession(uint64_t session, uint8_t localTalker, uint64_t talker) { + if (this->GetLocalTalkerIndex(talker) == 0xFF) { + return this->m_soundManager->IsRemoteTalkerTalkingInSession(session, localTalker, talker); + } + return this->m_soundManager->IsLocalPlayerTalking(localTalker); +} + +// VERIFY: b10e168c auto +// OFFSET: 0x0087FD00 +bool ComSat::Manager::DoesTalkerHaveHeadset(uint64_t talker) { + return true; +} + +// VERIFY: b0dbd72a auto +// OFFSET: 0x008873A0 +bool ComSat::Manager::DoesLocalPlayerHaveHeadset(uint8_t localTalker) { + return true; +} + +// VERIFY: 6512fb0f auto +// OFFSET: 0x0087FD10 +int32_t ComSat::Manager::EnumerateOutputDevices(ComSat::DeviceInfo* devices, int32_t maxDevices) { + return this->m_soundManager->EnumerateOutputDevices(devices, maxDevices); +} + +// VERIFY: 876fcfd1 auto +// OFFSET: 0x0087FD20 +int32_t ComSat::Manager::EnumerateCaptureDevices(ComSat::DeviceInfo* devices, int32_t maxDevices) { + return this->m_soundManager->EnumerateCaptureDevices(devices, maxDevices); +} + +// VERIFY: 6221267c manual +// OFFSET: 0x0087FD30 +bool ComSat::Manager::UnpackStableBitrateData(uint64_t session, uint64_t talker, const uint8_t* data, uint32_t size) { + bool reliable = false; + uint32_t offset = 2; + do { + uint8_t length = data[offset]; + if (!length) { + reliable = true; + } + offset += length + 1; + } while (offset < size); + ComSat::Sound::Manager::VoicePacket packet; + packet.m_sequence = *reinterpret_cast(data); + packet.m_bits = this->m_soundManager->GetMaxEncodedFrameLength(); + uint32_t bytes = static_cast(this->m_soundManager->GetMaxEncodedFrameLength()) >> 3; + int32_t frames = 0; + uint32_t position = 2; + if (size > 2) { + do { + if (size - position < bytes) { + break; + } + memcpy(packet.m_data, data + position, bytes); + this->m_soundManager->SubmitIncomingVoicePacket(session, talker, reinterpret_cast(&packet), bytes + 4, reliable); + packet.m_sequence++; + frames++; + position += bytes; + } while (position < size); + if (frames > 0) { + this->m_soundManager->SubmitIncomingFrameTimeData(talker, packet.m_sequence); + } + } + return true; +} + +// VERIFY: 866f6aa1 manual +// OFFSET: 0x0087FE30 +bool ComSat::Manager::UnpackVariableBitrateData(uint64_t session, uint64_t talker, const uint8_t* data, uint32_t size) { + uint16_t sequence = data[0] | (data[1] << 8); + uint32_t position = 3; + uint8_t header = data[2]; + bool reliable = header >> 7; + uint8_t count = header & 0x7F; + if (count > 20) { + count = 20; + } + ComSat::Sound::Manager::VoicePacket packet; + uint32_t lengths[20]; + for (int32_t i = 0; i < count; i++) { + lengths[i] = data[position]; + lengths[i] += this->m_soundManager->GetMinEncodedFrameLength(); + position++; + } + ComSat::BitUnpacker unpacker(&data[position], 8 * (size - position)); + for (int32_t i = 0; i < count; i++) { + uint32_t bits = lengths[i]; + packet.m_sequence = sequence; + packet.m_bits = bits; + if (bits && unpacker.UnpackBits(packet.m_data, bits)) { + uint32_t length = (bits >> 3) + 4; + if (bits & 7) { + length = (bits >> 3) + 5; + } + this->m_soundManager->SubmitIncomingVoicePacket(session, talker, reinterpret_cast(&packet), length, reliable); + } + sequence++; + } + if (count) { + this->m_soundManager->SubmitIncomingFrameTimeData(talker, sequence - 1); + } + return true; +} + +// VERIFY: 796aacf3 manual +// OFFSET: 0x0087FF70 +bool ComSat::Manager::UnpackBitpackedVariableBitrateData(uint64_t session, uint64_t talker, const uint8_t* data, uint32_t size) { + ComSat::Sound::Manager::VoicePacket packet; + packet.m_sequence = *reinterpret_cast(data); + ComSat::BitUnpacker unpacker(data + 2, 8 * size - 16); + packet.m_bits = 8 * size - 16; + if (!unpacker.UnpackBits(packet.m_data, packet.m_bits)) { + return false; + } + this->m_soundManager->SubmitIncomingVoicePacket(session, talker, reinterpret_cast(&packet), 132, false); + this->m_soundManager->SubmitIncomingFrameTimeData(talker, packet.m_sequence); + return true; +} + +// VERIFY: 70cd887e auto +// OFFSET: 0x00880030 +void ComSat::Manager::IncomingVoiceData(uint64_t session, uint64_t talker, const uint8_t* data, uint32_t size) { + if (this->m_soundManager->IsUsingVariableBitrateCodec()) { + if (this->m_soundManager->CanBitpackEncodedData()) { + this->UnpackBitpackedVariableBitrateData(session, talker, data, size); + } else { + this->UnpackVariableBitrateData(session, talker, data, size); + } + } else { + this->UnpackStableBitrateData(session, talker, data, size); + } +} + +// VERIFY: e0a023cd manual +// OFFSET: 0x008800B0 +bool ComSat::Manager::PackBitpackedVariableBitrateData(uint8_t player, uint8_t* buffer, int32_t& size) { + size = 0; + if (player >= this->m_maxLocalPlayers) { + return false; + } + LocalTalker* localTalker = this->m_localTalkers[player]; + if (!localTalker || !localTalker->m_frameCount) { + return false; + } + *reinterpret_cast(buffer) = localTalker->m_frames[0].m_sequence; + size += 2; + ComSat::BitPacker packer(buffer + size, 2560 - size); + for (int32_t i = 0; i < static_cast(localTalker->m_frameCount); i++) { + packer.PackBits(localTalker->m_frames[i].m_data, localTalker->m_frames[i].m_bits); + } + size += packer.Finalize(); + return true; +} + +// VERIFY: 16e90e0b manual +// OFFSET: 0x00880160 +bool ComSat::Manager::PackVariableBitrateData(uint8_t player, uint8_t* buffer, int32_t& size) { + size = 0; + if (player >= this->m_maxLocalPlayers) { + return false; + } + LocalTalker* localTalker = this->m_localTalkers[player]; + if (!localTalker || !localTalker->m_frameCount) { + return false; + } + int32_t minimum = this->m_soundManager->GetMinEncodedFrameLength(); + *reinterpret_cast(buffer + size) = localTalker->m_frames[0].m_sequence; + size += 2; + buffer[size] = localTalker->m_frameCount; + if (localTalker->m_time < 100) { + buffer[size] |= 0x80; + } + size++; + for (int32_t i = 0; i < static_cast(localTalker->m_frameCount); i++) { + int32_t length = localTalker->m_frames[i].m_bits - minimum; + if (length < 0) { + length = 0; + } else if (length > 255) { + length = 255; + } + buffer[size] = length; + size++; + } + ComSat::BitPacker packer(buffer + size, 2560 - size); + for (int32_t i = 0; i < static_cast(localTalker->m_frameCount); i++) { + packer.PackBits(localTalker->m_frames[i].m_data, localTalker->m_frames[i].m_bits); + } + size += packer.Finalize(); + return true; +} + +// VERIFY: 87720e76 manual +// OFFSET: 0x008802A0 +bool ComSat::Manager::PackStableBitrateData(uint8_t player, uint8_t* buffer, int32_t& size) { + size = 0; + if (player >= this->m_maxLocalPlayers) { + return false; + } + LocalTalker* localTalker = this->m_localTalkers[player]; + if (!localTalker || !localTalker->m_frameCount) { + return false; + } + *reinterpret_cast(buffer) = localTalker->m_frames[0].m_sequence; + size += 2; + uint32_t bytes = static_cast(this->m_soundManager->GetMaxEncodedFrameLength()) >> 3; + if (this->m_soundManager->GetMaxEncodedFrameLength() & 7) { + bytes++; + } + for (uint32_t i = 0; i < localTalker->m_frameCount; i++) { + memcpy(buffer + size, localTalker->m_frames[i].m_data, bytes); + size += bytes; + } + if (localTalker->m_time < 100) { + buffer[size++] = 0; + } + return true; +} + +// VERIFY: 6ca2c7b2 auto +// OFFSET: 0x00880380 +void ComSat::Manager::SendVoiceDataToCurrentSession(uint8_t player) { + if (player >= this->m_maxLocalPlayers) { + return; + } + LocalTalker* localTalker = this->m_localTalkers[player]; + if (!localTalker || !localTalker->m_frameCount) { + return; + } + if (localTalker->m_session) { + uint8_t buffer[2560]; + int32_t size = 0; + bool packed; + if (this->m_soundManager->IsUsingVariableBitrateCodec()) { + if (this->m_soundManager->CanBitpackEncodedData()) { + packed = this->PackBitpackedVariableBitrateData(player, buffer, size); + } else { + packed = this->PackVariableBitrateData(player, buffer, size); + } + } else { + packed = this->PackStableBitrateData(player, buffer, size); + } + if (!packed) { + return; + } + localTalker->m_session->Send(localTalker->m_guid, buffer, size); + } + localTalker->m_frameCount = 0; + localTalker->m_time = 0; +} + +// VERIFY: 42ef3c1d manual +// OFFSET: 0x00880450 +void ComSat::Manager::LocalChatDataReady(uint8_t player, uint8_t* data, uint32_t size, uint32_t time) { + if (player >= this->m_maxLocalPlayers) { + return; + } + LocalTalker* localTalker = this->m_localTalkers[player]; + if (!localTalker->m_guid) { + return; + } + if (!size) { + if (localTalker->m_talking) { + localTalker->m_talking = false; + if (this->m_callback) { + this->m_callback->NotifyLocalTalkerStop(player); + } + } + this->SendVoiceDataToCurrentSession(player); + return; + } + if (!localTalker->m_talking) { + localTalker->m_talking = true; + if (this->m_callback) { + this->m_callback->NotifyLocalTalkerStart(player); + } + } + if (size <= 128) { + LocalTalker* target = this->m_localTalkers[player]; + target->m_frames[target->m_frameCount].m_size = size; + memcpy(&target->m_frames[target->m_frameCount], data, size); + target->m_frameCount++; + target->m_time += time; + if (target->m_time >= 100) { + this->SendVoiceDataToCurrentSession(player); + } + } +} + +// VERIFY: aaea3c06 manual +// OFFSET: 0x00880550 +void ComSat::Manager::RemotePlayerTalkNotifyStart(uint8_t player, uint64_t talker, uint64_t session) { + if (this->m_callback) { + this->m_callback->NotifyTalkerStart(player, session, talker); + } +} + +// VERIFY: 39fa1c5d manual +// OFFSET: 0x00880580 +void ComSat::Manager::RemotePlayerTalkNotifyStop(uint8_t player, uint64_t talker, uint64_t session) { + if (this->m_callback) { + this->m_callback->NotifyTalkerStop(player, session, talker); + } +} + +// VERIFY: 582ba733 manual +// OFFSET: 0x008805B0 +void ComSat::Manager::LocalTalkerVoiceLevel(uint8_t player, float level, bool talking) { + if (this->m_callback) { + this->m_callback->NotifyLocalTalkerVoiceLevel(player, level, talking); + } +} + +// VERIFY: 0641685b auto +// OFFSET: 0x008805E0 +void ComSat::Manager::DeviceError(uint8_t player) { + if (this->m_callback && player < this->m_maxLocalPlayers) { + LocalTalker* localTalker = this->m_localTalkers[player]; + if (localTalker->m_guid && localTalker->m_deviceError != true) { + localTalker->m_deviceError = true; + this->m_callback->NotifyDeviceError(player); + } + } +} + +// VERIFY: de61f2c6 auto +// OFFSET: 0x00653A10 +void ComSat::Manager::MicrophoneStatusUpdate(uint8_t player, ComSat::Sound::HeadsetDeviceStatus status) { +} + +// VERIFY: f7010444 auto +// OFFSET: 0x00880630 +void ComSat::Manager::DebugSetSequenceDelay(int32_t delay) { + this->m_soundManager->DebugSetSequenceDelay(delay); +} + +// VERIFY: 4f0e7df6 auto +// OFFSET: 0x00880640 +void ComSat::Manager::DebugSetSoundOutputDelay(uint8_t localTalker, int32_t delay) { + this->m_soundManager->DebugSetSoundOutputDelay(localTalker, delay); +} + +// VERIFY: 51a7470f auto +// OFFSET: 0x00880710 +bool ComSat::Manager::LocalTalkerCreate(uint8_t localTalker, uint64_t talker, float threshold, int32_t outputDevice, int32_t captureDevice) { + LocalTalker* local = this->m_localTalkers[localTalker]; + if (!local) { + return false; + } + local->m_guid = talker; + local->m_session = nullptr; + local->m_frameCount = 0; + local->m_time = 0; + local->m_deviceError = false; + local->m_sessions.m_used = 0; + local->m_talking = false; + return this->m_soundManager->InitLocalPlayer(localTalker, threshold, outputDevice, captureDevice); +} + +// VERIFY: ae78af2b auto +// OFFSET: 0x00880780 +bool ComSat::Manager::LocalTalkerDestroy(uint8_t localTalker) { + LocalTalker* local = this->m_localTalkers[localTalker]; + if (!local || !local->m_guid) { + return true; + } + uint32_t count = local->m_sessions.Count(); + for (uint32_t i = 0; i < count; i++) { + this->SessionRemove(local->m_sessions[i], local->m_guid); + } + bool result = this->m_soundManager->DestroyLocalPlayer(localTalker); + local->m_guid = 0; + return result; +} + +// VERIFY: 4f3fb2d5 manual +// OFFSET: 0x00880810 +bool ComSat::Manager::SessionDestroy(uint64_t session) { + for (uint8_t i = 0; i < this->m_maxLocalPlayers; i++) { + LocalTalker* local = this->m_localTalkers[i]; + if (local->m_guid) { + ComSat::Session* current = local->m_session; + if (current && current->m_id == session) { + local->m_session = nullptr; + local->m_frameCount = 0; + local->m_time = 0; + } + } + } + uint32_t count = this->m_sessions.Count(); + uint32_t index = 0; + if (!count) { + return false; + } + while (this->m_sessions[index]->m_id != session) { + if (++index >= count) { + return false; + } + } + ComSat::Session* removed = this->m_sessions[index]; + this->m_sessions.RemoveAt(index); + if (!removed) { + return false; + } + this->m_networkManager->DestroySession(removed->GetNetworkSession()); + ComSat::Delete(*this->m_allocator, removed); + this->m_soundManager->SessionDestroy(session); + return true; +} + +// VERIFY: 4bc9f19f manual +// OFFSET: 0x00880920 +ComSat::Session* ComSat::Manager::FindSession(uint64_t id) { + for (uint32_t i = 0; i < this->m_sessions.Count(); i++) { + if (this->m_sessions[i]->m_id == id) { + return this->m_sessions[i]; + } + } + return nullptr; +} + +// VERIFY: 74ff654b manual +// OFFSET: 0x00880980 +bool ComSat::Manager::SessionAddRemote(uint64_t session, uint64_t talker, uint8_t networkId, const uint8_t (&key)[16], const char* address) { + ComSat::Session* current = this->FindSession(session); + if (!current) { + return false; + } + for (uint32_t i = 0; i < this->m_maxLocalPlayers; i++) { + if (this->m_localTalkers[i]->m_guid == talker) { + return false; + } + } + ComSat::Network::Address remote; + remote.SetAddress(address); + if (!remote.GetPort()) { + remote.SetPort(this->m_defaultPort); + } + current->Add(talker, networkId, key, remote); + return this->m_soundManager->RegisterRemoteTalkerForSession(session, talker); +} + +// VERIFY: a80b2754 manual +// OFFSET: 0x00880A50 +bool ComSat::Manager::SessionSetTalkerNetworkIdLocal(uint64_t session, uint64_t talker, uint8_t networkId) { + ComSat::Session* current = this->FindSession(session); + if (!current) { + return false; + } + ComSat::Network::Session* networkSession = current->GetNetworkSession(); + if (!networkSession) { + return false; + } + networkSession->SetTalkerNetworkIdLocal(talker, networkId); + return true; +} + +// VERIFY: 07b80142 manual +// OFFSET: 0x00880A90 +bool ComSat::Manager::SessionSetTalkerNetworkIdRemote(uint64_t session, uint64_t talker, uint8_t networkId) { + ComSat::Session* current = this->FindSession(session); + if (!current) { + return false; + } + ComSat::Network::Session* networkSession = current->GetNetworkSession(); + if (!networkSession) { + return false; + } + networkSession->SetTalkerNetworkIdRemote(talker, networkId); + return true; +} + +// VERIFY: bd6b44ca auto +// OFFSET: 0x00880BB0 +ComSat::Manager::Manager(ComSat::Sound::Manager& soundManager, ComSat::Network::Manager& networkManager, const ComSat::Initialization& init, ComSat::Allocator& allocator) : m_sessions(allocator) { + this->m_maxLocalPlayers = init.m_maxLocalPlayers; + this->unk_0010 = init.unk_0004; + this->m_soundManager = &soundManager; + this->m_networkManager = &networkManager; + this->m_allocator = &allocator; + this->m_defaultPort = init.m_port; + this->m_localTalkers = nullptr; + this->m_callback = nullptr; + this->m_localTalkers = static_cast(this->m_allocator->Alloc(sizeof(LocalTalker*) * this->m_maxLocalPlayers)); + for (uint32_t i = 0; i < this->m_maxLocalPlayers; i++) { + this->m_localTalkers[i] = new (this->m_allocator->Alloc(sizeof(LocalTalker))) LocalTalker(*this->m_allocator); + } + soundManager.SetCallback(this); +} + +// VERIFY: 27b35473 manual +// OFFSET: [0x00881150, 0x00881250] +ComSat::Manager::~Manager() { + for (uint32_t i = 0; i < this->m_maxLocalPlayers; i++) { + if (this->m_localTalkers[i]) { + ComSat::Delete(*this->m_allocator, this->m_localTalkers[i]); + this->m_localTalkers[i] = nullptr; + } + } + if (this->m_localTalkers) { + this->m_allocator->Free(this->m_localTalkers); + } + for (uint32_t i = 0; i < this->m_sessions.Count(); i++) { + ComSat::Delete(*this->m_allocator, this->m_sessions[i]); + } +} + +// VERIFY: 22930931 manual +// OFFSET: 0x00880CB0 +bool ComSat::Manager::SessionSetNetworkId(uint64_t session, uint16_t networkId) { + ComSat::Session* current = this->FindSession(session); + if (!current) { + return false; + } + ComSat::Network::Session* networkSession = current->GetNetworkSession(); + if (!networkSession) { + return false; + } + networkSession->SetNetworkId(networkId); + return true; +} + +// VERIFY: 5a142082 manual +// OFFSET: 0x00880CF0 +bool ComSat::Manager::LocalTalkerSelectSession(uint8_t localTalker, uint64_t session) { + if (localTalker >= this->m_maxLocalPlayers) { + return false; + } + LocalTalker* local = this->m_localTalkers[localTalker]; + if (local->m_session && local->m_session->m_id == session) { + return true; + } + this->SendVoiceDataToCurrentSession(localTalker); + if (!session) { + local->m_session = nullptr; + return true; + } + local->m_session = this->FindSession(session); + return local->m_session != nullptr; +} + +// VERIFY: a74d7eee manual +// OFFSET: 0x00880D70 +bool ComSat::Manager::SessionRemove(uint64_t session, uint64_t talker) { + ComSat::Session* current = this->FindSession(session); + if (!current) { + return false; + } + current->Remove(talker); + if (!this->m_localTalkers) { + return false; + } + uint8_t localTalker = 0xFF; + for (uint32_t i = 0; i < this->m_maxLocalPlayers; i++) { + if (this->m_localTalkers[i]->m_guid == talker) { + localTalker = i; + } + } + if (localTalker == 0xFF) { + return this->m_soundManager->UnregisterRemoteTalkerFromSession(session, talker); + } + bool result = this->m_soundManager->UnregisterLocalTalkerFromSession(session, localTalker); + bool unused = true; + for (uint32_t i = 0; i < this->m_maxLocalPlayers; i++) { + LocalTalker* local = this->m_localTalkers[i]; + if (local->m_guid) { + if (local->m_guid == talker) { + local->m_sessions.Remove(session); + } else { + uint32_t index = 0; + if (local->m_sessions.Find(session, index)) { + unused = false; + } + } + } + } + if (unused) { + this->SessionDestroy(session); + } + return result; +} + +// VERIFY: 0ca1a41a auto +// OFFSET: 0x00880FC0 +bool ComSat::Manager::SessionCreate(uint64_t session) { + if (this->FindSession(session)) { + return false; + } + void* memory = this->m_allocator->Alloc(sizeof(ComSat::Session)); + if (!memory) { + return false; + } + ComSat::Session* created = new (memory) ComSat::Session(*this, session, *this->m_allocator); + if (!created) { + return false; + } + ComSat::Network::Session* networkSession = this->m_networkManager->CreateSession(session, *created); + if (!networkSession) { + ComSat::Delete(*this->m_allocator, created); + return false; + } + this->m_sessions.PushBack(created); + created->SetNetworkSession(networkSession); + this->m_soundManager->SessionCreate(session); + return true; +} + +// VERIFY: 076cfaa1 manual +// OFFSET: 0x00881070 +bool ComSat::Manager::SessionAddLocal(uint64_t session, uint8_t localTalker, uint64_t talker) { + ComSat::Session* current = this->FindSession(session); + if (!current) { + return false; + } + if (localTalker >= this->m_maxLocalPlayers) { + return false; + } + LocalTalker* local = this->m_localTalkers[localTalker]; + if (!local->m_guid) { + local->m_guid = talker; + } + ComSat::Vector& sessions = this->m_localTalkers[localTalker]->m_sessions; + uint32_t index = 0; + if (!sessions.Find(session, index)) { + sessions.PushBack(session); + } + current->LocalAdd(talker); + bool result = this->m_soundManager->RegisterLocalTalkerForSession(session, localTalker); + if (result && !this->m_localTalkers[localTalker]->m_session) { + this->LocalTalkerSelectSession(localTalker, session); + } + return result; +} diff --git a/Engine/Source/ComSat/ComSatManager.h b/Engine/Source/ComSat/ComSatManager.h new file mode 100644 index 0000000..982e69e --- /dev/null +++ b/Engine/Source/ComSat/ComSatManager.h @@ -0,0 +1,108 @@ +#ifndef ENGINE_SOURCE_COMSAT_COMSATMANAGER_H +#define ENGINE_SOURCE_COMSAT_COMSATMANAGER_H + +#include +#include +#include "Engine/Source/ComSat/ComSatInterface.h" +#include "Engine/Source/ComSat/ComSatNetwork.h" +#include "Engine/Source/ComSat/ComSatSession.h" +#include "Engine/Source/ComSat/ComSatSoundManager.h" +#include "Engine/Source/ComSat/ComSatVector.h" + +namespace ComSat { + +class Manager : public Interface, public Sound::Manager::Callback, public SessionCallback { + public: + class LocalTalker { + public: + struct Frame { + /* 0000 */ uint16_t m_sequence; + /* 0002 */ uint16_t m_bits; + /* 0004 */ uint8_t m_data[124]; + /* 0080 */ uint16_t m_size; + }; + + /* 0000 */ uint64_t m_guid; + /* 0008 */ Session* m_session; + /* 000C */ Frame m_frames[100]; + /* 32D4 */ uint32_t m_frameCount; + /* 32D8 */ uint32_t m_time; + /* 32DC */ bool m_talking; + /* 32E0 */ Vector m_sessions; + /* 32F0 */ bool m_deviceError; + + LocalTalker(Allocator& allocator); + }; + + /* 000C */ uint32_t m_maxLocalPlayers; + /* 0010 */ uint32_t unk_0010; + /* 0014 */ Sound::Manager* m_soundManager; + /* 0018 */ Network::Manager* m_networkManager; + /* 001C */ Allocator* m_allocator; + /* 0020 */ uint16_t m_defaultPort; + /* 0024 */ Vector m_sessions; + /* 0034 */ LocalTalker** m_localTalkers; + /* 0038 */ Interface::Callback* m_callback; + + virtual ~Manager(); + virtual void Work(uint32_t elapsed); + virtual int32_t EnumerateOutputDevices(DeviceInfo* devices, int32_t maxDevices); + virtual int32_t EnumerateCaptureDevices(DeviceInfo* devices, int32_t maxDevices); + virtual void CallbackSet(Interface::Callback& callback); + virtual void CallbackClear(); + virtual bool SessionCreate(uint64_t session); + virtual bool SessionDestroy(uint64_t session); + virtual bool SessionSetNetworkId(uint64_t session, uint16_t networkId); + virtual bool SessionAddLocal(uint64_t session, uint8_t localTalker, uint64_t talker); + virtual bool SessionAddRemote(uint64_t session, uint64_t talker, uint8_t networkId, const uint8_t (&key)[16], const char* address); + virtual bool SessionSetTalkerNetworkIdLocal(uint64_t session, uint64_t talker, uint8_t networkId); + virtual bool SessionSetTalkerNetworkIdRemote(uint64_t session, uint64_t talker, uint8_t networkId); + virtual bool SessionRemove(uint64_t session, uint64_t talker); + virtual int32_t SessionNumMembers(uint64_t session); + virtual bool SessionGetTalkerByIndex(uint64_t session, int32_t index, uint64_t& talker, uint8_t& localTalker); + virtual bool SessionSetTalkerPriority(uint64_t session, uint64_t talker, uint8_t priority); + virtual bool LocalTalkerCreate(uint8_t localTalker, uint64_t talker, float threshold, int32_t outputDevice, int32_t captureDevice); + virtual bool LocalTalkerDestroy(uint8_t localTalker); + virtual bool LocalTalkerChangeOutputDevice(uint8_t localTalker, int32_t device); + virtual bool LocalTalkerChangeCaptureDevice(uint8_t localTalker, int32_t device); + virtual int32_t LocalTalkerGetCurrentOutputDeviceIndex(uint8_t localTalker); + virtual int32_t LocalTalkerGetCurrentCaptureDeviceIndex(uint8_t localTalker); + virtual bool LocalTalkerEnable(uint8_t localTalker, bool enable); + virtual bool LocalTalkerThreshold(uint8_t localTalker, float threshold); + virtual bool LocalTalkerEnableVoiceLevelCallback(uint8_t localTalker, bool enable); + virtual bool LocalTalkerSelectSession(uint8_t localTalker, uint64_t session); + virtual bool LocalTalkerSetSessionPriority(uint8_t localTalker, uint64_t session, uint8_t priority); + virtual bool LocalTalkerSetRemoteTalkerVolume(uint8_t localTalker, uint64_t talker, float volume); + virtual bool LocalTalkerSetSessionVolume(uint8_t localTalker, uint64_t session, float volume); + virtual bool MuteTalker(uint8_t localTalker, uint64_t talker, MuteSetting setting); + virtual bool IsTalkerMuted(uint8_t localTalker, uint64_t talker); + virtual bool MuteSession(uint8_t localTalker, uint64_t session, MuteSetting setting); + virtual bool IsSessionMuted(uint8_t localTalker, uint64_t session); + virtual bool IsTalkerTalkingInSession(uint64_t session, uint8_t localTalker, uint64_t talker); + virtual bool DoesTalkerHaveHeadset(uint64_t talker); + virtual bool DoesLocalPlayerHaveHeadset(uint8_t localTalker); + virtual void DebugSetSequenceDelay(int32_t delay); + virtual void DebugSetSoundOutputDelay(uint8_t localTalker, int32_t delay); + virtual void MicrophoneStatusUpdate(uint8_t player, Sound::HeadsetDeviceStatus status); + virtual void LocalChatDataReady(uint8_t player, uint8_t* data, uint32_t size, uint32_t time); + virtual void RemotePlayerTalkNotifyStart(uint8_t player, uint64_t talker, uint64_t session); + virtual void RemotePlayerTalkNotifyStop(uint8_t player, uint64_t talker, uint64_t session); + virtual void LocalTalkerVoiceLevel(uint8_t player, float level, bool talking); + virtual void DeviceError(uint8_t player); + virtual void IncomingVoiceData(uint64_t session, uint64_t talker, const uint8_t* data, uint32_t size); + + Manager(Sound::Manager& soundManager, Network::Manager& networkManager, const Initialization& init, Allocator& allocator); + Session* FindSession(uint64_t id); + uint8_t GetLocalTalkerIndex(uint64_t talker); + bool PackBitpackedVariableBitrateData(uint8_t player, uint8_t* buffer, int32_t& size); + bool PackStableBitrateData(uint8_t player, uint8_t* buffer, int32_t& size); + bool PackVariableBitrateData(uint8_t player, uint8_t* buffer, int32_t& size); + void SendVoiceDataToCurrentSession(uint8_t player); + bool UnpackBitpackedVariableBitrateData(uint64_t session, uint64_t talker, const uint8_t* data, uint32_t size); + bool UnpackStableBitrateData(uint64_t session, uint64_t talker, const uint8_t* data, uint32_t size); + bool UnpackVariableBitrateData(uint64_t session, uint64_t talker, const uint8_t* data, uint32_t size); +}; + +} + +#endif diff --git a/Engine/Source/ComSat/ComSatMap.h b/Engine/Source/ComSat/ComSatMap.h new file mode 100644 index 0000000..5f8d61f --- /dev/null +++ b/Engine/Source/ComSat/ComSatMap.h @@ -0,0 +1,287 @@ +#ifndef ENGINE_SOURCE_COMSAT_COMSATMAP_H +#define ENGINE_SOURCE_COMSAT_COMSATMAP_H + +#include +#include +#include +#include +#include "Engine/Source/ComSat/ComSatHash.h" +#include "Engine/Source/ComSat/ComSatInterface.h" + +namespace ComSat { + +template +class MapKey { + public: + /* 0000 */ uint32_t m_hash; + /* 0004 */ T m_value; + + MapKey(); + MapKey(const T& value); + ~MapKey(); + bool operator==(const MapKey& other) const; +}; + +template +class Map { + public: + class Entry { + public: + /* 0000 */ MapKey m_key; + /* 0004 */ V m_value; + + Entry(); + Entry(const MapKey& key); + Entry(const MapKey& key, const V& value); + }; + + /* 0000 */ Entry* m_entries; + /* 0004 */ uint32_t m_used; + /* 0008 */ uint32_t m_capacity; + /* 000C */ Allocator* m_allocator; + + Map(Allocator& allocator); + ~Map(); + void Clear(); + bool Find(const MapKey& key, uint32_t& index) const; + bool Get(const MapKey& key, V& value) const; + bool Insert(const MapKey& key, const V& value); + bool Next(uint32_t& iterator, MapKey& key, V& value) const; + uint32_t Reinsert(const Entry* entries, uint32_t count); + bool Remove(const MapKey& key, V& value); + void Resize(uint32_t capacity); + bool Shrink(); + V& operator[](const MapKey& key); +}; + +} + +// INLINED +template +ComSat::MapKey::MapKey() { + this->m_hash = 0; +} + +// VERIFY: d000525b auto +// OFFSET: [0x008814B0] +template +ComSat::MapKey::MapKey(const T& value) { + this->m_hash = ComSat::Hash32(&value, sizeof(T), 0x811C9DC5) | 0x80000000; + this->m_value = value; +} + +// INLINED +template +ComSat::MapKey::~MapKey() { + if (this->m_hash) { + this->m_hash = 0; + } +} + +// INLINED +template +bool ComSat::MapKey::operator==(const ComSat::MapKey& other) const { + return this->m_hash == other.m_hash && this->m_value == other.m_value; +} + +// INLINED +template +ComSat::Map::Entry::Entry() { +} + +// INLINED +template +ComSat::Map::Entry::Entry(const ComSat::MapKey& key) : m_key(key) { +} + +// INLINED +template +ComSat::Map::Entry::Entry(const ComSat::MapKey& key, const V& value) : m_key(key), m_value(value) { +} + +// INLINED +template +ComSat::Map::Map(ComSat::Allocator& allocator) { + this->m_entries = nullptr; + this->m_used = 0; + this->m_capacity = 0; + this->m_allocator = &allocator; +} + +// INLINED +template +ComSat::Map::~Map() { + this->Clear(); +} + +// VERIFY: 9fa4466f auto +// OFFSET: [0x00881600, 0x00881660] +template +void ComSat::Map::Clear() { + for (uint32_t i = 0; i < this->m_capacity; i++) { + this->m_entries[i].~Entry(); + } + this->m_used = 0; + if (this->m_entries) { + this->m_allocator->Free(this->m_entries); + this->m_entries = nullptr; + this->m_capacity = 0; + } +} + +// VERIFY: 1b43d470 auto +// OFFSET: [0x008816C0, 0x00886C10] +template +bool ComSat::Map::Find(const ComSat::MapKey& key, uint32_t& index) const { + if (!this->m_capacity) { + return false; + } + uint32_t start = key.m_hash & (this->m_capacity - 1); + index = start; + if (!this->m_entries[start].m_key.m_hash) { + return false; + } + do { + if (this->m_entries[index].m_key == key) { + return true; + } + index++; + index &= this->m_capacity - 1; + } while (index != start && this->m_entries[index].m_key.m_hash); + return false; +} + +// VERIFY: 60c1870c manual +// OFFSET: [0x00881950, 0x00881990, 0x008819D0] +template +bool ComSat::Map::Get(const ComSat::MapKey& key, V& value) const { + uint32_t index; + if (!this->Find(key, index)) { + return false; + } + value = this->m_entries[index].m_value; + return true; +} + +// VERIFY: 4e1ca7d3 auto +// OFFSET: [0x008835E0, 0x00886F80] +template +bool ComSat::Map::Insert(const ComSat::MapKey& key, const V& value) { + if (this->m_used >= (3 * this->m_capacity) >> 2) { + this->Resize(std::max(this->m_capacity * 2, 8u)); + } + uint32_t index; + if (this->Find(key, index)) { + return false; + } + this->m_used++; + new (&this->m_entries[index]) Entry(key, value); + return true; +} + +// VERIFY: d2f62888 auto +// OFFSET: [0x00881520, 0x00881590, 0x00886BB0] +template +bool ComSat::Map::Next(uint32_t& iterator, ComSat::MapKey& key, V& value) const { + if (iterator >= this->m_capacity) { + return false; + } + while (!this->m_entries[iterator].m_key.m_hash) { + if (++iterator >= this->m_capacity) { + return false; + } + } + key = this->m_entries[iterator].m_key; + value = this->m_entries[iterator].m_value; + iterator++; + return true; +} + +// VERIFY: add4d98c manual +// OFFSET: [0x00881750, 0x008817D0, 0x00881850, 0x008818D0] +template +uint32_t ComSat::Map::Reinsert(const Entry* entries, uint32_t count) { + uint32_t inserted = 0; + for (uint32_t i = 0; i < count; i++) { + if (entries->m_key.m_hash) { + uint32_t index; + this->Find(entries->m_key, index); + new (&this->m_entries[index]) Entry(*entries); + inserted++; + } + entries++; + } + return inserted; +} + +// VERIFY: 3e245a8e auto +// OFFSET: [0x00883680, 0x00883770, 0x00883860, 0x00887010] +template +bool ComSat::Map::Remove(const ComSat::MapKey& key, V& value) { + uint32_t index; + if (!this->Find(key, index)) { + return false; + } + value = this->m_entries[index].m_value; + this->m_entries[index].m_key.m_hash = 0; + this->m_used--; + if (!this->Shrink()) { + for (uint32_t i = (index + 1) & (this->m_capacity - 1); this->m_entries[i].m_key.m_hash; i = (this->m_capacity - 1) & (i + 1)) { + Entry* entry = &this->m_entries[i]; + uint32_t slot; + if (!this->Find(entry->m_key, slot)) { + new (&this->m_entries[slot]) Entry(*entry); + this->m_entries[i].m_key.m_hash = 0; + } + } + } + return true; +} + +// VERIFY: 9ecb3dce manual +// OFFSET: [0x00881A10, 0x00881AA0, 0x00881B30, 0x00881BC0] +template +void ComSat::Map::Resize(uint32_t capacity) { + uint32_t oldCapacity = this->m_capacity; + Entry* oldEntries = this->m_entries; + this->m_entries = static_cast(this->m_allocator->Alloc(sizeof(Entry) * capacity)); + this->m_capacity = capacity; + for (uint32_t i = 0; i < capacity; i++) { + new (&this->m_entries[i]) Entry(); + } + if (oldEntries) { + this->Reinsert(oldEntries, oldCapacity); + for (uint32_t i = 0; i < oldCapacity; i++) { + oldEntries[i].~Entry(); + } + this->m_allocator->Free(oldEntries); + } +} + +// VERIFY: 13f7ee3c auto +// OFFSET: [0x00882BA0, 0x00882BF0, 0x00882C40, 0x00882C90] +template +bool ComSat::Map::Shrink() { + if (this->m_used >= (3 * this->m_capacity) >> 3 || this->m_capacity <= 8) { + return false; + } + this->Resize(std::max(this->m_capacity >> 1, 8u)); + return true; +} + +// VERIFY: 632dc38d auto +// OFFSET: [0x008834C0, 0x00883550] +template +V& ComSat::Map::operator[](const ComSat::MapKey& key) { + if (this->m_used >= (3 * this->m_capacity) >> 2) { + this->Resize(std::max(this->m_capacity * 2, 8u)); + } + uint32_t index; + if (!this->Find(key, index)) { + this->m_used++; + new (&this->m_entries[index]) Entry(key); + } + return this->m_entries[index].m_value; +} + +#endif diff --git a/Engine/Source/ComSat/ComSatNetwork.h b/Engine/Source/ComSat/ComSatNetwork.h new file mode 100644 index 0000000..93b40fb --- /dev/null +++ b/Engine/Source/ComSat/ComSatNetwork.h @@ -0,0 +1,143 @@ +#ifndef ENGINE_SOURCE_COMSAT_COMSATNETWORK_H +#define ENGINE_SOURCE_COMSAT_COMSATNETWORK_H + +#include +#include +#include "Engine/Source/ComSat/ComSatInterface.h" +#include "Engine/Source/ComSat/ComSatMD5.h" +#include "Engine/Source/ComSat/ComSatVector.h" + +namespace ComSat { +namespace Network { + +class Address { + public: + /* 0000 */ int32_t m_length; + /* 0004 */ uint16_t m_family; + /* 0006 */ uint16_t m_port; + /* 0008 */ uint32_t m_ip; + /* 000C */ uint8_t m_zero[8]; + /* 0014 */ uint8_t unk_0014[12]; + + Address(); + int32_t GetPort() const; + bool operator==(const Address& other) const; + void SetAddress(const char* address); + void SetPort(int32_t port); +}; + +class Socket { + public: + static Socket* Create(Allocator& allocator); + + virtual ~Socket(); + virtual bool Bind(int32_t port) = 0; + virtual int32_t SendTo(const Address& address, const uint8_t* data, uint32_t size) = 0; + virtual bool RecvFrom(Address& address, uint8_t* data, uint32_t& size) = 0; +}; + +class SocketPosix : public Socket { + public: + /* 0004 */ uintptr_t m_socket; + + virtual ~SocketPosix(); + virtual bool Bind(int32_t port); + virtual int32_t SendTo(const Address& address, const uint8_t* data, uint32_t size); + virtual bool RecvFrom(Address& address, uint8_t* data, uint32_t& size); + + SocketPosix(); +}; + +struct Endpoint { + /* 0000 */ Address m_address; + /* 0020 */ uint8_t m_key[16]; + /* 0030 */ uint32_t m_refCount; +}; + +#pragma pack(push, 1) +struct Packet { + /* 0000 */ uint32_t m_signature; + /* 0004 */ uint8_t m_talker; + /* 0005 */ uint16_t m_networkId; + /* 0007 */ uint8_t m_data[1017]; +}; +#pragma pack(pop) + +class HMAC { + public: + /* 0000 */ MD5 m_inner; + /* 0058 */ uint8_t m_innerPad[64]; + /* 0098 */ uint8_t m_outerPad[64]; + + void Init(const uint8_t* key, uint32_t length); +}; + +class Manager; + +class Session { + public: + class Callback { + public: + virtual ~Callback(); + virtual void Recv(uint64_t talker, const uint8_t* data, uint32_t size) = 0; + }; + + struct LocalTalker { + /* 0000 */ uint64_t m_talker; + /* 0008 */ uint8_t m_networkId; + + bool operator==(const LocalTalker& other) const; + }; + + struct RemoteTalker { + /* 0000 */ uint64_t m_talker; + /* 0008 */ uint8_t m_networkId; + /* 000C */ Endpoint* m_endpoint; + + bool operator==(const RemoteTalker& other) const; + }; + + /* 0000 */ Manager* m_manager; + /* 0008 */ uint64_t m_id; + /* 0010 */ uint16_t m_networkId; + /* 0014 */ Callback* m_callback; + /* 0018 */ uint32_t m_lastSendTime; + /* 001C */ Vector m_localTalkers; + /* 002C */ Vector m_endpoints; + /* 003C */ Vector m_remoteTalkers; + + Session(Manager& manager, uint64_t id, Callback& callback); + ~Session(); + bool Add(uint64_t talker, uint8_t networkId, const uint8_t (&key)[16], const Address& address); + bool LocalAdd(uint64_t talker); + void Recv(uint64_t talker, const uint8_t* data, uint32_t size); + bool Remove(uint64_t talker); + bool Resolve(uint8_t networkId, const Address& address, uint64_t& talker, const uint8_t (*&key)[16]); + bool Send(uint64_t talker, const uint8_t* data, uint32_t size); + void SetNetworkId(uint16_t networkId); + void SetTalkerNetworkIdLocal(uint64_t talker, uint8_t networkId); + void SetTalkerNetworkIdRemote(uint64_t talker, uint8_t networkId); + void Work(); +}; + +class Manager { + public: + /* 0000 */ Allocator* m_allocator; + /* 0004 */ Vector m_sessions; + /* 0014 */ Socket* m_socket; + /* 0018 */ uint32_t m_time; + + Manager(const Initialization& init, Allocator& allocator); + ~Manager(); + Session* CreateSession(uint64_t id, Session::Callback& callback); + void DestroySession(Session* session); + bool Send(uint16_t networkId, uint8_t talker, const uint8_t (&key)[16], const Address& address, const uint8_t* data, uint32_t size); + void Work(uint32_t time); +}; + +uint32_t ComputeSignature(const uint8_t (&key)[16], const uint8_t* data, uint32_t size); + +} +} + +#endif diff --git a/Engine/Source/ComSat/ComSatNetworkAddress.cpp b/Engine/Source/ComSat/ComSatNetworkAddress.cpp new file mode 100644 index 0000000..d1e819b --- /dev/null +++ b/Engine/Source/ComSat/ComSatNetworkAddress.cpp @@ -0,0 +1,19 @@ +#include "Engine/Source/ComSat/ComSatNetwork.h" +#include + +// VERIFY: 86ec6037 auto +// OFFSET: 0x00885CB0 +ComSat::Network::Address::Address() { + this->m_length = 16; + this->m_family = 0; + this->m_port = 0; + this->m_ip = 0; + memset(this->m_zero, 0, sizeof(this->m_zero)); + this->m_family = 2; +} + +// VERIFY: 62366b28 auto +// OFFSET: 0x00885C70 +bool ComSat::Network::Address::operator==(const ComSat::Network::Address& other) const { + return this->m_length == other.m_length && this->m_family == other.m_family && this->m_port == other.m_port && this->m_ip == other.m_ip; +} diff --git a/Engine/Source/ComSat/ComSatNetworkManager.cpp b/Engine/Source/ComSat/ComSatNetworkManager.cpp new file mode 100644 index 0000000..afea3e9 --- /dev/null +++ b/Engine/Source/ComSat/ComSatNetworkManager.cpp @@ -0,0 +1,125 @@ +#include "Engine/Source/ComSat/ComSatNetwork.h" +#include "Engine/Source/ComSat/ComSatAllocator.h" +#include +#include + +// VERIFY: 4e6c6ef0 manual +// OFFSET: 0x008851D0 +void ComSat::Network::HMAC::Init(const uint8_t* key, uint32_t length) { + memset(this->m_innerPad, 0x36, sizeof(this->m_innerPad)); + memset(this->m_outerPad, 0x5C, sizeof(this->m_outerPad)); + for (uint32_t i = 0; i < length; i++) { + this->m_innerPad[i] ^= key[i]; + this->m_outerPad[i] ^= key[i]; + } + this->m_inner.Prepare(); + this->m_inner.Process(this->m_innerPad, sizeof(this->m_innerPad)); +} + +// VERIFY: 1eaea78a auto +// OFFSET: 0x008852E0 +uint32_t ComSat::Network::ComputeSignature(const uint8_t (&key)[16], const uint8_t* data, uint32_t size) { + HMAC hmac; + uint8_t innerDigest[16]; + MD5 outer; + uint32_t digest[4]; + + hmac.Init(key, sizeof(key)); + hmac.m_inner.Process(data + 4, size - 4); + hmac.m_inner.Finish(innerDigest); + outer.Prepare(); + outer.Process(hmac.m_outerPad, sizeof(hmac.m_outerPad)); + outer.Process(innerDigest, sizeof(innerDigest)); + outer.Finish(reinterpret_cast(digest)); + return digest[3] ^ digest[2] ^ digest[1] ^ digest[0]; +} + +// VERIFY: f663e4d8 auto +// OFFSET: 0x008853D0 +ComSat::Network::Manager::Manager(const ComSat::Initialization& init, ComSat::Allocator& allocator) : m_allocator(&allocator), m_sessions(allocator) { + this->m_socket = ComSat::Network::Socket::Create(allocator); + this->m_socket->Bind(init.m_port); +} + +// VERIFY: bab26ca7 manual +// OFFSET: 0x00885620 +ComSat::Network::Manager::~Manager() { + if (this->m_socket) { + ComSat::Delete(*this->m_allocator, this->m_socket); + this->m_socket = nullptr; + } + while (this->m_sessions.Count()) { + ComSat::Network::Session* session = this->m_sessions[0]; + this->m_sessions.Remove(session); + ComSat::Delete(*this->m_allocator, session); + } +} + +// VERIFY: 0d1cf108 auto +// OFFSET: 0x00885410 +void ComSat::Network::Manager::Work(uint32_t time) { + ComSat::Network::Address from; + ComSat::Network::Packet packet; + uint32_t size; + + this->m_time = time; + size = sizeof(packet); + int32_t remaining = 10; + if (this->m_socket->RecvFrom(from, reinterpret_cast(&packet), size)) { + while (remaining--) { + if (size > 7) { + uint16_t networkId = packet.m_networkId; + uint8_t talkerId = packet.m_talker; + uint64_t talker = 0; + const uint8_t (*key)[16] = nullptr; + for (uint32_t i = 0; i < this->m_sessions.Count(); i++) { + ComSat::Network::Session* session = this->m_sessions[i]; + if (session->m_networkId == networkId && session->Resolve(talkerId, from, talker, key)) { + session = this->m_sessions[i]; + if (session && ComSat::Network::ComputeSignature(*key, reinterpret_cast(&packet), size) == packet.m_signature) { + session->Recv(talker, packet.m_data, size - 7); + } + break; + } + } + } + if (!this->m_socket->RecvFrom(from, reinterpret_cast(&packet), size)) { + break; + } + } + } + for (uint32_t i = 0; i < this->m_sessions.Count(); i++) { + this->m_sessions[i]->Work(); + } +} + +// VERIFY: 2076d25f auto +// OFFSET: 0x00885560 +void ComSat::Network::Manager::DestroySession(ComSat::Network::Session* session) { + this->m_sessions.Remove(session); + ComSat::Delete(*this->m_allocator, session); +} + +// VERIFY: ddf7f762 manual +// OFFSET: 0x00885590 +bool ComSat::Network::Manager::Send(uint16_t networkId, uint8_t talker, const uint8_t (&key)[16], const ComSat::Network::Address& address, const uint8_t* data, uint32_t size) { + ComSat::Network::Packet packet; + uint32_t length = size + 7; + if (length > sizeof(packet)) { + return false; + } + packet.m_talker = talker; + packet.m_networkId = networkId; + memcpy(packet.m_data, data, length - 7); + packet.m_signature = ComSat::Network::ComputeSignature(key, reinterpret_cast(&packet), length); + this->m_socket->SendTo(address, reinterpret_cast(&packet), length); + return true; +} + +// VERIFY: f240b463 manual +// OFFSET: 0x008856D0 +ComSat::Network::Session* ComSat::Network::Manager::CreateSession(uint64_t id, ComSat::Network::Session::Callback& callback) { + ComSat::Network::Session* session = new (this->m_allocator->Alloc(sizeof(ComSat::Network::Session))) ComSat::Network::Session(*this, id, callback); + this->m_sessions.PushBack(session); + return session; +} diff --git a/Engine/Source/ComSat/ComSatNetworkSession.cpp b/Engine/Source/ComSat/ComSatNetworkSession.cpp new file mode 100644 index 0000000..b170c03 --- /dev/null +++ b/Engine/Source/ComSat/ComSatNetworkSession.cpp @@ -0,0 +1,201 @@ +#include "Engine/Source/ComSat/ComSatNetwork.h" +#include "Engine/Source/ComSat/ComSatAllocator.h" +#include +#include + +// INLINED +bool ComSat::Network::Session::LocalTalker::operator==(const ComSat::Network::Session::LocalTalker& other) const { + return this->m_talker == other.m_talker; +} + +// INLINED +bool ComSat::Network::Session::RemoteTalker::operator==(const ComSat::Network::Session::RemoteTalker& other) const { + return this->m_talker == other.m_talker; +} + +// VERIFY: 5934156a auto +// OFFSET: 0x00885D70 +void ComSat::Network::Session::SetNetworkId(uint16_t networkId) { + if (this->m_networkId != networkId) { + this->m_networkId = networkId; + } +} + +// VERIFY: b8190494 auto +// OFFSET: 0x00885D90 +void ComSat::Network::Session::Recv(uint64_t talker, const uint8_t* data, uint32_t size) { + this->m_callback->Recv(talker, data, size); +} + +// VERIFY: 1281d185 auto +// OFFSET: 0x00885E80 +void ComSat::Network::Session::SetTalkerNetworkIdLocal(uint64_t talker, uint8_t networkId) { + LocalTalker key; + key.m_talker = talker; + key.m_networkId = networkId; + uint32_t index = 0; + if (this->m_localTalkers.Find(key, index)) { + this->m_localTalkers[index].m_networkId = networkId; + } +} + +// VERIFY: 3c6357f0 auto +// OFFSET: 0x00885ED0 +void ComSat::Network::Session::SetTalkerNetworkIdRemote(uint64_t talker, uint8_t networkId) { + RemoteTalker key; + key.m_talker = talker; + key.m_networkId = networkId; + key.m_endpoint = nullptr; + uint32_t index = 0; + if (this->m_remoteTalkers.Find(key, index)) { + this->m_remoteTalkers[index].m_networkId = networkId; + } +} + +// VERIFY: 58a3362f manual +// OFFSET: 0x00885F20 +bool ComSat::Network::Session::Send(uint64_t talker, const uint8_t* data, uint32_t size) { + uint8_t networkId = 0; + uint32_t i = 0; + uint32_t count = this->m_localTalkers.Count(); + if (count) { + for (; i < count; i++) { + if (this->m_localTalkers[i].m_talker == talker) { + networkId = this->m_localTalkers[i].m_networkId; + break; + } + } + } + if (i == count) { + return false; + } + for (uint32_t j = 0; j < this->m_endpoints.Count(); j++) { + ComSat::Network::Endpoint* endpoint = this->m_endpoints[j]; + this->m_manager->Send(this->m_networkId, networkId, endpoint->m_key, endpoint->m_address, data, size); + } + this->m_lastSendTime = this->m_manager->m_time; + return true; +} + +// VERIFY: e3cf28b9 auto +// OFFSET: 0x00885FC0 +void ComSat::Network::Session::Work() { + if (this->m_localTalkers.Count() && static_cast(this->m_manager->m_time - this->m_lastSendTime) > 10000) { + uint8_t networkId = this->m_localTalkers[0].m_networkId; + for (uint32_t i = 0; i < this->m_endpoints.Count(); i++) { + ComSat::Network::Endpoint* endpoint = this->m_endpoints[i]; + this->m_manager->Send(this->m_networkId, networkId, endpoint->m_key, endpoint->m_address, nullptr, 0); + } + this->m_lastSendTime = this->m_manager->m_time; + } +} + +// VERIFY: 22e4bf9c manual +// OFFSET: 0x00886030 +bool ComSat::Network::Session::Resolve(uint8_t networkId, const ComSat::Network::Address& address, uint64_t& talker, const uint8_t (*&key)[16]) { + for (uint32_t i = 0; i < this->m_remoteTalkers.Count(); i++) { + RemoteTalker& remote = this->m_remoteTalkers[i]; + if (remote.m_networkId == networkId && remote.m_endpoint->m_address == address) { + talker = this->m_remoteTalkers[i].m_talker; + key = &this->m_remoteTalkers[i].m_endpoint->m_key; + return true; + } + } + return false; +} + +// VERIFY: a894f8f5 auto +// OFFSET: 0x00886110 +ComSat::Network::Session::Session(ComSat::Network::Manager& manager, uint64_t id, ComSat::Network::Session::Callback& callback) : m_localTalkers(*manager.m_allocator), m_endpoints(*manager.m_allocator), m_remoteTalkers(*manager.m_allocator) { + this->m_id = id; + this->m_manager = &manager; + this->m_networkId = 0; + this->m_lastSendTime = 0; + this->m_callback = &callback; +} + +// VERIFY: 64b74af2 manual +// OFFSET: 0x00886170 +ComSat::Network::Session::~Session() { + while (this->m_endpoints.Count()) { + ComSat::Network::Endpoint* endpoint = this->m_endpoints[0]; + this->m_endpoints.Remove(endpoint); + this->m_manager->m_allocator->Free(endpoint); + } +} + +// VERIFY: 924481df manual +// OFFSET: 0x00886230 +bool ComSat::Network::Session::Remove(uint64_t talker) { + RemoteTalker key; + key.m_talker = talker; + key.m_networkId = 0; + key.m_endpoint = nullptr; + uint32_t index = 0; + if (this->m_remoteTalkers.Find(key, index)) { + ComSat::Network::Endpoint* endpoint = this->m_remoteTalkers[index].m_endpoint; + if (endpoint->m_refCount-- == 1) { + this->m_endpoints.Remove(endpoint); + this->m_manager->m_allocator->Free(endpoint); + } + this->m_remoteTalkers.RemoveAt(index); + return true; + } + LocalTalker local; + local.m_talker = talker; + local.m_networkId = 0; + return this->m_localTalkers.Remove(local); +} + +// VERIFY: 3e4d527c manual +// OFFSET: 0x00886300 +bool ComSat::Network::Session::LocalAdd(uint64_t talker) { + LocalTalker key; + key.m_talker = talker; + key.m_networkId = 0; + uint32_t index; + if (this->m_localTalkers.Find(key, index)) { + return false; + } + this->m_localTalkers.PushBack(key); + return true; +} + +// VERIFY: 124a5ef6 manual +// OFFSET: 0x00886380 +bool ComSat::Network::Session::Add(uint64_t talker, uint8_t networkId, const uint8_t (&key)[16], const ComSat::Network::Address& address) { + RemoteTalker remote; + remote.m_talker = talker; + remote.m_networkId = networkId; + remote.m_endpoint = nullptr; + uint32_t index; + if (this->m_remoteTalkers.Find(remote, index)) { + ComSat::Network::Endpoint* existing = this->m_remoteTalkers[index].m_endpoint; + memcpy(&existing->m_address, &address, sizeof(existing->m_address)); + memcpy(existing->m_key, key, sizeof(existing->m_key)); + this->m_remoteTalkers[index].m_networkId = networkId; + return true; + } + ComSat::Network::Endpoint* endpoint = nullptr; + for (uint32_t i = 0; i < this->m_endpoints.Count(); i++) { + if (this->m_endpoints[i]->m_address == address && !memcmp(this->m_endpoints[i]->m_key, key, sizeof(key))) { + endpoint = this->m_endpoints[i]; + break; + } + } + if (!endpoint) { + endpoint = new (this->m_manager->m_allocator->Alloc(sizeof(ComSat::Network::Endpoint))) ComSat::Network::Endpoint; + memcpy(&endpoint->m_address, &address, sizeof(endpoint->m_address)); + memcpy(endpoint->m_key, key, sizeof(endpoint->m_key)); + endpoint->m_refCount = 0; + this->m_endpoints.PushBack(endpoint); + for (uint32_t i = 0; i < this->m_localTalkers.Count(); i++) { + this->m_manager->Send(this->m_networkId, this->m_localTalkers[i].m_networkId, key, address, nullptr, 0); + } + } + endpoint->m_refCount++; + remote.m_networkId = networkId; + remote.m_endpoint = endpoint; + this->m_remoteTalkers.PushBack(remote); + return true; +} diff --git a/Engine/Source/ComSat/ComSatNetworkSocket.cpp b/Engine/Source/ComSat/ComSatNetworkSocket.cpp new file mode 100644 index 0000000..5e9cfab --- /dev/null +++ b/Engine/Source/ComSat/ComSatNetworkSocket.cpp @@ -0,0 +1,13 @@ +#include "Engine/Source/ComSat/ComSatNetwork.h" +#include + +// VERIFY: 63d037b6 manual +// OFFSET: 0x00888780 +ComSat::Network::Socket::~Socket() { +} + +// VERIFY: 4679db72 manual +// OFFSET: 0x00888980 +ComSat::Network::Socket* ComSat::Network::Socket::Create(ComSat::Allocator& allocator) { + return new (allocator.Alloc(sizeof(ComSat::Network::SocketPosix))) ComSat::Network::SocketPosix(); +} diff --git a/Engine/Source/ComSat/ComSatRunningAverageCalculator.cpp b/Engine/Source/ComSat/ComSatRunningAverageCalculator.cpp new file mode 100644 index 0000000..4169b45 --- /dev/null +++ b/Engine/Source/ComSat/ComSatRunningAverageCalculator.cpp @@ -0,0 +1,57 @@ +#include "Engine/Source/ComSat/ComSatRunningAverageCalculator.h" + +// VERIFY: 08159cc8 auto +// OFFSET: 0x00886600 +ComSat::RunningAverageCalculator::RunningAverageCalculator(ComSat::Allocator& allocator) { + this->m_sum = 0.0; + this->m_allocator = &allocator; + this->m_values = nullptr; + this->m_count = 0; + this->m_index = 0; +} + +// VERIFY: 94225611 auto +// OFFSET: 0x00886750 +ComSat::RunningAverageCalculator::~RunningAverageCalculator() { + if (this->m_values) { + this->m_allocator->Free(this->m_values); + this->m_values = nullptr; + } + this->m_count = 0; + this->m_sum = 0.0; + this->m_index = 0; +} + +// VERIFY: fac249da manual +// OFFSET: 0x00886630 +void ComSat::RunningAverageCalculator::Init(double value, uint32_t count) { + if (this->m_values) { + this->m_allocator->Free(this->m_values); + this->m_values = nullptr; + } + this->m_sum = 0.0; + this->m_count = 0; + this->m_index = 0; + this->m_values = static_cast(this->m_allocator->Alloc(sizeof(double) * count)); + this->m_count = count; + for (uint32_t i = 0; i < count; i++) { + this->m_values[i] = value; + this->m_sum += value; + } +} + +// VERIFY: daa1cb75 auto +// OFFSET: 0x008866F0 +void ComSat::RunningAverageCalculator::SubmitData(double value) { + if (this->m_values) { + this->m_sum = this->m_sum - this->m_values[this->m_index] + value; + this->m_values[this->m_index] = value; + this->m_index = (this->m_index + 1) % this->m_count; + } +} + +// VERIFY: e888bf5d auto +// OFFSET: 0x00886730 +double ComSat::RunningAverageCalculator::GetCurrentAverage() { + return this->m_sum / this->m_count; +} diff --git a/Engine/Source/ComSat/ComSatRunningAverageCalculator.h b/Engine/Source/ComSat/ComSatRunningAverageCalculator.h new file mode 100644 index 0000000..9b25410 --- /dev/null +++ b/Engine/Source/ComSat/ComSatRunningAverageCalculator.h @@ -0,0 +1,28 @@ +#ifndef ENGINE_SOURCE_COMSAT_COMSATRUNNINGAVERAGECALCULATOR_H +#define ENGINE_SOURCE_COMSAT_COMSATRUNNINGAVERAGECALCULATOR_H + +#include +#include +#include "Engine/Source/ComSat/ComSatInterface.h" + +namespace ComSat { + +class RunningAverageCalculator { + public: + /* 0008 */ Allocator* m_allocator; + /* 000C */ double* m_values; + /* 0010 */ uint32_t m_count; + /* 0014 */ uint32_t m_index; + /* 0018 */ double m_sum; + + virtual ~RunningAverageCalculator(); + + RunningAverageCalculator(Allocator& allocator); + double GetCurrentAverage(); + void Init(double value, uint32_t count); + void SubmitData(double value); +}; + +} + +#endif diff --git a/Engine/Source/ComSat/ComSatSession.cpp b/Engine/Source/ComSat/ComSatSession.cpp new file mode 100644 index 0000000..d8344b4 --- /dev/null +++ b/Engine/Source/ComSat/ComSatSession.cpp @@ -0,0 +1,70 @@ +#include "Engine/Source/ComSat/ComSatSession.h" + +// VERIFY: 0de96b64 auto +// OFFSET: 0x0087F960 +ComSat::SessionCallback::~SessionCallback() { +} + +// INLINED +ComSat::Network::Session::Callback::~Callback() { +} + +// VERIFY: dd0145f9 auto +// OFFSET: 0x00885AD0 +void ComSat::Session::SetNetworkSession(ComSat::Network::Session* session) { + this->m_networkSession = session; +} + +// VERIFY: 7100e0e3 auto +// OFFSET: 0x00885AE0 +ComSat::Network::Session* ComSat::Session::GetNetworkSession() { + return this->m_networkSession; +} + +// VERIFY: 9e7e52b0 auto +// OFFSET: 0x00885AF0 +bool ComSat::Session::LocalAdd(uint64_t talker) { + return this->m_networkSession && this->m_networkSession->LocalAdd(talker); +} + +// VERIFY: 944f9c23 auto +// OFFSET: 0x00885B20 +bool ComSat::Session::Add(uint64_t talker, uint8_t networkId, const uint8_t (&key)[16], const ComSat::Network::Address& address) { + return this->m_networkSession && this->m_networkSession->Add(talker, networkId, key, address); +} + +// VERIFY: b8411e51 auto +// OFFSET: 0x00885B60 +void ComSat::Session::Remove(uint64_t talker) { + if (this->m_networkSession) { + this->m_networkSession->Remove(talker); + } +} + +// VERIFY: 6f4715dd auto +// OFFSET: 0x00885B80 +bool ComSat::Session::Send(uint64_t talker, const uint8_t* data, uint32_t size) { + return this->m_networkSession && this->m_networkSession->Send(talker, data, size); +} + +// VERIFY: 8429dcf3 auto +// OFFSET: 0x00885BC0 +void ComSat::Session::Recv(uint64_t talker, const uint8_t* data, uint32_t size) { + if (data && size) { + this->m_callback->IncomingVoiceData(this->m_id, talker, data, size); + } +} + +// VERIFY: dedccfab auto +// OFFSET: 0x00885C00 +ComSat::Session::Session(ComSat::SessionCallback& callback, uint64_t id, ComSat::Allocator& allocator) { + this->m_callback = &callback; + this->m_id = id; + this->m_networkSession = nullptr; + this->m_allocator = &allocator; +} + +// VERIFY: 0eb3a7af manual +// OFFSET: 0x00885C30 +ComSat::Session::~Session() { +} diff --git a/Engine/Source/ComSat/ComSatSession.h b/Engine/Source/ComSat/ComSatSession.h new file mode 100644 index 0000000..28e3473 --- /dev/null +++ b/Engine/Source/ComSat/ComSatSession.h @@ -0,0 +1,38 @@ +#ifndef ENGINE_SOURCE_COMSAT_COMSATSESSION_H +#define ENGINE_SOURCE_COMSAT_COMSATSESSION_H + +#include +#include +#include "Engine/Source/ComSat/ComSatInterface.h" +#include "Engine/Source/ComSat/ComSatNetwork.h" + +namespace ComSat { + +class SessionCallback { + public: + virtual ~SessionCallback(); + virtual void IncomingVoiceData(uint64_t session, uint64_t talker, const uint8_t* data, uint32_t size) = 0; +}; + +class Session : public Network::Session::Callback { + public: + /* 0004 */ SessionCallback* m_callback; + /* 0008 */ Network::Session* m_networkSession; + /* 0010 */ uint64_t m_id; + /* 0018 */ Allocator* m_allocator; + + virtual ~Session(); + virtual void Recv(uint64_t talker, const uint8_t* data, uint32_t size); + + Session(SessionCallback& callback, uint64_t id, Allocator& allocator); + bool Add(uint64_t talker, uint8_t networkId, const uint8_t (&key)[16], const Network::Address& address); + Network::Session* GetNetworkSession(); + bool LocalAdd(uint64_t talker); + void Remove(uint64_t talker); + bool Send(uint64_t talker, const uint8_t* data, uint32_t size); + void SetNetworkSession(Network::Session* session); +}; + +} + +#endif diff --git a/Engine/Source/ComSat/ComSatSoundCODEC.cpp b/Engine/Source/ComSat/ComSatSoundCODEC.cpp new file mode 100644 index 0000000..cd1dedb --- /dev/null +++ b/Engine/Source/ComSat/ComSatSoundCODEC.cpp @@ -0,0 +1,322 @@ +#include "Engine/Source/ComSat/ComSatSoundCODEC.h" +#include "Engine/Source/ComSat/ComSatAllocator.h" +#include "Engine/Source/ComSat/ComSatSoundLevelCalculator.h" +#include "Engine/Source/ComSat/ComSatSpirit.h" +#include +#include + +// STATIC: 0x00A503A0 +const uint8_t ComSat::Sound::CODECIPMR6000::s_invalidPlayer = 0xFF; + +// STATIC: 0x00A503A4 +const int32_t ComSat::Sound::CODECIPMR6000::s_maxFramesPerPacket = 20; + +// STATIC: 0x00A503A8 +const int32_t ComSat::Sound::CODECIPMR6000::s_sampleRate = 8000; + +// STATIC: 0x00A503AC +const int32_t ComSat::Sound::CODECIPMR6000::s_bitsPerSample = 16; + +// STATIC: 0x00A503B0 +const int32_t ComSat::Sound::CODECIPMR6000::s_samplesPerFrame = 800; + +// STATIC: 0x00A503B4 +const int32_t ComSat::Sound::CODECIPMR6000::s_minEncodedFrameLength = 360; + +// STATIC: 0x00A503B8 +const int32_t ComSat::Sound::CODECIPMR6000::s_maxEncodedFrameLength = 960; + +// STATIC: 0x00A503BC +const uint32_t ComSat::Sound::CODECIPMR6000::s_bytesPerFrame = 1600; + +// VERIFY: 27be376e manual +// OFFSET: 0x008867E0 +ComSat::Sound::CODECIPMR6000::LocalPlayer::LocalPlayer(ComSat::Allocator& allocator, int32_t channelCount, uint8_t* tables) { + this->m_threshold = 0.5f; + this->m_tables = tables; + this->m_allocator = &allocator; + this->m_channelCount = channelCount; + this->m_hangover = 0; + this->m_decoders = static_cast(allocator.Alloc(sizeof(uint8_t*) * channelCount)); + if (this->m_decoders) { + for (int32_t i = 0; i < channelCount; i++) { + this->m_decoders[i] = static_cast(this->m_allocator->Alloc(sizeof(this->m_encoder))); + if (this->m_decoders[i] && SPIRIT_IP_MR_V3_1_Init(this->m_decoders[i], this->m_tables)) { + this->m_allocator->Free(this->m_decoders[i]); + this->m_decoders[i] = nullptr; + } + } + } + SPIRIT_IP_MR_V3_1_Init(this->m_encoder, this->m_tables); +} + +// VERIFY: b5a425c3 auto +// OFFSET: [0x008868C0, 0x00886BA0] +ComSat::Sound::CODECIPMR6000::LocalPlayer::~LocalPlayer() { + if (this->m_decoders) { + for (int32_t i = 0; i < this->m_channelCount; i++) { + this->m_allocator->Free(this->m_decoders[i]); + this->m_decoders[i] = nullptr; + } + this->m_allocator->Free(this->m_decoders); + this->m_decoders = nullptr; + } +} + +// VERIFY: 2b94f608 manual +// OFFSET: 0x00886930 +bool ComSat::Sound::CODECIPMR6000::LocalPlayer::CompressRawData(const uint8_t* pcm, uint32_t size, uint8_t* data, uint32_t* bits, bool* voice) { + uint8_t* encoder = this->m_encoder; + if (!encoder || size != 1600 || *bits < 960) { + return false; + } + if (this->m_hangover > 0) { + this->m_hangover--; + } + float level; + float decibels; + ComSat::Sound::LevelCalculator16Bit::CalculateLevelForFrame(pcm, 1600, level, decibels); + if (this->m_threshold <= decibels) { + this->m_hangover = 20; + } + if (this->m_hangover <= 0) { + *voice = false; + return true; + } + SPIRIT_IPMR_STREAM stream; + stream.m_data = data; + stream.m_bits = 0; + stream.m_size = *bits >> 3; + SPIRIT_IPMR_INFO info; + memset(&info, 0, sizeof(info)); + SPIRIT_IPMR_PARAMS params; + params.unk_0000 = 0; + params.unk_0004 = 0; + params.unk_0006 = 1; + int32_t result = 0; + for (int32_t i = 0; i < 5; i++) { + result = SPIRIT_IP_MR_V3_1_Encode(encoder, pcm, ¶ms, &stream, &info); + pcm += 320; + if (result) { + break; + } + } + *bits = stream.m_bits; + *voice = true; + return result == 0; +} + +// VERIFY: 9fa1eded manual +// OFFSET: 0x00886A50 +bool ComSat::Sound::CODECIPMR6000::LocalPlayer::DecompressEncodedData(int32_t channel, const uint8_t* data, uint32_t bits, uint8_t* pcm, uint32_t* size) { + if (bits > 960 || *size < 1600) { + return false; + } + if (channel < 0 || channel >= this->m_channelCount || !this->m_decoders || !this->m_decoders[channel]) { + return false; + } + uint32_t bytes = bits >> 3; + if (bits & 7) { + bytes++; + } + SPIRIT_IPMR_PARAMS params; + params.unk_0000 = 0; + params.unk_0004 = 0; + SPIRIT_IPMR_STREAM stream; + stream.m_bits = 0; + stream.m_size = bytes; + params.unk_0006 = 1; + stream.m_data = data; + int32_t result = 0; + while (bits - stream.m_bits >= 72) { + result = SPIRIT_IP_MR_V3_1_Decode(this->m_decoders[channel], pcm, ¶ms, &stream, nullptr); + pcm += 320; + if (result) { + break; + } + } + *size = 1600; + return result == 0; +} + +// VERIFY: 0560a550 auto +// OFFSET: [0x00886B30, 0x008889A0] +ComSat::Sound::CODEC::~CODEC() { +} + +// INLINED +ComSat::Sound::CODEC::CODEC(ComSat::Allocator& allocator) : m_allocator(&allocator) { +} + +// VERIFY: 151c084d auto +// OFFSET: 0x008A1420 +bool ComSat::Sound::CODEC::Init() { + return true; +} + +// VERIFY: dfe4af70 auto +// OFFSET: 0x008A1420 +bool ComSat::Sound::CODEC::Reset() { + return true; +} + +// VERIFY: c46dc152 auto +// OFFSET: 0x005EEB70 +void ComSat::Sound::CODEC::Shutdown() { +} + +// VERIFY: 0a45f794 auto +// OFFSET: 0x008A1420 +bool ComSat::Sound::CODEC::CanBitpackFrames() { + return true; +} + +// VERIFY: d247f3ba auto +// OFFSET: 0x008A1420 +bool ComSat::Sound::CODEC::IsEncodedBitrateVariable() { + return true; +} + +// VERIFY: e146742c auto +// OFFSET: 0x0095BFB0 +uint32_t ComSat::Sound::CODEC::MinimumSafeFramesBetweenResets() { + return 32; +} + +// VERIFY: 98756928 auto +// OFFSET: 0x00886B40 +bool ComSat::Sound::CODECIPMR6000::Init() { + if (this->m_initialized) { + this->Shutdown(); + } + if (SPIRIT_IP_MR_V3_1_GenerateTables(this->m_tables)) { + return false; + } + this->m_initialized = true; + return true; +} + +// VERIFY: d6cc4d79 auto +// OFFSET: 0x00886B70 +bool ComSat::Sound::CODECIPMR6000::Reset() { + return this->Init(); +} + +// VERIFY: 78c49031 auto +// OFFSET: 0x00886B80 +void ComSat::Sound::CODECIPMR6000::GenerateSilence(uint8_t* pcm, uint32_t size) { + memset(pcm, 0, size); +} + +// VERIFY: 5d9ec280 auto +// OFFSET: 0x00886CA0 +ComSat::Sound::CODEC* ComSat::Sound::CODEC::Create(const ComSat::Initialization& init, ComSat::Allocator& allocator) { + ComSat::Sound::CODEC* codec = new (allocator.Alloc(sizeof(ComSat::Sound::CODECIPMR6000))) ComSat::Sound::CODECIPMR6000(init, allocator); + codec->Init(); + return codec; +} + +// INLINED +ComSat::Sound::CODECIPMR6000::CODECIPMR6000(const ComSat::Initialization& init, ComSat::Allocator& allocator) : CODEC(allocator), m_players(allocator) { + this->m_maxChannels = init.m_maxChannels; + this->m_initialized = false; +} + +// VERIFY: 4be450a4 auto +// OFFSET: 0x00886D10 +void ComSat::Sound::CODECIPMR6000::ResetPlayerChannelDecoder(uint8_t player, int32_t channel) { + if (this->m_initialized) { + LocalPlayer* localPlayer; + if (this->m_players.Get(ComSat::MapKey(player), localPlayer) && localPlayer->m_decoders && channel >= 0 && channel < localPlayer->m_channelCount && localPlayer->m_decoders[channel]) { + SPIRIT_IP_MR_V3_1_Init(localPlayer->m_decoders[channel], localPlayer->m_tables); + } + } +} + +// VERIFY: cecb1a97 auto +// OFFSET: 0x00886DA0 +void ComSat::Sound::CODECIPMR6000::ResetPlayerChannelEncoder(uint8_t player) { + if (this->m_initialized) { + LocalPlayer* localPlayer; + if (this->m_players.Get(ComSat::MapKey(player), localPlayer)) { + SPIRIT_IP_MR_V3_1_Init(localPlayer->m_encoder, localPlayer->m_tables); + } + } +} + +// VERIFY: adcedc12 manual +// OFFSET: 0x00886E10 +bool ComSat::Sound::CODECIPMR6000::CompressRawData(uint8_t player, const uint8_t* pcm, uint32_t size, uint8_t* data, uint32_t* bits, bool* voice) { + LocalPlayer* localPlayer; + return this->m_initialized && this->m_players.Get(ComSat::MapKey(player), localPlayer) && localPlayer->CompressRawData(pcm, size, data, bits, voice); +} + +// VERIFY: 0fa6d60b manual +// OFFSET: 0x00886E90 +bool ComSat::Sound::CODECIPMR6000::DecompressEncodedData(uint8_t player, int32_t channel, const uint8_t* data, uint32_t bits, uint8_t* pcm, uint32_t* size) { + LocalPlayer* localPlayer; + return this->m_initialized && this->m_players.Get(ComSat::MapKey(player), localPlayer) && localPlayer->DecompressEncodedData(channel, data, bits, pcm, size); +} + +// VERIFY: e47f31e7 auto +// OFFSET: 0x00886F10 +void ComSat::Sound::CODECIPMR6000::SetThreshold(uint8_t player, float threshold) { + LocalPlayer* localPlayer; + if (this->m_players.Get(ComSat::MapKey(player), localPlayer)) { + localPlayer->m_threshold = ComSat::Sound::LevelCalculator16Bit::GetMaxDecibelLevel() * threshold; + } +} + +// VERIFY: 02adc07a manual +// OFFSET: 0x008870F0 +void ComSat::Sound::CODECIPMR6000::Shutdown() { + LocalPlayer* localPlayer = nullptr; + ComSat::MapKey key(s_invalidPlayer); + uint32_t iterator = 0; + while (this->m_players.Next(iterator, key, localPlayer)) { + LocalPlayer* removed; + this->m_players.Remove(key, removed); + ComSat::Delete(*this->m_allocator, localPlayer); + } + this->m_initialized = false; +} + +// VERIFY: b32780fd manual +// OFFSET: 0x008871A0 +bool ComSat::Sound::CODECIPMR6000::InitLocalPlayer(uint8_t player, float threshold) { + if (!this->m_initialized) { + return false; + } + uint32_t index; + if (this->m_players.Find(ComSat::MapKey(player), index)) { + return false; + } + LocalPlayer* localPlayer = new (this->m_allocator->Alloc(sizeof(LocalPlayer))) LocalPlayer(*this->m_allocator, this->m_maxChannels, this->m_tables); + localPlayer->m_threshold = ComSat::Sound::LevelCalculator16Bit::GetMaxDecibelLevel() * threshold; + this->m_players.Insert(ComSat::MapKey(player), localPlayer); + return true; +} + +// VERIFY: b9d5e115 auto +// OFFSET: 0x00887280 +bool ComSat::Sound::CODECIPMR6000::RemoveLocalPlayer(uint8_t player) { + if (!this->m_initialized) { + return false; + } + LocalPlayer* localPlayer = nullptr; + if (this->m_players.Remove(ComSat::MapKey(player), localPlayer)) { + ComSat::Delete(*this->m_allocator, localPlayer); + } + return true; +} + +// VERIFY: 8e319759 auto +// OFFSET: 0x00887300 +ComSat::Sound::CODECIPMR6000::~CODECIPMR6000() { + this->Shutdown(); +} + +// VERIFY: 9adda6e6 auto +// OFFSET: 0x0047ADD0 +void ComSat::Sound::CODECIPMR6000::ApplyVoiceEffects(uint8_t player, uint8_t* pcm, uint32_t* size) { +} diff --git a/Engine/Source/ComSat/ComSatSoundCODEC.h b/Engine/Source/ComSat/ComSatSoundCODEC.h new file mode 100644 index 0000000..7f07f35 --- /dev/null +++ b/Engine/Source/ComSat/ComSatSoundCODEC.h @@ -0,0 +1,91 @@ +#ifndef ENGINE_SOURCE_COMSAT_COMSATSOUNDCODEC_H +#define ENGINE_SOURCE_COMSAT_COMSATSOUNDCODEC_H + +#include +#include +#include "Engine/Source/ComSat/ComSatInterface.h" +#include "Engine/Source/ComSat/ComSatMap.h" + +namespace ComSat { +namespace Sound { + +class CODEC { + public: + static CODEC* Create(const Initialization& init, Allocator& allocator); + static bool CanBitpackFrames(); + static bool IsEncodedBitrateVariable(); + static uint32_t MinimumSafeFramesBetweenResets(); + + /* 0004 */ Allocator* m_allocator; + + virtual ~CODEC(); + virtual bool Init(); + virtual bool Reset(); + virtual void Shutdown(); + virtual bool InitLocalPlayer(uint8_t player, float threshold) = 0; + virtual bool RemoveLocalPlayer(uint8_t player) = 0; + virtual void ResetPlayerChannelEncoder(uint8_t player) = 0; + virtual void ResetPlayerChannelDecoder(uint8_t player, int32_t channel) = 0; + virtual bool CompressRawData(uint8_t player, const uint8_t* pcm, uint32_t size, uint8_t* data, uint32_t* bits, bool* voice) = 0; + virtual bool DecompressEncodedData(uint8_t player, int32_t channel, const uint8_t* data, uint32_t bits, uint8_t* pcm, uint32_t* size) = 0; + virtual void SetThreshold(uint8_t player, float threshold) = 0; + virtual void GenerateSilence(uint8_t* pcm, uint32_t size) = 0; + virtual void ApplyVoiceEffects(uint8_t player, uint8_t* pcm, uint32_t* size) = 0; + + CODEC(Allocator& allocator); +}; + +class CODECIPMR6000 : public CODEC { + public: + class LocalPlayer { + public: + /* 0004 */ Allocator* m_allocator; + /* 0008 */ int32_t m_channelCount; + /* 000C */ uint8_t m_encoder[13504]; + /* 34CC */ uint8_t** m_decoders; + /* 34D0 */ uint8_t* m_tables; + /* 34D4 */ int32_t m_hangover; + /* 34D8 */ float m_threshold; + + virtual ~LocalPlayer(); + + LocalPlayer(Allocator& allocator, int32_t channelCount, uint8_t* tables); + bool CompressRawData(const uint8_t* pcm, uint32_t size, uint8_t* data, uint32_t* bits, bool* voice); + bool DecompressEncodedData(int32_t channel, const uint8_t* data, uint32_t bits, uint8_t* pcm, uint32_t* size); + }; + + static const uint8_t s_invalidPlayer; + static const int32_t s_maxFramesPerPacket; + static const int32_t s_sampleRate; + static const int32_t s_bitsPerSample; + static const int32_t s_samplesPerFrame; + static const int32_t s_minEncodedFrameLength; + static const int32_t s_maxEncodedFrameLength; + static const uint32_t s_bytesPerFrame; + + /* 0008 */ bool m_initialized; + /* 000C */ uint32_t m_maxChannels; + /* 0010 */ uint8_t m_tables[48096]; + /* BBF0 */ Map m_players; + + virtual ~CODECIPMR6000(); + virtual bool Init(); + virtual bool Reset(); + virtual void Shutdown(); + virtual bool InitLocalPlayer(uint8_t player, float threshold); + virtual bool RemoveLocalPlayer(uint8_t player); + virtual void ResetPlayerChannelEncoder(uint8_t player); + virtual void ResetPlayerChannelDecoder(uint8_t player, int32_t channel); + virtual bool CompressRawData(uint8_t player, const uint8_t* pcm, uint32_t size, uint8_t* data, uint32_t* bits, bool* voice); + virtual bool DecompressEncodedData(uint8_t player, int32_t channel, const uint8_t* data, uint32_t bits, uint8_t* pcm, uint32_t* size); + virtual void SetThreshold(uint8_t player, float threshold); + virtual void GenerateSilence(uint8_t* pcm, uint32_t size); + virtual void ApplyVoiceEffects(uint8_t player, uint8_t* pcm, uint32_t* size); + + CODECIPMR6000(const Initialization& init, Allocator& allocator); +}; + +} +} + +#endif diff --git a/Engine/Source/ComSat/ComSatSoundIOSoundEngine.cpp b/Engine/Source/ComSat/ComSatSoundIOSoundEngine.cpp index 60b5f58..a05d57e 100644 --- a/Engine/Source/ComSat/ComSatSoundIOSoundEngine.cpp +++ b/Engine/Source/ComSat/ComSatSoundIOSoundEngine.cpp @@ -1 +1,276 @@ -#include "ComSatSoundIOSoundEngine.h" +#include "Engine/Source/ComSat/ComSatSoundIOSoundEngine.h" +#include "Engine/Source/ComSat/ComSatAllocator.h" +#include "Engine/Source/ConsoleBase/ConsoleVar.h" +#include "Engine/Source/Storm/H/storm.h" +#include "WoW/Source/Game/GameClient/ComSatClient.h" +#include +#include + +// VERIFY: ed1c5c8c manual +// OFFSET: 0x00635DD0 +ComSat::Sound::IOCallback::~IOCallback() { +} + +// VERIFY: 2b11346e manual +// OFFSET: 0x00887360 +ComSat::Sound::IO::~IO() { +} + +// VERIFY: f1d0cb09 manual +// OFFSET: 0x00887B10 +ComSat::Sound::IO* ComSat::Sound::IO::Create(const ComSat::Initialization& init, ComSat::Sound::IOCallback& callback, ComSat::Allocator& allocator) { + return new (allocator.Alloc(sizeof(ComSat::Sound::IOSoundEngine))) ComSat::Sound::IOSoundEngine(init, callback, allocator); +} + +// INLINED +ComSat::Sound::CaptureChannel::CaptureChannel(ComSat::Allocator& allocator) : m_allocator(&allocator) { +} + +// VERIFY: b21ec2d3 auto +// OFFSET: 0x008879F0 +ComSat::Sound::CaptureChannel::~CaptureChannel() { +} + +// VERIFY: 78652afa auto +// OFFSET: 0x00887810 +void ComSat::Sound::CaptureChannel::ProcessData(int16_t* data, uint32_t samples) { + SI2::VoiceChat_AmplifyMicrophoneInput(data, samples); + this->m_buffer.Write(data, samples); +} + +// INLINED +ComSat::Sound::OutputChannel::OutputChannel(ComSat::Allocator& allocator) : m_allocator(&allocator) { +} + +// VERIFY: 5311437b auto +// OFFSET: 0x00887DB0 +ComSat::Sound::OutputChannel::~OutputChannel() { +} + +// VERIFY: 471a153b manual +// OFFSET: 0x00887840 +bool ComSat::Sound::OutputChannel::GetSamples(uint32_t position, uint32_t count, float* buffer) { + return this->m_buffer.Read(buffer, count) != 0; +} + +// VERIFY: 7b6c81ad auto +// OFFSET: 0x00887B50 +void ComSat::Sound::OutputChannel::Delete() { + ComSat::Delete(*this->m_allocator, this); +} + +// VERIFY: fb0351ec manual +// OFFSET: 0x00887A10 +ComSat::Sound::IOSoundEngine::IOSoundEngine(const ComSat::Initialization& init, ComSat::Sound::IOCallback& callback, ComSat::Allocator& allocator) : m_allocator(&allocator), m_callback(&callback), m_captureChannel(allocator) { + this->m_outputDevice = 0; + this->m_captureDevice = 0; + this->m_channels.SetCount(init.m_maxChannels); + for (uint32_t i = 0; i < this->m_channels.Count(); i++) { + this->m_channels[i] = nullptr; + } +} + +// VERIFY: 9d711460 manual +// OFFSET: 0x00887AC0 +ComSat::Sound::IOSoundEngine::~IOSoundEngine() { + this->ShutDownCapture(); +} + +// VERIFY: eaf35b9b auto +// OFFSET: 0x008A1420 +bool ComSat::Sound::IOSoundEngine::Init() { + return true; +} + +// VERIFY: 5996f1c6 auto +// OFFSET: 0x00632050 +void ComSat::Sound::IOSoundEngine::Work(uint32_t time) { +} + +// VERIFY: 27bc5b3f auto +// OFFSET: 0x005EEB70 +void ComSat::Sound::IOSoundEngine::Shutdown() { +} + +// VERIFY: f9893773 auto +// OFFSET: 0x008873A0 +bool ComSat::Sound::IOSoundEngine::DestroyLocalPlayer(uint8_t player) { + return true; +} + +// VERIFY: 2afc43cd auto +// OFFSET: 0x008873B0 +int32_t ComSat::Sound::IOSoundEngine::GetInputBlockSize(uint8_t player) { + return this->m_samplesPerFrame * this->m_bitsPerSample / 8; +} + +// VERIFY: 67c3c3bb auto +// OFFSET: 0x008873B0 +int32_t ComSat::Sound::IOSoundEngine::GetPlaybackBlockSize(uint8_t player) { + return this->m_samplesPerFrame * this->m_bitsPerSample / 8; +} + +// VERIFY: 2149bcf9 auto +// OFFSET: 0x008873D0 +int32_t ComSat::Sound::IOSoundEngine::EnumerateOutputDevices(ComSat::DeviceInfo* devices, int32_t maxDevices) { + int32_t count = SI2::GetNumOutputDrivers(1); + if (maxDevices < count) { + count = maxDevices; + } + for (int32_t i = 0; i < count; i++) { + SI2::GetOutputDriverName(i, devices[i].m_name, sizeof(devices[i].m_name), 1); + } + return count; +} + +// VERIFY: 22e8394e auto +// OFFSET: 0x00887420 +int32_t ComSat::Sound::IOSoundEngine::EnumerateCaptureDevices(ComSat::DeviceInfo* devices, int32_t maxDevices) { + int32_t count = SI2::GetNumInputDrivers(1); + if (maxDevices < count) { + count = maxDevices; + } + for (int32_t i = 0; i < count; i++) { + SI2::GetInputDriverName(i, devices[i].m_name, sizeof(devices[i].m_name), 1); + } + return count; +} + +// VERIFY: 7235d738 auto +// OFFSET: 0x00887470 +int32_t ComSat::Sound::IOSoundEngine::LocalPlayerGetCurrentOutputDeviceIndex(uint8_t player) { + return this->m_outputDevice; +} + +// VERIFY: 53c51fa7 auto +// OFFSET: 0x00887480 +int32_t ComSat::Sound::IOSoundEngine::LocalPlayerGetCurrentCaptureDeviceIndex(uint8_t player) { + return this->m_captureDevice; +} + +// VERIFY: 2c2332ed auto +// OFFSET: 0x00887780 +void ComSat::Sound::IOSoundEngine::ShutDownCapture() { + for (uint32_t i = 0; i < this->m_channels.Count(); i++) { + if (this->m_channels[i]) { + SI2::StopSound(&this->m_channels[i]->m_object, 1, -1.0f, 1); + this->m_channels[i] = nullptr; + } + } + SI2::VoiceChat_CleanUpLoopbackSound(); + SI2::VoiceChat_ShutDownCapture(); +} + +// VERIFY: 157b0a60 auto +// OFFSET: 0x008877E0 +void ComSat::Sound::IOSoundEngine::SetPlayerPlaybackVolume(uint8_t player, int32_t channel, float volume) { + SI2::SetVolume(&this->m_channels[channel]->m_object, volume); +} + +// VERIFY: 4c066a98 manual +// OFFSET: 0x00887860 +bool ComSat::Sound::IOSoundEngine::PlayDataForPlayer(uint8_t player, int32_t channel, uint8_t* data, uint32_t size, double rate) { + double pitch = 0.9; + if (rate >= 0.9) { + pitch = rate; + if (rate >= 1.1) { + pitch = 1.1; + } + } + SI2::SetPitch(&this->m_channels[channel]->m_object, static_cast(pitch * this->m_sampleRate)); + uint32_t count = size >> 1; + float* samples = static_cast(alloca(sizeof(float) * count)); + const int16_t* pcm = reinterpret_cast(data); + for (uint32_t i = 0; i < count; i++) { + samples[i] = pcm[i] * (1.0f / 32768.0f); + } + this->m_channels[channel]->m_buffer.Write(samples, count); + return true; +} + +// VERIFY: ffd08db7 manual +// OFFSET: 0x00887980 +int32_t ComSat::Sound::IOSoundEngine::GetRemainingPlaybackBytes(uint8_t player, int32_t channel) { + return 2 * this->m_channels[channel]->m_buffer.Count(); +} + +// VERIFY: 11476088 auto +// OFFSET: 0x008879B0 +int32_t ComSat::Sound::IOSoundEngine::ReadDataForPlayer(uint8_t player, uint8_t* data, int32_t size) { + return 2 * this->m_captureChannel.m_buffer.Read(reinterpret_cast(data), static_cast(size) >> 1); +} + +// VERIFY: 84034483 auto +// OFFSET: 0x008879D0 +int32_t ComSat::Sound::IOSoundEngine::GetAvailableDataBytes(uint8_t player) { + return 2 * this->m_captureChannel.m_buffer.Count(); +} + +// VERIFY: 94733445 manual +// OFFSET: 0x00887B70 +void ComSat::Sound::IOSoundEngine::InitCapture() { + SI2::VoiceChat_InitCapture(this->m_sampleRate); + SI2::VoiceChat_SetPrimaryCaptureCallback(&this->m_captureChannel); + SI2::VoiceChat_ActivatePrimaryCaptureCallback(); + // STATIC: 0x00D439A0 + static CVar* s_enableMicrophone = CVar::Lookup("EnableMicrophone"); + // STATIC: 0x00D4399C + static CVar* s_enableVoiceChat = CVar::Lookup("EnableVoiceChat"); + if (s_enableVoiceChat && s_enableVoiceChat->m_intValue && s_enableMicrophone && s_enableMicrophone->m_intValue && !ComSatClient_IsComsatDisabledByClient()) { + SI2::VoiceChat_StartCapture(); + } + if (SI2::VoiceChat_IsVoiceChatInitialized()) { + for (uint32_t i = 0; i < this->m_channels.Count(); i++) { + this->m_channels[i] = new (this->m_allocator->Alloc(sizeof(ComSat::Sound::OutputChannel))) ComSat::Sound::OutputChannel(*this->m_allocator); + ComSat::Sound::OutputChannel* channel = this->m_channels[i]; + SI2::VoiceChat_CreateChatSound(&channel->m_object, channel, 1); + SI2SoundUserData* userData = new (SMemAlloc(sizeof(SI2SoundUserData), __FILE__, __LINE__, 0)) SI2SoundUserData(); + userData->m_name = ""; + userData->m_soundKitId = 0; + userData->m_def = nullptr; + userData->m_group = 3; + channel->m_object.m_sound.SetUserData(userData); + SI2::SetPitch(&channel->m_object, this->m_sampleRate); + SI2::VoiceChat_Play(&channel->m_object); + } + } +} + +// VERIFY: ed3c735f auto +// OFFSET: 0x00887D10 +bool ComSat::Sound::IOSoundEngine::InitLocalPlayer(uint8_t player, int32_t outputDevice, int32_t captureDevice, int32_t sampleRate, int32_t bitsPerSample, int32_t samplesPerFrame) { + this->m_outputDevice = outputDevice; + this->m_sampleRate = static_cast(sampleRate); + this->m_captureDevice = captureDevice; + this->m_bitsPerSample = bitsPerSample; + this->m_samplesPerFrame = samplesPerFrame; + this->InitCapture(); + return true; +} + +// VERIFY: e904d241 auto +// OFFSET: 0x00887D50 +bool ComSat::Sound::IOSoundEngine::LocalPlayerChangeOutputDevice(uint8_t player, int32_t device) { + this->ShutDownCapture(); + SI2::VoiceChat_DestroyChatSystem(); + this->m_outputDevice = device; + SI2::VoiceChat_SetOutputDevice(device); + this->InitCapture(); + return true; +} + +// VERIFY: dfe4484f auto +// OFFSET: 0x00887D80 +bool ComSat::Sound::IOSoundEngine::LocalPlayerChangeCaptureDevice(uint8_t player, int32_t device) { + this->ShutDownCapture(); + SI2::VoiceChat_DestroyChatSystem(); + this->m_captureDevice = device; + SI2::VoiceChat_SetCaptureDevice(device); + this->InitCapture(); + return true; +} + +// VERIFY: 0f8734c7 auto +// OFFSET: 0x00653A10 +void ComSat::Sound::IOSoundEngine::DebugSetSoundOutputDelay(uint8_t player, int32_t delay) { +} diff --git a/Engine/Source/ComSat/ComSatSoundIOSoundEngine.h b/Engine/Source/ComSat/ComSatSoundIOSoundEngine.h index bd9faa5..74799c3 100644 --- a/Engine/Source/ComSat/ComSatSoundIOSoundEngine.h +++ b/Engine/Source/ComSat/ComSatSoundIOSoundEngine.h @@ -3,50 +3,189 @@ #include #include - -namespace ComSat { -struct Manager { - /* 0000 */ uint8_t unk_0000 [8]; - /* 0008 */ int32_t unk_0008; - /* 000C */ int32_t unk_000C; - /* 0010 */ uint8_t unk_0010 [4]; - /* 0014 */ int32_t unk_0014; - /* 0018 */ uint8_t unk_0018 [4]; - /* 001C */ int32_t unk_001C; - /* 0020 */ int16_t unk_0020; - /* 0022 */ uint8_t unk_0022[2]; - /* 0024 */ int32_t unk_0024; - /* 0028 */ int32_t unk_0028; - /* 002C */ uint8_t unk_002C [4]; - /* 0030 */ int32_t unk_0030; - /* 0034 */ int32_t unk_0034; - /* 0038 */ int32_t unk_0038; - /* 003C */ uint8_t unk_003C [44]; - /* 0068 */ int32_t unk_0068; -}; -} - -namespace ComSat { -struct Session { - /* 0000 */ uint8_t unk_0000 [4]; - /* 0004 */ int32_t unk_0004; - /* 0008 */ uint8_t unk_0008 [8]; - /* 0010 */ int32_t unk_0010; - /* 0014 */ int32_t unk_0014; -}; -} +#include +#include "Engine/Source/ComSat/ComSatInterface.h" +#include "Engine/Source/SoundEngine/SoundEngine.h" +#include "Engine/Source/Storm/H/stpl.h" +#include "Engine/Source/Storm/Source/SLock.h" +#include "WoW/Source/SoundInterface/SoundInterface2.h" namespace ComSat { namespace Sound { -struct Manager { - /* 0004 */ uint8_t unk_0004 [8]; - /* 000C */ int32_t unk_000C; - /* 0010 */ uint8_t unk_0010 [8]; - /* 0018 */ int32_t unk_0018; - virtual ~Manager(); +class IOCallback { + public: + virtual ~IOCallback(); + virtual void DeviceError(uint8_t player) = 0; }; + +class IO { + public: + static IO* Create(const Initialization& init, IOCallback& callback, Allocator& allocator); + + virtual ~IO(); + virtual bool Init() = 0; + virtual void Work(uint32_t time) = 0; + virtual void Shutdown() = 0; + virtual bool InitLocalPlayer(uint8_t player, int32_t outputDevice, int32_t captureDevice, int32_t sampleRate, int32_t bitsPerSample, int32_t samplesPerFrame) = 0; + virtual bool DestroyLocalPlayer(uint8_t player) = 0; + virtual bool LocalPlayerChangeOutputDevice(uint8_t player, int32_t device) = 0; + virtual bool LocalPlayerChangeCaptureDevice(uint8_t player, int32_t device) = 0; + virtual int32_t LocalPlayerGetCurrentOutputDeviceIndex(uint8_t player) = 0; + virtual int32_t LocalPlayerGetCurrentCaptureDeviceIndex(uint8_t player) = 0; + virtual void SetPlayerPlaybackVolume(uint8_t player, int32_t channel, float volume) = 0; + virtual bool PlayDataForPlayer(uint8_t player, int32_t channel, uint8_t* data, uint32_t size, double rate) = 0; + virtual int32_t GetRemainingPlaybackBytes(uint8_t player, int32_t channel) = 0; + virtual int32_t GetInputBlockSize(uint8_t player) = 0; + virtual int32_t GetPlaybackBlockSize(uint8_t player) = 0; + virtual int32_t ReadDataForPlayer(uint8_t player, uint8_t* data, int32_t size) = 0; + virtual int32_t GetAvailableDataBytes(uint8_t player) = 0; + virtual int32_t EnumerateOutputDevices(DeviceInfo* devices, int32_t maxDevices) = 0; + virtual int32_t EnumerateCaptureDevices(DeviceInfo* devices, int32_t maxDevices) = 0; + virtual void DebugSetSoundOutputDelay(uint8_t player, int32_t delay) = 0; +}; + +template +class RingBuffer { + public: + /* 0000 */ int32_t m_position; + /* 0004 */ uint32_t m_count; + /* 0008 */ SCritSect m_lock; + /* 0030 */ T m_samples[0x4000]; + + RingBuffer(); + uint32_t Count(); + uint32_t Read(T* samples, uint32_t count); + bool Write(const T* samples, uint32_t count); +}; + +class CaptureChannel : public SECaptureCallbacks { + public: + /* 0004 */ Allocator* m_allocator; + /* 0008 */ RingBuffer m_buffer; + + virtual ~CaptureChannel(); + virtual void ProcessData(int16_t* data, uint32_t samples); + + CaptureChannel(Allocator& allocator); +}; + +class OutputChannel : public SEStreamCallbacks { + public: + /* 0004 */ Allocator* m_allocator; + /* 0008 */ SE2SoundKitObject m_object; + /* 001C */ RingBuffer m_buffer; + + virtual ~OutputChannel(); + virtual bool GetSamples(uint32_t position, uint32_t count, float* buffer); + virtual void Delete(); + + OutputChannel(Allocator& allocator); +}; + +class IOSoundEngine : public IO { + public: + /* 0004 */ Allocator* m_allocator; + /* 0008 */ IOCallback* m_callback; + /* 000C */ TSGrowableArray m_channels; + /* 001C */ CaptureChannel m_captureChannel; + /* 8054 */ int32_t m_outputDevice; + /* 8058 */ int32_t m_captureDevice; + /* 805C */ float m_sampleRate; + /* 8060 */ int32_t m_bitsPerSample; + /* 8064 */ int32_t m_samplesPerFrame; + + virtual ~IOSoundEngine(); + virtual bool Init(); + virtual void Work(uint32_t time); + virtual void Shutdown(); + virtual bool InitLocalPlayer(uint8_t player, int32_t outputDevice, int32_t captureDevice, int32_t sampleRate, int32_t bitsPerSample, int32_t samplesPerFrame); + virtual bool DestroyLocalPlayer(uint8_t player); + virtual bool LocalPlayerChangeOutputDevice(uint8_t player, int32_t device); + virtual bool LocalPlayerChangeCaptureDevice(uint8_t player, int32_t device); + virtual int32_t LocalPlayerGetCurrentOutputDeviceIndex(uint8_t player); + virtual int32_t LocalPlayerGetCurrentCaptureDeviceIndex(uint8_t player); + virtual void SetPlayerPlaybackVolume(uint8_t player, int32_t channel, float volume); + virtual bool PlayDataForPlayer(uint8_t player, int32_t channel, uint8_t* data, uint32_t size, double rate); + virtual int32_t GetRemainingPlaybackBytes(uint8_t player, int32_t channel); + virtual int32_t GetInputBlockSize(uint8_t player); + virtual int32_t GetPlaybackBlockSize(uint8_t player); + virtual int32_t ReadDataForPlayer(uint8_t player, uint8_t* data, int32_t size); + virtual int32_t GetAvailableDataBytes(uint8_t player); + virtual int32_t EnumerateOutputDevices(DeviceInfo* devices, int32_t maxDevices); + virtual int32_t EnumerateCaptureDevices(DeviceInfo* devices, int32_t maxDevices); + virtual void DebugSetSoundOutputDelay(uint8_t player, int32_t delay); + + IOSoundEngine(const Initialization& init, IOCallback& callback, Allocator& allocator); + void InitCapture(); + void ShutDownCapture(); +}; + } } +// INLINED +template +ComSat::Sound::RingBuffer::RingBuffer() : m_position(0), m_count(0) { +} + +// INLINED +template +uint32_t ComSat::Sound::RingBuffer::Count() { + this->m_lock.Enter(); + uint32_t count = this->m_count; + this->m_lock.Leave(); + return count; +} + +// VERIFY: 815eb058 manual +// OFFSET: [0x00887590, 0x008876F0] +template +uint32_t ComSat::Sound::RingBuffer::Read(T* samples, uint32_t count) { + uint32_t read = 0; + this->m_lock.Enter(); + if (this->m_count) { + int32_t position = this->m_position - this->m_count; + if (position < 0) { + position += 0x4000; + } + read = count; + if (count >= this->m_count) { + read = this->m_count; + } + this->m_count -= read; + for (uint32_t i = 0; i < read; i++) { + *samples = this->m_samples[position]; + position = (position + 1) & 0x3FFF; + samples++; + } + if (read < count) { + memset(samples, 0, sizeof(T) * (count - read)); + } + } + this->m_lock.Leave(); + return read; +} + +// VERIFY: a7947d25 auto +// OFFSET: [0x00887520, 0x00887680] +template +bool ComSat::Sound::RingBuffer::Write(const T* samples, uint32_t count) { + this->m_lock.Enter(); + if (count > 0x4000 - this->m_count) { + this->m_lock.Leave(); + return false; + } + this->m_count += count; + int32_t position = this->m_position; + for (; count; count--) { + this->m_samples[position] = *samples; + samples++; + position = (position + 1) & 0x3FFF; + } + this->m_position = position; + this->m_lock.Leave(); + return true; +} + #endif diff --git a/Engine/Source/ComSat/ComSatSoundLevelCalculator.cpp b/Engine/Source/ComSat/ComSatSoundLevelCalculator.cpp new file mode 100644 index 0000000..141eece --- /dev/null +++ b/Engine/Source/ComSat/ComSatSoundLevelCalculator.cpp @@ -0,0 +1,34 @@ +#include "Engine/Source/ComSat/ComSatSoundLevelCalculator.h" +#include + +// VERIFY: 8d8479ca auto +// OFFSET: 0x00887DE0 +void ComSat::Sound::LevelCalculator16Bit::CalculateLevelForFrame(const uint8_t* data, uint32_t size, float& level, float& decibels) { + level = 0.0f; + decibels = 0.0f; + const int16_t* samples = reinterpret_cast(data); + int32_t count = size >> 1; + int16_t maximum = -32768; + int16_t minimum = 32767; + if (count > 0) { + for (int32_t i = 0; i < count; i++) { + int16_t sample = samples[i]; + if (sample < minimum) { + minimum = sample; + } + if (sample > maximum) { + maximum = sample; + } + } + if (minimum <= maximum) { + level = static_cast(maximum - minimum) * (1.0f / 65536.0f); + decibels = log10f((static_cast(maximum) - minimum) * 0.002f) * 20.0f; + } + } +} + +// VERIFY: d71b6a92 auto +// OFFSET: 0x00887E80 +float ComSat::Sound::LevelCalculator16Bit::GetMaxDecibelLevel() { + return static_cast(log10(131.072) * 20.0f); +} diff --git a/Engine/Source/ComSat/ComSatSoundLevelCalculator.h b/Engine/Source/ComSat/ComSatSoundLevelCalculator.h new file mode 100644 index 0000000..fa09224 --- /dev/null +++ b/Engine/Source/ComSat/ComSatSoundLevelCalculator.h @@ -0,0 +1,19 @@ +#ifndef ENGINE_SOURCE_COMSAT_COMSATSOUNDLEVELCALCULATOR_H +#define ENGINE_SOURCE_COMSAT_COMSATSOUNDLEVELCALCULATOR_H + +#include +#include + +namespace ComSat { +namespace Sound { + +class LevelCalculator16Bit { + public: + static void CalculateLevelForFrame(const uint8_t* data, uint32_t size, float& level, float& decibels); + static float GetMaxDecibelLevel(); +}; + +} +} + +#endif diff --git a/Engine/Source/ComSat/ComSatSoundManager.cpp b/Engine/Source/ComSat/ComSatSoundManager.cpp new file mode 100644 index 0000000..32556b1 --- /dev/null +++ b/Engine/Source/ComSat/ComSatSoundManager.cpp @@ -0,0 +1,1178 @@ +#include "Engine/Source/ComSat/ComSatSoundManager.h" +#include "Engine/Source/ComSat/ComSatAllocator.h" +#include "Engine/Source/ComSat/ComSatSoundLevelCalculator.h" +#include "Engine/Source/Os/Processor.h" +#include +#include +#include +#include + +// STATIC: 0x00D43990 +static uint32_t s_lastEncodeTime; + +// STATIC: 0x00D43994 +static int32_t s_jitterBufferSize = (ComSat::Sound::CODECIPMR6000::s_sampleRate * ComSat::Sound::CODECIPMR6000::s_bitsPerSample / 8) / ComSat::Sound::CODECIPMR6000::s_bytesPerFrame; + +// STATIC: 0x00D43998 +static int32_t s_frameTimeWindow = (ComSat::Sound::CODECIPMR6000::s_sampleRate * ComSat::Sound::CODECIPMR6000::s_bitsPerSample / 8 * 2) / ComSat::Sound::CODECIPMR6000::s_bytesPerFrame; + +// VERIFY: 83e2f3a6 auto +// OFFSET: 0x0087F930 +ComSat::Sound::Manager::Callback::~Callback() { +} + +// VERIFY: 58ec21e6 auto +// OFFSET: 0x00881260 +ComSat::Sound::Manager::RemoteTalker::RemoteTalker(ComSat::Allocator& allocator) : m_allocator(&allocator), m_packets(nullptr), m_frameTime(allocator) { + this->m_packets = static_cast(allocator.Alloc(sizeof(VoicePacket) * s_jitterBufferSize)); +} + +// VERIFY: 68ac5962 auto +// OFFSET: 0x008812B0 +void ComSat::Sound::Manager::SetCallback(ComSat::Sound::Manager::Callback* callback) { + this->m_callback = callback; +} + +// VERIFY: 95032179 auto +// OFFSET: 0x008812C0 +bool ComSat::Sound::Manager::LocalTalkerChangeOutputDevice(uint8_t player, int32_t device) { + if (this->m_io) { + return this->m_io->LocalPlayerChangeOutputDevice(player, device); + } + return false; +} + +// VERIFY: f7e4bc4b auto +// OFFSET: 0x008812E0 +bool ComSat::Sound::Manager::LocalTalkerChangeCaptureDevice(uint8_t player, int32_t device) { + if (this->m_io) { + return this->m_io->LocalPlayerChangeCaptureDevice(player, device); + } + return false; +} + +// VERIFY: eab244f7 manual +// OFFSET: 0x00881300 +int32_t ComSat::Sound::Manager::LocalTalkerGetCurrentOutputDeviceIndex(uint8_t player) { + if (this->m_io) { + return this->m_io->LocalPlayerGetCurrentOutputDeviceIndex(player); + } + return -1; +} + +// VERIFY: dbc4fd0b manual +// OFFSET: 0x00881320 +int32_t ComSat::Sound::Manager::LocalTalkerGetCurrentCaptureDeviceIndex(uint8_t player) { + if (this->m_io) { + return this->m_io->LocalPlayerGetCurrentCaptureDeviceIndex(player); + } + return -1; +} + +// VERIFY: 6af853ca manual +// OFFSET: 0x00881340 +bool ComSat::Sound::Manager::LocalTalkerThreshold(uint8_t player, float threshold) { + if (!this->m_codec) { + return false; + } + this->m_codec->SetThreshold(player, threshold); + return true; +} + +// VERIFY: 7e70ce48 auto +// OFFSET: 0x00881370 +bool ComSat::Sound::Manager::CanBitpackEncodedData() { + return ComSat::Sound::CODEC::CanBitpackFrames(); +} + +// VERIFY: 996b2e46 auto +// OFFSET: 0x00881370 +bool ComSat::Sound::Manager::IsUsingVariableBitrateCodec() { + return ComSat::Sound::CODEC::IsEncodedBitrateVariable(); +} + +// VERIFY: 5b24b547 auto +// OFFSET: 0x00881380 +int32_t ComSat::Sound::Manager::GetMinEncodedFrameLength() { + return ComSat::Sound::CODECIPMR6000::s_minEncodedFrameLength; +} + +// VERIFY: b74c7db0 auto +// OFFSET: 0x00881390 +int32_t ComSat::Sound::Manager::GetMaxEncodedFrameLength() { + return ComSat::Sound::CODECIPMR6000::s_maxEncodedFrameLength; +} + +// VERIFY: 7308e0a0 auto +// OFFSET: 0x00437720 +bool ComSat::Sound::Manager::IsRemoteTalkerTalkingInSession(uint64_t session, uint8_t player, uint64_t talker) { + return false; +} + +// VERIFY: 2049629b auto +// OFFSET: 0x008813A0 +bool ComSat::Sound::Manager::IsLocalPlayerTalking(uint8_t player) { + return false; +} + +// VERIFY: c4f9bc66 manual +// OFFSET: 0x008813B0 +int32_t ComSat::Sound::Manager::EnumerateOutputDevices(ComSat::DeviceInfo* devices, int32_t maxDevices) { + if (!this->m_io) { + return 0; + } + return this->m_io->EnumerateOutputDevices(devices, maxDevices); +} + +// VERIFY: e5b0261b manual +// OFFSET: 0x008813D0 +int32_t ComSat::Sound::Manager::EnumerateCaptureDevices(ComSat::DeviceInfo* devices, int32_t maxDevices) { + if (!this->m_io) { + return 0; + } + return this->m_io->EnumerateCaptureDevices(devices, maxDevices); +} + +// VERIFY: cf900560 manual +// OFFSET: 0x008813F0 +void ComSat::Sound::Manager::AdvancePlayCursorForRemoteTalker(ComSat::Sound::Manager::RemoteTalker* talker) { + int32_t cursor = static_cast(talker->m_playCursor); + talker->m_playCursor += ComSat::Sound::CODECIPMR6000::s_samplesPerFrame * 1000.0f / ComSat::Sound::CODECIPMR6000::s_sampleRate / talker->m_frameTime.GetCurrentAverage(); + int32_t end = static_cast(talker->m_playCursor) % s_jitterBufferSize; + talker->m_playCursor = fmod(talker->m_playCursor, static_cast(s_jitterBufferSize)); + for (; cursor != end; cursor = (cursor + 1) % s_jitterBufferSize) { + talker->m_packets[cursor].m_valid = false; + } +} + +// VERIFY: ced4a441 auto +// OFFSET: 0x00881480 +void ComSat::Sound::Manager::DebugSetSequenceDelay(int32_t delay) { + this->m_sequenceDelay = this->m_jitterDelay + delay; +} + +// VERIFY: de383fb8 manual +// OFFSET: 0x00881490 +void ComSat::Sound::Manager::DebugSetSoundOutputDelay(uint8_t player, int32_t delay) { + if (this->m_io) { + this->m_io->DebugSetSoundOutputDelay(player, delay); + } +} + +// VERIFY: 7e52a2ba auto +// OFFSET: 0x008814F0 +ComSat::Sound::Manager::RemoteTalker::~RemoteTalker() { + this->m_allocator->Free(this->m_packets); +} + +// VERIFY: b4173bb3 auto +// OFFSET: 0x00881C50 +ComSat::Sound::Manager::LocalPlayer::~LocalPlayer() { +} + +// VERIFY: 73854b3e auto +// OFFSET: 0x00881CA0 +ComSat::Sound::Manager::LocalPlayer::LocalPlayer(ComSat::Allocator& allocator) : m_sessionPriorities(allocator), m_mutedSessions(allocator), m_mutedTalkers(allocator), m_talkerVolumes(allocator), m_sessionVolumes(allocator) { +} + +// INLINED +ComSat::Sound::Manager::Session::Session(ComSat::Allocator& allocator) : m_id(0), m_talkerPriorities(allocator) { +} + +// VERIFY: 4458ca17 manual +// OFFSET: 0x00881CF0 +ComSat::Sound::Manager::Manager(const ComSat::Initialization& init, ComSat::Allocator& allocator) : m_localPlayers(allocator), m_sessions(allocator), m_remoteTalkers(allocator) { + this->m_maxLocalPlayers = init.m_maxLocalPlayers; + this->m_allocator = &allocator; + this->m_callback = nullptr; + this->m_codec = nullptr; + this->m_io = ComSat::Sound::IO::Create(init, *this, allocator); + this->m_jitterDelay = 5; + this->m_sequenceDelay = 5; + this->m_maxChannels = init.m_maxChannels; + this->m_currentFrame = 0; + this->m_startTime = init.m_time; + this->m_currentTime = init.m_time; + if (OsGetProcessorFeatures() & 4) { + this->m_codec = ComSat::Sound::CODEC::Create(init, allocator); + int32_t bytesPerSecond = ComSat::Sound::CODECIPMR6000::s_sampleRate * ComSat::Sound::CODECIPMR6000::s_bitsPerSample / 8; + this->m_framesPerSecond = static_cast(bytesPerSecond) / ComSat::Sound::CODECIPMR6000::s_bytesPerFrame; + this->m_holdFrames = static_cast(ceil(this->m_framesPerSecond * 500.0f * 0.001f)); + this->m_frameDuration = ComSat::Sound::CODECIPMR6000::s_samplesPerFrame * 1000.0f / ComSat::Sound::CODECIPMR6000::s_sampleRate; + this->m_jitterDelay = static_cast(this->m_framesPerSecond * 0.1f); + if (!this->m_jitterDelay) { + this->m_jitterDelay = 1; + } + this->m_sequenceDelay = 2 * this->m_jitterDelay; + } +} + +// VERIFY: 2e83be4f manual +// OFFSET: 0x00881E20 +bool ComSat::Sound::Manager::LocalTalkerEnable(uint8_t player, bool enable) { + LocalPlayer* localPlayer; + if (!this->m_localPlayers.Get(ComSat::MapKey(player), localPlayer)) { + return false; + } + if (!enable && localPlayer->m_enabled && this->m_callback) { + this->m_callback->LocalChatDataReady(player, nullptr, 0, 0); + } + localPlayer->m_enabled = enable; + return true; +} + +// VERIFY: ed8ef859 auto +// OFFSET: 0x00881EC0 +bool ComSat::Sound::Manager::LocalTalkerEnableVoiceLevelCallback(uint8_t player, bool enable) { + LocalPlayer* localPlayer; + if (!this->m_localPlayers.Get(ComSat::MapKey(player), localPlayer)) { + return false; + } + localPlayer->m_voiceLevelCallback = enable; + return true; +} + +// VERIFY: c25f698a manual +// OFFSET: 0x00881F30 +int32_t ComSat::Sound::Manager::SessionNumMembers(uint64_t session) { + Session* info; + if (!this->m_sessions.Get(ComSat::MapKey(session), info)) { + return -1; + } + int32_t count = info->m_talkerPriorities.m_used; + uint32_t iterator = 0; + ComSat::MapKey key; + LocalPlayer* localPlayer; + while (this->m_localPlayers.Next(iterator, key, localPlayer)) { + uint32_t index; + if (localPlayer->m_sessionPriorities.Find(ComSat::MapKey(session), index)) { + count++; + } + } + return count; +} + +// VERIFY: b51edc25 manual +// OFFSET: 0x00882030 +bool ComSat::Sound::Manager::SessionGetTalkerByIndex(uint64_t session, int32_t index, uint64_t& talker, uint8_t& player) { + if (index >= this->SessionNumMembers(session)) { + return false; + } + int32_t count = 0; + LocalPlayer* localPlayer = nullptr; + uint32_t iterator = 0; + ComSat::MapKey playerKey; + while (this->m_localPlayers.Next(iterator, playerKey, localPlayer)) { + uint32_t found; + if (localPlayer->m_sessionPriorities.Find(ComSat::MapKey(session), found)) { + if (index == count) { + talker = 0; + player = playerKey.m_value; + return true; + } + count++; + } + } + player = 0xFF; + iterator = 0; + Session* info; + if (!this->m_sessions.Get(ComSat::MapKey(session), info)) { + return false; + } + ComSat::MapKey talkerKey; + uint8_t priority; + if (info->m_talkerPriorities.Next(iterator, talkerKey, priority)) { + while (count < index) { + count++; + if (!info->m_talkerPriorities.Next(iterator, talkerKey, priority)) { + break; + } + } + } + if (count != index) { + return false; + } + talker = talkerKey.m_value; + return true; +} + +// VERIFY: 8f19331f manual +// OFFSET: 0x008821C0 +void ComSat::Sound::Manager::RecenterJitterBufferForRemoteTalker(uint64_t talker, int32_t offset) { + RemoteTalker* remote; + if (!this->m_remoteTalkers.Get(ComSat::MapKey(talker), remote)) { + return; + } + VoicePacket* packets = static_cast(this->m_allocator->Alloc(sizeof(VoicePacket) * s_jitterBufferSize)); + memcpy(packets, remote->m_packets, sizeof(VoicePacket) * s_jitterBufferSize); + for (int32_t i = 0; i < s_jitterBufferSize; i++) { + remote->m_packets[i].m_valid = false; + } + int32_t cursor = static_cast(remote->m_playCursor); + for (int32_t i = 0; i < s_jitterBufferSize; i++) { + if (!packets[i].m_valid) { + continue; + } + int32_t slot = (offset + i) % s_jitterBufferSize; + if (slot < 0) { + slot += s_jitterBufferSize; + } + int32_t delay = this->m_jitterDelay; + int32_t remaining = s_jitterBufferSize - cursor; + if (slot < cursor) { + if (remaining >= delay) { + memcpy(&remote->m_packets[slot], &packets[i], sizeof(VoicePacket)); + continue; + } + delay -= s_jitterBufferSize; + } else if (remaining < delay) { + continue; + } + if (slot >= cursor + delay) { + memcpy(&remote->m_packets[slot], &packets[i], sizeof(VoicePacket)); + } + } + this->m_allocator->Free(packets); +} + +// VERIFY: 6b28c289 auto +// OFFSET: 0x00882330 +void ComSat::Sound::Manager::SubmitIncomingFrameTimeData(uint64_t talker, uint16_t sequence) { + RemoteTalker* remote; + if (!this->m_remoteTalkers.Get(ComSat::MapKey(talker), remote)) { + return; + } + uint32_t lastTime = remote->m_lastPacketTime; + if (lastTime && lastTime != this->m_currentTime) { + double elapsed = static_cast(this->m_currentTime) - lastTime; + uint16_t lastSequence = remote->m_lastSequence; + int32_t frames = sequence - lastSequence; + if (frames < 0) { + frames += 0x10000; + } + if (frames > 0 && lastSequence) { + if (frames > s_frameTimeWindow) { + frames = s_frameTimeWindow; + } + if (frames > 0) { + double frameTime = elapsed / frames; + for (int32_t i = frames; i; i--) { + remote->m_frameTime.SubmitData(frameTime); + } + } + } + remote->m_lastSequence = sequence; + } + remote->m_lastPacketTime = this->m_currentTime; +} + +// VERIFY: 35250d18 manual +// OFFSET: 0x00882440 +void ComSat::Sound::Manager::SubmitIncomingVoicePacket(uint64_t session, uint64_t talker, uint8_t* data, uint32_t size, bool reliable) { + if (size > static_cast(ComSat::Sound::CODECIPMR6000::s_maxEncodedFrameLength + 4)) { + return; + } + RemoteTalker* remote; + if (!this->m_remoteTalkers.Get(ComSat::MapKey(talker), remote)) { + return; + } + VoicePacket* packets = remote->m_packets; + VoicePacket* packet = reinterpret_cast(data); + int32_t cursor = static_cast(remote->m_playCursor); + int32_t slot = cursor; + int32_t skipped = 0; + int32_t target; + while (!packets[slot].m_valid) { + slot = (slot + 1) % s_jitterBufferSize; + skipped++; + if (slot == cursor) { + target = (cursor + this->m_sequenceDelay) % s_jitterBufferSize; + remote->m_recenterTime = this->m_currentTime; + goto store; + } + } + target = cursor + skipped + (packet->m_sequence - packets[slot].m_sequence); + if (this->m_currentTime != remote->m_recenterTime && !reliable) { + remote->m_recenterTime = this->m_currentTime; + int32_t expected = cursor + this->m_sequenceDelay; + if (abs(target - expected) > 2) { + int32_t delta = expected - target; + target = expected; + this->RecenterJitterBufferForRemoteTalker(talker, delta); + } + } +store: + int32_t index = (target < 0 ? 0 : target) % s_jitterBufferSize; + memcpy(&remote->m_packets[index], data, size); + remote->m_packets[index].m_valid = true; + remote->m_packets[index].m_session = session; +} + +// VERIFY: ff2f231b manual +// OFFSET: 0x008825D0 +uint32_t ComSat::Sound::Manager::CalculateTotalVoicePriorityForRemoteTalkerInSessionForLocalPlayer(uint8_t player, uint64_t talker, uint64_t session) { + LocalPlayer* localPlayer; + if (!this->m_localPlayers.Get(ComSat::MapKey(player), localPlayer)) { + return 0; + } + uint32_t index; + if (localPlayer->m_mutedSessions.Find(session, index)) { + return 0; + } + if (localPlayer->m_mutedTalkers.Find(talker, index)) { + return 0; + } + uint8_t sessionPriority = 0; + if (!localPlayer->m_sessionPriorities.Get(ComSat::MapKey(session), sessionPriority)) { + return 0; + } + Session* info; + if (sessionPriority && this->m_sessions.Get(ComSat::MapKey(session), info)) { + uint8_t talkerPriority = 0; + if (info->m_talkerPriorities.Get(ComSat::MapKey(talker), talkerPriority) && talkerPriority) { + return talkerPriority + (sessionPriority << 8); + } + } + return 0; +} + +// VERIFY: 667d951e manual +// OFFSET: 0x00882700 +bool ComSat::Sound::Manager::DecodeVoicePacket(uint8_t player, int32_t channel, ComSat::Sound::Manager::VoicePacket* packet, uint32_t* size) { + LocalPlayer* localPlayer; + if (!this->m_localPlayers.Get(ComSat::MapKey(player), localPlayer)) { + return false; + } + *size = sizeof(localPlayer->m_buffer); + return this->m_codec->DecompressEncodedData(player, channel, packet->m_data, packet->m_bits, localPlayer->m_buffer, size); +} + +// VERIFY: 1c265579 auto +// OFFSET: 0x00882780 +void ComSat::Sound::Manager::WriteVoiceDataToHeadsetDeviceBuffer(uint8_t player, int32_t channel, uint32_t size, double rate) { + if (!size) { + return; + } + LocalPlayer* localPlayer; + if (this->m_localPlayers.Get(ComSat::MapKey(player), localPlayer) && this->m_io) { + this->m_io->PlayDataForPlayer(player, channel, localPlayer->m_buffer, size, rate); + } +} + +// VERIFY: 9c3ab779 auto +// OFFSET: 0x00882810 +void ComSat::Sound::Manager::TransferEncodedVoiceDataForLocalPlayer(uint8_t player, const uint8_t* data, uint32_t bits, uint32_t time) { + if (!data || bits > static_cast(ComSat::Sound::CODECIPMR6000::s_maxEncodedFrameLength) || bits < static_cast(ComSat::Sound::CODECIPMR6000::s_minEncodedFrameLength)) { + return; + } + LocalPlayer* localPlayer; + if (this->m_localPlayers.Get(ComSat::MapKey(player), localPlayer)) { + uint32_t bytes = bits >> 3; + VoicePacket packet; + packet.m_sequence = localPlayer->m_sequence; + packet.m_bits = bits; + if (bits & 7) { + bytes++; + } + memcpy(packet.m_data, data, bytes); + this->m_callback->LocalChatDataReady(player, reinterpret_cast(&packet), bytes + 4, time); + } +} + +// VERIFY: abf0507c auto +// OFFSET: 0x008828E0 +bool ComSat::Sound::Manager::IsRemoteTalkerMuted(uint8_t player, uint64_t talker) { + LocalPlayer* localPlayer; + if (!this->m_localPlayers.Get(ComSat::MapKey(player), localPlayer)) { + return false; + } + uint32_t index; + return localPlayer->m_mutedTalkers.Find(talker, index); +} + +// VERIFY: e3a12132 manual +// OFFSET: 0x00882950 +bool ComSat::Sound::Manager::SetTalkerMuted(uint8_t player, uint64_t talker, ComSat::MuteSetting setting) { + LocalPlayer* localPlayer; + if (!this->m_localPlayers.Get(ComSat::MapKey(player), localPlayer)) { + return false; + } + uint32_t index; + bool mute = setting == ComSat::MUTE_SETTING_MUTE; + if ((setting == ComSat::MUTE_SETTING_TOGGLE && !localPlayer->m_mutedTalkers.Find(talker, index)) || mute) { + if (!localPlayer->m_mutedTalkers.Find(talker, index)) { + localPlayer->m_mutedTalkers.PushBack(talker); + } + return true; + } + return localPlayer->m_mutedTalkers.Remove(talker); +} + +// VERIFY: b712fdb6 auto +// OFFSET: 0x00882A00 +bool ComSat::Sound::Manager::IsSessionMuted(uint8_t player, uint64_t session) { + LocalPlayer* localPlayer; + if (!this->m_localPlayers.Get(ComSat::MapKey(player), localPlayer)) { + return false; + } + uint32_t index; + return localPlayer->m_mutedSessions.Find(session, index); +} + +// VERIFY: d8c69071 manual +// OFFSET: 0x00882A70 +bool ComSat::Sound::Manager::SetSessionMuted(uint8_t player, uint64_t session, ComSat::MuteSetting setting) { + LocalPlayer* localPlayer; + if (!this->m_localPlayers.Get(ComSat::MapKey(player), localPlayer)) { + return false; + } + uint32_t index; + bool mute = setting == ComSat::MUTE_SETTING_MUTE; + if ((setting == ComSat::MUTE_SETTING_TOGGLE && !localPlayer->m_mutedSessions.Find(session, index)) || mute) { + if (!localPlayer->m_mutedSessions.Find(session, index)) { + localPlayer->m_mutedSessions.PushBack(session); + } + return true; + } + return localPlayer->m_mutedSessions.Remove(session); +} + +// VERIFY: df093e1a auto +// OFFSET: 0x00882B20 +void ComSat::Sound::Manager::DeviceError(uint8_t player) { + LocalPlayer* localPlayer; + if (this->m_localPlayers.Get(ComSat::MapKey(player), localPlayer) && !localPlayer->m_deviceError) { + localPlayer->m_deviceError = true; + this->m_callback->DeviceError(player); + } +} + +// VERIFY: 6fa4598d manual +// OFFSET: 0x00882CE0 +void ComSat::Sound::Manager::AssignTalkersToChannelsForLocalPlayer(uint8_t player, int32_t channelCount, ComSat::Sound::Manager::TalkingTalkerInfo* infos) { + LocalPlayer* localPlayer; + if (!this->m_localPlayers.Get(ComSat::MapKey(player), localPlayer)) { + return; + } + uint32_t priorities[4]; + if (channelCount > 0) { + memset(priorities, 0, sizeof(uint32_t) * channelCount); + for (int32_t i = 0; i < channelCount; i++) { + infos[i].m_talker = 0; + infos[i].m_session = 0; + infos[i].m_active = false; + } + } + for (int32_t c = 0; c < channelCount; c++) { + TalkingTalkerInfo& current = localPlayer->m_channels[c]; + if (!current.m_talker) { + continue; + } + uint64_t talker = current.m_talker; + uint64_t session = current.m_session; + RemoteTalker* remote; + if (!this->m_remoteTalkers.Get(ComSat::MapKey(talker), remote)) { + continue; + } + double average = remote->m_frameTime.GetCurrentAverage(); + uint64_t best = 0; + uint8_t bestPriority = 0; + int32_t end = static_cast(ComSat::Sound::CODECIPMR6000::s_samplesPerFrame * 1000.0f / ComSat::Sound::CODECIPMR6000::s_sampleRate / average + remote->m_playCursor) % s_jitterBufferSize; + for (int32_t slot = static_cast(remote->m_playCursor); slot != end; slot = (slot + 1) % s_jitterBufferSize) { + VoicePacket& packet = remote->m_packets[slot]; + if (packet.m_valid) { + uint8_t priority; + if (localPlayer->m_sessionPriorities.Get(ComSat::MapKey(packet.m_session), priority) && priority > bestPriority) { + bestPriority = priority; + best = remote->m_packets[slot].m_session; + } + } + } + if (best == session || !best) { + uint32_t total = this->CalculateTotalVoicePriorityForRemoteTalkerInSessionForLocalPlayer(player, talker, session); + if (total) { + infos[c].m_talker = current.m_talker; + infos[c].m_session = current.m_session; + infos[c].m_active = best == session; + infos[c].m_holdFrames = current.m_holdFrames; + priorities[c] = total; + } + } + } + uint32_t iterator = 0; + ComSat::MapKey key; + RemoteTalker* remote; + while (this->m_remoteTalkers.Next(iterator, key, remote)) { + uint64_t talker = remote->m_guid; + uint64_t best = 0; + double average = remote->m_frameTime.GetCurrentAverage(); + bool assigned = false; + if (channelCount > 0) { + for (int32_t i = 0; i < channelCount; i++) { + if (infos[i].m_talker == talker) { + assigned = true; + } + } + if (assigned) { + continue; + } + } + uint8_t bestPriority = 0; + int32_t end = static_cast(ComSat::Sound::CODECIPMR6000::s_samplesPerFrame * 1000.0f / ComSat::Sound::CODECIPMR6000::s_sampleRate / average + remote->m_playCursor) % s_jitterBufferSize; + int32_t slot = static_cast(remote->m_playCursor); + if (slot == end) { + continue; + } + do { + VoicePacket& packet = remote->m_packets[slot]; + if (packet.m_valid) { + uint8_t priority; + if (localPlayer->m_sessionPriorities.Get(ComSat::MapKey(packet.m_session), priority) && priority > bestPriority) { + bestPriority = priority; + best = remote->m_packets[slot].m_session; + } + } + slot = (slot + 1) % s_jitterBufferSize; + } while (slot != end); + if (!best) { + continue; + } + uint32_t total = this->CalculateTotalVoicePriorityForRemoteTalkerInSessionForLocalPlayer(player, talker, best); + int32_t replace = -1; + if (channelCount > 0) { + for (int32_t i = 0; i < channelCount; i++) { + if (total > priorities[i] && (replace == -1 || priorities[i] < priorities[replace])) { + replace = i; + } + } + if (replace != -1) { + priorities[replace] = total; + infos[replace].m_talker = talker; + infos[replace].m_session = best; + infos[replace].m_active = true; + } + } + } +} + +// VERIFY: 2abf7a9a manual +// OFFSET: 0x008831C0 +void ComSat::Sound::Manager::GenerateAndWriteSilenceToHeadsetDeviceBuffer(uint8_t player, int32_t channel, float frames, double rate) { + LocalPlayer* localPlayer; + if (!this->m_localPlayers.Get(ComSat::MapKey(player), localPlayer)) { + return; + } + this->m_codec->GenerateSilence(localPlayer->m_buffer, ComSat::Sound::CODECIPMR6000::s_bytesPerFrame); + while (frames >= 1.0f) { + this->WriteVoiceDataToHeadsetDeviceBuffer(player, channel, ComSat::Sound::CODECIPMR6000::s_bytesPerFrame, rate); + frames -= 1.0f; + } +} + +// VERIFY: 4067ca64 auto +// OFFSET: 0x00883270 +void ComSat::Sound::Manager::EncodeAvailableVoiceDataForLocalPlayer(uint8_t player, ComSat::Sound::Manager::LocalPlayer* localPlayer) { + if (!this->m_io || !this->m_codec) { + return; + } + int32_t available = this->m_io->GetAvailableDataBytes(player); + int32_t attempts = 5; + if (!available) { + return; + } + int32_t blockSize = ComSat::Sound::CODECIPMR6000::s_samplesPerFrame * ComSat::Sound::CODECIPMR6000::s_bitsPerSample / 8; + if (available < blockSize) { + return; + } + while (attempts-- > 0) { + int32_t read = this->m_io->ReadDataForPlayer(player, localPlayer->m_buffer, blockSize); + s_lastEncodeTime = this->m_currentTime; + if (read < blockSize) { + break; + } + int32_t remaining = this->m_io->GetAvailableDataBytes(player); + uint32_t bits = 1024; + uint8_t encoded[128]; + bool transmit = localPlayer->m_enabled; + uint32_t sequence = localPlayer->m_sequence; + if (sequence < localPlayer->m_lastResetSequence) { + sequence += 0x10000; + } + if (sequence - localPlayer->m_lastResetSequence >= static_cast(ComSat::Sound::CODEC::MinimumSafeFramesBetweenResets()) && ComSat::Sound::CODEC::MinimumSafeFramesBetweenResets() && !(localPlayer->m_sequence % static_cast(ComSat::Sound::CODEC::MinimumSafeFramesBetweenResets()))) { + localPlayer->m_resetEncoder = true; + } + if (transmit || localPlayer->m_voiceLevelCallback) { + if (localPlayer->m_resetEncoder) { + this->m_codec->ResetPlayerChannelEncoder(player); + localPlayer->m_resetEncoder = false; + localPlayer->m_lastResetSequence = localPlayer->m_sequence; + } + bool voice = false; + if (!this->m_codec->CompressRawData(player, localPlayer->m_buffer, blockSize, encoded, &bits, &voice)) { + transmit = false; + } + if (!voice) { + transmit = false; + localPlayer->m_resetEncoder = true; + } + if (localPlayer->m_voiceLevelCallback) { + float level = 0.0f; + float decibels = 0.0f; + ComSat::Sound::LevelCalculator16Bit::CalculateLevelForFrame(localPlayer->m_buffer, blockSize, level, decibels); + this->m_callback->LocalTalkerVoiceLevel(player, level, voice); + } + } + if (transmit) { + int32_t bytesPerSecond = ComSat::Sound::CODECIPMR6000::s_sampleRate * ComSat::Sound::CODECIPMR6000::s_bitsPerSample / 8; + this->TransferEncodedVoiceDataForLocalPlayer(player, encoded, bits, 1000u / static_cast(bytesPerSecond / blockSize)); + localPlayer->m_talking = true; + } else if (localPlayer->m_talking && this->m_callback) { + this->m_callback->LocalChatDataReady(player, nullptr, 0, 0); + localPlayer->m_talking = false; + } + localPlayer->m_sequence++; + if (remaining < blockSize) { + break; + } + } +} + +// VERIFY: a3cc71d9 manual +// OFFSET: 0x00883950 +bool ComSat::Sound::Manager::InitLocalPlayer(uint8_t player, float threshold, int32_t outputDevice, int32_t captureDevice) { + uint32_t index; + if (this->m_localPlayers.Find(ComSat::MapKey(player), index)) { + return false; + } + LocalPlayer* localPlayer = new (this->m_allocator->Alloc(sizeof(LocalPlayer))) LocalPlayer(*this->m_allocator); + localPlayer->m_sequence = 0; + localPlayer->m_enabled = false; + localPlayer->m_talking = false; + localPlayer->m_deviceError = false; + localPlayer->m_voiceLevelCallback = false; + localPlayer->m_lastResetSequence = 0; + for (int32_t i = 0; i < 4; i++) { + localPlayer->m_channels[i].m_talker = 0; + localPlayer->m_channels[i].m_session = 0; + localPlayer->m_channels[i].m_active = false; + localPlayer->m_channels[i].m_holdFrames = 0; + } + this->m_localPlayers.Insert(ComSat::MapKey(player), localPlayer); + if (this->m_io) { + this->m_io->InitLocalPlayer(player, outputDevice, captureDevice, ComSat::Sound::CODECIPMR6000::s_sampleRate, ComSat::Sound::CODECIPMR6000::s_bitsPerSample, ComSat::Sound::CODECIPMR6000::s_samplesPerFrame); + } + if (this->m_codec) { + this->m_codec->InitLocalPlayer(player, threshold); + } + return true; +} + +// VERIFY: d85d2efb auto +// OFFSET: 0x00883A90 +bool ComSat::Sound::Manager::LocalTalkerSetRemoteTalkerVolume(uint8_t player, uint64_t talker, float volume) { + LocalPlayer* localPlayer; + if (!this->m_localPlayers.Get(ComSat::MapKey(player), localPlayer)) { + return false; + } + localPlayer->m_talkerVolumes[ComSat::MapKey(talker)] = volume; + return true; +} + +// VERIFY: 6aaa876a auto +// OFFSET: 0x00883B30 +bool ComSat::Sound::Manager::LocalTalkerSetSessionVolume(uint8_t player, uint64_t session, float volume) { + LocalPlayer* localPlayer; + if (!this->m_localPlayers.Get(ComSat::MapKey(player), localPlayer)) { + return false; + } + localPlayer->m_sessionVolumes[ComSat::MapKey(session)] = volume; + return true; +} + +// VERIFY: 7f3bf85f manual +// OFFSET: 0x00883BD0 +bool ComSat::Sound::Manager::SessionCreate(uint64_t session) { + uint32_t index; + if (!this->m_sessions.Find(ComSat::MapKey(session), index)) { + Session* info = new (this->m_allocator->Alloc(sizeof(Session))) Session(*this->m_allocator); + info->m_id = session; + this->m_sessions.Insert(ComSat::MapKey(session), info); + } + return true; +} + +// VERIFY: a8653a42 manual +// OFFSET: 0x00883C90 +bool ComSat::Sound::Manager::RegisterLocalTalkerForSession(uint64_t session, uint8_t player) { + LocalPlayer* localPlayer; + if (!this->m_localPlayers.Get(ComSat::MapKey(player), localPlayer)) { + return false; + } + uint32_t index; + if (!this->m_sessions.Find(ComSat::MapKey(session), index)) { + return false; + } + localPlayer->m_sessionPriorities[ComSat::MapKey(session)] = 0x80; + localPlayer->m_sessionVolumes[ComSat::MapKey(session)] = 1.0f; + localPlayer->m_mutedSessions.Remove(session); + return true; +} + +// VERIFY: 63bf831f manual +// OFFSET: 0x00883DB0 +bool ComSat::Sound::Manager::RegisterRemoteTalkerForSession(uint64_t session, uint64_t talker) { + Session* info; + if (!this->m_sessions.Get(ComSat::MapKey(session), info)) { + return false; + } + uint32_t index; + if (!this->m_remoteTalkers.Find(ComSat::MapKey(talker), index)) { + RemoteTalker* remote = new (this->m_allocator->Alloc(sizeof(RemoteTalker))) RemoteTalker(*this->m_allocator); + remote->m_guid = talker; + for (int32_t i = 0; i < s_jitterBufferSize; i++) { + remote->m_packets[i].m_valid = false; + } + remote->m_frameTime.Init(this->m_frameDuration, s_frameTimeWindow); + remote->m_lastPacketTime = 0; + remote->m_lastSequence = 0; + remote->m_playCursor = 0.0; + remote->m_lastResetSequence = 0; + this->m_remoteTalkers.Insert(ComSat::MapKey(talker), remote); + } + if (!info->m_talkerPriorities.Find(ComSat::MapKey(talker), index)) { + info->m_talkerPriorities[ComSat::MapKey(talker)] = 0x80; + } + return true; +} + +// VERIFY: 0149312b auto +// OFFSET: 0x00883F90 +bool ComSat::Sound::Manager::SetPlaybackPriorityForPlayerInSession(uint64_t session, uint64_t talker, uint8_t priority) { + Session* info; + if (!this->m_sessions.Get(ComSat::MapKey(session), info)) { + return false; + } + info->m_talkerPriorities[ComSat::MapKey(talker)] = priority; + return true; +} + +// VERIFY: f96bfd70 auto +// OFFSET: 0x00884030 +bool ComSat::Sound::Manager::SetPlaybackPriorityForSession(uint64_t session, uint8_t player, uint8_t priority) { + LocalPlayer* localPlayer; + if (!this->m_localPlayers.Get(ComSat::MapKey(player), localPlayer)) { + return false; + } + localPlayer->m_sessionPriorities[ComSat::MapKey(session)] = priority; + return true; +} + +// VERIFY: 7684e1bc manual +// OFFSET: 0x008840D0 +void ComSat::Sound::Manager::PlayVoiceDataForLocalPlayer(uint8_t player, int32_t frames) { + bool reset = false; + LocalPlayer* localPlayer; + if (!this->m_localPlayers.Get(ComSat::MapKey(player), localPlayer)) { + return; + } + int32_t channelCount = this->m_maxChannels; + TalkingTalkerInfo infos[4]; + for (int32_t i = 0; i < 4; i++) { + infos[i].m_talker = 0; + infos[i].m_session = 0; + infos[i].m_active = false; + } + for (int32_t c = 0; c < channelCount; c++) { + TalkingTalkerInfo& channel = localPlayer->m_channels[c]; + if (channel.m_talker && --channel.m_holdFrames <= 0) { + channel.m_talker = 0; + channel.m_session = 0; + channel.m_holdFrames = 0; + } + } + this->AssignTalkersToChannelsForLocalPlayer(player, channelCount, infos); + for (int32_t c = 0; c < channelCount; c++) { + TalkingTalkerInfo& info = infos[c]; + TalkingTalkerInfo& channel = localPlayer->m_channels[c]; + if (info.m_talker && info.m_active && (channel.m_talker != info.m_talker || channel.m_session != info.m_session || !channel.m_active)) { + uint32_t index; + if (this->m_remoteTalkers.Find(ComSat::MapKey(info.m_talker), index)) { + this->m_callback->RemotePlayerTalkNotifyStart(player, info.m_talker, info.m_session); + reset = true; + } + } + } + for (int32_t c = 0; c < channelCount; c++) { + TalkingTalkerInfo& info = infos[c]; + TalkingTalkerInfo& channel = localPlayer->m_channels[c]; + if (channel.m_talker && channel.m_active && (info.m_talker != channel.m_talker || info.m_session != channel.m_session || !info.m_active)) { + uint32_t index; + if (this->m_remoteTalkers.Find(ComSat::MapKey(channel.m_talker), index)) { + this->m_callback->RemotePlayerTalkNotifyStop(player, channel.m_talker, channel.m_session); + } + } + } + for (int32_t c = 0; c < channelCount; c++) { + TalkingTalkerInfo& channel = localPlayer->m_channels[c]; + channel.m_talker = infos[c].m_talker; + channel.m_session = infos[c].m_session; + channel.m_active = infos[c].m_active; + if (infos[c].m_active) { + channel.m_holdFrames = this->m_holdFrames; + } + } + for (int32_t c = 0; c < channelCount; c++) { + TalkingTalkerInfo& info = infos[c]; + if (!info.m_talker) { + continue; + } + if (!info.m_active) { + RemoteTalker* remote; + if (this->m_remoteTalkers.Get(ComSat::MapKey(info.m_talker), remote)) { + double rate = ComSat::Sound::CODECIPMR6000::s_samplesPerFrame * 1000.0f / ComSat::Sound::CODECIPMR6000::s_sampleRate / remote->m_frameTime.GetCurrentAverage(); + this->GenerateAndWriteSilenceToHeadsetDeviceBuffer(player, c, 1.0f, rate); + } + continue; + } + double buffered = 0.0; + if (this->m_io) { + int32_t blockSize = this->m_io->GetPlaybackBlockSize(player); + if (blockSize) { + buffered = this->m_io->GetRemainingPlaybackBytes(player, c) / blockSize; + } + } + if (info.m_active && info.m_talker) { + uint32_t elapsed = this->m_currentTime - this->m_startTime; + double missing = frames - elapsed * 0.001 * this->m_framesPerSecond - buffered; + if (missing >= 1.0 && 0.0 == buffered) { + this->GenerateAndWriteSilenceToHeadsetDeviceBuffer(player, c, static_cast(missing), 1.0); + } + } + RemoteTalker* remote; + if (!this->m_remoteTalkers.Get(ComSat::MapKey(info.m_talker), remote)) { + continue; + } + float sessionVolume; + if (!localPlayer->m_sessionVolumes.Get(ComSat::MapKey(info.m_session), sessionVolume)) { + sessionVolume = 1.0f; + } + float talkerVolume; + if (!localPlayer->m_talkerVolumes.Get(ComSat::MapKey(info.m_talker), talkerVolume)) { + talkerVolume = 1.0f; + } + this->m_io->SetPlayerPlaybackVolume(player, c, talkerVolume * sessionVolume); + double average = remote->m_frameTime.GetCurrentAverage(); + int32_t slot = static_cast(remote->m_playCursor); + double rate = ComSat::Sound::CODECIPMR6000::s_samplesPerFrame * 1000.0f / ComSat::Sound::CODECIPMR6000::s_sampleRate / average; + int32_t end = static_cast(remote->m_playCursor + rate) % s_jitterBufferSize; + for (; slot != end; slot = (slot + 1) % s_jitterBufferSize) { + VoicePacket* packet = &remote->m_packets[slot]; + if (!packet->m_valid) { + this->GenerateAndWriteSilenceToHeadsetDeviceBuffer(player, c, 1.0f, rate); + continue; + } + uint32_t sequence = packet->m_sequence; + if (sequence < remote->m_lastResetSequence) { + sequence += 0x10000; + } + if ((sequence - remote->m_lastResetSequence >= static_cast(ComSat::Sound::CODEC::MinimumSafeFramesBetweenResets()) && ComSat::Sound::CODEC::MinimumSafeFramesBetweenResets() && !(packet->m_sequence % ComSat::Sound::CODEC::MinimumSafeFramesBetweenResets())) || reset) { + this->m_codec->ResetPlayerChannelDecoder(player, c); + remote->m_lastResetSequence = packet->m_sequence; + reset = false; + } + uint32_t size; + this->DecodeVoicePacket(player, c, packet, &size); + LocalPlayer* target; + if (this->m_localPlayers.Get(ComSat::MapKey(player), target)) { + this->m_codec->ApplyVoiceEffects(player, target->m_buffer, &size); + } + this->WriteVoiceDataToHeadsetDeviceBuffer(player, c, size, rate); + } + } +} + +// VERIFY: 38d75a44 auto +// OFFSET: 0x00884850 +void ComSat::Sound::Manager::EncodeAvailableVoiceData() { + uint32_t iterator = 0; + ComSat::MapKey key; + LocalPlayer* localPlayer; + while (this->m_localPlayers.Next(iterator, key, localPlayer)) { + this->EncodeAvailableVoiceDataForLocalPlayer(key.m_value, localPlayer); + } +} + +// VERIFY: a25f3ffc manual +// OFFSET: [0x008848B0, 0x00884DA0] +ComSat::Sound::Manager::~Manager() { + uint32_t iterator = 0; + ComSat::MapKey playerKey; + LocalPlayer* localPlayer; + for (; this->m_localPlayers.Next(iterator, playerKey, localPlayer); iterator = 0) { + LocalPlayer* removed; + this->m_localPlayers.Remove(playerKey, removed); + ComSat::Delete(*this->m_allocator, localPlayer); + } + iterator = 0; + ComSat::MapKey key; + Session* info; + for (; this->m_sessions.Next(iterator, key, info); iterator = 0) { + Session* removed; + this->m_sessions.Remove(key, removed); + ComSat::Delete(*this->m_allocator, info); + } + this->m_sessions.Clear(); + iterator = 0; + RemoteTalker* remote; + for (; this->m_remoteTalkers.Next(iterator, key, remote); iterator = 0) { + RemoteTalker* removed; + this->m_remoteTalkers.Remove(key, removed); + ComSat::Delete(*this->m_allocator, remote); + } + if (this->m_io) { + ComSat::Delete(*this->m_allocator, this->m_io); + } + if (this->m_codec) { + ComSat::Delete(*this->m_allocator, this->m_codec); + } +} + +// VERIFY: 8880502e manual +// OFFSET: 0x00884AB0 +bool ComSat::Sound::Manager::UnregisterRemoteTalkerFromSession(uint64_t session, uint64_t talker) { + Session* info; + if (!this->m_sessions.Get(ComSat::MapKey(session), info)) { + return false; + } + RemoteTalker* remote; + if (!this->m_remoteTalkers.Get(ComSat::MapKey(talker), remote)) { + return false; + } + uint8_t priority; + info->m_talkerPriorities.Remove(ComSat::MapKey(talker), priority); + uint32_t iterator = 0; + ComSat::MapKey key(0); + Session* other; + while (this->m_sessions.Next(iterator, key, other)) { + if (key.m_value != session) { + uint32_t index; + if (other->m_talkerPriorities.Find(ComSat::MapKey(talker), index)) { + return true; + } + } + } + RemoteTalker* removed; + this->m_remoteTalkers.Remove(ComSat::MapKey(talker), removed); + ComSat::Delete(*this->m_allocator, remote); + return true; +} + +// VERIFY: 3e78c7de manual +// OFFSET: 0x00884CA0 +void ComSat::Sound::Manager::PlayScheduledVoiceData() { + uint32_t elapsed = this->m_currentTime - this->m_startTime; + double frames = elapsed * 0.001 * this->m_framesPerSecond; + int32_t frame = static_cast(frames + 1.0); + int32_t count = static_cast(this->m_jitterDelay - this->m_currentFrame + frames); + if (count > this->m_jitterDelay) { + count = this->m_jitterDelay; + } + frame += this->m_jitterDelay - count; + for (; count > 0; count--) { + uint32_t iterator = 0; + ComSat::MapKey playerKey; + LocalPlayer* localPlayer; + while (this->m_localPlayers.Next(iterator, playerKey, localPlayer)) { + this->PlayVoiceDataForLocalPlayer(playerKey.m_value, frame); + } + iterator = 0; + ComSat::MapKey key; + RemoteTalker* remote; + while (this->m_remoteTalkers.Next(iterator, key, remote)) { + this->AdvancePlayCursorForRemoteTalker(remote); + } + this->m_currentFrame = frame++; + } +} + +// VERIFY: ef10a638 auto +// OFFSET: 0x00884DB0 +void ComSat::Sound::Manager::Work(uint32_t time) { + this->m_currentTime = time; + if (this->m_io) { + this->m_io->Work(time); + } + this->PlayScheduledVoiceData(); + this->EncodeAvailableVoiceData(); +} + +// VERIFY: 28a13445 manual +// OFFSET: 0x00884DE0 +bool ComSat::Sound::Manager::SessionDestroy(uint64_t session) { + Session* info; + if (this->m_sessions.Get(ComSat::MapKey(session), info)) { + uint32_t iterator = 0; + ComSat::MapKey key(0); + uint8_t priority; + while (info->m_talkerPriorities.Next(iterator, key, priority)) { + this->UnregisterRemoteTalkerFromSession(session, key.m_value); + } + if (this->m_sessions.Remove(ComSat::MapKey(session), info)) { + ComSat::Delete(*this->m_allocator, info); + } + } + return true; +} + +// VERIFY: a1c02a9e manual +// OFFSET: 0x00884F10 +bool ComSat::Sound::Manager::UnregisterLocalTalkerFromSession(uint64_t session, uint8_t player) { + LocalPlayer* localPlayer; + if (!this->m_localPlayers.Get(ComSat::MapKey(player), localPlayer)) { + return false; + } + uint32_t index; + if (!this->m_sessions.Find(ComSat::MapKey(session), index)) { + return false; + } + localPlayer->m_mutedSessions.Remove(session); + uint8_t priority; + localPlayer->m_sessionPriorities.Remove(ComSat::MapKey(session), priority); + float volume; + localPlayer->m_sessionVolumes.Remove(ComSat::MapKey(session), volume); + LocalPlayer* other = nullptr; + ComSat::MapKey key(0); + uint32_t iterator = 0; + bool last = true; + while (this->m_localPlayers.Next(iterator, key, other)) { + if (player != key.m_value && other->m_sessionPriorities.Find(ComSat::MapKey(session), index)) { + last = false; + } + } + if (last) { + this->SessionDestroy(session); + } + return true; +} + +// VERIFY: 717e19dc auto +// OFFSET: 0x008850F0 +bool ComSat::Sound::Manager::DestroyLocalPlayer(uint8_t player) { + uint32_t iterator = 0; + ComSat::MapKey key; + Session* info; + while (this->m_sessions.Next(iterator, key, info)) { + this->UnregisterLocalTalkerFromSession(key.m_value, player); + } + LocalPlayer* localPlayer; + if (this->m_localPlayers.Remove(ComSat::MapKey(player), localPlayer)) { + ComSat::Delete(*this->m_allocator, localPlayer); + if (this->m_io) { + this->m_io->DestroyLocalPlayer(player); + } + if (this->m_codec) { + this->m_codec->RemoveLocalPlayer(player); + } + } + return true; +} diff --git a/Engine/Source/ComSat/ComSatSoundManager.h b/Engine/Source/ComSat/ComSatSoundManager.h new file mode 100644 index 0000000..adc29ee --- /dev/null +++ b/Engine/Source/ComSat/ComSatSoundManager.h @@ -0,0 +1,168 @@ +#ifndef ENGINE_SOURCE_COMSAT_COMSATSOUNDMANAGER_H +#define ENGINE_SOURCE_COMSAT_COMSATSOUNDMANAGER_H + +#include +#include +#include "Engine/Source/ComSat/ComSatInterface.h" +#include "Engine/Source/ComSat/ComSatMap.h" +#include "Engine/Source/ComSat/ComSatRunningAverageCalculator.h" +#include "Engine/Source/ComSat/ComSatSoundCODEC.h" +#include "Engine/Source/ComSat/ComSatSoundIOSoundEngine.h" +#include "Engine/Source/ComSat/ComSatVector.h" + +namespace ComSat { +namespace Sound { + +class Manager : public IOCallback { + public: + class Callback { + public: + virtual ~Callback(); + virtual void MicrophoneStatusUpdate(uint8_t player, HeadsetDeviceStatus status) = 0; + virtual void LocalChatDataReady(uint8_t player, uint8_t* data, uint32_t size, uint32_t time) = 0; + virtual void RemotePlayerTalkNotifyStart(uint8_t player, uint64_t talker, uint64_t session) = 0; + virtual void RemotePlayerTalkNotifyStop(uint8_t player, uint64_t talker, uint64_t session) = 0; + virtual void LocalTalkerVoiceLevel(uint8_t player, float level, bool talking) = 0; + virtual void DeviceError(uint8_t player) = 0; + }; + + struct TalkingTalkerInfo { + /* 0000 */ uint64_t m_talker; + /* 0008 */ uint64_t m_session; + /* 0010 */ int32_t m_holdFrames; + /* 0014 */ bool m_active; + }; + + struct VoicePacket { + /* 0000 */ uint16_t m_sequence; + /* 0002 */ uint16_t m_bits; + /* 0004 */ uint8_t m_data[128]; + /* 0084 */ bool m_valid; + /* 0088 */ uint64_t m_session; + }; + + class LocalPlayer { + public: + /* 0000 */ Map m_sessionPriorities; + /* 0010 */ Vector m_mutedSessions; + /* 0020 */ Vector m_mutedTalkers; + /* 0030 */ Map m_talkerVolumes; + /* 0040 */ Map m_sessionVolumes; + /* 0050 */ int32_t m_sequence; + /* 0054 */ uint8_t m_buffer[2048]; + /* 0854 */ bool m_enabled; + /* 0855 */ bool m_talking; + /* 0856 */ bool m_resetEncoder; + /* 0858 */ TalkingTalkerInfo m_channels[4]; + /* 08B8 */ uint16_t m_lastResetSequence; + /* 08BA */ bool m_voiceLevelCallback; + /* 08BB */ bool m_deviceError; + + LocalPlayer(Allocator& allocator); + ~LocalPlayer(); + }; + + class RemoteTalker { + public: + /* 0008 */ Allocator* m_allocator; + /* 000C */ VoicePacket* m_packets; + /* 0010 */ double m_playCursor; + /* 0018 */ RunningAverageCalculator m_frameTime; + /* 0038 */ uint32_t m_lastPacketTime; + /* 003C */ uint16_t m_lastSequence; + /* 003E */ uint16_t m_lastResetSequence; + /* 0040 */ uint32_t m_recenterTime; + /* 0048 */ uint64_t m_guid; + + virtual ~RemoteTalker(); + + RemoteTalker(Allocator& allocator); + }; + + class Session { + public: + /* 0000 */ uint64_t m_id; + /* 0008 */ Map m_talkerPriorities; + + Session(Allocator& allocator); + }; + + /* 0004 */ uint32_t m_maxLocalPlayers; + /* 0008 */ Allocator* m_allocator; + /* 000C */ Callback* m_callback; + /* 0010 */ CODEC* m_codec; + /* 0014 */ IO* m_io; + /* 0018 */ Map m_localPlayers; + /* 0028 */ Map m_sessions; + /* 0038 */ Map m_remoteTalkers; + /* 0048 */ int32_t m_jitterDelay; + /* 004C */ int32_t m_sequenceDelay; + /* 0050 */ int32_t m_holdFrames; + /* 0054 */ float m_framesPerSecond; + /* 0058 */ uint32_t m_maxChannels; + /* 005C */ int32_t m_currentFrame; + /* 0060 */ float m_frameDuration; + /* 0064 */ uint32_t m_startTime; + /* 0068 */ uint32_t m_currentTime; + + virtual ~Manager(); + virtual void DeviceError(uint8_t player); + + Manager(const Initialization& init, Allocator& allocator); + void AdvancePlayCursorForRemoteTalker(RemoteTalker* talker); + void AssignTalkersToChannelsForLocalPlayer(uint8_t player, int32_t channelCount, TalkingTalkerInfo* infos); + bool CanBitpackEncodedData(); + uint32_t CalculateTotalVoicePriorityForRemoteTalkerInSessionForLocalPlayer(uint8_t player, uint64_t talker, uint64_t session); + void DebugSetSequenceDelay(int32_t delay); + void DebugSetSoundOutputDelay(uint8_t player, int32_t delay); + bool DecodeVoicePacket(uint8_t player, int32_t channel, VoicePacket* packet, uint32_t* size); + bool DestroyLocalPlayer(uint8_t player); + void EncodeAvailableVoiceData(); + void EncodeAvailableVoiceDataForLocalPlayer(uint8_t player, LocalPlayer* localPlayer); + int32_t EnumerateCaptureDevices(DeviceInfo* devices, int32_t maxDevices); + int32_t EnumerateOutputDevices(DeviceInfo* devices, int32_t maxDevices); + int32_t GetMaxEncodedFrameLength(); + int32_t GetMinEncodedFrameLength(); + void GenerateAndWriteSilenceToHeadsetDeviceBuffer(uint8_t player, int32_t channel, float frames, double rate); + bool InitLocalPlayer(uint8_t player, float threshold, int32_t outputDevice, int32_t captureDevice); + bool IsLocalPlayerTalking(uint8_t player); + bool IsRemoteTalkerMuted(uint8_t player, uint64_t talker); + bool IsRemoteTalkerTalkingInSession(uint64_t session, uint8_t player, uint64_t talker); + bool IsSessionMuted(uint8_t player, uint64_t session); + bool IsUsingVariableBitrateCodec(); + bool LocalTalkerChangeCaptureDevice(uint8_t player, int32_t device); + bool LocalTalkerChangeOutputDevice(uint8_t player, int32_t device); + bool LocalTalkerEnable(uint8_t player, bool enable); + bool LocalTalkerEnableVoiceLevelCallback(uint8_t player, bool enable); + int32_t LocalTalkerGetCurrentCaptureDeviceIndex(uint8_t player); + int32_t LocalTalkerGetCurrentOutputDeviceIndex(uint8_t player); + bool LocalTalkerSetRemoteTalkerVolume(uint8_t player, uint64_t talker, float volume); + bool LocalTalkerSetSessionVolume(uint8_t player, uint64_t session, float volume); + bool LocalTalkerThreshold(uint8_t player, float threshold); + void PlayScheduledVoiceData(); + void PlayVoiceDataForLocalPlayer(uint8_t player, int32_t frames); + void RecenterJitterBufferForRemoteTalker(uint64_t talker, int32_t offset); + bool RegisterLocalTalkerForSession(uint64_t session, uint8_t player); + bool RegisterRemoteTalkerForSession(uint64_t session, uint64_t talker); + bool SessionCreate(uint64_t session); + bool SessionDestroy(uint64_t session); + bool SessionGetTalkerByIndex(uint64_t session, int32_t index, uint64_t& talker, uint8_t& player); + int32_t SessionNumMembers(uint64_t session); + void SetCallback(Callback* callback); + bool SetPlaybackPriorityForPlayerInSession(uint64_t session, uint64_t talker, uint8_t priority); + bool SetPlaybackPriorityForSession(uint64_t session, uint8_t player, uint8_t priority); + bool SetSessionMuted(uint8_t player, uint64_t session, MuteSetting setting); + bool SetTalkerMuted(uint8_t player, uint64_t talker, MuteSetting setting); + void SubmitIncomingFrameTimeData(uint64_t talker, uint16_t sequence); + void SubmitIncomingVoicePacket(uint64_t session, uint64_t talker, uint8_t* data, uint32_t size, bool reliable); + void TransferEncodedVoiceDataForLocalPlayer(uint8_t player, const uint8_t* data, uint32_t bits, uint32_t time); + bool UnregisterLocalTalkerFromSession(uint64_t session, uint8_t player); + bool UnregisterRemoteTalkerFromSession(uint64_t session, uint64_t talker); + void Work(uint32_t time); + void WriteVoiceDataToHeadsetDeviceBuffer(uint8_t player, int32_t channel, uint32_t size, double rate); +}; + +} +} + +#endif diff --git a/Engine/Source/ComSat/ComSatSpirit.h b/Engine/Source/ComSat/ComSatSpirit.h new file mode 100644 index 0000000..499a41a --- /dev/null +++ b/Engine/Source/ComSat/ComSatSpirit.h @@ -0,0 +1,29 @@ +#ifndef ENGINE_SOURCE_COMSAT_COMSATSPIRIT_H +#define ENGINE_SOURCE_COMSAT_COMSATSPIRIT_H + +#include +#include + +struct SPIRIT_IPMR_PARAMS { + /* 0000 */ int32_t unk_0000; + /* 0004 */ int16_t unk_0004; + /* 0006 */ int16_t unk_0006; +}; + +struct SPIRIT_IPMR_STREAM { + /* 0000 */ const uint8_t* m_data; + /* 0004 */ uint32_t m_bits; + /* 0008 */ uint32_t m_size; +}; + +struct SPIRIT_IPMR_INFO { + /* 0000 */ uint32_t unk_0000[6]; + /* 0018 */ int16_t unk_0018; +}; + +extern "C" int32_t SPIRIT_IP_MR_V3_1_GenerateTables(void* tables); +extern "C" int32_t SPIRIT_IP_MR_V3_1_Init(void* state, const void* tables); +extern "C" int32_t SPIRIT_IP_MR_V3_1_Encode(void* state, const uint8_t* pcm, SPIRIT_IPMR_PARAMS* params, SPIRIT_IPMR_STREAM* stream, SPIRIT_IPMR_INFO* info); +extern "C" int32_t SPIRIT_IP_MR_V3_1_Decode(void* state, uint8_t* pcm, SPIRIT_IPMR_PARAMS* params, SPIRIT_IPMR_STREAM* stream, SPIRIT_IPMR_INFO* info); + +#endif diff --git a/Engine/Source/ComSat/ComSatVector.h b/Engine/Source/ComSat/ComSatVector.h new file mode 100644 index 0000000..ec57213 --- /dev/null +++ b/Engine/Source/ComSat/ComSatVector.h @@ -0,0 +1,131 @@ +#ifndef ENGINE_SOURCE_COMSAT_COMSATVECTOR_H +#define ENGINE_SOURCE_COMSAT_COMSATVECTOR_H + +#include +#include +#include +#include +#include "Engine/Source/ComSat/ComSatInterface.h" + +namespace ComSat { + +template +class Vector { + public: + /* 0000 */ T* m_data; + /* 0004 */ uint32_t m_used; + /* 0008 */ uint32_t m_capacity; + /* 000C */ Allocator* m_allocator; + + Vector(Allocator& allocator); + ~Vector(); + bool Find(const T& value, uint32_t& index) const; + bool Reserve(uint32_t size); + T* PushBack(const T& value); + bool Remove(const T& value); + void RemoveAt(uint32_t offset); + uint32_t Count() const; + T& operator[](uint32_t index); +}; + +} + +// INLINED +template +ComSat::Vector::Vector(ComSat::Allocator& allocator) { + this->m_data = nullptr; + this->m_used = 0; + this->m_capacity = 0; + this->m_allocator = &allocator; +} + +// INLINED +template +ComSat::Vector::~Vector() { + T* data = this->m_data; + this->m_used = 0; + if (data) { + this->m_allocator->Free(data); + } +} + +// VERIFY: 69732af2 manual +// OFFSET: [0x00880650, 0x00885240, 0x00885DC0] +template +bool ComSat::Vector::Find(const T& value, uint32_t& index) const { + index = 0; + if (!this->m_used) { + return false; + } + while (!(this->m_data[index] == value)) { + if (++index >= this->m_used) { + return false; + } + } + return true; +} + +// VERIFY: c18fa1fe auto +// OFFSET: [0x008806A0, 0x00885280, 0x00885E20] +template +bool ComSat::Vector::Reserve(uint32_t size) { + if (size < this->m_used) { + return false; + } + T* data = static_cast(this->m_allocator->Alloc(sizeof(T) * size)); + if (this->m_data) { + memcpy(data, this->m_data, sizeof(T) * this->m_used); + this->m_allocator->Free(this->m_data); + } + this->m_data = data; + this->m_capacity = size; + return true; +} + +// VERIFY: 9ab41809 auto +// OFFSET: [0x00880EB0, 0x00880EF0] +template +T* ComSat::Vector::PushBack(const T& value) { + if (this->m_used == this->m_capacity) { + this->Reserve(this->m_capacity + 10); + } + T* element = new (&this->m_data[this->m_used]) T(value); + this->m_used++; + return element; +} + +// VERIFY: 02a41f26 manual +// OFFSET: [0x00880AD0, 0x00885370, 0x008860B0] +template +bool ComSat::Vector::Remove(const T& value) { + uint32_t index; + if (!this->Find(value, index)) { + return false; + } + this->RemoveAt(index); + return true; +} + +// INLINED +template +void ComSat::Vector::RemoveAt(uint32_t offset) { + uint32_t remaining = this->m_used - offset; + if (remaining > 1) { + memmove(&this->m_data[offset], &this->m_data[offset + 1], sizeof(T) * (remaining - 1)); + } + this->m_used--; +} + +// INLINED +template +uint32_t ComSat::Vector::Count() const { + return this->m_used; +} + +// INLINED +template +T& ComSat::Vector::operator[](uint32_t index) { + return this->m_data[index]; +} + +#endif diff --git a/Engine/Source/ComSat/Types.h b/Engine/Source/ComSat/Types.h index 06aed52..edc8d52 100644 --- a/Engine/Source/ComSat/Types.h +++ b/Engine/Source/ComSat/Types.h @@ -5,27 +5,22 @@ #include namespace ComSat { -namespace Sound { -struct IOSoundEngine { - /* 0000 */ uint8_t unk_0000 [8]; - /* 0008 */ int32_t unk_0008; - /* 000C */ uint8_t unk_000C[4]; - /* 0010 */ int32_t unk_0010; - /* 0014 */ int32_t unk_0014; - /* 0018 */ uint8_t unk_0018 [4]; - /* 001C */ int32_t unk_001C; - /* 0020 */ uint8_t unk_0020 [4]; - /* 0024 */ int32_t unk_0024; - /* 0028 */ int32_t unk_0028; - /* 002C */ int32_t unk_002C; - /* 0030 */ uint8_t unk_0030 [32804]; - /* 8054 */ int32_t unk_8054; - /* 8058 */ int32_t unk_8058; - /* 805C */ int32_t unk_805C; - /* 8060 */ int32_t unk_8060; - /* 8064 */ int32_t unk_8064; + +enum MuteSetting { + MUTE_SETTING_MUTE = 0, + MUTE_SETTING_UNMUTE = 1, + MUTE_SETTING_TOGGLE = 2, }; + +namespace Sound { + +enum HeadsetDeviceStatus { + HEADSET_DEVICE_STATUS_OK = 0, + HEADSET_DEVICE_STATUS_ERROR = 1, +}; + } + } #endif diff --git a/Engine/Source/ComSat/Win32/ComSatNetworkAddress.cpp b/Engine/Source/ComSat/Win32/ComSatNetworkAddress.cpp new file mode 100644 index 0000000..86e79bf --- /dev/null +++ b/Engine/Source/ComSat/Win32/ComSatNetworkAddress.cpp @@ -0,0 +1,37 @@ +#if defined(WOWDECOMP_ARCH_32) + +#include +#include +#include +#include "Engine/Source/ComSat/ComSatNetwork.h" + +// VERIFY: 4d04cc78 auto +// OFFSET: 0x00885C40 +void ComSat::Network::Address::SetPort(int32_t port) { + this->m_port = htons(static_cast(port)); +} + +// VERIFY: f308d459 auto +// OFFSET: 0x00885C60 +int32_t ComSat::Network::Address::GetPort() const { + return ntohs(this->m_port); +} + +// VERIFY: 18ffc29e manual +// OFFSET: 0x00885CD0 +void ComSat::Network::Address::SetAddress(const char* address) { + const char* colon = strchr(address, ':'); + if (colon) { + if (strlen(address) < 128) { + char host[128]; + strcpy(host, address); + host[colon - address] = '\0'; + this->m_ip = inet_addr(host); + this->m_port = htons(static_cast(strtol(colon + 1, nullptr, 10))); + } + } else { + this->m_ip = inet_addr(address); + } +} + +#endif diff --git a/Engine/Source/ComSat/Win32/ComSatNetworkSocketPosix.cpp b/Engine/Source/ComSat/Win32/ComSatNetworkSocketPosix.cpp new file mode 100644 index 0000000..db3f3cf --- /dev/null +++ b/Engine/Source/ComSat/Win32/ComSatNetworkSocketPosix.cpp @@ -0,0 +1,74 @@ +#if defined(WOWDECOMP_ARCH_32) + +#include +#include +#include +#include "Engine/Source/ComSat/ComSatNetwork.h" + +typedef int (WSAAPI* WSAIOCTLPROC)(SOCKET, DWORD, LPVOID, DWORD, LPVOID, DWORD, LPDWORD, LPWSAOVERLAPPED, LPWSAOVERLAPPED_COMPLETION_ROUTINE); + +// VERIFY: 4d719c9d manual +// OFFSET: 0x00888790 +static void DisableConnectionReset(ComSat::Network::SocketPosix* socket) { + HMODULE library = LoadLibraryA("ws2_32.dll"); + if (library) { + WSAIOCTLPROC wsaIoctl = reinterpret_cast(GetProcAddress(library, "WSAIoctl")); + if (wsaIoctl) { + BOOL behavior = FALSE; + DWORD bytesReturned = 0; + wsaIoctl(socket->m_socket, 0x9800000C, &behavior, sizeof(behavior), nullptr, 0, &bytesReturned, nullptr, nullptr); + } + FreeLibrary(library); + } +} + +// VERIFY: 335e954a auto +// OFFSET: 0x008888F0 +ComSat::Network::SocketPosix::SocketPosix() { + this->m_socket = socket(AF_INET, SOCK_DGRAM, 0); + DisableConnectionReset(this); + u_long value = 1; + ioctlsocket(this->m_socket, FIONBIO, &value); + value = 0x8000; + setsockopt(this->m_socket, SOL_SOCKET, SO_RCVBUF, reinterpret_cast(&value), sizeof(value)); +} + +// VERIFY: 10b1177d manual +// OFFSET: 0x00888960 +ComSat::Network::SocketPosix::~SocketPosix() { + closesocket(this->m_socket); +} + +// VERIFY: 8433c742 auto +// OFFSET: 0x00888800 +bool ComSat::Network::SocketPosix::Bind(int32_t port) { + ComSat::Network::Address address; + address.SetPort(port); + int32_t reuse = 1; + setsockopt(this->m_socket, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&reuse), sizeof(reuse)); + return bind(this->m_socket, reinterpret_cast(&address.m_family), address.m_length) != SOCKET_ERROR; +} + +// VERIFY: 417b79dd auto +// OFFSET: 0x00888860 +int32_t ComSat::Network::SocketPosix::SendTo(const ComSat::Network::Address& address, const uint8_t* data, uint32_t size) { + return sendto(this->m_socket, reinterpret_cast(data), size, 0, reinterpret_cast(&address.m_family), address.m_length); +} + +// VERIFY: 7024ca54 auto +// OFFSET: 0x00888890 +bool ComSat::Network::SocketPosix::RecvFrom(ComSat::Network::Address& address, uint8_t* data, uint32_t& size) { + memset(data, 0, size); + int32_t received = recvfrom(this->m_socket, reinterpret_cast(data), size, 0, reinterpret_cast(&address.m_family), &address.m_length); + if (received == SOCKET_ERROR) { + WSAGetLastError(); + return false; + } + if (!received) { + return false; + } + size = received; + return true; +} + +#endif diff --git a/Engine/Source/ComSat/Win64/ComSatNetworkAddress.cpp b/Engine/Source/ComSat/Win64/ComSatNetworkAddress.cpp new file mode 100644 index 0000000..19b33ef --- /dev/null +++ b/Engine/Source/ComSat/Win64/ComSatNetworkAddress.cpp @@ -0,0 +1,34 @@ +#if defined(WOWDECOMP_ARCH_64) + +#include +#include +#include +#include "Engine/Source/ComSat/ComSatNetwork.h" + +// OFFSET: 0x00885C40 +void ComSat::Network::Address::SetPort(int32_t port) { + this->m_port = htons(static_cast(port)); +} + +// OFFSET: 0x00885C60 +int32_t ComSat::Network::Address::GetPort() const { + return ntohs(this->m_port); +} + +// OFFSET: 0x00885CD0 +void ComSat::Network::Address::SetAddress(const char* address) { + const char* colon = strchr(address, ':'); + if (colon) { + if (strlen(address) < 128) { + char host[128]; + strcpy(host, address); + host[colon - address] = '\0'; + this->m_ip = inet_addr(host); + this->m_port = htons(static_cast(strtol(colon + 1, nullptr, 10))); + } + } else { + this->m_ip = inet_addr(address); + } +} + +#endif diff --git a/Engine/Source/ComSat/Win64/ComSatNetworkSocketPosix.cpp b/Engine/Source/ComSat/Win64/ComSatNetworkSocketPosix.cpp new file mode 100644 index 0000000..934985c --- /dev/null +++ b/Engine/Source/ComSat/Win64/ComSatNetworkSocketPosix.cpp @@ -0,0 +1,68 @@ +#if defined(WOWDECOMP_ARCH_64) + +#include +#include +#include +#include "Engine/Source/ComSat/ComSatNetwork.h" + +typedef int (WSAAPI* WSAIOCTLPROC)(SOCKET, DWORD, LPVOID, DWORD, LPVOID, DWORD, LPDWORD, LPWSAOVERLAPPED, LPWSAOVERLAPPED_COMPLETION_ROUTINE); + +// OFFSET: 0x00888790 +static void DisableConnectionReset(ComSat::Network::SocketPosix* socket) { + HMODULE library = LoadLibraryA("ws2_32.dll"); + if (library) { + WSAIOCTLPROC wsaIoctl = reinterpret_cast(GetProcAddress(library, "WSAIoctl")); + if (wsaIoctl) { + BOOL behavior = FALSE; + DWORD bytesReturned = 0; + wsaIoctl(socket->m_socket, 0x9800000C, &behavior, sizeof(behavior), nullptr, 0, &bytesReturned, nullptr, nullptr); + } + FreeLibrary(library); + } +} + +// OFFSET: 0x008888F0 +ComSat::Network::SocketPosix::SocketPosix() { + this->m_socket = socket(AF_INET, SOCK_DGRAM, 0); + DisableConnectionReset(this); + u_long value = 1; + ioctlsocket(this->m_socket, FIONBIO, &value); + value = 0x8000; + setsockopt(this->m_socket, SOL_SOCKET, SO_RCVBUF, reinterpret_cast(&value), sizeof(value)); +} + +// OFFSET: 0x00888960 +ComSat::Network::SocketPosix::~SocketPosix() { + closesocket(this->m_socket); +} + +// OFFSET: 0x00888800 +bool ComSat::Network::SocketPosix::Bind(int32_t port) { + ComSat::Network::Address address; + address.SetPort(port); + int32_t reuse = 1; + setsockopt(this->m_socket, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&reuse), sizeof(reuse)); + return bind(this->m_socket, reinterpret_cast(&address.m_family), address.m_length) != SOCKET_ERROR; +} + +// OFFSET: 0x00888860 +int32_t ComSat::Network::SocketPosix::SendTo(const ComSat::Network::Address& address, const uint8_t* data, uint32_t size) { + return sendto(this->m_socket, reinterpret_cast(data), size, 0, reinterpret_cast(&address.m_family), address.m_length); +} + +// OFFSET: 0x00888890 +bool ComSat::Network::SocketPosix::RecvFrom(ComSat::Network::Address& address, uint8_t* data, uint32_t& size) { + memset(data, 0, size); + int32_t received = recvfrom(this->m_socket, reinterpret_cast(data), size, 0, reinterpret_cast(&address.m_family), &address.m_length); + if (received == SOCKET_ERROR) { + WSAGetLastError(); + return false; + } + if (!received) { + return false; + } + size = received; + return true; +} + +#endif diff --git a/Engine/Source/Frame/CSimpleModel_Scripts.cpp b/Engine/Source/Frame/CSimpleModel_Scripts.cpp index 40fff79..aa1cc32 100644 --- a/Engine/Source/Frame/CSimpleModel_Scripts.cpp +++ b/Engine/Source/Frame/CSimpleModel_Scripts.cpp @@ -71,7 +71,7 @@ int32_t FrameScript_GetColorNoAlpha(lua_State* L, int32_t index, CImVector& colo return index; } -// VERIFY: cb764878 auto +// VERIFY: e336fe44 auto // OFFSET: 0x00960530 static int32_t Script_SetModel(lua_State* L) { CSimpleModel* model = static_cast(FrameScript_GetObjectThis(L, CSimpleModel::GetObjectType())); diff --git a/Engine/Source/FrameScript/FrameScript_Scripts.cpp b/Engine/Source/FrameScript/FrameScript_Scripts.cpp index b4488ed..b157c9e 100644 --- a/Engine/Source/FrameScript/FrameScript_Scripts.cpp +++ b/Engine/Source/FrameScript/FrameScript_Scripts.cpp @@ -130,7 +130,7 @@ static int32_t Script_strsplit(lua_State* L) { return count + 1; } -// VERIFY: d9d09017 auto +// VERIFY: cad68086 auto // OFFSET: 0x00816B60 static int32_t Script_strjoin(lua_State* L) { size_t length; @@ -249,7 +249,7 @@ static int32_t Script_issecure(lua_State* L) { return 1; } -// VERIFY: ace6c122 auto +// VERIFY: ed335c44 auto // OFFSET: 0x00816DE0 static int32_t Script_issecurevariable(lua_State* L) { if (lua_type(L, 1) != LUA_TTABLE) { @@ -347,7 +347,7 @@ static int32_t Script_securecall(lua_State* L) { return top; } -// VERIFY: 622ed2b1 auto +// VERIFY: 458bba82 auto // OFFSET: 0x00817170 static int32_t Script_hooksecurefunc(lua_State* L) { if (lua_type(L, 1) != LUA_TTABLE) { @@ -702,7 +702,7 @@ static int32_t Script_scrub(lua_State* L) { return top; } -// VERIFY: 6b683ae5 auto +// VERIFY: d7c57f5a auto // OFFSET: 0x00817C70 static int32_t Script_strlenutf8(lua_State* L) { if (!lua_isstring(L, 1)) { diff --git a/Engine/Source/SoundEngine/SoundEngine.cpp b/Engine/Source/SoundEngine/SoundEngine.cpp index 2fd3741..e8ed782 100644 --- a/Engine/Source/SoundEngine/SoundEngine.cpp +++ b/Engine/Source/SoundEngine/SoundEngine.cpp @@ -286,6 +286,16 @@ static void F_CALLBACK FSoundFreeCallback(void* ptr, FMOD_MEMORY_TYPE type) { SMemFree(ptr, "FMod", 0, 0); } +// VERIFY: 8b89c458 manual +// OFFSET: 0x00887370 +SEStreamCallbacks::~SEStreamCallbacks() { +} + +// VERIFY: d276738b auto +// OFFSET: 0x005EEB70 +void SEStreamCallbacks::Delete() { +} + // VERIFY: 762ff4ed manual // OFFSET: 0x00878110 void SEStreamCallbacks::DiscardSamples(uint32_t position, uint32_t count) { diff --git a/Engine/Source/SoundEngine/fmodex/src/fmod_dsp_sfxreverb.cpp b/Engine/Source/SoundEngine/fmodex/src/fmod_dsp_sfxreverb.cpp index 83a3ad6..9cc55ba 100644 --- a/Engine/Source/SoundEngine/fmodex/src/fmod_dsp_sfxreverb.cpp +++ b/Engine/Source/SoundEngine/fmodex/src/fmod_dsp_sfxreverb.cpp @@ -503,7 +503,7 @@ FMOD_RESULT DSPSfxReverb::readInternal(float *inbuffer, float *outbuffer, unsign [SEE_ALSO] ] */ -// VERIFY: 0f365b7d auto +// VERIFY: e791a70f auto // OFFSET: 0x008E8FB0 FMOD_RESULT DSPSfxReverb::setParameterInternal(int index, float value) { diff --git a/Engine/Source/Storm/H/stpl.h b/Engine/Source/Storm/H/stpl.h index eb942c8..f9876a7 100644 --- a/Engine/Source/Storm/H/stpl.h +++ b/Engine/Source/Storm/H/stpl.h @@ -727,7 +727,7 @@ void TSFixedArray::ReallocAndClearData(uint32_t count) { } // VERIFY: e2efd710 manual -// OFFSET: [0x00403760, 0x004037F0, 0x00408340, 0x004083F0, 0x00408490, 0x00408D80, 0x004644C0, 0x004657D0, 0x00466910, 0x0047CCC0, 0x0047D9F0, 0x0047DA80, 0x00480EE0, 0x004827C0, 0x00490A80, 0x00493A40, 0x00493AD0, 0x00496680, 0x00497970, 0x00497A00>*>, 0x004B7580, 0x004B9990, 0x004B9A20, 0x004BB060, 0x004BBDA0, 0x004BBF00, 0x004BC060, 0x004BE170, 0x004BEBB0, 0x004C00B0, 0x004C46C0, 0x004C4750, 0x004CA380, 0x004CB930, 0x004CB9C0, 0x004CC360, 0x004CC4C0, 0x004CDB20, 0x004CEA00, 0x004CEAA0, 0x004CEF00, 0x004D0910, 0x004D2D90, 0x004D34A0, 0x004D4FF0, 0x004D85A0, 0x004DE520, 0x004E0EC0, 0x004E25C0, 0x004E6660, 0x004F2FB0, 0x004FCFC0, 0x004FD050, 0x004FD150, 0x004FFCE0, 0x005014A0, 0x005023E0, 0x00502540, 0x005026A0, 0x00502800, 0x005034E0, 0x00514100, 0x005141A0, 0x0051A2E0, 0x00525720, 0x00525880, 0x00527D10, 0x0052EF00, 0x0053B790, 0x0053B820, 0x0053EFA0, 0x005436A0, 0x00547C20, 0x00548640, 0x005489C0, 0x0054EC50, 0x0054ECF0, 0x00553220, 0x005532C0, 0x00553350, 0x005533E0, 0x00558710, 0x00558870, 0x0055EAD0, 0x0055EC30, 0x0055ED90, 0x0055EEF0, 0x0055F050, 0x00564CE0, 0x00566790, 0x005685D0, 0x0056BAD0, 0x0056BD40, 0x0056D780, 0x0056D810, 0x00575DC0, 0x00577410, 0x0057C120, 0x0057C1B0, 0x0057E360, 0x0057E400, 0x0058E030, 0x0058F8F0, 0x005907A0, 0x00590870>, 0x00590920, 0x005909C0, 0x00590A60, 0x00591F70, 0x00592180, 0x00592290, 0x00593FC0, 0x00594050, 0x00599030, 0x0059B150, 0x0059B1F0, 0x005A2AF0, 0x005A46F0, 0x005B49B0, 0x005B4B10, 0x005B8C80, 0x005BDF60, 0x005BE0C0, 0x005C58D0, 0x005C5960, 0x005C6C60, 0x005C6DC0, 0x005C9080, 0x005CA3D0, 0x005CD240, 0x005CD2D0, 0x005CEB50, 0x005CFFB0, 0x005D0080, 0x005D0110, 0x005D2360, 0x005D3260, 0x005DA3F0, 0x005DA480, 0x005DA510, 0x005E6E40, 0x005E7940, 0x005ED620, 0x005EEB80, 0x005F0240, 0x005F0440, 0x005F1420, 0x005F39B0, 0x005F4E30, 0x005F5020, 0x005F5180, 0x005F52E0, 0x005FC9C0, 0x005FEF70, 0x0060A1C0, 0x0060A260, 0x006152E0, 0x006169A0, 0x00616C20, 0x00617280, 0x006173E0, 0x00617540, 0x0061BD20, 0x0061BDB0, 0x00634790, 0x00634820, 0x00669EB0, 0x0066CD10, 0x0066CE70, 0x0066CFD0, 0x0066D130, 0x0066D290, 0x0066D3F0, 0x0066D550, 0x0066D6B0, 0x0066D810, 0x0066D970, 0x0066DAD0, 0x0066DC30, 0x0066DD90, 0x0066DEF0, 0x0066E050, 0x00681800, 0x006822B0, 0x00683760, 0x00683810, 0x006838B0, 0x00683960, 0x00688040, 0x00689F90, 0x006A54A0, 0x006A9440, 0x006B1EF0, 0x006BA590, 0x006BBBE0, 0x006C26E0, 0x006C2840, 0x006C4210, 0x006C4E20, 0x006C5EE0, 0x006C5F80, 0x006C6020, 0x006C8220, 0x006C9DF0, 0x006CF4A0, 0x006CF540, 0x006CF5E0, 0x006E4BF0, 0x006E4D50, 0x006F2120, 0x006F2280, 0x006F23E0, 0x006F2540, 0x006F26A0, 0x006F2800, 0x006F2960, 0x006FECD0, 0x00709580, 0x007096E0, 0x00716260, 0x00716300, 0x007163B0, 0x0072FE60, 0x00746400, 0x00747C10, 0x00747CA0, 0x007583D0, 0x00767490, 0x00768460, 0x00769D80, 0x0076D060, 0x007760A0<_SOURCE>, 0x00776950, 0x00786B90, 0x00790250, 0x007902E0, 0x00790370, 0x007917D0, 0x00791870, 0x0079B370, 0x0079BA30, 0x0079D510, 0x0079F650, 0x007A01C0, 0x007B0370, 0x007B0D60, 0x007B0DF0, 0x007B0E80, 0x007B4F10, 0x007BA120, 0x007BDFE0, 0x007BE140, 0x007C30B0, 0x007CC020, 0x007CCBE0, 0x007CCC80, 0x007CDEC0, 0x007DBB10, 0x007DBBC0, 0x007DD0A0, 0x007DD200, 0x007E0050, 0x007E6600, 0x007E7FF0, 0x007EBEA0, 0x007ECFF0, 0x007F1F80, 0x007F3BF0, 0x007F3D70, 0x007F4CF0, 0x007F78F0, 0x007F79C0, 0x007F8E30, 0x007F9F80, 0x007FA020, 0x007FA0B0, 0x00804830, 0x00804990, 0x00810370, 0x00810500, 0x00810660, 0x008107C0, 0x008128D0, 0x00812A30, 0x00814800, 0x008196A0, 0x0081A2F0, 0x0081CDC0, 0x00824660, 0x00824700, 0x00848890, 0x0084B140, 0x0084B2A0, 0x008555E0, 0x0086D0E0, 0x0086E8E0, 0x008704B0, 0x00876370, 0x00878E90, 0x00878F30, 0x0087AEB0, 0x00887490, 0x008A17D0, 0x008A1860, 0x008A18F0, 0x00959260, 0x0095E2C0, 0x009633C0, 0x00967E50, 0x00967EF0, 0x009690F0, 0x00969540, 0x00978EC0, 0x0097BBE0, 0x0097F650, 0x00980EE0, 0x009A80F0, 0x009A8D50, 0x009A8DF0, 0x0040A800] +// OFFSET: [0x00403760, 0x004037F0, 0x00408340, 0x004083F0, 0x00408490, 0x00408D80, 0x004644C0, 0x004657D0, 0x00466910, 0x0047CCC0, 0x0047D9F0, 0x0047DA80, 0x00480EE0, 0x004827C0, 0x00490A80, 0x00493A40, 0x00493AD0, 0x00496680, 0x00497970, 0x00497A00>*>, 0x004B7580, 0x004B9990, 0x004B9A20, 0x004BB060, 0x004BBDA0, 0x004BBF00, 0x004BC060, 0x004BE170, 0x004BEBB0, 0x004C00B0, 0x004C46C0, 0x004C4750, 0x004CA380, 0x004CB930, 0x004CB9C0, 0x004CC360, 0x004CC4C0, 0x004CDB20, 0x004CEA00, 0x004CEAA0, 0x004CEF00, 0x004D0910, 0x004D2D90, 0x004D34A0, 0x004D4FF0, 0x004D85A0, 0x004DE520, 0x004E0EC0, 0x004E25C0, 0x004E6660, 0x004F2FB0, 0x004FCFC0, 0x004FD050, 0x004FD150, 0x004FFCE0, 0x005014A0, 0x005023E0, 0x00502540, 0x005026A0, 0x00502800, 0x005034E0, 0x00514100, 0x005141A0, 0x0051A2E0, 0x00525720, 0x00525880, 0x00527D10, 0x0052EF00, 0x0053B790, 0x0053B820, 0x0053EFA0, 0x005436A0, 0x00547C20, 0x00548640, 0x005489C0, 0x0054EC50, 0x0054ECF0, 0x00553220, 0x005532C0, 0x00553350, 0x005533E0, 0x00558710, 0x00558870, 0x0055EAD0, 0x0055EC30, 0x0055ED90, 0x0055EEF0, 0x0055F050, 0x00564CE0, 0x00566790, 0x005685D0, 0x0056BAD0, 0x0056BD40, 0x0056D780, 0x0056D810, 0x00575DC0, 0x00577410, 0x0057C120, 0x0057C1B0, 0x0057E360, 0x0057E400, 0x0058E030, 0x0058F8F0, 0x005907A0, 0x00590870>, 0x00590920, 0x005909C0, 0x00590A60, 0x00591F70, 0x00592180, 0x00592290, 0x00593FC0, 0x00594050, 0x00599030, 0x0059B150, 0x0059B1F0, 0x005A2AF0, 0x005A46F0, 0x005B49B0, 0x005B4B10, 0x005B8C80, 0x005BDF60, 0x005BE0C0, 0x005C58D0, 0x005C5960, 0x005C6C60, 0x005C6DC0, 0x005C9080, 0x005CA3D0, 0x005CD240, 0x005CD2D0, 0x005CEB50, 0x005CFFB0, 0x005D0080, 0x005D0110, 0x005D2360, 0x005D3260, 0x005DA3F0, 0x005DA480, 0x005DA510, 0x005E6E40, 0x005E7940, 0x005ED620, 0x005EEB80, 0x005F0240, 0x005F0440, 0x005F1420, 0x005F39B0, 0x005F4E30, 0x005F5020, 0x005F5180, 0x005F52E0, 0x005FC9C0, 0x005FEF70, 0x0060A1C0, 0x0060A260, 0x006152E0, 0x006169A0, 0x00616C20, 0x00617280, 0x006173E0, 0x00617540, 0x0061BD20, 0x0061BDB0, 0x00634790, 0x00634820, 0x00669EB0, 0x0066CD10, 0x0066CE70, 0x0066CFD0, 0x0066D130, 0x0066D290, 0x0066D3F0, 0x0066D550, 0x0066D6B0, 0x0066D810, 0x0066D970, 0x0066DAD0, 0x0066DC30, 0x0066DD90, 0x0066DEF0, 0x0066E050, 0x00681800, 0x006822B0, 0x00683760, 0x00683810, 0x006838B0, 0x00683960, 0x00688040, 0x00689F90, 0x006A54A0, 0x006A9440, 0x006B1EF0, 0x006BA590, 0x006BBBE0, 0x006C26E0, 0x006C2840, 0x006C4210, 0x006C4E20, 0x006C5EE0, 0x006C5F80, 0x006C6020, 0x006C8220, 0x006C9DF0, 0x006CF4A0, 0x006CF540, 0x006CF5E0, 0x006E4BF0, 0x006E4D50, 0x006F2120, 0x006F2280, 0x006F23E0, 0x006F2540, 0x006F26A0, 0x006F2800, 0x006F2960, 0x006FECD0, 0x00709580, 0x007096E0, 0x00716260, 0x00716300, 0x007163B0, 0x0072FE60, 0x00746400, 0x00747C10, 0x00747CA0, 0x007583D0, 0x00767490, 0x00768460, 0x00769D80, 0x0076D060, 0x007760A0<_SOURCE>, 0x00776950, 0x00786B90, 0x00790250, 0x007902E0, 0x00790370, 0x007917D0, 0x00791870, 0x0079B370, 0x0079BA30, 0x0079D510, 0x0079F650, 0x007A01C0, 0x007B0370, 0x007B0D60, 0x007B0DF0, 0x007B0E80, 0x007B4F10, 0x007BA120, 0x007BDFE0, 0x007BE140, 0x007C30B0, 0x007CC020, 0x007CCBE0, 0x007CCC80, 0x007CDEC0, 0x007DBB10, 0x007DBBC0, 0x007DD0A0, 0x007DD200, 0x007E0050, 0x007E6600, 0x007E7FF0, 0x007EBEA0, 0x007ECFF0, 0x007F1F80, 0x007F3BF0, 0x007F3D70, 0x007F4CF0, 0x007F78F0, 0x007F79C0, 0x007F8E30, 0x007F9F80, 0x007FA020, 0x007FA0B0, 0x00804830, 0x00804990, 0x00810370, 0x00810500, 0x00810660, 0x008107C0, 0x008128D0, 0x00812A30, 0x00814800, 0x008196A0, 0x0081A2F0, 0x0081CDC0, 0x00824660, 0x00824700, 0x00848890, 0x0084B140, 0x0084B2A0, 0x008555E0, 0x0086D0E0, 0x0086E8E0, 0x008704B0, 0x00876370, 0x00878E90, 0x00878F30, 0x0087AEB0, 0x00887490, 0x008A17D0, 0x008A1860, 0x008A18F0, 0x00959260, 0x0095E2C0, 0x009633C0, 0x00967E50, 0x00967EF0, 0x009690F0, 0x00969540, 0x00978EC0, 0x0097BBE0, 0x0097F650, 0x00980EE0, 0x009A80F0, 0x009A8D50, 0x009A8DF0, 0x0040A800, 0x008C64B0, 0x008C6550] template void TSFixedArray::ReallocData(uint32_t count) { T* olddata = this->m_data; diff --git a/Engine/Source/lua-5.1/src/lbaselib.c b/Engine/Source/lua-5.1/src/lbaselib.c index 41b7a2d..1d3c3d4 100644 --- a/Engine/Source/lua-5.1/src/lbaselib.c +++ b/Engine/Source/lua-5.1/src/lbaselib.c @@ -118,7 +118,7 @@ static void getfunc (lua_State *L) { } -// VERIFY: 9bb620ce auto +// VERIFY: fa88bdc8 auto // OFFSET: 0x008543E0 static int luaB_getfenv (lua_State *L) { getfunc(L); diff --git a/WoW/Source/Battlenet/BSN/BSNCpp.cpp b/WoW/Source/Battlenet/BSN/BSNCpp.cpp new file mode 100644 index 0000000..e484d03 --- /dev/null +++ b/WoW/Source/Battlenet/BSN/BSNCpp.cpp @@ -0,0 +1,152 @@ +#include "WoW/Source/Battlenet/BSN/Protocol.h" + +// STATIC: 0x00A50650 +const BSN::Utf8Sequence BSN::s_utf8Sequences[9] = { + { 1, { { 0x01, 0x7F }, { 0x00, 0x00 }, { 0x00, 0x00 }, { 0x00, 0x00 } } }, + { 2, { { 0xC2, 0xDF }, { 0x80, 0xBF }, { 0x00, 0x00 }, { 0x00, 0x00 } } }, + { 3, { { 0xE0, 0xE0 }, { 0xA0, 0xBF }, { 0x80, 0xBF }, { 0x00, 0x00 } } }, + { 3, { { 0xE1, 0xEC }, { 0x80, 0xBF }, { 0x80, 0xBF }, { 0x00, 0x00 } } }, + { 3, { { 0xED, 0xED }, { 0x80, 0x9F }, { 0x80, 0xBF }, { 0x00, 0x00 } } }, + { 3, { { 0xEE, 0xEF }, { 0x80, 0xBF }, { 0x80, 0xBF }, { 0x00, 0x00 } } }, + { 4, { { 0xF0, 0xF0 }, { 0x90, 0xBF }, { 0x80, 0xBF }, { 0x80, 0xBF } } }, + { 4, { { 0xF1, 0xF3 }, { 0x80, 0xBF }, { 0x80, 0xBF }, { 0x80, 0xBF } } }, + { 4, { { 0xF4, 0xF4 }, { 0x80, 0x8F }, { 0x80, 0xBF }, { 0x80, 0xBF } } }, +}; + +// INLINED +BSN::FourCC::FourCC() { + this->m_value = 0; +} + +// VERIFY: 612ba6d5 manual +// OFFSET: 0x008BFD00 +BSN::FourCC::FourCC(const char* string) { + this->m_value = 0; + + for (; *string; string++) { + this->m_value = (this->m_value << 8) | static_cast(*string); + } +} + +// VERIFY: 7945e18c auto +// OFFSET: 0x005309C0 +void BSN::FourCC::ToString(char* dest, uint32_t size) const { + uint32_t index = 3; + + for (int32_t shift = 24; shift >= 0; shift -= 8) { + if (index >= 4) { + SErrDisplayAppFatalMessage("", "", 0); + } + + uint32_t c = this->m_value >> shift; + + if (c && size--) { + *dest++ = static_cast(c); + } + + index--; + } + + if (size) { + *dest = '\0'; + } +} + +// VERIFY: f06c475f auto +// OFFSET: 0x00888F70 +uint32_t BSN::AsciiStringCopy(char* dest, const char* source, uint32_t maxLength) { + char* out = dest; + + while (maxLength) { + maxLength--; + + if (!*source) { + break; + } + + *out++ = *source++; + } + + *out = '\0'; + return static_cast(out - dest); +} + +// VERIFY: 65b62442 manual +// OFFSET: 0x00888FB0 +uint32_t BSN::UTF8StringCopy(char* dest, const char* source, uint32_t maxChars, uint32_t& length) { + char* out = dest; + uint32_t count = 0; + + for (; maxChars; maxChars--) { + char c = *source++; + uint32_t extra; + + if (c < 0) { + if ((c & 0xE0) == 0xC0) { + extra = 1; + } else if ((c & 0xF0) == 0xE0) { + extra = 2; + } else if ((c & 0xF8) == 0xF0) { + extra = 3; + } else { + break; + } + } else { + if (!c) { + break; + } + + extra = 0; + } + + char* start = out; + *out++ = c; + + while (extra) { + char next = *source; + extra--; + source++; + + if ((next & 0xC0) != 0x80) { + out = start; + break; + } + + *out++ = next; + } + + count++; + } + + *out = '\0'; + length = static_cast(out - dest); + return count; +} + +// VERIFY: 0ff918da auto +// OFFSET: 0x0088A240 +void BSN::Cpp::ReadInt(const void* data, uint32_t size, bool isSigned, uint64_t& value) { + const uint8_t* bytes = static_cast(data); + + if (isSigned && bytes[size - 1] >= 0x80) { + value = static_cast(-1); + } else { + value = 0; + } + + while (size) { + size--; + value = (value << 8) | bytes[size]; + } +} + +// VERIFY: 2efe51e9 auto +// OFFSET: 0x0088A2A0 +void BSN::Cpp::WriteInt(uint64_t value, uint32_t size, void* data) { + uint8_t* bytes = static_cast(data); + + for (; size; size--) { + *bytes++ = static_cast(value); + value >>= 8; + } +} diff --git a/WoW/Source/Battlenet/BSN/BSNEncodeInterface.cpp b/WoW/Source/Battlenet/BSN/BSNEncodeInterface.cpp new file mode 100644 index 0000000..1fc28e3 --- /dev/null +++ b/WoW/Source/Battlenet/BSN/BSNEncodeInterface.cpp @@ -0,0 +1,963 @@ +#include "WoW/Source/Battlenet/BSN/BSNEncodeInterface.h" +#include +#include + +// VERIFY: 2c86983e manual +// OFFSET: 0x00530B00 +void BSN::EncodeContext::ResolveType() { + if (!this->m_protocol || !this->m_typeId) { + return; + } + + this->m_header = BSN::Protocol::Meta::Base(this->m_protocol, this->m_typeId).m_header & 0x3F; + + while (this->m_header == BSN::META_USER) { + this->m_typeId = BSN::Protocol::Meta::User(this->m_protocol, this->m_typeId).m_userTypeId; + this->m_header = BSN::Protocol::Meta::Base(this->m_protocol, this->m_typeId).m_header & 0x3F; + } +} + +// VERIFY: 1cd08270 manual +// OFFSET: 0x00531150 +BSN::PrimitiveEncoder::~PrimitiveEncoder() { +} + +// VERIFY: c9d390cd auto +// OFFSET: 0x008BE480 +uint32_t BSN::BSNPrimitiveEncoder::GetContextSize() const { + return sizeof(EncodeContext); +} + +// VERIFY: 78a347d2 manual +// OFFSET: 0x00889420 +BSN::EncodeContext* BSN::BSNPrimitiveEncoder::ConstructContext(void* memory) const { + if (!memory) { + return nullptr; + } + + EncodeContext* context = static_cast(memory); + context->m_protocol = nullptr; + context->m_typeId = 0; + context->m_data = context; + context->ResolveType(); + return context; +} + +// VERIFY: 2b1d3d87 auto +// OFFSET: 0x00632050 +void BSN::BSNPrimitiveEncoder::DestroyContext(EncodeContext* context) const { +} + +// VERIFY: ca67d88c manual +// OFFSET: 0x00889060 +uint64_t BSN::BSNPrimitiveEncoder::GetUInt(const EncodeContext* context) const { + uint64_t value; + + if (context->m_header == BSN::META_INT) { + BSN::Protocol::Meta::Int meta(context->m_protocol, context->m_typeId); + BSN::Cpp::ReadInt(context->m_data, static_cast(reinterpret_cast(meta.m_codeInfo[0])), (meta.m_bounds.m_intType & 1) == 0, value); + return value; + } + + if (context->m_header == BSN::META_ENUM) { + BSN::Protocol::Meta::Enum meta(context->m_protocol, context->m_typeId); + BSN::Cpp::ReadInt(context->m_data, static_cast(reinterpret_cast(meta.m_codeInfo[0])), (meta.m_bounds.m_intType & 1) == 0, value); + return value; + } + + return 0; +} + +// VERIFY: 89060b43 auto +// OFFSET: 0x00889100 +int64_t BSN::BSNPrimitiveEncoder::GetInt(const EncodeContext* context) const { + return this->GetUInt(context); +} + +// VERIFY: b12cc6f5 auto +// OFFSET: 0x00889110 +bool BSN::BSNPrimitiveEncoder::GetBool(const EncodeContext* context) const { + if (context->m_header != BSN::META_BOOL) { + return false; + } + + BSN::Protocol::Meta::Bool meta(context->m_protocol, context->m_typeId); + uint64_t value; + BSN::Cpp::ReadInt(context->m_data, static_cast(reinterpret_cast(meta.m_codeInfo[0])), false, value); + return value != 0; +} + +// VERIFY: 94855040 auto +// OFFSET: 0x00889170 +double BSN::BSNPrimitiveEncoder::GetReal(const EncodeContext* context) const { + if (context->m_header == BSN::META_REAL32) { + BSN::Protocol::Meta::Real32 meta(context->m_protocol, context->m_typeId); + return *static_cast(context->m_data); + } + + if (context->m_header == BSN::META_REAL64) { + BSN::Protocol::Meta::Real64 meta(context->m_protocol, context->m_typeId); + return *static_cast(context->m_data); + } + + return 0.0; +} + +// VERIFY: da6fb5a5 manual +// OFFSET: 0x00889450 +uint32_t BSN::BSNPrimitiveEncoder::GetFourCC(const EncodeContext* context) const { + if (context->m_header != BSN::META_FOURCC) { + return 0; + } + + BSN::Protocol::Meta::FourCC meta(context->m_protocol, context->m_typeId); + return reinterpret_cast(meta.m_codeInfo[0])(context->m_data); +} + +// VERIFY: 5d67be71 auto +// OFFSET: 0x00889490 +uint32_t BSN::BSNPrimitiveEncoder::GetStringLength(const EncodeContext* context) const { + if (context->m_header == BSN::META_ASCII_STRING) { + BSN::Protocol::Meta::AsciiString meta(context->m_protocol, context->m_typeId); + return reinterpret_cast(meta.m_codeInfo[0])(context->m_data); + } + + if (context->m_header == BSN::META_STRING) { + BSN::Protocol::Meta::String meta(context->m_protocol, context->m_typeId); + return reinterpret_cast(meta.m_codeInfo[0])(context->m_data); + } + + return 0; +} + +// VERIFY: 471108be manual +// OFFSET: 0x00889500 +bool BSN::BSNPrimitiveEncoder::GetString(const EncodeContext* context, char* buffer, uint32_t size) const { + if (context->m_header == BSN::META_ASCII_STRING) { + BSN::Protocol::Meta::AsciiString meta(context->m_protocol, context->m_typeId); + uint32_t length = reinterpret_cast(meta.m_codeInfo[0])(context->m_data); + + if (length >= size) { + length = size - 1; + } + + memcpy(buffer, reinterpret_cast(meta.m_codeInfo[1])(context->m_data), length); + buffer[length] = '\0'; + return true; + } + + if (context->m_header == BSN::META_STRING) { + BSN::Protocol::Meta::String meta(context->m_protocol, context->m_typeId); + uint32_t length = reinterpret_cast(meta.m_codeInfo[0])(context->m_data); + + if (length >= size) { + length = size - 1; + } + + memcpy(buffer, reinterpret_cast(meta.m_codeInfo[1])(context->m_data), length); + buffer[length] = '\0'; + return true; + } + + *buffer = '\0'; + return false; +} + +// VERIFY: 53abd1d2 manual +// OFFSET: 0x008895D0 +uint32_t BSN::BSNPrimitiveEncoder::GetBitArrayLength(const EncodeContext* context) const { + if (context->m_header != BSN::META_BIT_ARRAY) { + return 0; + } + + BSN::Protocol::Meta::BitArray meta(context->m_protocol, context->m_typeId); + return reinterpret_cast(meta.m_codeInfo[0])(context->m_data); +} + +// VERIFY: 8283051f auto +// OFFSET: 0x00889610 +bool BSN::BSNPrimitiveEncoder::GetBitArray(const EncodeContext* context, uint8_t* buffer, uint32_t bits) const { + if (context->m_header != BSN::META_BIT_ARRAY) { + return false; + } + + BSN::Protocol::Meta::BitArray meta(context->m_protocol, context->m_typeId); + uint32_t length = reinterpret_cast(meta.m_codeInfo[0])(context->m_data); + + if (length > bits) { + length = bits; + } + + memcpy(buffer, reinterpret_cast(meta.m_codeInfo[1])(context->m_data), (length + 7) >> 3); + return true; +} + +// VERIFY: d604ed4a manual +// OFFSET: 0x00889680 +uint32_t BSN::BSNPrimitiveEncoder::GetBlobLength(const EncodeContext* context) const { + if (context->m_header != BSN::META_BLOB) { + return 0; + } + + BSN::Protocol::Meta::Blob meta(context->m_protocol, context->m_typeId); + return reinterpret_cast(meta.m_codeInfo[0])(context->m_data); +} + +// VERIFY: 19cebf40 auto +// OFFSET: 0x008896C0 +bool BSN::BSNPrimitiveEncoder::GetBlob(const EncodeContext* context, uint8_t* buffer, uint32_t size) const { + if (context->m_header != BSN::META_BLOB) { + return false; + } + + BSN::Protocol::Meta::Blob meta(context->m_protocol, context->m_typeId); + uint32_t length = reinterpret_cast(meta.m_codeInfo[0])(context->m_data); + + if (length > size) { + length = size; + } + + memcpy(buffer, reinterpret_cast(meta.m_codeInfo[1])(context->m_data), length); + return true; +} + +// VERIFY: cf04e8bf manual +// OFFSET: 0x00889730 +bool BSN::BSNPrimitiveEncoder::GetMemberContext(const EncodeContext* context, const char* name, EncodeContext* member) const { + member->m_protocol = context->m_protocol; + + if (context->m_header == BSN::META_CHOICE) { + BSN::Protocol::Meta::Choice meta(context->m_protocol, context->m_typeId); + uint32_t count = meta.m_count; + + if (!count) { + return false; + } + + uint32_t field = 0; + + while (strcmp(meta.m_protocol->DumpString(meta.m_dumpInfo, field + 1), name)) { + if (++field >= count) { + return false; + } + } + + if (!meta.GetFieldTypeId(field, member->m_typeId)) { + return false; + } + + member->ResolveType(); + member->m_data = reinterpret_cast(meta.m_codeInfo[2])(context->m_data); + return true; + } + + if (context->m_header == BSN::META_OPTIONAL) { + BSN::Protocol::Meta::Optional meta(context->m_protocol, context->m_typeId); + + if (!reinterpret_cast(meta.m_codeInfo[0])(context->m_data)) { + return false; + } + + member->m_typeId = meta.m_elementTypeId; + member->ResolveType(); + member->m_data = const_cast(reinterpret_cast(meta.m_codeInfo[1])(context->m_data)); + return true; + } + + if (context->m_header == BSN::META_STRUCT) { + BSN::Protocol::Meta::Struct meta(context->m_protocol, context->m_typeId); + uint32_t count = meta.m_count; + + if (!count) { + return false; + } + + uint32_t index = 0; + + while (strcmp(meta.m_protocol->DumpString(meta.m_dumpInfo, index + 1), name)) { + if (++index >= count) { + return false; + } + } + + uint32_t offset; + + if (!meta.GetMember(index, offset, member->m_typeId)) { + return false; + } + + member->ResolveType(); + member->m_data = static_cast(context->m_data) + offset; + return true; + } + + return false; +} + +// VERIFY: a771d440 auto +// OFFSET: 0x00889920 +bool BSN::BSNPrimitiveEncoder::GetElementContext(const EncodeContext* context, uint32_t index, EncodeContext* element) const { + element->m_protocol = context->m_protocol; + + if (context->m_header != BSN::META_ARRAY) { + return false; + } + + BSN::Protocol::Meta::Array meta(context->m_protocol, context->m_typeId); + + if (index >= reinterpret_cast(meta.m_codeInfo[1])(context->m_data)) { + return false; + } + + element->m_typeId = meta.m_elementTypeId; + element->ResolveType(); + + uint32_t elementSize = static_cast(reinterpret_cast(meta.m_codeInfo[0])); + element->m_data = const_cast(static_cast(reinterpret_cast(meta.m_codeInfo[2])(context->m_data))) + index * elementSize; + return true; +} + +// VERIFY: 2ff35390 auto +// OFFSET: 0x008899A0 +bool BSN::BSNPrimitiveEncoder::GetChoiceName(const EncodeContext* context, char* buffer, uint32_t size) const { + if (context->m_header == BSN::META_CHOICE) { + BSN::Protocol::Meta::Choice meta(context->m_protocol, context->m_typeId); + int32_t tag = reinterpret_cast(meta.m_codeInfo[1])(context->m_data); + uint32_t field; + + if (meta.GetTagField(static_cast(tag), field)) { + const char* name = meta.m_protocol->DumpString(meta.m_dumpInfo, field + 1); + uint32_t length = static_cast(strlen(name)); + + if (length >= size) { + length = size - 1; + } + + memcpy(buffer, name, length); + buffer[length] = '\0'; + return true; + } + } + + *buffer = '\0'; + return false; +} + +// VERIFY: e10235e0 manual +// OFFSET: 0x00889A50 +uint32_t BSN::BSNPrimitiveEncoder::GetArrayLength(const EncodeContext* context) const { + if (context->m_header != BSN::META_ARRAY) { + return 0; + } + + BSN::Protocol::Meta::Array meta(context->m_protocol, context->m_typeId); + return reinterpret_cast(meta.m_codeInfo[1])(context->m_data); +} + +// VERIFY: e85768a5 manual +// OFFSET: 0x00889A90 +bool BSN::BSNPrimitiveEncoder::GetOptional(const EncodeContext* context) const { + if (context->m_header != BSN::META_OPTIONAL) { + return false; + } + + BSN::Protocol::Meta::Optional meta(context->m_protocol, context->m_typeId); + return reinterpret_cast(meta.m_codeInfo[0])(context->m_data); +} + +// VERIFY: 249005f2 manual +// OFFSET: 0x008891D0 +bool BSN::BSNPrimitiveEncoder::SetUInt(EncodeContext* context, uint64_t value) const { + if (context->m_header == BSN::META_INT) { + BSN::Protocol::Meta::Int meta(context->m_protocol, context->m_typeId); + + if (meta.m_bounds.Contains(value)) { + BSN::Cpp::WriteInt(value, static_cast(reinterpret_cast(meta.m_codeInfo[0])), context->m_data); + return true; + } + } + + if (context->m_header == BSN::META_ENUM) { + BSN::Protocol::Meta::Enum meta(context->m_protocol, context->m_typeId); + uint32_t field; + + if (meta.GetEnumField(value, field) || (meta.m_bounds.m_variable && meta.m_bounds.Contains(value))) { + BSN::Cpp::WriteInt(value, static_cast(reinterpret_cast(meta.m_codeInfo[0])), context->m_data); + return true; + } + } + + return false; +} + +// VERIFY: ffa44e1e auto +// OFFSET: 0x00889290 +bool BSN::BSNPrimitiveEncoder::SetInt(EncodeContext* context, int64_t value) const { + return this->SetUInt(context, value); +} + +// VERIFY: 2fa56178 manual +// OFFSET: 0x008892B0 +bool BSN::BSNPrimitiveEncoder::SetBool(EncodeContext* context, bool value) const { + if (context->m_header != BSN::META_BOOL) { + return false; + } + + BSN::Protocol::Meta::Bool meta(context->m_protocol, context->m_typeId); + BSN::Cpp::WriteInt(value, static_cast(reinterpret_cast(meta.m_codeInfo[0])), context->m_data); + return true; +} + +// VERIFY: 99da62a2 auto +// OFFSET: 0x00889300 +bool BSN::BSNPrimitiveEncoder::SetReal(EncodeContext* context, double value) const { + if (context->m_header == BSN::META_REAL32) { + *static_cast(context->m_data) = static_cast(value); + return true; + } + + if (context->m_header == BSN::META_REAL64) { + *static_cast(context->m_data) = value; + return true; + } + + return false; +} + +// VERIFY: 853384b7 manual +// OFFSET: 0x00889BC0 +bool BSN::BSNPrimitiveEncoder::SetFourCC(EncodeContext* context, uint32_t value) const { + if (context->m_header != BSN::META_FOURCC) { + return false; + } + + BSN::Protocol::Meta::FourCC meta(context->m_protocol, context->m_typeId); + reinterpret_cast(meta.m_codeInfo[1])(context->m_data, value); + return true; +} + +// VERIFY: 86bd315b auto +// OFFSET: 0x00889AD0 +bool BSN::BSNPrimitiveEncoder::SetString(EncodeContext* context, const char* value) const { + if (context->m_header == BSN::META_ASCII_STRING) { + BSN::Protocol::Meta::AsciiString meta(context->m_protocol, context->m_typeId); + uint32_t length = static_cast(strlen(value)); + char* data = static_cast(reinterpret_cast(meta.m_codeInfo[2])(context->m_data, length)); + memcpy(data, value, length); + data[length] = '\0'; + return true; + } + + if (context->m_header == BSN::META_STRING) { + BSN::Protocol::Meta::String meta(context->m_protocol, context->m_typeId); + uint32_t length = static_cast(strlen(value)); + char* data = static_cast(reinterpret_cast(meta.m_codeInfo[2])(context->m_data, length)); + memcpy(data, value, length); + data[length] = '\0'; + + uint32_t count; + + if (BSN::Protocol::Meta::String::IsValid(length, reinterpret_cast(data), count)) { + reinterpret_cast(meta.m_codeInfo[3])(context->m_data, count); + return true; + } + } + + return false; +} + +// VERIFY: 4bf86d27 auto +// OFFSET: 0x00889C10 +bool BSN::BSNPrimitiveEncoder::SetBitArray(EncodeContext* context, const uint8_t* data, uint32_t bits) const { + if (context->m_header != BSN::META_BIT_ARRAY) { + return false; + } + + BSN::Protocol::Meta::BitArray meta(context->m_protocol, context->m_typeId); + + if (!meta.m_bounds.Contains(bits)) { + return false; + } + + memcpy(reinterpret_cast(meta.m_codeInfo[2])(context->m_data, bits), data, (bits + 7) >> 3); + return true; +} + +// VERIFY: 6dd0c075 auto +// OFFSET: 0x00889C80 +bool BSN::BSNPrimitiveEncoder::SetBlob(EncodeContext* context, const uint8_t* data, uint32_t size) const { + if (context->m_header != BSN::META_BLOB) { + return false; + } + + BSN::Protocol::Meta::Blob meta(context->m_protocol, context->m_typeId); + + if (!meta.m_bounds.Contains(size)) { + return false; + } + + memcpy(reinterpret_cast(meta.m_codeInfo[2])(context->m_data, size), data, size); + return true; +} + +// VERIFY: d7d51bdb auto +// OFFSET: 0x00889340 +bool BSN::BSNPrimitiveEncoder::SetStruct(EncodeContext* context, const char* name) const { + return context->m_header == BSN::META_STRUCT; +} + +// VERIFY: 41903193 manual +// OFFSET: 0x00889CF0 +bool BSN::BSNPrimitiveEncoder::SetChoice(EncodeContext* context, const char* typeName, const char* choiceName) const { + if (context->m_header != BSN::META_CHOICE) { + return false; + } + + BSN::Protocol::Meta::Choice meta(context->m_protocol, context->m_typeId); + uint32_t count = meta.m_count; + + if (!count) { + return false; + } + + uint32_t field = 0; + + while (strcmp(meta.m_protocol->DumpString(meta.m_dumpInfo, field + 1), choiceName)) { + if (++field >= count) { + return false; + } + } + + uint64_t tag; + + if (meta.GetFieldTag(field, tag)) { + reinterpret_cast(meta.m_codeInfo[3])(context->m_data, static_cast(tag)); + } + + return true; +} + +// VERIFY: 53c575c3 auto +// OFFSET: 0x00889DA0 +bool BSN::BSNPrimitiveEncoder::SetArray(EncodeContext* context, uint32_t length) const { + if (context->m_header != BSN::META_ARRAY) { + return false; + } + + BSN::Protocol::Meta::Array meta(context->m_protocol, context->m_typeId); + + if (!meta.m_bounds.Contains(length)) { + return false; + } + + reinterpret_cast(meta.m_codeInfo[3])(context->m_data, length); + return true; +} + +// VERIFY: 38a7a061 manual +// OFFSET: 0x00889E00 +bool BSN::BSNPrimitiveEncoder::SetOptional(EncodeContext* context, bool exists) const { + if (context->m_header != BSN::META_OPTIONAL) { + return false; + } + + BSN::Protocol::Meta::Optional meta(context->m_protocol, context->m_typeId); + reinterpret_cast(meta.m_codeInfo[2])(context->m_data, exists); + return true; +} + +// VERIFY: 284266a9 auto +// OFFSET: 0x00889360 +bool BSN::BSNPrimitiveEncoder::WalkAndSet(const PrimitiveEncoder* encoder, EncodeContext* context, const EncodeContext* source) const { + if (!source->m_protocol->m_dumpInfoSize) { + return false; + } + + BSNPrimitiveWalker::Context walkContext; + walkContext.m_protocol = source->m_protocol; + walkContext.m_typeId = source->m_typeId; + walkContext.m_sourceEncoder = this; + walkContext.m_sourceContext = source; + walkContext.m_targetEncoder = encoder; + walkContext.m_targetContext = context; + + BSNPrimitiveWalker walker; + return walker.Copy(walkContext) == BSN::WALK_VALID; +} + +// VERIFY: c490c34a auto +// OFFSET: 0x008893C0 +bool BSN::BSNPrimitiveEncoder::WalkAndGet(const PrimitiveEncoder* encoder, const EncodeContext* source, EncodeContext* context) const { + if (!context->m_protocol->m_dumpInfoSize) { + return false; + } + + BSNPrimitiveWalker::Context walkContext; + walkContext.m_protocol = context->m_protocol; + walkContext.m_typeId = context->m_typeId; + walkContext.m_sourceEncoder = encoder; + walkContext.m_sourceContext = source; + walkContext.m_targetEncoder = this; + walkContext.m_targetContext = context; + + BSNPrimitiveWalker walker; + return walker.Copy(walkContext) == BSN::WALK_VALID; +} + +// VERIFY: 671c3b71 manual +// OFFSET: 0x0077A200 +BSN::BSNPrimitiveWalker::~BSNPrimitiveWalker() { +} + +// VERIFY: 48a98202 auto +// OFFSET: 0x0088A2D0 +int32_t BSN::BSNPrimitiveWalker::Copy(const Context& context) { + return BSN::BSNPrimitiveWalker::Walk(*this, context); +} + +// VERIFY: c98743b2 auto +// OFFSET: 0x0088A2F0 +int32_t BSN::BSNPrimitiveWalker::Array(const Protocol::Meta::Array& meta, const Context& context) { + const PrimitiveEncoder* sourceEncoder = context.m_sourceEncoder; + const EncodeContext* sourceContext = context.m_sourceContext; + const PrimitiveEncoder* targetEncoder = context.m_targetEncoder; + EncodeContext* targetContext = context.m_targetContext; + int32_t result = BSN::WALK_VALID; + + void* sourceMemory = _alloca(sourceEncoder->GetContextSize()); + void* targetMemory = _alloca(targetEncoder->GetContextSize()); + + uint32_t length = sourceEncoder->GetArrayLength(sourceContext); + + if (!targetEncoder->SetArray(targetContext, length)) { + return BSN::WALK_INVALID; + } + + uint32_t elementTypeId = meta.m_elementTypeId; + + for (uint32_t i = 0; i < length; i++) { + if (result) { + return result; + } + + EncodeContext* sourceElement = sourceEncoder->ConstructContext(sourceMemory); + EncodeContext* targetElement = targetEncoder->ConstructContext(targetMemory); + + if (sourceEncoder->GetElementContext(sourceContext, i, sourceElement) && targetEncoder->GetElementContext(targetContext, i, targetElement)) { + Context element; + element.m_protocol = context.m_protocol; + element.m_typeId = elementTypeId; + element.m_sourceEncoder = context.m_sourceEncoder; + element.m_sourceContext = sourceElement; + element.m_targetEncoder = context.m_targetEncoder; + element.m_targetContext = targetElement; + result = BSN::BSNPrimitiveWalker::Walk(*this, element); + } else { + result = BSN::WALK_INVALID; + } + + sourceEncoder->DestroyContext(sourceElement); + targetEncoder->DestroyContext(targetElement); + } + + return result; +} + +// VERIFY: ef743b63 manual +// OFFSET: 0x0088A470 +int32_t BSN::BSNPrimitiveWalker::BitArray(const Protocol::Meta::BitArray& meta, const Context& context) { + uint32_t bits = context.m_sourceEncoder->GetBitArrayLength(context.m_sourceContext); + uint8_t* buffer = static_cast(_alloca((bits + 7) >> 3)); + return !context.m_sourceEncoder->GetBitArray(context.m_sourceContext, buffer, bits) || !context.m_targetEncoder->SetBitArray(context.m_targetContext, buffer, bits); +} + +// VERIFY: c297a372 manual +// OFFSET: 0x0088A4E0 +int32_t BSN::BSNPrimitiveWalker::Blob(const Protocol::Meta::Blob& meta, const Context& context) { + uint32_t size = context.m_sourceEncoder->GetBlobLength(context.m_sourceContext); + uint8_t* buffer = static_cast(_alloca(size)); + return !context.m_sourceEncoder->GetBlob(context.m_sourceContext, buffer, size) || !context.m_targetEncoder->SetBlob(context.m_targetContext, buffer, size); +} + +// VERIFY: 89ea671d manual +// OFFSET: 0x0088A550 +int32_t BSN::BSNPrimitiveWalker::Bool(const Protocol::Meta::Bool& meta, const Context& context) { + return !context.m_targetEncoder->SetBool(context.m_targetContext, context.m_sourceEncoder->GetBool(context.m_sourceContext)); +} + +// VERIFY: 3b9d061b manual +// OFFSET: 0x0088A590 +int32_t BSN::BSNPrimitiveWalker::Choice(const Protocol::Meta::Choice& meta, const Context& context) { + char name[1024]; + + if (!context.m_sourceEncoder->GetChoiceName(context.m_sourceContext, name, sizeof(name))) { + return BSN::WALK_INVALID; + } + + uint32_t field = 0; + uint32_t typeId = 0; + uint32_t count = meta.m_count; + + if (!count) { + return BSN::WALK_INVALID; + } + + while (strcmp(meta.m_protocol->DumpString(meta.m_dumpInfo, field + 1), name)) { + if (++field >= count) { + return BSN::WALK_INVALID; + } + } + + if (!meta.GetFieldTypeId(field, typeId)) { + return BSN::WALK_INVALID; + } + + const PrimitiveEncoder* sourceEncoder = context.m_sourceEncoder; + const EncodeContext* sourceContext = context.m_sourceContext; + EncodeContext* sourceMember = sourceEncoder->ConstructContext(_alloca(sourceEncoder->GetContextSize())); + + const PrimitiveEncoder* targetEncoder = context.m_targetEncoder; + EncodeContext* targetContext = context.m_targetContext; + EncodeContext* targetMember = targetEncoder->ConstructContext(_alloca(targetEncoder->GetContextSize())); + + int32_t result; + + if (targetEncoder->SetChoice(targetContext, meta.m_protocol->DumpString(meta.m_dumpInfo, 0), name) && sourceEncoder->GetMemberContext(sourceContext, name, sourceMember) && targetEncoder->GetMemberContext(targetContext, name, targetMember)) { + Context member; + member.m_protocol = context.m_protocol; + member.m_typeId = typeId; + member.m_sourceEncoder = context.m_sourceEncoder; + member.m_sourceContext = sourceMember; + member.m_targetEncoder = context.m_targetEncoder; + member.m_targetContext = targetMember; + result = BSN::BSNPrimitiveWalker::Walk(*this, member); + } else { + result = BSN::WALK_INVALID; + } + + sourceEncoder->DestroyContext(sourceMember); + targetEncoder->DestroyContext(targetMember); + return result; +} + +// VERIFY: b4715f8e manual +// OFFSET: 0x0088A770 +int32_t BSN::BSNPrimitiveWalker::FourCC(const Protocol::Meta::FourCC& meta, const Context& context) { + return !context.m_targetEncoder->SetFourCC(context.m_targetContext, context.m_sourceEncoder->GetFourCC(context.m_sourceContext)); +} + +// VERIFY: 201b2d12 manual +// OFFSET: 0x0088A7B0 +int32_t BSN::BSNPrimitiveWalker::Int(const Protocol::Meta::Int& meta, const Context& context) { + return !context.m_targetEncoder->SetInt(context.m_targetContext, context.m_sourceEncoder->GetInt(context.m_sourceContext)); +} + +// VERIFY: e67aa21e manual +// OFFSET: 0x0088A7B0 +int32_t BSN::BSNPrimitiveWalker::Enum(const Protocol::Meta::Enum& meta, const Context& context) { + return !context.m_targetEncoder->SetInt(context.m_targetContext, context.m_sourceEncoder->GetInt(context.m_sourceContext)); +} + +// VERIFY: 66ab0209 auto +// OFFSET: 0x0088A7F0 +int32_t BSN::BSNPrimitiveWalker::Optional(const Protocol::Meta::Optional& meta, const Context& context) { + const PrimitiveEncoder* sourceEncoder = context.m_sourceEncoder; + const EncodeContext* sourceContext = context.m_sourceContext; + const PrimitiveEncoder* targetEncoder = context.m_targetEncoder; + EncodeContext* targetContext = context.m_targetContext; + + if (!sourceEncoder->GetOptional(sourceContext)) { + return !targetEncoder->SetOptional(targetContext, false); + } + + EncodeContext* sourceMember = sourceEncoder->ConstructContext(_alloca(sourceEncoder->GetContextSize())); + EncodeContext* targetMember = targetEncoder->ConstructContext(_alloca(targetEncoder->GetContextSize())); + + int32_t result; + + if (targetEncoder->SetOptional(targetContext, true) && sourceEncoder->GetMemberContext(sourceContext, nullptr, sourceMember) && targetEncoder->GetMemberContext(targetContext, nullptr, targetMember)) { + Context member; + member.m_protocol = context.m_protocol; + member.m_typeId = meta.m_elementTypeId; + member.m_sourceEncoder = context.m_sourceEncoder; + member.m_sourceContext = sourceMember; + member.m_targetEncoder = context.m_targetEncoder; + member.m_targetContext = targetMember; + result = BSN::BSNPrimitiveWalker::Walk(*this, member); + } else { + result = BSN::WALK_INVALID; + } + + sourceEncoder->DestroyContext(sourceMember); + targetEncoder->DestroyContext(targetMember); + return result; +} + +// VERIFY: f3a78d35 manual +// OFFSET: 0x0088A930 +int32_t BSN::BSNPrimitiveWalker::Real32(const Protocol::Meta::Real32& meta, const Context& context) { + return !context.m_targetEncoder->SetReal(context.m_targetContext, context.m_sourceEncoder->GetReal(context.m_sourceContext)); +} + +// VERIFY: de69fa9f manual +// OFFSET: 0x0088A930 +int32_t BSN::BSNPrimitiveWalker::Real64(const Protocol::Meta::Real64& meta, const Context& context) { + return !context.m_targetEncoder->SetReal(context.m_targetContext, context.m_sourceEncoder->GetReal(context.m_sourceContext)); +} + +// VERIFY: e2743af6 auto +// OFFSET: 0x0088A970 +int32_t BSN::BSNPrimitiveWalker::Struct(const Protocol::Meta::Struct& meta, const Context& context) { + const PrimitiveEncoder* sourceEncoder = context.m_sourceEncoder; + const EncodeContext* sourceContext = context.m_sourceContext; + int32_t result = BSN::WALK_VALID; + void* sourceMemory = _alloca(sourceEncoder->GetContextSize()); + + const PrimitiveEncoder* targetEncoder = context.m_targetEncoder; + EncodeContext* targetContext = context.m_targetContext; + void* targetMemory = _alloca(targetEncoder->GetContextSize()); + + if (!targetEncoder->SetStruct(targetContext, meta.m_protocol->DumpString(meta.m_dumpInfo, 0))) { + return BSN::WALK_INVALID; + } + + uint32_t count = meta.m_count; + + for (uint32_t index = 0; index < count; index++) { + if (result) { + return result; + } + + uint32_t offset; + uint32_t typeId; + + if (!meta.GetMember(index, offset, typeId)) { + return BSN::WALK_INVALID; + } + + const char* name = meta.m_protocol->DumpString(meta.m_dumpInfo, index + 1); + EncodeContext* sourceMember = sourceEncoder->ConstructContext(sourceMemory); + EncodeContext* targetMember = targetEncoder->ConstructContext(targetMemory); + + if (sourceEncoder->GetMemberContext(sourceContext, name, sourceMember) && targetEncoder->GetMemberContext(targetContext, name, targetMember)) { + Context member; + member.m_protocol = context.m_protocol; + member.m_typeId = typeId; + member.m_sourceEncoder = context.m_sourceEncoder; + member.m_sourceContext = sourceMember; + member.m_targetEncoder = context.m_targetEncoder; + member.m_targetContext = targetMember; + result = BSN::BSNPrimitiveWalker::Walk(*this, member); + } else { + result = BSN::WALK_INVALID; + } + + sourceEncoder->DestroyContext(sourceMember); + targetEncoder->DestroyContext(targetMember); + } + + return result; +} + +// VERIFY: 7bd05265 manual +// OFFSET: 0x0088AB10 +int32_t BSN::BSNPrimitiveWalker::AsciiString(const Protocol::Meta::AsciiString& meta, const Context& context) { + uint32_t size = context.m_sourceEncoder->GetStringLength(context.m_sourceContext) + 1; + char* buffer = static_cast(_alloca(size)); + return !context.m_sourceEncoder->GetString(context.m_sourceContext, buffer, size) || !context.m_targetEncoder->SetString(context.m_targetContext, buffer); +} + +// VERIFY: 9a3f3973 manual +// OFFSET: 0x0088AB10 +int32_t BSN::BSNPrimitiveWalker::String(const Protocol::Meta::String& meta, const Context& context) { + uint32_t size = context.m_sourceEncoder->GetStringLength(context.m_sourceContext) + 1; + char* buffer = static_cast(_alloca(size)); + return !context.m_sourceEncoder->GetString(context.m_sourceContext, buffer, size) || !context.m_targetEncoder->SetString(context.m_targetContext, buffer); +} + +// VERIFY: 4edd3aac auto +// OFFSET: 0x0088AB80 +int32_t BSN::BSNPrimitiveWalker::User(const Protocol::Meta::User& meta, const Context& context) { + Context user = context; + user.m_typeId = meta.m_userTypeId; + return BSN::BSNPrimitiveWalker::Walk(*this, user); +} + +// VERIFY: 503d7eef auto +// OFFSET: 0x0088ABD0 +int32_t BSN::BSNPrimitiveWalker::Walk(BSNPrimitiveWalker& walker, const Context& context) { + switch (BSN::Protocol::Meta::PeekHeaderEnum(context.m_protocol, context.m_typeId)) { + case BSN::META_ARRAY: + return walker.Array(BSN::Protocol::Meta::Array(context.m_protocol, context.m_typeId), context); + case BSN::META_ASCII_STRING: + return walker.AsciiString(BSN::Protocol::Meta::AsciiString(context.m_protocol, context.m_typeId), context); + case BSN::META_BIT_ARRAY: + return walker.BitArray(BSN::Protocol::Meta::BitArray(context.m_protocol, context.m_typeId), context); + case BSN::META_BLOB: + return walker.Blob(BSN::Protocol::Meta::Blob(context.m_protocol, context.m_typeId), context); + case BSN::META_BOOL: + return walker.Bool(BSN::Protocol::Meta::Bool(context.m_protocol, context.m_typeId), context); + case BSN::META_CHOICE: + return walker.Choice(BSN::Protocol::Meta::Choice(context.m_protocol, context.m_typeId), context); + case BSN::META_ENUM: + return walker.Enum(BSN::Protocol::Meta::Enum(context.m_protocol, context.m_typeId), context); + case BSN::META_FOURCC: + return walker.FourCC(BSN::Protocol::Meta::FourCC(context.m_protocol, context.m_typeId), context); + case BSN::META_INT: + return walker.Int(BSN::Protocol::Meta::Int(context.m_protocol, context.m_typeId), context); + case BSN::META_NULL: + BSN::Protocol::Meta::Null(context.m_protocol, context.m_typeId); + return BSN::WALK_VALID; + case BSN::META_OPTIONAL: + return walker.Optional(BSN::Protocol::Meta::Optional(context.m_protocol, context.m_typeId), context); + case BSN::META_REAL32: + return walker.Real32(BSN::Protocol::Meta::Real32(context.m_protocol, context.m_typeId), context); + case BSN::META_REAL64: + return walker.Real64(BSN::Protocol::Meta::Real64(context.m_protocol, context.m_typeId), context); + case BSN::META_STRUCT: + return walker.Struct(BSN::Protocol::Meta::Struct(context.m_protocol, context.m_typeId), context); + case BSN::META_STRING: + return walker.String(BSN::Protocol::Meta::String(context.m_protocol, context.m_typeId), context); + case BSN::META_USER: + return walker.User(BSN::Protocol::Meta::User(context.m_protocol, context.m_typeId), context); + default: + return BSN::WALK_UNKNOWN_TYPE; + } +} + +// INLINED +BSN::EncodedObject::EncodedObject() : m_refCount(0) { +} + +// VERIFY: a47520f6 manual +// OFFSET: 0x00530AD0 +BSN::EncodedObject::~EncodedObject() { +} + +// VERIFY: 3ffdb1e2 manual +// OFFSET: 0x00530A20 +bool BSN::EncodedObject::WalkAndGet(const EncodedObject* source) { + const PrimitiveEncoder* encoder = this->GetEncoder(); + return encoder->WalkAndGet(source->GetEncoder(), source->GetContext(), this->GetContext()); +} + +// VERIFY: 46c247d7 manual +// OFFSET: 0x00530A70 +bool BSN::EncodedObject::WalkAndSet(EncodedObject* target) const { + const PrimitiveEncoder* encoder = this->GetEncoder(); + return encoder->WalkAndSet(target->GetEncoder(), target->GetContext(), this->GetContext()); +} + +// VERIFY: 238a3ef0 auto +// OFFSET: 0x00530B70 +void BSN::EncodedObject::IncRef() const { + const_cast(this)->m_refCount++; +} + +// VERIFY: 66c35562 manual +// OFFSET: 0x00530AC0 +void BSN::EncodedObject::DecRef() const { + if (const_cast(this)->m_refCount-- == 1) { + this->Destroy(); + } +} diff --git a/WoW/Source/Battlenet/BSN/BSNEncodeInterface.h b/WoW/Source/Battlenet/BSN/BSNEncodeInterface.h new file mode 100644 index 0000000..669b0f7 --- /dev/null +++ b/WoW/Source/Battlenet/BSN/BSNEncodeInterface.h @@ -0,0 +1,300 @@ +#ifndef WOW_SOURCE_BATTLENET_BSN_BSNENCODEINTERFACE_H +#define WOW_SOURCE_BATTLENET_BSN_BSNENCODEINTERFACE_H + +#include +#include +#include "WoW/Source/Battlenet/BSN/Protocol.h" +#include "WoW/Source/Battlenet/BSN/Types.h" +#include "Engine/Source/Storm/H/storm.h" + +namespace BSN { +struct EncodeContext { + /* 0000 */ const Protocol::Protocol* m_protocol; + /* 0004 */ uint32_t m_typeId; + /* 0008 */ uint32_t m_header; + /* 000C */ void* m_data; + + void ResolveType(); +}; + +class PrimitiveEncoder { + public: + virtual ~PrimitiveEncoder(); + virtual uint32_t GetContextSize() const = 0; + virtual EncodeContext* ConstructContext(void* memory) const = 0; + virtual void DestroyContext(EncodeContext* context) const = 0; + virtual uint64_t GetUInt(const EncodeContext* context) const = 0; + virtual int64_t GetInt(const EncodeContext* context) const = 0; + virtual bool GetBool(const EncodeContext* context) const = 0; + virtual double GetReal(const EncodeContext* context) const = 0; + virtual uint32_t GetFourCC(const EncodeContext* context) const = 0; + virtual uint32_t GetStringLength(const EncodeContext* context) const = 0; + virtual bool GetString(const EncodeContext* context, char* buffer, uint32_t size) const = 0; + virtual uint32_t GetBitArrayLength(const EncodeContext* context) const = 0; + virtual bool GetBitArray(const EncodeContext* context, uint8_t* buffer, uint32_t bits) const = 0; + virtual uint32_t GetBlobLength(const EncodeContext* context) const = 0; + virtual bool GetBlob(const EncodeContext* context, uint8_t* buffer, uint32_t size) const = 0; + virtual bool GetMemberContext(const EncodeContext* context, const char* name, EncodeContext* member) const = 0; + virtual bool GetElementContext(const EncodeContext* context, uint32_t index, EncodeContext* element) const = 0; + virtual bool GetChoiceName(const EncodeContext* context, char* buffer, uint32_t size) const = 0; + virtual uint32_t GetArrayLength(const EncodeContext* context) const = 0; + virtual bool GetOptional(const EncodeContext* context) const = 0; + virtual bool SetUInt(EncodeContext* context, uint64_t value) const = 0; + virtual bool SetInt(EncodeContext* context, int64_t value) const = 0; + virtual bool SetBool(EncodeContext* context, bool value) const = 0; + virtual bool SetReal(EncodeContext* context, double value) const = 0; + virtual bool SetFourCC(EncodeContext* context, uint32_t value) const = 0; + virtual bool SetString(EncodeContext* context, const char* value) const = 0; + virtual bool SetBitArray(EncodeContext* context, const uint8_t* data, uint32_t bits) const = 0; + virtual bool SetBlob(EncodeContext* context, const uint8_t* data, uint32_t size) const = 0; + virtual bool SetStruct(EncodeContext* context, const char* name) const = 0; + virtual bool SetChoice(EncodeContext* context, const char* typeName, const char* choiceName) const = 0; + virtual bool SetArray(EncodeContext* context, uint32_t length) const = 0; + virtual bool SetOptional(EncodeContext* context, bool exists) const = 0; + virtual bool WalkAndSet(const PrimitiveEncoder* encoder, EncodeContext* context, const EncodeContext* source) const = 0; + virtual bool WalkAndGet(const PrimitiveEncoder* encoder, const EncodeContext* source, EncodeContext* context) const = 0; +}; + +class BSNPrimitiveEncoder : public PrimitiveEncoder { + public: + uint32_t GetContextSize() const override; + EncodeContext* ConstructContext(void* memory) const override; + void DestroyContext(EncodeContext* context) const override; + uint64_t GetUInt(const EncodeContext* context) const override; + int64_t GetInt(const EncodeContext* context) const override; + bool GetBool(const EncodeContext* context) const override; + double GetReal(const EncodeContext* context) const override; + uint32_t GetFourCC(const EncodeContext* context) const override; + uint32_t GetStringLength(const EncodeContext* context) const override; + bool GetString(const EncodeContext* context, char* buffer, uint32_t size) const override; + uint32_t GetBitArrayLength(const EncodeContext* context) const override; + bool GetBitArray(const EncodeContext* context, uint8_t* buffer, uint32_t bits) const override; + uint32_t GetBlobLength(const EncodeContext* context) const override; + bool GetBlob(const EncodeContext* context, uint8_t* buffer, uint32_t size) const override; + bool GetMemberContext(const EncodeContext* context, const char* name, EncodeContext* member) const override; + bool GetElementContext(const EncodeContext* context, uint32_t index, EncodeContext* element) const override; + bool GetChoiceName(const EncodeContext* context, char* buffer, uint32_t size) const override; + uint32_t GetArrayLength(const EncodeContext* context) const override; + bool GetOptional(const EncodeContext* context) const override; + bool SetUInt(EncodeContext* context, uint64_t value) const override; + bool SetInt(EncodeContext* context, int64_t value) const override; + bool SetBool(EncodeContext* context, bool value) const override; + bool SetReal(EncodeContext* context, double value) const override; + bool SetFourCC(EncodeContext* context, uint32_t value) const override; + bool SetString(EncodeContext* context, const char* value) const override; + bool SetBitArray(EncodeContext* context, const uint8_t* data, uint32_t bits) const override; + bool SetBlob(EncodeContext* context, const uint8_t* data, uint32_t size) const override; + bool SetStruct(EncodeContext* context, const char* name) const override; + bool SetChoice(EncodeContext* context, const char* typeName, const char* choiceName) const override; + bool SetArray(EncodeContext* context, uint32_t length) const override; + bool SetOptional(EncodeContext* context, bool exists) const override; + bool WalkAndSet(const PrimitiveEncoder* encoder, EncodeContext* context, const EncodeContext* source) const override; + bool WalkAndGet(const PrimitiveEncoder* encoder, const EncodeContext* source, EncodeContext* context) const override; +}; + +class BSNPrimitiveWalker { + public: + struct Context { + /* 0000 */ const Protocol::Protocol* m_protocol; + /* 0004 */ uint32_t m_typeId; + /* 0008 */ const PrimitiveEncoder* m_sourceEncoder; + /* 000C */ const EncodeContext* m_sourceContext; + /* 0010 */ const PrimitiveEncoder* m_targetEncoder; + /* 0014 */ EncodeContext* m_targetContext; + }; + + static int32_t Walk(BSNPrimitiveWalker& walker, const Context& context); + + virtual ~BSNPrimitiveWalker(); + + int32_t Copy(const Context& context); + int32_t Array(const Protocol::Meta::Array& meta, const Context& context); + int32_t BitArray(const Protocol::Meta::BitArray& meta, const Context& context); + int32_t Blob(const Protocol::Meta::Blob& meta, const Context& context); + int32_t Bool(const Protocol::Meta::Bool& meta, const Context& context); + int32_t Choice(const Protocol::Meta::Choice& meta, const Context& context); + int32_t FourCC(const Protocol::Meta::FourCC& meta, const Context& context); + int32_t Int(const Protocol::Meta::Int& meta, const Context& context); + int32_t Enum(const Protocol::Meta::Enum& meta, const Context& context); + int32_t Optional(const Protocol::Meta::Optional& meta, const Context& context); + int32_t Real32(const Protocol::Meta::Real32& meta, const Context& context); + int32_t Real64(const Protocol::Meta::Real64& meta, const Context& context); + int32_t Struct(const Protocol::Meta::Struct& meta, const Context& context); + int32_t AsciiString(const Protocol::Meta::AsciiString& meta, const Context& context); + int32_t String(const Protocol::Meta::String& meta, const Context& context); + int32_t User(const Protocol::Meta::User& meta, const Context& context); +}; + +class EncodedObject { + public: + /* 0004 */ uint32_t m_refCount; + + virtual ~EncodedObject(); + virtual uint32_t GetEncodingType() const = 0; + virtual const PrimitiveEncoder* GetEncoder() const = 0; + virtual EncodeContext* GetContext() = 0; + virtual const EncodeContext* GetContext() const = 0; + virtual void Destroy() const = 0; + virtual bool WalkAndGet(const EncodedObject* source); + virtual bool WalkAndSet(EncodedObject* target) const; + virtual void IncRef() const; + virtual void DecRef() const; + + EncodedObject(); +}; + +template +class BSNEncodedObject : public EncodedObject { + public: + /* 0008 */ T m_data; + /* 0008+T */ BSNPrimitiveEncoder m_encoder; + /* 000C+T */ EncodeContext m_context; + + ~BSNEncodedObject() override; + uint32_t GetEncodingType() const override; + const PrimitiveEncoder* GetEncoder() const override; + EncodeContext* GetContext() override; + const EncodeContext* GetContext() const override; + void Destroy() const override; + + BSNEncodedObject(); + explicit BSNEncodedObject(const EncodedObject* source); +}; + +template +class BSNEncodedObjectPtr : public EncodedObject { + public: + /* 0008 */ BSNPrimitiveEncoder m_encoder; + /* 000C */ EncodeContext m_context; + + ~BSNEncodedObjectPtr() override; + uint32_t GetEncodingType() const override; + const PrimitiveEncoder* GetEncoder() const override; + EncodeContext* GetContext() override; + const EncodeContext* GetContext() const override; + void Destroy() const override; + + explicit BSNEncodedObjectPtr(const T* data); +}; +} + +// VERIFY: 7567f6df manual +// OFFSET: [0x00532CC0, 0x00532D70, 0x00537A60, 0x008C6BD0, 0x008C6EB0] +template +BSN::BSNEncodedObject::BSNEncodedObject() { + this->m_context.m_protocol = &P::s_protocol; + this->m_context.m_typeId = P::template TypeIdOf::s_typeId; + this->m_context.m_data = &this->m_data; + this->m_context.ResolveType(); +} + +// VERIFY: af0c9998 auto +// OFFSET: [0x005328E0, 0x005329B0, 0x00532A80, 0x00532B40, 0x00532BF0] +template +BSN::BSNEncodedObject::BSNEncodedObject(const EncodedObject* source) { + this->m_context.m_protocol = &P::s_protocol; + this->m_context.m_typeId = P::template TypeIdOf::s_typeId; + this->m_context.m_data = &this->m_data; + this->m_context.ResolveType(); + + if (source) { + this->EncodedObject::WalkAndGet(source); + } +} + +// VERIFY: d66fa723 manual +// OFFSET: [0x00532960, 0x00532A20, 0x00532B00, 0x00532BB0, 0x00532C80, 0x00532D30, 0x00532DD0, 0x00537AF0, 0x008C6C40, 0x008C6F30, 0x009C25A0] +template +BSN::BSNEncodedObject::~BSNEncodedObject() { +} + +// VERIFY: fa821c7f auto +// OFFSET: 0x008C8DE0 +template +uint32_t BSN::BSNEncodedObject::GetEncodingType() const { + return 1; +} + +// VERIFY: 2a27d6bc auto +// OFFSET: [0x00532940, 0x00532990, 0x00532AF0, 0x00532C60, 0x00532C70, 0x00532D10, 0x00532DB0, 0x00537AD0, 0x00662470, 0x008C6C20, 0x008C6F10] +template +const BSN::PrimitiveEncoder* BSN::BSNEncodedObject::GetEncoder() const { + return &this->m_encoder; +} + +// VERIFY: 56f20e47 auto +// OFFSET: [0x005329A0, 0x00532A10, 0x00532C70, 0x00532D20, 0x00532DC0, 0x00537AE0, 0x00714230, 0x008C6C30, 0x008C6F20, 0x00978BE0, 0x009C2590] +template +BSN::EncodeContext* BSN::BSNEncodedObject::GetContext() { + return &this->m_context; +} + +// VERIFY: a189645b auto +// OFFSET: [0x005329A0, 0x00532A10, 0x00532C70, 0x00532D20, 0x00532DC0, 0x00537AE0, 0x00714230, 0x008C6C30, 0x008C6F20, 0x00978BE0, 0x009C2590] +template +const BSN::EncodeContext* BSN::BSNEncodedObject::GetContext() const { + return &this->m_context; +} + +// VERIFY: 9953dd3a auto +// OFFSET: 0x00532950 +template +void BSN::BSNEncodedObject::Destroy() const { + delete this; +} + +// INLINED +template +BSN::BSNEncodedObjectPtr::BSNEncodedObjectPtr(const T* data) { + this->m_context.m_protocol = &P::s_protocol; + this->m_context.m_typeId = P::template TypeIdOf::s_typeId; + this->m_context.m_data = const_cast(data); + this->m_context.ResolveType(); +} + +// VERIFY: d5d4c71f manual +// OFFSET: 0x009C1FE0 +template +BSN::BSNEncodedObjectPtr::~BSNEncodedObjectPtr() { +} + +// VERIFY: f934db2f auto +// OFFSET: 0x008C8DE0 +template +uint32_t BSN::BSNEncodedObjectPtr::GetEncodingType() const { + return 1; +} + +// VERIFY: 8761f830 auto +// OFFSET: 0x008C6C80 +template +const BSN::PrimitiveEncoder* BSN::BSNEncodedObjectPtr::GetEncoder() const { + return &this->m_encoder; +} + +// VERIFY: 45425827 auto +// OFFSET: 0x009C1FD0 +template +BSN::EncodeContext* BSN::BSNEncodedObjectPtr::GetContext() { + return &this->m_context; +} + +// VERIFY: 1564967c auto +// OFFSET: 0x009C1FD0 +template +const BSN::EncodeContext* BSN::BSNEncodedObjectPtr::GetContext() const { + return &this->m_context; +} + +// VERIFY: a7da6e0e auto +// OFFSET: [0x00532950, 0x00532A60] +template +void BSN::BSNEncodedObjectPtr::Destroy() const { + if (ON_STACK) { + SErrDisplayAppFatalMessage("", "", 0); + } + + delete this; +} + +#endif diff --git a/WoW/Source/Battlenet/BSN/Encoder.cpp b/WoW/Source/Battlenet/BSN/Encoder.cpp new file mode 100644 index 0000000..6e6cd93 --- /dev/null +++ b/WoW/Source/Battlenet/BSN/Encoder.cpp @@ -0,0 +1,363 @@ +#include "WoW/Source/Battlenet/BSN/Encoder.h" +#include + +// VERIFY: 6ad2f43e manual +// OFFSET: 0x009C1820 +BSN::Encoder::~Encoder() { +} + +// VERIFY: 9e566c27 auto +// OFFSET: 0x005EEB70 +void BSN::Encoder::Flush() { +} + +// VERIFY: 59f54676 manual +// OFFSET: 0x009C2A90 +void BSN::Encoder::SetData(void* data, uint32_t bytes) { + this->m_data = static_cast(data); + this->m_size = 8 * bytes; + this->m_position = 0; +} + +// INLINED +int32_t BSN::Encoder::PutBits(uint32_t bits, uint32_t value) { + uint32_t remaining = bits; + + while (true) { + uint32_t position = this->m_position; + + if (position >= this->m_size) { + this->Flush(); + position = this->m_position; + + if (position >= this->m_size) { + return BSN::CODEC_OVERFLOW; + } + } + + uint32_t shift = position & 7; + uint32_t count = 8 - shift; + + if (count >= remaining) { + count = remaining; + } + + remaining -= count; + + uint8_t mask = static_cast((1 << count) - 1); + uint8_t* byte = &this->m_data[position >> 3]; + *byte = (*byte & ~(mask << shift)) | ((mask & (value >> remaining)) << shift); + this->m_position += count; + + if (!remaining) { + return BSN::CODEC_VALID; + } + } +} + +// VERIFY: 340d8567 manual +// OFFSET: 0x009C2AC0 +int32_t BSN::Encoder::PutUInt32(uint32_t value) { + return this->PutBits(32, value); +} + +// VERIFY: 6e56aceb manual +// OFFSET: 0x009C2B70 +int32_t BSN::Encoder::PutData(uint32_t bits, const uint8_t* data) { + if ((this->m_position & 7) == 0 && bits >= 8) { + do { + uint32_t position = this->m_position; + uint32_t size = this->m_size; + + if (position >= size) { + this->Flush(); + position = this->m_position; + size = this->m_size; + + if (position >= size) { + return BSN::CODEC_OVERFLOW; + } + + if (position & 7) { + break; + } + } + + uint32_t chunk = bits & ~7u; + + if (chunk >= size - position) { + chunk = size - position; + } + + memcpy(&this->m_data[position >> 3], data, chunk >> 3); + this->m_position += chunk; + data += chunk >> 3; + bits -= chunk; + } while (bits >= 8); + } + + while (bits >= 32) { + uint32_t value = (data[0] << 24) | (data[1] << 16) | (data[2] << 8) | data[3]; + + if (this->PutBits(32, value)) { + return BSN::CODEC_OVERFLOW; + } + + data += 4; + bits -= 32; + } + + if (!bits) { + return BSN::CODEC_VALID; + } + + uint32_t total = bits; + uint32_t value = 0; + + for (; bits >= 8; bits -= 8) { + value = (value << 8) | *data++; + } + + if (bits) { + value = (value << bits) | (*data & ((1 << bits) - 1)); + } + + return this->PutBits(total, value); +} + +// VERIFY: 763968dc manual +// OFFSET: 0x009C2DC0 +int32_t BSN::Encoder::Align() { + uint32_t position = this->m_position; + uint32_t aligned = (position + 7) & ~7u; + + if (aligned <= position) { + return BSN::CODEC_VALID; + } + + uint32_t remaining = aligned - position; + + while (true) { + position = this->m_position; + + if (position >= this->m_size) { + this->Flush(); + position = this->m_position; + + if (position >= this->m_size) { + return BSN::CODEC_OVERFLOW; + } + } + + uint32_t shift = position & 7; + uint32_t count = 8 - shift; + + if (count >= remaining) { + count = remaining; + } + + remaining -= count; + this->m_data[position >> 3] &= ~(((1 << count) - 1) << shift); + this->m_position += count; + + if (!remaining) { + return BSN::CODEC_VALID; + } + } +} + +// VERIFY: 9225c4f4 manual +// OFFSET: 0x009C2E70 +int32_t BSN::Encoder::PutAlignedData(uint32_t bytes, const uint8_t* data) { + int32_t result = this->Align(); + + if (result) { + return result; + } + + return this->PutData(8 * bytes, data); +} + +// VERIFY: bf7f2ea1 manual +// OFFSET: 0x009C1850 +BSN::Decoder::~Decoder() { +} + +// VERIFY: fc1e5dd8 auto +// OFFSET: 0x008E5250 +int32_t BSN::Decoder::Fill() { + return BSN::CODEC_VALID; +} + +// VERIFY: 879e63dc manual +// OFFSET: 0x009C2A90 +void BSN::Decoder::SetData(const void* data, uint32_t bytes) { + this->m_data = static_cast(data); + this->m_size = 8 * bytes; + this->m_position = 0; +} + +// VERIFY: 98ba4b34 manual +// OFFSET: 0x009C2EA0 +int32_t BSN::Decoder::GetData(uint32_t bits, uint8_t* data) { + if ((this->m_position & 7) == 0 && bits >= 8) { + do { + uint32_t position = this->m_position; + uint32_t size = this->m_size; + + if (position >= size) { + int32_t result = this->Fill(); + + if (result) { + return result; + } + + position = this->m_position; + size = this->m_size; + + if (position >= size) { + return BSN::CODEC_OVERFLOW; + } + + if (position & 7) { + break; + } + } + + uint32_t chunk = bits & ~7u; + + if (chunk >= size - position) { + chunk = size - position; + } + + memcpy(data, &this->m_data[position >> 3], chunk >> 3); + this->m_position += chunk; + data += chunk >> 3; + bits -= chunk; + } while (bits >= 8); + } + + while (bits >= 32) { + uint32_t remaining = 32; + uint32_t value = 0; + + while (true) { + uint32_t position = this->m_position; + + if (position >= this->m_size) { + int32_t result = this->Fill(); + + if (result) { + return result; + } + + position = this->m_position; + + if (position >= this->m_size) { + return BSN::CODEC_OVERFLOW; + } + } + + uint32_t shift = position & 7; + uint32_t count = 8 - shift; + + if (count >= remaining) { + count = remaining; + } + + uint32_t byte = this->m_data[position >> 3] >> shift; + remaining -= count; + this->m_position += count; + value |= (((1 << count) - 1) & byte) << remaining; + + if (!remaining) { + break; + } + } + + data[0] = static_cast(value >> 24); + data[1] = static_cast(value >> 16); + data[2] = static_cast(value >> 8); + data[3] = static_cast(value); + data += 4; + bits -= 32; + } + + if (!bits) { + return BSN::CODEC_VALID; + } + + uint32_t remaining = bits; + uint32_t value = 0; + + while (true) { + uint32_t position = this->m_position; + + if (position >= this->m_size) { + int32_t result = this->Fill(); + + if (result) { + return result; + } + + position = this->m_position; + + if (position >= this->m_size) { + return BSN::CODEC_OVERFLOW; + } + } + + uint32_t shift = position & 7; + uint32_t count = 8 - shift; + + if (count >= remaining) { + count = remaining; + } + + uint32_t byte = this->m_data[position >> 3] >> shift; + remaining -= count; + this->m_position += count; + value |= (((1 << count) - 1) & byte) << remaining; + + if (!remaining) { + break; + } + } + + if (bits >= 8) { + uint32_t shift = bits - 8; + + for (uint32_t i = bits >> 3; i; i--) { + *data++ = static_cast(value >> shift); + bits -= 8; + shift -= 8; + } + } + + if (bits) { + *data = value & ((1 << bits) - 1); + } + + return BSN::CODEC_VALID; +} + +// VERIFY: ba215381 manual +// OFFSET: 0x009C30F0 +int32_t BSN::Decoder::GetAlignedData(uint32_t bytes, uint8_t* data) { + this->m_position = (this->m_position + 7) & ~7u; + return this->GetData(8 * bytes, data); +} + +// INLINED +BSN::SizeEncoder::SizeEncoder() : m_size(0) { +} + +// VERIFY: af9cc010 manual +// OFFSET: 0x0077A200 +BSN::SizeEncoder::~SizeEncoder() { +} + +// VERIFY: 79ac8543 manual +// OFFSET: 0x009C1880 +BSN::Hard::SizeEncoder::~SizeEncoder() { +} diff --git a/WoW/Source/Battlenet/BSN/Encoder.h b/WoW/Source/Battlenet/BSN/Encoder.h new file mode 100644 index 0000000..ddd1804 --- /dev/null +++ b/WoW/Source/Battlenet/BSN/Encoder.h @@ -0,0 +1,65 @@ +#ifndef WOW_SOURCE_BATTLENET_BSN_ENCODER_H +#define WOW_SOURCE_BATTLENET_BSN_ENCODER_H + +#include +#include +#include "WoW/Source/Battlenet/BSN/Types.h" + +namespace BSN { +class Encoder { + public: + /* 0004 */ uint8_t* m_data; + /* 0008 */ uint32_t m_size; + /* 000C */ uint32_t m_position; + + virtual ~Encoder(); + virtual void Flush(); + + void SetData(void* data, uint32_t bytes); + int32_t PutBits(uint32_t bits, uint32_t value); + int32_t PutUInt32(uint32_t value); + int32_t PutData(uint32_t bits, const uint8_t* data); + int32_t Align(); + int32_t PutAlignedData(uint32_t bytes, const uint8_t* data); +}; + +class Decoder { + public: + /* 0004 */ const uint8_t* m_data; + /* 0008 */ uint32_t m_size; + /* 000C */ uint32_t m_position; + + virtual ~Decoder(); + virtual int32_t Fill(); + + void SetData(const void* data, uint32_t bytes); + int32_t GetData(uint32_t bits, uint8_t* data); + int32_t GetAlignedData(uint32_t bytes, uint8_t* data); +}; + +class SizeEncoder { + public: + /* 0004 */ uint32_t m_size; + + virtual ~SizeEncoder(); + + SizeEncoder(); +}; + +namespace Hard { +class Encoder : public BSN::Encoder { + public: +}; + +class Decoder : public BSN::Decoder { + public: +}; + +class SizeEncoder : public BSN::SizeEncoder { + public: + ~SizeEncoder() override; +}; +} +} + +#endif diff --git a/WoW/Source/Battlenet/BSN/Protocol.cpp b/WoW/Source/Battlenet/BSN/Protocol.cpp new file mode 100644 index 0000000..6308f28 --- /dev/null +++ b/WoW/Source/Battlenet/BSN/Protocol.cpp @@ -0,0 +1,116 @@ +#include "WoW/Source/Battlenet/BSN/Protocol.h" + +// VERIFY: fcec72ef auto +// OFFSET: 0x00889E50 +uint32_t BSN::Protocol::GetUInt32(const uint8_t*& cursor) { + uint32_t value = 0; + + for (uint32_t i = 4; i; i--) { + value = (value << 8) | *cursor++; + } + + return value; +} + +// VERIFY: af4a973b auto +// OFFSET: 0x00889E80 +BSN::Protocol::Protocol::Protocol(const uint8_t* bytecode, uint32_t bytecodeSize, const void* const* codeInfo, uint32_t codeInfoCount) { + this->m_bytecodeSize = bytecodeSize; + this->m_codeInfoCount = codeInfoCount; + this->m_codeInfo = codeInfo; + this->m_bytecode = bytecode; + + const uint8_t* cursor = bytecode; + + uint32_t version = 0; + for (uint32_t i = 4; i; i--) { + version = (version << 8) | *cursor++; + } + this->m_version = version; + + uint32_t value = 0; + for (uint32_t i = 4; i; i--) { + value = (value << 8) | *cursor++; + } + this->unk_0014 = value; + + uint32_t typeIdCount = 0; + for (uint32_t i = 4; i; i--) { + typeIdCount = (typeIdCount << 8) | *cursor++; + } + this->m_typeIdCount = typeIdCount; + + uint32_t typeInfoSize = 0; + for (uint32_t i = 4; i; i--) { + typeInfoSize = (typeInfoSize << 8) | *cursor++; + } + this->m_typeInfoSize = typeInfoSize; + + uint32_t dumpInfoSize = 0; + for (uint32_t i = 4; i; i--) { + dumpInfoSize = (dumpInfoSize << 8) | *cursor++; + } + this->m_dumpInfoSize = dumpInfoSize; + + this->m_typeOffsets = cursor; + const uint8_t* typeInfo = &cursor[4 * typeIdCount]; + this->m_typeInfo = typeInfo; + + const uint8_t* dumpOffsets = &typeInfo[typeInfoSize]; + + if (dumpOffsets == &bytecode[bytecodeSize]) { + this->m_dumpInfoSize = 0; + this->m_dumpOffsets = nullptr; + this->m_dumpInfo = nullptr; + } else { + this->m_dumpInfo = &dumpOffsets[4 * typeIdCount]; + this->m_dumpOffsets = dumpOffsets; + } +} + +// VERIFY: 40eb7cef auto +// OFFSET: 0x00889F80 +const uint8_t* BSN::Protocol::Protocol::TypeInfo(uint32_t typeId) const { + const uint8_t* cursor = &this->m_typeOffsets[4 * typeId]; + uint32_t offset = 0; + + for (uint32_t i = 4; i; i--) { + offset = (offset << 8) | *cursor++; + } + + return &this->m_bytecode[offset]; +} + +// VERIFY: de035afd auto +// OFFSET: 0x00889FC0 +const uint8_t* BSN::Protocol::Protocol::DumpInfo(uint32_t typeId) const { + if (!this->m_dumpInfoSize) { + return nullptr; + } + + const uint8_t* cursor = &this->m_dumpOffsets[4 * typeId]; + uint32_t offset = BSN::Protocol::GetUInt32(cursor); + + if (!offset) { + return nullptr; + } + + return &this->m_bytecode[offset]; +} + +// VERIFY: 0f8cdc61 auto +// OFFSET: 0x0088A000 +const char* BSN::Protocol::Protocol::DumpString(const uint8_t* dumpInfo, uint32_t index) const { + if (!this->m_dumpInfoSize || !dumpInfo) { + return ""; + } + + const uint8_t* cursor = &dumpInfo[4 * index]; + uint32_t offset = BSN::Protocol::GetUInt32(cursor); + + if (!offset) { + return nullptr; + } + + return reinterpret_cast(&this->m_bytecode[offset]); +} diff --git a/WoW/Source/Battlenet/BSN/Protocol.h b/WoW/Source/Battlenet/BSN/Protocol.h new file mode 100644 index 0000000..1f88457 --- /dev/null +++ b/WoW/Source/Battlenet/BSN/Protocol.h @@ -0,0 +1,204 @@ +#ifndef WOW_SOURCE_BATTLENET_BSN_PROTOCOL_H +#define WOW_SOURCE_BATTLENET_BSN_PROTOCOL_H + +#include +#include +#include "WoW/Source/Battlenet/BSN/Types.h" + +namespace BSN { +class FourCC { + public: + /* 0000 */ uint32_t m_value; + + FourCC(); + FourCC(const char* string); + void ToString(char* dest, uint32_t size) const; +}; + +namespace Protocol { +class Protocol { + public: + /* 0000 */ uint32_t m_bytecodeSize; + /* 0004 */ const uint8_t* m_bytecode; + /* 0008 */ uint32_t m_codeInfoCount; + /* 000C */ const void* const* m_codeInfo; + /* 0010 */ uint32_t m_version; + /* 0014 */ uint32_t unk_0014; + /* 0018 */ uint32_t m_typeIdCount; + /* 001C */ uint32_t m_typeInfoSize; + /* 0020 */ uint32_t m_dumpInfoSize; + /* 0024 */ const uint8_t* m_typeOffsets; + /* 0028 */ const uint8_t* m_typeInfo; + /* 002C */ const uint8_t* m_dumpOffsets; + /* 0030 */ const uint8_t* m_dumpInfo; + + Protocol(const uint8_t* bytecode, uint32_t bytecodeSize, const void* const* codeInfo, uint32_t codeInfoCount); + const uint8_t* TypeInfo(uint32_t typeId) const; + const uint8_t* DumpInfo(uint32_t typeId) const; + const char* DumpString(const uint8_t* dumpInfo, uint32_t index) const; +}; + +uint32_t GetUInt32(const uint8_t*& cursor); + +namespace Type { +struct Bounds { + /* 0000 */ int32_t m_intType; + /* 0004 */ uint32_t m_bits; + /* 0008 */ uint64_t m_min; + /* 0010 */ uint64_t m_max; + /* 0018 */ bool m_variable; + + static void Get(bool fixed, const uint8_t*& cursor, Bounds& bounds); + + bool Contains(uint64_t value) const; +}; + +void GetTypeId(const uint8_t*& cursor, uint32_t& typeId); + +namespace Int { +void Get(int32_t intType, const uint8_t*& cursor, uint64_t& value); +void Get(int32_t intType, const uint8_t*& cursor, uint32_t& value); +void GetSize(const uint8_t*& cursor, uint32_t& value); +} +} + +namespace Meta { +uint32_t PeekHeaderEnum(const Protocol* protocol, uint32_t typeId); + +class Base { + public: + /* 0000 */ const Protocol* m_protocol; + /* 0004 */ uint32_t m_typeId; + /* 0008 */ uint8_t m_header; + /* 000C */ const uint8_t* m_typeInfo; + /* 0010 */ const uint8_t* m_dumpInfo; + /* 0014 */ const void* const* m_codeInfo; + + Base(const Protocol* protocol, uint32_t typeId); +}; + +class Bool : public Base { + public: + Bool(const Protocol* protocol, uint32_t typeId); +}; + +class FourCC : public Base { + public: + FourCC(const Protocol* protocol, uint32_t typeId); +}; + +class Null : public Base { + public: + Null(const Protocol* protocol, uint32_t typeId); +}; + +class Real32 : public Base { + public: + Real32(const Protocol* protocol, uint32_t typeId); +}; + +class Real64 : public Base { + public: + Real64(const Protocol* protocol, uint32_t typeId); +}; + +class Int : public Base { + public: + /* 0018 */ Type::Bounds m_bounds; + + Int(const Protocol* protocol, uint32_t typeId); +}; + +class AsciiString : public Base { + public: + /* 0018 */ Type::Bounds m_bounds; + + AsciiString(const Protocol* protocol, uint32_t typeId); +}; + +class BitArray : public Base { + public: + /* 0018 */ Type::Bounds m_bounds; + + BitArray(const Protocol* protocol, uint32_t typeId); +}; + +class Blob : public Base { + public: + /* 0018 */ Type::Bounds m_bounds; + + Blob(const Protocol* protocol, uint32_t typeId); +}; + +class Array : public Base { + public: + /* 0018 */ Type::Bounds m_bounds; + /* 0038 */ uint32_t m_elementTypeId; + + Array(const Protocol* protocol, uint32_t typeId); +}; + +class Enum : public Base { + public: + /* 0018 */ Type::Bounds m_bounds; + /* 0038 */ uint32_t m_count; + + Enum(const Protocol* protocol, uint32_t typeId); + bool GetEnumField(uint64_t value, uint32_t& field) const; +}; + +class Choice : public Base { + public: + /* 0018 */ Type::Bounds m_bounds; + /* 0038 */ uint32_t m_count; + + Choice(const Protocol* protocol, uint32_t typeId); + bool GetTagField(uint64_t tag, uint32_t& field) const; + bool GetFieldTag(uint32_t field, uint64_t& tag) const; + bool GetFieldTypeId(uint32_t field, uint32_t& typeId) const; +}; + +class Struct : public Base { + public: + /* 0018 */ Type::Bounds m_bounds; + /* 0038 */ uint32_t m_count; + + Struct(const Protocol* protocol, uint32_t typeId); + bool GetMember(uint32_t index, uint32_t& offset, uint32_t& typeId) const; +}; + +class String : public Base { + public: + static bool IsValid(uint32_t length, const uint8_t* data, uint32_t& count); + + /* 0018 */ Type::Bounds m_bounds; + /* 0038 */ Type::Bounds m_charBounds; + + String(const Protocol* protocol, uint32_t typeId); +}; + +class User : public Base { + public: + /* 0018 */ uint32_t m_userTypeId; + + User(const Protocol* protocol, uint32_t typeId); +}; + +class Optional : public Base { + public: + /* 0018 */ uint32_t m_elementTypeId; + + Optional(const Protocol* protocol, uint32_t typeId); +}; +} +} + +namespace Cpp { +void ReadInt(const void* data, uint32_t size, bool isSigned, uint64_t& value); +void WriteInt(uint64_t value, uint32_t size, void* data); +} + +extern const Utf8Sequence s_utf8Sequences[9]; +} + +#endif diff --git a/WoW/Source/Battlenet/BSN/ProtocolMeta.cpp b/WoW/Source/Battlenet/BSN/ProtocolMeta.cpp new file mode 100644 index 0000000..9edbe0b --- /dev/null +++ b/WoW/Source/Battlenet/BSN/ProtocolMeta.cpp @@ -0,0 +1,285 @@ +#include "WoW/Source/Battlenet/BSN/Protocol.h" + +// VERIFY: b89f54af auto +// OFFSET: 0x008889E0 +uint32_t BSN::Protocol::Meta::PeekHeaderEnum(const Protocol* protocol, uint32_t typeId) { + return *protocol->TypeInfo(typeId) & 0x3F; +} + +// VERIFY: 254e0587 auto +// OFFSET: 0x00888A00 +BSN::Protocol::Meta::Base::Base(const Protocol* protocol, uint32_t typeId) { + this->m_protocol = protocol; + this->m_typeId = typeId; + this->m_typeInfo = protocol->TypeInfo(typeId); + this->m_dumpInfo = protocol->DumpInfo(typeId); + + const void* const* codeInfo = protocol->m_codeInfo; + uintptr_t index = reinterpret_cast(codeInfo[typeId + 1]); + this->m_codeInfo = index ? &codeInfo[index] : nullptr; + + this->m_header = *this->m_typeInfo++; +} + +// VERIFY: 37fb8121 auto +// OFFSET: 0x00888A60 +BSN::Protocol::Meta::Array::Array(const Protocol* protocol, uint32_t typeId) : Base(protocol, typeId) { + BSN::Protocol::Type::Bounds::Get(this->m_header >> 7, this->m_typeInfo, this->m_bounds); + BSN::Protocol::Type::GetTypeId(this->m_typeInfo, this->m_elementTypeId); +} + +// VERIFY: e473c50c auto +// OFFSET: 0x00888AA0 +BSN::Protocol::Meta::BitArray::BitArray(const Protocol* protocol, uint32_t typeId) : Base(protocol, typeId) { + BSN::Protocol::Type::Bounds::Get(this->m_header >> 7, this->m_typeInfo, this->m_bounds); +} + +// VERIFY: 360f5363 auto +// OFFSET: 0x00888AA0 +BSN::Protocol::Meta::Blob::Blob(const Protocol* protocol, uint32_t typeId) : Base(protocol, typeId) { + BSN::Protocol::Type::Bounds::Get(this->m_header >> 7, this->m_typeInfo, this->m_bounds); +} + +// VERIFY: 2a93db84 manual +// OFFSET: 0x00888AE0 +bool BSN::Protocol::Meta::Choice::GetTagField(uint64_t tag, uint32_t& field) const { + if (static_cast(this->m_header) >= 0) { + uint32_t size = 1 << (this->m_bounds.m_intType >> 1); + field = 0; + + if (this->m_count) { + do { + const uint8_t* cursor = &this->m_typeInfo[size * field]; + uint64_t value; + BSN::Protocol::Type::Int::Get(this->m_bounds.m_intType, cursor, value); + + if (tag == value) { + return true; + } + } while (++field < this->m_count); + } + } else if (this->m_bounds.Contains(tag)) { + field = static_cast(tag - this->m_bounds.m_min); + return true; + } + + return false; +} + +// VERIFY: 79b7916b manual +// OFFSET: 0x00888B80 +bool BSN::Protocol::Meta::Choice::GetFieldTag(uint32_t field, uint64_t& tag) const { + if (static_cast(this->m_header) >= 0) { + if (field < this->m_count) { + const uint8_t* cursor = &this->m_typeInfo[field * (1 << (this->m_bounds.m_intType >> 1))]; + BSN::Protocol::Type::Int::Get(this->m_bounds.m_intType, cursor, tag); + return true; + } + } else { + tag = field + this->m_bounds.m_min; + + if (this->m_bounds.Contains(tag)) { + return true; + } + } + + return false; +} + +// VERIFY: 18d682f6 manual +// OFFSET: 0x00888C00 +bool BSN::Protocol::Meta::Choice::GetFieldTypeId(uint32_t field, uint32_t& typeId) const { + if (field >= this->m_count) { + return false; + } + + const uint8_t* cursor; + + if (static_cast(this->m_header) >= 0) { + cursor = &this->m_typeInfo[this->m_count * (1 << (this->m_bounds.m_intType >> 1)) + 4 * field]; + } else { + cursor = &this->m_typeInfo[4 * field]; + } + + BSN::Protocol::Type::GetTypeId(cursor, typeId); + return true; +} + +// VERIFY: b478940d manual +// OFFSET: 0x00888C70 +bool BSN::Protocol::Meta::Enum::GetEnumField(uint64_t value, uint32_t& field) const { + if (static_cast(this->m_header) >= 0) { + const uint8_t* cursor = this->m_typeInfo; + field = 0; + + if (this->m_count) { + do { + uint64_t entry; + BSN::Protocol::Type::Int::Get(this->m_bounds.m_intType, cursor, entry); + + if (value == entry) { + return true; + } + } while (++field < this->m_count); + } + } else if (this->m_bounds.Contains(value)) { + field = static_cast(value - this->m_bounds.m_min); + return true; + } + + return false; +} + +// VERIFY: 1a17d977 auto +// OFFSET: 0x00888D00 +BSN::Protocol::Meta::Int::Int(const Protocol* protocol, uint32_t typeId) : Base(protocol, typeId) { + BSN::Protocol::Type::Bounds::Get(false, this->m_typeInfo, this->m_bounds); +} + +// VERIFY: e404c9f1 auto +// OFFSET: 0x00888D00 +BSN::Protocol::Meta::AsciiString::AsciiString(const Protocol* protocol, uint32_t typeId) : Base(protocol, typeId) { + BSN::Protocol::Type::Bounds::Get(false, this->m_typeInfo, this->m_bounds); +} + +// VERIFY: 1fc467b3 auto +// OFFSET: 0x00888D30 +BSN::Protocol::Meta::User::User(const Protocol* protocol, uint32_t typeId) : Base(protocol, typeId) { + BSN::Protocol::Type::GetTypeId(this->m_typeInfo, this->m_userTypeId); +} + +// VERIFY: d22bab36 auto +// OFFSET: 0x00888D30 +BSN::Protocol::Meta::Optional::Optional(const Protocol* protocol, uint32_t typeId) : Base(protocol, typeId) { + BSN::Protocol::Type::GetTypeId(this->m_typeInfo, this->m_elementTypeId); +} + +// VERIFY: c0b3cda7 auto +// OFFSET: 0x00888D60 +BSN::Protocol::Meta::Bool::Bool(const Protocol* protocol, uint32_t typeId) : Base(protocol, typeId) { +} + +// VERIFY: 0f1b830e auto +// OFFSET: 0x00888D60 +BSN::Protocol::Meta::FourCC::FourCC(const Protocol* protocol, uint32_t typeId) : Base(protocol, typeId) { +} + +// VERIFY: 4ef8154b auto +// OFFSET: 0x00888D60 +BSN::Protocol::Meta::Null::Null(const Protocol* protocol, uint32_t typeId) : Base(protocol, typeId) { +} + +// VERIFY: 5a46550a auto +// OFFSET: 0x00888D60 +BSN::Protocol::Meta::Real32::Real32(const Protocol* protocol, uint32_t typeId) : Base(protocol, typeId) { +} + +// VERIFY: 01c1ae32 auto +// OFFSET: 0x00888D60 +BSN::Protocol::Meta::Real64::Real64(const Protocol* protocol, uint32_t typeId) : Base(protocol, typeId) { +} + +// VERIFY: c8d2bcd7 manual +// OFFSET: 0x00888D80 +BSN::Protocol::Meta::Enum::Enum(const Protocol* protocol, uint32_t typeId) : Base(protocol, typeId) { + BSN::Protocol::Type::Bounds::Get(false, this->m_typeInfo, this->m_bounds); + + if (static_cast(this->m_header) >= 0) { + BSN::Protocol::Type::Int::GetSize(this->m_typeInfo, this->m_count); + } else { + this->m_count = static_cast(this->m_bounds.m_max) - static_cast(this->m_bounds.m_min) + 1; + } +} + +// VERIFY: 8b106e47 manual +// OFFSET: 0x00888D80 +BSN::Protocol::Meta::Choice::Choice(const Protocol* protocol, uint32_t typeId) : Base(protocol, typeId) { + BSN::Protocol::Type::Bounds::Get(false, this->m_typeInfo, this->m_bounds); + + if (static_cast(this->m_header) >= 0) { + BSN::Protocol::Type::Int::GetSize(this->m_typeInfo, this->m_count); + } else { + this->m_count = static_cast(this->m_bounds.m_max) - static_cast(this->m_bounds.m_min) + 1; + } +} + +// VERIFY: 39bb5ffb manual +// OFFSET: 0x00888D80 +BSN::Protocol::Meta::Struct::Struct(const Protocol* protocol, uint32_t typeId) : Base(protocol, typeId) { + BSN::Protocol::Type::Bounds::Get(false, this->m_typeInfo, this->m_bounds); + + if (static_cast(this->m_header) >= 0) { + BSN::Protocol::Type::Int::GetSize(this->m_typeInfo, this->m_count); + } else { + this->m_count = static_cast(this->m_bounds.m_max) - static_cast(this->m_bounds.m_min) + 1; + } +} + +// VERIFY: e1ec8bc2 manual +// OFFSET: 0x00888DE0 +bool BSN::Protocol::Meta::Struct::GetMember(uint32_t index, uint32_t& offset, uint32_t& typeId) const { + if (index >= this->m_count) { + return false; + } + + offset = static_cast(reinterpret_cast(this->m_codeInfo[index + 1])); + + const uint8_t* cursor; + + if (static_cast(this->m_header) >= 0) { + cursor = &this->m_typeInfo[4 * index + this->m_count * (1 << (this->m_bounds.m_intType >> 1))]; + } else { + cursor = &this->m_typeInfo[4 * index]; + } + + BSN::Protocol::Type::GetTypeId(cursor, typeId); + return true; +} + +// VERIFY: 30249418 manual +// OFFSET: 0x00888E60 +BSN::Protocol::Meta::String::String(const Protocol* protocol, uint32_t typeId) : Base(protocol, typeId) { + BSN::Protocol::Type::Bounds::Get(false, this->m_typeInfo, this->m_charBounds); + this->m_bounds = this->m_charBounds; + this->m_bounds.m_bits += 2; + this->m_bounds.m_max *= 4; +} + +// VERIFY: d65c5c93 manual +// OFFSET: 0x00888EC0 +bool BSN::Protocol::Meta::String::IsValid(uint32_t length, const uint8_t* data, uint32_t& count) { + uint32_t position = 0; + count = 0; + + if (!length) { + return true; + } + + do { + const uint8_t* sequence = &data[position]; + uint32_t index = 0; + + while (*sequence < BSN::s_utf8Sequences[index].m_ranges[0][0] || *sequence > BSN::s_utf8Sequences[index].m_ranges[0][1]) { + if (++index >= 9) { + return false; + } + } + + uint32_t sequenceLength = BSN::s_utf8Sequences[index].m_length; + + if (length - position < sequenceLength) { + return false; + } + + for (uint32_t i = 1; i < sequenceLength; i++) { + if (sequence[i] < BSN::s_utf8Sequences[index].m_ranges[i][0] || sequence[i] > BSN::s_utf8Sequences[index].m_ranges[i][1]) { + return false; + } + } + + position += sequenceLength; + count++; + } while (position < length); + + return true; +} diff --git a/WoW/Source/Battlenet/BSN/ProtocolType.cpp b/WoW/Source/Battlenet/BSN/ProtocolType.cpp new file mode 100644 index 0000000..420dc2d --- /dev/null +++ b/WoW/Source/Battlenet/BSN/ProtocolType.cpp @@ -0,0 +1,76 @@ +#include "WoW/Source/Battlenet/BSN/Protocol.h" + +// VERIFY: b7cad848 manual +// OFFSET: 0x0088A050 +void BSN::Protocol::Type::Int::Get(int32_t intType, const uint8_t*& cursor, uint64_t& value) { + uint32_t size = 1 << (intType >> 1); + + if ((intType & 1) || *cursor < 0x80) { + value = 0; + } else { + value = static_cast(-1); + } + + for (; size; size--) { + value = (value << 8) | *cursor++; + } +} + +// VERIFY: b0a9090d auto +// OFFSET: 0x0088A0C0 +void BSN::Protocol::Type::Int::Get(int32_t intType, const uint8_t*& cursor, uint32_t& value) { + uint32_t size = 1 << (intType >> 1); + + for (value = 0; size; cursor++) { + value <<= 8; + size--; + value |= *cursor; + } +} + +// VERIFY: ec7bb8f9 manual +// OFFSET: 0x0088A100 +void BSN::Protocol::Type::Int::GetSize(const uint8_t*& cursor, uint32_t& value) { + uint8_t intType = *cursor++; + BSN::Protocol::Type::Int::Get(intType, cursor, value); +} + +// VERIFY: 88b02841 manual +// OFFSET: 0x0088A130 +bool BSN::Protocol::Type::Bounds::Contains(uint64_t value) const { + if (this->m_intType & 1) { + return value >= this->m_min && value <= this->m_max; + } + + return static_cast(value) >= static_cast(this->m_min) && static_cast(value) <= static_cast(this->m_max); +} + +// VERIFY: fa5dc7e8 manual +// OFFSET: 0x0088A180 +void BSN::Protocol::Type::Bounds::Get(bool fixed, const uint8_t*& cursor, Bounds& bounds) { + uint8_t intType = *cursor++; + bounds.m_intType = intType; + + if (fixed) { + bounds.m_variable = false; + bounds.m_bits = 0; + BSN::Protocol::Type::Int::Get(intType, cursor, bounds.m_min); + bounds.m_max = bounds.m_min; + } else { + bounds.m_variable = *cursor >> 7; + bounds.m_bits = *cursor++ & 0x7F; + BSN::Protocol::Type::Int::Get(bounds.m_intType, cursor, bounds.m_min); + BSN::Protocol::Type::Int::Get(bounds.m_intType, cursor, bounds.m_max); + } +} + +// VERIFY: 3ee45e08 auto +// OFFSET: 0x0088A200 +void BSN::Protocol::Type::GetTypeId(const uint8_t*& cursor, uint32_t& typeId) { + typeId = 0; + + for (uint32_t i = 4; i; i--) { + typeId <<= 8; + typeId |= *cursor++; + } +} diff --git a/WoW/Source/Battlenet/BSN/Types.h b/WoW/Source/Battlenet/BSN/Types.h new file mode 100644 index 0000000..cd376cd --- /dev/null +++ b/WoW/Source/Battlenet/BSN/Types.h @@ -0,0 +1,322 @@ +#ifndef WOW_SOURCE_BATTLENET_BSN_TYPES_H +#define WOW_SOURCE_BATTLENET_BSN_TYPES_H + +#include +#include +#include +#include +#include "Engine/Source/Storm/H/storm.h" + +namespace BSN { +enum MetaType { + META_ARRAY = 1, + META_ASCII_STRING = 2, + META_BIT_ARRAY = 3, + META_BLOB = 4, + META_BOOL = 5, + META_CHOICE = 6, + META_ENUM = 7, + META_FOURCC = 8, + META_INT = 9, + META_NULL = 10, + META_OPTIONAL = 11, + META_REAL32 = 12, + META_REAL64 = 13, + META_STRUCT = 14, + META_STRING = 15, + META_USER = 16, +}; + +enum WalkResult { + WALK_VALID = 0, + WALK_INVALID = 1, + WALK_UNKNOWN_TYPE = 2, +}; + +enum CodecResult { + CODEC_VALID = 0, + CODEC_INVALID = 1, + CODEC_OVERFLOW = 2, +}; + +typedef uint32_t (*AdapterGetLength)(const void* data); +typedef const void* (*AdapterGetElements)(const void* data); +typedef void* (*AdapterSetLength)(void* data, uint32_t length); +typedef void (*AdapterSetCount)(void* data, uint32_t count); +typedef bool (*AdapterGetExists)(const void* data); +typedef void* (*AdapterSetExists)(void* data, bool exists); +typedef int32_t (*AdapterGetTag)(const void* data); +typedef void* (*AdapterGetChoice)(const void* data); +typedef void (*AdapterSetTag)(void* data, int32_t tag); +typedef uint32_t (*AdapterGetFourCC)(const void* data); +typedef void (*AdapterSetFourCC)(void* data, uint32_t value); + +struct Utf8Sequence { + /* 0000 */ uint32_t m_length; + /* 0004 */ uint8_t m_ranges[4][2]; +}; + +uint32_t AsciiStringCopy(char* dest, const char* source, uint32_t maxLength); +uint32_t UTF8StringCopy(char* dest, const char* source, uint32_t maxChars, uint32_t& length); + +template +class AsciiString { + public: + /* 0000 */ uint32_t m_length; + /* 0004 */ char m_data[N + 1]; + + AsciiString(); + explicit AsciiString(const char* source); + AsciiString& operator=(const char* source); +}; + +template +class String { + public: + /* 0000 */ uint32_t m_size; + /* 0004 */ uint32_t m_length; + /* 0008 */ char m_data[4 * N + 1]; + + String(); + String& operator=(const char* source); + String& operator+=(const char* source); +}; + +template +class Array { + public: + /* 0000 */ uint32_t m_count; + /* 0004 */ T m_data[N]; + + Array(); + T& operator[](uint32_t index); + const T& operator[](uint32_t index) const; + T* New(); + void Remove(uint32_t index); + void SetCount(uint32_t count); +}; + +template +class FixedArray { + public: + /* 0000 */ T m_data[SIZE]; + + const T& operator[](uint32_t index) const; +}; + +template +class Optional { + public: + /* 0000 */ bool m_exists; + /* 0004 */ T m_value; + + Optional(); + Optional(const Optional& other); + Optional& operator=(const Optional& other); + const T& Get() const; +}; + +class Choice { + public: + /* 0000 */ int32_t m_tag; + + template + T& Get(); + template + const T& Get() const; + template + T* Set(); +}; +} + +// INLINED +template +BSN::AsciiString::AsciiString() { + this->m_length = 0; + this->m_data[0] = '\0'; +} + +// INLINED +template +BSN::AsciiString::AsciiString(const char* source) { + this->m_length = BSN::AsciiStringCopy(this->m_data, source, N); +} + +// VERIFY: b5f69c14 auto +// OFFSET: [0x008C63C0<255>, 0x008C63F0<320>, 0x008C6480<31>] +template +BSN::AsciiString& BSN::AsciiString::operator=(const char* source) { + this->m_length = BSN::AsciiStringCopy(this->m_data, source, N); + return *this; +} + +// INLINED +template +BSN::String::String() { + this->m_size = 0; + this->m_length = 0; + this->m_data[0] = '\0'; +} + +// VERIFY: 497fac72 auto +// OFFSET: 0x00530FB0<127> +template +BSN::String& BSN::String::operator=(const char* source) { + this->m_size = BSN::UTF8StringCopy(this->m_data, source, N, this->m_length); + return *this; +} + +// INLINED +template +BSN::String& BSN::String::operator+=(const char* source) { + uint32_t length; + this->m_size += BSN::UTF8StringCopy(&this->m_data[this->m_size], source, N - this->m_length, length); + this->m_length += length; + return *this; +} + +// VERIFY: c98431e8 manual +// OFFSET: [0x008C6B90, 0x00537B30] +template +BSN::Array::Array() { + this->m_count = 0; +} + +// VERIFY: 902008f6 auto +// OFFSET: [0x008C6390, 0x00531000, 0x005310C0] +template +T& BSN::Array::operator[](uint32_t index) { + if (index >= this->m_count) { + SErrDisplayAppFatalMessage("", "", 0); + } + + return this->m_data[index]; +} + +// VERIFY: ae8dfdec auto +// OFFSET: [0x008C6420, 0x008C6450] +template +const T& BSN::Array::operator[](uint32_t index) const { + if (index >= this->m_count) { + SErrDisplayAppFatalMessage("", "", 0); + } + + return this->m_data[index]; +} + +// VERIFY: 566cee18 auto +// OFFSET: 0x00531030 +template +T* BSN::Array::New() { + if (this->m_count >= N) { + SErrDisplayAppFatalMessage("", "", 0); + } + + return &this->m_data[this->m_count++]; +} + +// INLINED +template +const T& BSN::FixedArray::operator[](uint32_t index) const { + if (index >= SIZE) { + SErrDisplayAppFatalMessage("", "", 0); + } + + return this->m_data[index]; +} + +// INLINED +template +BSN::Optional::Optional() : m_exists(false), m_value() { +} + +// INLINED +template +BSN::Optional::Optional(const Optional& other) : m_exists(other.m_exists), m_value() { + if (this->m_exists) { + this->m_value = other.m_value; + } +} + +// INLINED +template +BSN::Optional& BSN::Optional::operator=(const Optional& other) { + this->m_exists = other.m_exists; + + if (this->m_exists) { + this->m_value = other.m_value; + } + + return *this; +} + +// VERIFY: 49436f17 auto +// OFFSET: 0x00530FE0> +template +const T& BSN::Optional::Get() const { + if (!this->m_exists) { + SErrDisplayAppFatalMessage("", "", 0); + } + + return this->m_value; +} + +// INLINED +template +T& BSN::Choice::Get() { + if (this->m_tag != TAG) { + SErrDisplayAppFatalMessage("", "", 0); + } + + return *reinterpret_cast(this + 1); +} + +// VERIFY: dec6a3bb auto +// OFFSET: [0x00531060, 0x005310F0] +template +void BSN::Array::Remove(uint32_t index) { + if (index >= this->m_count) { + SErrDisplayAppFatalMessage("", "", 0); + } + + if (this->m_count - index > 1) { + memmove(&this->m_data[index], &this->m_data[index + 1], (this->m_count - index - 1) * sizeof(T)); + } + + this->m_count--; +} + +// INLINED +template +void BSN::Array::SetCount(uint32_t count) { + if (count > N) { + SErrDisplayAppFatalMessage("", "", 0); + } + + for (uint32_t i = this->m_count; i < count; i++) { + this->m_data[i] = T(); + } + + this->m_count = count; +} + +// VERIFY: df702c9e auto +// OFFSET: [0x008C66E0<2, Battlenet::Realm::JoinResponse>, 0x008C6700<3, uint32_t>, 0x008C6720<0, Battlenet::Authentication::ModuleRequest>, 0x008C6740<1, uint32_t>, 0x008C6760<9, Battlenet::Realm::Response>, 0x00531180<6, int32_t>, 0x005311A0<17, Battlenet::Toon::FullName>, 0x005311C0<18, Battlenet::Presence::AccountName>] +template +const T& BSN::Choice::Get() const { + if (this->m_tag != TAG) { + SErrDisplayAppFatalMessage("", "", 0); + } + + return *reinterpret_cast(this + 1); +} + +// VERIFY: 31bcc217 manual +// OFFSET: [0x008C7000<0, Battlenet::Authentication::Request>, 0x008C6FD0<2, Battlenet::Authentication::ModuleMessage>, 0x008C6C90<1, BSN::AsciiString<320>>, 0x008C6CB0<0, BSN::AsciiString<31>>, 0x008C6CD0<12, Battlenet::Event::Creep::Portal>] +template +T* BSN::Choice::Set() { + this->m_tag = TAG; + return new (this + 1) T(); +} + +#endif diff --git a/WoW/Source/Battlenet/Battlenet.cpp b/WoW/Source/Battlenet/Battlenet.cpp new file mode 100644 index 0000000..5749474 --- /dev/null +++ b/WoW/Source/Battlenet/Battlenet.cpp @@ -0,0 +1,124 @@ +#include "WoW/Source/Battlenet/Battlenet.h" +#include +#include "Engine/Source/Storm/H/storm.h" + +// STATIC: 0x00DCED2C +Battlenet::Allocator* Battlenet::g_allocator; + +// INLINED +Battlenet::Allocator::~Allocator() { +} + +// VERIFY: 90ab8d30 auto +// OFFSET: 0x009C0D10 +bool Battlenet::Initialize(Allocator& allocator) { + Battlenet::g_allocator = &allocator; + return true; +} + +// VERIFY: c34fc70e auto +// OFFSET: 0x009C0D20 +void Battlenet::Teardown() { + Battlenet::g_allocator = nullptr; +} + +// VERIFY: 3576828e auto +// OFFSET: 0x009BFEA0 +uint32_t Battlenet::StringCopy(void* dest, const char* source, uint32_t size) { + if (!size) { + return 0; + } + + size--; + uint32_t length = static_cast(strlen(source)); + + if (size > length) { + size = length; + } + + memcpy(dest, source, size); + static_cast(dest)[size] = '\0'; + return size; +} + +// INLINED +Battlenet::Event::Header::Header() { + this->m_source.m_exists = false; + this->m_source.m_adapter = 0; + this->m_source.m_event = static_cast(-1); + this->m_target.m_type = 0; +} + +// VERIFY: 4794d187 manual +// OFFSET: 0x009BFD80 +Battlenet::SystemClient::~SystemClient() { +} + +// VERIFY: c726b2a6 auto +// OFFSET: 0x008C50C0 +void Battlenet::SystemServer::Log(const char* message) { + this->LogLevel(message, 5); +} + +// VERIFY: 6be4e15c manual +// OFFSET: 0x008C50E0 +Battlenet::SystemServer::~SystemServer() { +} + +// INLINED +Battlenet::EventSubscriber::EventSubscriber() { + this->m_eventId.m_value = 0; +} + +// VERIFY: 719d8eeb manual +// OFFSET: 0x008C5110 +Battlenet::EventSubscriber::~EventSubscriber() { +} + +// VERIFY: 991ad3f1 manual +// OFFSET: 0x009C0C40 +Battlenet::EventInterface::~EventInterface() { +} + +// VERIFY: 42a57769 manual +// OFFSET: 0x009C2880 +Battlenet::Library::~Library() { +} + +// VERIFY: f3ddd817 manual +// OFFSET: 0x009C29C0 +Battlenet::Library* Battlenet::Library::LoadApplicationBundle(const char* name, Allocator& allocator) { + uint32_t length = SStrLen(name); + + if (length + 5 < length) { + return nullptr; + } + + char* path = static_cast(allocator.Alloc(length + 5)); + + if (!path) { + return nullptr; + } + + memcpy(path, name, length); + strcpy(&path[length], ".dll"); + + Library* library = Battlenet::Library::Load(path, allocator); + allocator.Free(path); + return library; +} + +// VERIFY: dc515e8e auto +// OFFSET: 0x009C2A70 +void Battlenet::WindowsLibrary::Destroy() { + Allocator* allocator = this->m_allocator; + this->~WindowsLibrary(); + allocator->Free(this); +} + +// VERIFY: 82c53b15 auto +// OFFSET: 0x009C2010 +bool Battlenet::GetProc(Library* library, void*& proc, uint32_t ordinal) { + proc = library->GetProc(ordinal); + return proc != nullptr; +} diff --git a/WoW/Source/Battlenet/Battlenet.h b/WoW/Source/Battlenet/Battlenet.h new file mode 100644 index 0000000..f37d1f5 --- /dev/null +++ b/WoW/Source/Battlenet/Battlenet.h @@ -0,0 +1,171 @@ +#ifndef WOW_SOURCE_BATTLENET_BATTLENET_H +#define WOW_SOURCE_BATTLENET_BATTLENET_H + +#include +#include +#include "WoW/Source/Battlenet/BSN/BSNEncodeInterface.h" + +#ifdef GetCurrentTime +#undef GetCurrentTime +#endif + +namespace Battlenet { +class Allocator { + public: + virtual ~Allocator(); + virtual void* Alloc(uint32_t size) = 0; + virtual void Free(void* memory) = 0; + + template + void Delete(T*& object); +}; + +extern Allocator* g_allocator; + +bool Initialize(Allocator& allocator); +void Teardown(); + +namespace IP4 { +struct Address { + /* 0000 */ uint8_t m_value[4]; +}; + +struct AddressPort { + /* 0000 */ uint8_t m_address[4]; + /* 0004 */ uint8_t m_port[2]; +}; +} + +namespace Client { +struct DNSInfo { + /* 0000 */ BSN::Array m_addresses; + /* 0200 */ BSN::AsciiString<255> m_name; +}; +} + +namespace Event { +struct Header { + struct Source { + /* 0000 */ bool m_exists; + /* 0004 */ uint32_t m_adapter; + /* 0008 */ uint32_t m_event; + }; + + struct Target { + /* 0000 */ uint32_t m_type; + /* 0004 */ uint32_t m_value; + }; + + /* 0000 */ uint8_t m_eventType; + /* 0004 */ Source m_source; + /* 0010 */ Target m_target; + + Header(); +}; +} + +class ApplicationFile; + +class SystemClient { + public: + virtual void Resolved(uint32_t request, const Client::DNSInfo& info) = 0; + virtual void Connected(uint32_t connection, const IP4::AddressPort& address) = 0; + virtual void Disconnected(uint32_t connection) = 0; + virtual bool Recv(uint32_t connection, void* data, uint32_t size, uint32_t& used) = 0; + virtual bool RecvDatagram(uint32_t connection, void* data, uint32_t size, const IP4::AddressPort& address) = 0; + virtual void Process(uint32_t time) = 0; + virtual ~SystemClient(); +}; + +class SystemServer { + public: + virtual uint32_t Resolve(uint32_t token, const char* hostname) = 0; + virtual uint32_t Connect(const IP4::AddressPort& address, const uint32_t& tendrilId) = 0; + virtual void Disconnect(uint32_t connection) = 0; + virtual bool Send(uint32_t connection, const void* data, uint32_t size) = 0; + virtual uint32_t OpenDatagram(int32_t port, const uint32_t& tendrilId) = 0; + virtual void CloseDatagram(uint32_t connection) = 0; + virtual bool SendDatagram(uint32_t connection, const void* data, uint32_t size, const IP4::AddressPort& address) = 0; + virtual uint64_t GetCurrentTime() const = 0; + virtual uint64_t GetCurrentTick() const = 0; + virtual void LogLevel(const char* message, int32_t level) = 0; + virtual void Log(const char* message); + virtual ApplicationFile* OpenApplicationFile(const char* name) = 0; + virtual void CloseApplicationFile(ApplicationFile* file) = 0; + virtual ~SystemServer(); +}; + +class EventSubscriber { + public: + /* 0004 */ BSN::FourCC m_eventId; + + virtual void RecvEvent(const Event::Header& header, const BSN::EncodedObject* data) = 0; + virtual ~EventSubscriber(); + + EventSubscriber(); +}; + +class EventInterface { + public: + virtual void SendEvent(uint8_t eventType, uint32_t adapter, const BSN::EncodedObject* data) = 0; + virtual void SendEvent(uint8_t eventType, BSN::FourCC eventId, const BSN::EncodedObject* data) = 0; + virtual void Subscribe(BSN::FourCC eventId, const uint32_t& tendrilId) = 0; + virtual ~EventInterface(); +}; + +class Application : public EventSubscriber, public SystemServer { + public: +}; + +class Library { + public: + static Library* Load(const char* path, Allocator& allocator); + static Library* LoadApplicationBundle(const char* name, Allocator& allocator); + + virtual void Destroy() = 0; + virtual ~Library(); + virtual void* GetProc(const char* name) = 0; + virtual void* GetProc(uint32_t ordinal) = 0; +}; + +class WindowsLibrary : public Library { + public: + /* 0004 */ void* m_module; + /* 0008 */ Allocator* m_allocator; + + void Destroy() override; + ~WindowsLibrary() override; + void* GetProc(const char* name) override; + void* GetProc(uint32_t ordinal) override; +}; + +bool GetProc(Library* library, void*& proc, uint32_t ordinal); +uint32_t StringCopy(void* dest, const char* source, uint32_t size); + +template +void Delete(T* object); +} + +// VERIFY: 4e792b5b auto +// OFFSET: 0x008C65F0 +template +void Battlenet::Allocator::Delete(T*& object) { + if (object) { + object->~T(); + this->Free(object); + object = nullptr; + } +} + +// INLINED +template +void Battlenet::Delete(T* object) { + Allocator* allocator = Battlenet::g_allocator; + + if (object) { + object->~T(); + allocator->Free(object); + } +} + +#endif diff --git a/WoW/Source/Battlenet/BattlenetMap.cpp b/WoW/Source/Battlenet/BattlenetMap.cpp new file mode 100644 index 0000000..199085e --- /dev/null +++ b/WoW/Source/Battlenet/BattlenetMap.cpp @@ -0,0 +1,123 @@ +#include "WoW/Source/Battlenet/BattlenetMap.h" + +// INLINED +Battlenet::String::String() { + this->m_block = nullptr; + this->m_string = nullptr; +} + +// VERIFY: 25c8cd5e manual +// OFFSET: 0x009BFF00 +Battlenet::String::String(const char* string) { + if (!string) { + this->m_block = nullptr; + this->m_string = nullptr; + return; + } + + uint32_t capacity = (static_cast(strlen(string)) + 40) & ~31u; + Block* block = static_cast(Battlenet::g_allocator->Alloc(capacity + sizeof(Block))); + + if (block) { + block->m_refCount = 1; + block->m_capacity = capacity; + Battlenet::StringCopy(block + 1, string, capacity); + } + + this->m_block = block; + this->m_string = reinterpret_cast(block + 1); +} + +// INLINED +Battlenet::String::String(const String& other) { + this->m_block = other.m_block; + this->m_string = other.m_string; + + if (this->m_block) { + this->m_block->m_refCount++; + } +} + +// INLINED +Battlenet::String::~String() { + this->Release(); +} + +// INLINED +void Battlenet::String::Release() { + if (this->m_block) { + if (this->m_block->m_refCount-- == 1) { + Battlenet::g_allocator->Free(this->m_block); + } + + this->m_block = nullptr; + } + + this->m_string = nullptr; +} + +// INLINED +Battlenet::String& Battlenet::String::operator=(const String& other) { + this->Release(); + this->m_block = other.m_block; + this->m_string = other.m_string; + + if (this->m_block) { + this->m_block->m_refCount++; + } + + return *this; +} + +// INLINED +const char* Battlenet::String::GetString() const { + return this->m_string ? this->m_string : ""; +} + +// INLINED +Battlenet::MapKey::MapKey() { + this->m_hash = 0; +} + +// VERIFY: 3ed3a97e manual +// OFFSET: 0x009C01B0 +Battlenet::MapKey::MapKey(const String& value) { + const char* string = value.GetString(); + uint32_t hash = 0x811C9DC5; + + for (uint8_t c = *string; c; c = *++string) { + hash = 16777619 * (c ^ hash); + } + + this->m_hash = hash | 0x80000000; + this->m_value.m_block = value.m_block; + this->m_value.m_string = value.m_string; + + if (value.m_block) { + value.m_block->m_refCount++; + } +} + +// VERIFY: 208e50e4 manual +// OFFSET: 0x009C0210 +Battlenet::MapKey::MapKey(const char* value) : MapKey(String(value)) { +} + +// VERIFY: 3e7e1881 manual +// OFFSET: 0x009C0260 +Battlenet::MapKey::~MapKey() { + this->m_hash = 0; +} + +// VERIFY: 84dfa24e manual +// OFFSET: 0x009C02A0 +Battlenet::MapKey& Battlenet::MapKey::operator=(const MapKey& other) { + this->m_hash = other.m_hash; + this->m_value = other.m_value; + return *this; +} + +// INLINED +bool Battlenet::MapKey::operator==(const MapKey& other) const { + return this->m_hash == other.m_hash && !strcmp(this->m_value.m_string, other.m_value.m_string); +} diff --git a/WoW/Source/Battlenet/BattlenetMap.h b/WoW/Source/Battlenet/BattlenetMap.h new file mode 100644 index 0000000..a26a89f --- /dev/null +++ b/WoW/Source/Battlenet/BattlenetMap.h @@ -0,0 +1,269 @@ +#ifndef WOW_SOURCE_BATTLENET_BATTLENETMAP_H +#define WOW_SOURCE_BATTLENET_BATTLENETMAP_H + +#include +#include +#include +#include +#include "WoW/Source/Battlenet/Battlenet.h" + +namespace Battlenet { +class String { + public: + struct Block { + /* 0000 */ uint32_t m_refCount; + /* 0004 */ uint32_t m_capacity; + }; + + /* 0000 */ Block* m_block; + /* 0004 */ const char* m_string; + + String(); + String(const char* string); + String(const String& other); + ~String(); + String& operator=(const String& other); + void Release(); + const char* GetString() const; +}; + +class MapKey { + public: + /* 0000 */ uint32_t m_hash; + /* 0004 */ String m_value; + + MapKey(); + MapKey(const String& value); + MapKey(const char* value); + ~MapKey(); + MapKey& operator=(const MapKey& other); + bool operator==(const MapKey& other) const; +}; + +template +class Map { + public: + class Entry { + public: + /* 0000 */ MapKey m_key; + /* 000C */ V m_value; + + Entry(); + Entry(const MapKey& key); + }; + + /* 0000 */ Entry* m_entries; + /* 0004 */ uint32_t m_used; + /* 0008 */ uint32_t m_capacity; + + Map(); + ~Map(); + void Clear(); + bool Find(const MapKey& key, uint32_t& index) const; + bool Next(uint32_t& iterator, MapKey& key, V& value) const; + uint32_t Reinsert(const Entry* entries, uint32_t count); + bool Remove(const MapKey& key, V& value); + void Resize(uint32_t capacity); + bool Shrink(); + V& operator[](const MapKey& key); +}; +} + +// INLINED +template +Battlenet::Map::Entry::Entry() { +} + +// INLINED +template +Battlenet::Map::Entry::Entry(const MapKey& key) : m_key(key), m_value() { +} + +// INLINED +template +Battlenet::Map::Map() { + this->m_entries = nullptr; + this->m_used = 0; + this->m_capacity = 0; +} + +// INLINED +template +Battlenet::Map::~Map() { + this->Clear(); +} + +// VERIFY: 51ae2a94 manual +// OFFSET: 0x009C06E0 +template +void Battlenet::Map::Clear() { + for (uint32_t i = 0; i < this->m_capacity; i++) { + if (this->m_entries[i].m_key.m_hash) { + this->m_entries[i].~Entry(); + } + } + + this->m_used = 0; + + if (this->m_entries) { + Battlenet::g_allocator->Free(this->m_entries); + this->m_entries = nullptr; + this->m_capacity = 0; + } +} + +// VERIFY: c3f75e70 manual +// OFFSET: 0x009C02F0 +template +bool Battlenet::Map::Find(const MapKey& key, uint32_t& index) const { + if (!this->m_capacity) { + return false; + } + + index = key.m_hash & (this->m_capacity - 1); + + while (this->m_entries[index].m_key.m_hash) { + if (this->m_entries[index].m_key == key) { + return true; + } + + index = (index + 1) & (this->m_capacity - 1); + } + + return false; +} + +// VERIFY: 4da873ed manual +// OFFSET: 0x009C0420 +template +bool Battlenet::Map::Next(uint32_t& iterator, MapKey& key, V& value) const { + if (iterator >= this->m_capacity) { + return false; + } + + while (!this->m_entries[iterator].m_key.m_hash) { + if (++iterator >= this->m_capacity) { + return false; + } + } + + key = this->m_entries[iterator].m_key; + value = this->m_entries[iterator].m_value; + iterator++; + return true; +} + +// VERIFY: 5e206c99 manual +// OFFSET: 0x009C0390 +template +uint32_t Battlenet::Map::Reinsert(const Entry* entries, uint32_t count) { + uint32_t inserted = 0; + + for (; count; count--, entries++) { + uint32_t index; + + if (entries->m_key.m_hash && !this->Find(entries->m_key, index)) { + new (&this->m_entries[index]) Entry(*entries); + inserted++; + } + } + + return inserted; +} + +// VERIFY: 1062102e manual +// OFFSET: 0x009C0860 +template +bool Battlenet::Map::Remove(const MapKey& key, V& value) { + uint32_t index; + + if (!this->Find(key, index)) { + return false; + } + + value = this->m_entries[index].m_value; + this->m_entries[index].~Entry(); + this->m_used--; + + if (this->Shrink()) { + return true; + } + + index = (index + 1) & (this->m_capacity - 1); + + while (this->m_entries[index].m_key.m_hash) { + uint32_t target; + + if (!this->Find(this->m_entries[index].m_key, target)) { + new (&this->m_entries[target]) Entry(this->m_entries[index]); + this->m_entries[index].~Entry(); + } + + index = (index + 1) & (this->m_capacity - 1); + } + + return true; +} + +// VERIFY: 5d6163b0 manual +// OFFSET: 0x009C0490 +template +void Battlenet::Map::Resize(uint32_t capacity) { + uint32_t oldCapacity = this->m_capacity; + Entry* oldEntries = this->m_entries; + + this->m_entries = static_cast(Battlenet::g_allocator->Alloc(sizeof(Entry) * capacity)); + this->m_capacity = capacity; + + for (uint32_t i = 0; i < capacity; i++) { + new (&this->m_entries[i]) Entry(); + } + + if (oldEntries) { + this->Reinsert(oldEntries, oldCapacity); + + for (uint32_t i = 0; i < oldCapacity; i++) { + if (oldEntries[i].m_key.m_hash) { + oldEntries[i].~Entry(); + } + } + + Battlenet::g_allocator->Free(oldEntries); + } +} + +// VERIFY: c6cc5a2e auto +// OFFSET: 0x009C0770 +template +bool Battlenet::Map::Shrink() { + uint32_t capacity = this->m_capacity; + + if (this->m_used >= (3 * capacity) >> 3 || capacity <= 8) { + return false; + } + + this->Resize(capacity >> 1 < 8 ? 8 : capacity >> 1); + return true; +} + +// VERIFY: 1d94e297 manual +// OFFSET: 0x009C07C0 +template +V& Battlenet::Map::operator[](const MapKey& key) { + uint32_t capacity = this->m_capacity; + + if (this->m_used >= (3 * capacity) >> 2) { + this->Resize(2 * capacity < 8 ? 8 : 2 * capacity); + } + + uint32_t index; + + if (!this->Find(key, index)) { + this->m_used++; + new (&this->m_entries[index]) Entry(key); + } + + return this->m_entries[index].m_value; +} + +#endif diff --git a/WoW/Source/Battlenet/BattlenetProtocol.cpp b/WoW/Source/Battlenet/BattlenetProtocol.cpp new file mode 100644 index 0000000..4b73715 --- /dev/null +++ b/WoW/Source/Battlenet/BattlenetProtocol.cpp @@ -0,0 +1,370 @@ +#include "WoW/Source/Battlenet/BattlenetProtocol.h" +#include + +// STATIC: 0x00D4511C +BSN::Protocol::Protocol Protocol::s_protocol(Protocol::s_bytecode, sizeof(Protocol::s_bytecode), Protocol::s_codeInfo, sizeof(Protocol::s_codeInfo) / sizeof(Protocol::s_codeInfo[0])); + +// STATIC: 0x00DCEE80 +BSN::AsciiString<63> Battlenet::Event::AuthModule::RequestGameAccount("RequestGameAccount"); + +// STATIC: 0x00DCEEC8 +BSN::AsciiString<63> Battlenet::Event::AuthModule::RequestSurveyInfo("RequestSurveyInfo"); + +// STATIC: 0x00DCEF10 +BSN::AsciiString<63> Battlenet::Event::AuthModule::FinalizeMatrixCard("FinalizeMatrixCard"); + +// STATIC: 0x00DCEF58 +BSN::AsciiString<63> Battlenet::Event::AuthModule::RequestToken("RequestToken"); + +// STATIC: 0x00DCEFA0 +BSN::AsciiString<63> Battlenet::Event::AuthModule::CommitMatrixCard("CommitMatrixCard"); + +// STATIC: 0x00DCEFE8 +BSN::AsciiString<63> Battlenet::Event::AuthModule::SurveyDialogComplete("SurveyDialogComplete"); + +// STATIC: 0x00DCF030 +BSN::AsciiString<63> Battlenet::Event::AuthModule::RequestMatrixCard("RequestMatrixCard"); + +// STATIC: 0x00DCF078 +BSN::AsciiString<63> Battlenet::Event::AuthModule::DisplayAgreement("DisplayAgreement"); + +// STATIC: 0x00DCF0C0 +BSN::AsciiString<63> Battlenet::Event::AuthModule::RequestVirtualKeypadPIN("RequestVirtualKeypadPIN"); + +// STATIC: 0x00DCF108 +BSN::AsciiString<63> Battlenet::Event::AuthModule::EnterMatrixCard("EnterMatrixCard"); + +// STATIC: 0x00DCF150 +BSN::AsciiString<63> Battlenet::Event::AuthModule::ClearGameAccounts("ClearGameAccounts"); + +// STATIC: 0x00DCF198 +BSN::AsciiString<63> Battlenet::Event::AuthModule::RevertMatrixCard("RevertMatrixCard"); + +// STATIC: 0x00DCF1E0 +BSN::AsciiString<63> Battlenet::Event::AuthModule::RequestPassword("RequestPassword"); + +// STATIC: 0x00DCF228 +BSN::AsciiString<63> Battlenet::Event::AuthModule::AddGameAccount("AddGameAccount"); + +// STATIC: 0x00DCF270 +BSN::AsciiString<63> Battlenet::Event::AuthModule::ShowSurveyDialog("ShowSurveyDialog"); + +// STATIC: 0x00DCF2B8 +BSN::AsciiString<63> Battlenet::Event::AuthModule::AcceptAgreement("AcceptAgreement"); + +// STATIC: 0x00D45154 +BSN::FourCC Battlenet::Program::WOW("WoW"); + +// INLINED +Battlenet::Presence::FieldVal::FieldVal() { + this->m_tag = -1; + memset(this->m_value, 0, sizeof(this->m_value)); +} + +// VERIFY: cfb3016d manual +// OFFSET: 0x005327B0 +Battlenet::Friends::FriendInvite& Battlenet::Friends::FriendInvite::operator=(const FriendInvite& other) { + this->m_presenceId = other.m_presenceId; + this->m_message = other.m_message; + this->unk_0210 = other.unk_0210; + this->m_time = other.m_time; + return *this; +} + +// INLINED +Battlenet::Authentication::ModuleParam::ModuleParam() { + this->m_tag = -1; + memset(this->m_value, 0, sizeof(this->m_value)); +} + +// INLINED +Battlenet::Authentication::Request::Request() { + this->m_tag = -1; + memset(this->m_value, 0, sizeof(this->m_value)); +} + +// INLINED +Battlenet::Authentication::Response::Response() { + this->m_tag = -1; + memset(this->m_value, 0, sizeof(this->m_value)); +} + +// INLINED +Battlenet::Service::State::State() { + this->m_tag = -1; + memset(this->m_value, 0, sizeof(this->m_value)); +} + +// INLINED +Battlenet::Realm::InfoUpdate::InfoUpdate() { + this->m_tag = -1; + memset(this->m_value, 0, sizeof(this->m_value)); +} + +// INLINED +Battlenet::Realm::Request::Request() { + this->m_tag = -1; + memset(this->m_value, 0, sizeof(this->m_value)); +} + +// INLINED +Battlenet::Realm::List::List() { + this->m_tag = -1; + memset(this->m_value, 0, sizeof(this->m_value)); +} + +// INLINED +Battlenet::Realm::JoinResponse::JoinResponse() { + this->m_tag = -1; + memset(this->m_value, 0, sizeof(this->m_value)); +} + +// INLINED +Battlenet::Realm::Response::Response() { + this->m_tag = -1; + memset(this->m_value, 0, sizeof(this->m_value)); +} + +// INLINED +Battlenet::Event::Creep::Portal::Portal() { + this->m_tag = -1; + memset(this->m_value, 0, sizeof(this->m_value)); +} + +// VERIFY: 37efee87 auto +// OFFSET: 0x008C6A40 +Battlenet::Event::Creep::Invoke::Invoke() { + this->m_tag = -1; + memset(this->m_value, 0, sizeof(this->m_value)); +} + +// INLINED +Battlenet::Event::Larva::Invoke::Invoke() { + this->m_tag = -1; + memset(this->m_value, 0, sizeof(this->m_value)); +} + +// VERIFY: d7ede7c5 manual +// OFFSET: 0x008C66A0 +Battlenet::Authentication::Settings::Settings() { + this->m_seedLength = 0; + this->m_program.m_value = 0; + this->m_platform.m_value = 0; + this->m_locale.m_value = 0; + this->m_systemLocale.m_value = 0; + this->m_components.m_count = 0; + + for (int32_t i = 0; i < 63; i++) { + this->m_components.m_data[i].m_program.m_value = 0; + this->m_components.m_data[i].m_platform.m_value = 0; + } +} + +// VERIFY: 12c6d6a9 auto +// OFFSET: 0x009C5090 +int32_t ProtocolHard::TypeInfoOf::Encode(const Battlenet::IP4::AddressPort& value, BSN::Hard::Encoder& encoder) { + int32_t result = encoder.PutAlignedData(4, value.m_address); + + if (result) { + return result; + } + + return encoder.PutAlignedData(2, value.m_port); +} + +// VERIFY: d7de79e1 auto +// OFFSET: 0x009C50C0 +int32_t ProtocolHard::TypeInfoOf::Decode(Battlenet::IP4::AddressPort& value, BSN::Hard::Decoder& decoder) { + int32_t result = decoder.GetAlignedData(4, value.m_address); + + if (result) { + return result; + } + + return decoder.GetAlignedData(2, value.m_port); +} + +// VERIFY: 93bd1407 manual +// OFFSET: 0x009C50F0 +int32_t ProtocolHard::TypeInfoOf::Encode(const Battlenet::IP4::AddressPort& value, BSN::Hard::SizeEncoder& encoder) { + encoder.m_size = ((((encoder.m_size + 7) & ~7u) + 32) & ~7u) + 16; + return BSN::CODEC_VALID; +} + +// VERIFY: f38cf32d manual +// OFFSET: 0x009C5110 +int32_t ProtocolHard::TypeInfoOf::Encode(const Battlenet::Client::DNSInfo& value, BSN::Hard::Encoder& encoder) { + uint32_t count = value.m_addresses.m_count; + + if (count > 0x7F) { + return BSN::CODEC_INVALID; + } + + int32_t result = encoder.PutBits(7, count); + + if (result) { + return result; + } + + for (uint32_t i = 0; i < count; i++) { + result = encoder.PutAlignedData(4, value.m_addresses.m_data[i].m_value); + + if (result) { + return result; + } + } + + uint32_t length = value.m_name.m_length; + + if (length > 0xFF) { + return BSN::CODEC_INVALID; + } + + result = encoder.PutBits(8, length); + + if (result) { + return result; + } + + return encoder.PutAlignedData(length, reinterpret_cast(value.m_name.m_data)); +} + +// VERIFY: 451c706b manual +// OFFSET: 0x009C52C0 +int32_t ProtocolHard::TypeInfoOf::Encode(const Battlenet::Client::DNSInfo& value, BSN::Hard::SizeEncoder& encoder) { + uint32_t count = value.m_addresses.m_count; + + if (count > 0x7F) { + return BSN::CODEC_INVALID; + } + + encoder.m_size += 7; + + for (; count; count--) { + encoder.m_size = ((encoder.m_size + 7) & ~7u) + 32; + } + + uint32_t length = value.m_name.m_length; + + if (length > 0xFF) { + return BSN::CODEC_INVALID; + } + + encoder.m_size += 8; + encoder.m_size = ((encoder.m_size + 7) & ~7u) + 8 * length; + return BSN::CODEC_VALID; +} + +// VERIFY: 2482ba92 manual +// OFFSET: 0x009C5320 +int32_t ProtocolHard::TypeInfoOf::Encode(const Battlenet::Authentication::Component& value, BSN::Hard::Encoder& encoder) { + int32_t result = encoder.PutUInt32(value.m_program.m_value); + + if (result) { + return result; + } + + result = encoder.PutUInt32(value.m_platform.m_value); + + if (result) { + return result; + } + + return encoder.PutBits(32, value.m_version); +} + +// VERIFY: 0d670084 manual +// OFFSET: 0x009C5400 +int32_t ProtocolHard::TypeInfoOf::Encode(const Battlenet::Authentication::Settings& value, BSN::Hard::Encoder& encoder) { + uint32_t seedLength = value.m_seedLength; + + if (seedLength > 0x3FF) { + return BSN::CODEC_INVALID; + } + + int32_t result = encoder.PutBits(10, seedLength); + + if (result) { + return result; + } + + result = encoder.PutAlignedData(seedLength, value.m_seed); + + if (result) { + return result; + } + + result = encoder.PutUInt32(value.m_program.m_value); + + if (result) { + return result; + } + + result = encoder.PutUInt32(value.m_platform.m_value); + + if (result) { + return result; + } + + result = encoder.PutUInt32(value.m_locale.m_value); + + if (result) { + return result; + } + + result = encoder.PutUInt32(value.m_systemLocale.m_value); + + if (result) { + return result; + } + + uint32_t componentCount = value.m_components.m_count; + + if (componentCount > 0x3F) { + return BSN::CODEC_INVALID; + } + + result = encoder.PutBits(6, componentCount); + + if (result) { + return result; + } + + for (uint32_t i = 0; i < componentCount; i++) { + result = ProtocolHard::TypeInfoOf::Encode(value.m_components.m_data[i], encoder); + + if (result) { + return result; + } + } + + return BSN::CODEC_VALID; +} + +// VERIFY: b7d31bbb manual +// OFFSET: 0x009C5610 +int32_t ProtocolHard::TypeInfoOf::Encode(const Battlenet::Authentication::Settings& value, BSN::Hard::SizeEncoder& encoder) { + uint32_t seedLength = value.m_seedLength; + + if (seedLength > 0x3FF) { + return BSN::CODEC_INVALID; + } + + encoder.m_size += 10; + encoder.m_size = ((encoder.m_size + 7) & ~7u) + 8 * seedLength + 128; + + uint32_t componentCount = value.m_components.m_count; + + if (componentCount > 0x3F) { + return BSN::CODEC_INVALID; + } + + encoder.m_size += 6; + + for (uint32_t i = 0; i < componentCount; i++) { + encoder.m_size += 64; + encoder.m_size += 32; + } + + return BSN::CODEC_VALID; +} diff --git a/WoW/Source/Battlenet/BattlenetProtocol.h b/WoW/Source/Battlenet/BattlenetProtocol.h new file mode 100644 index 0000000..12fcfe7 --- /dev/null +++ b/WoW/Source/Battlenet/BattlenetProtocol.h @@ -0,0 +1,446 @@ +#ifndef WOW_SOURCE_BATTLENET_BATTLENETPROTOCOL_H +#define WOW_SOURCE_BATTLENET_BATTLENETPROTOCOL_H + +#include +#include +#include "WoW/Source/Battlenet/Battlenet.h" +#include "WoW/Source/Battlenet/BSN/Encoder.h" +#include "WoW/Source/Battlenet/BSN/Protocol.h" + +namespace Battlenet { +namespace Authentication { +struct Component { + /* 0000 */ BSN::FourCC m_program; + /* 0004 */ BSN::FourCC m_platform; + /* 0008 */ uint32_t m_version; +}; + +struct Settings { + /* 0000 */ uint32_t m_seedLength; + /* 0004 */ uint8_t m_seed[1024]; + /* 0404 */ BSN::FourCC m_program; + /* 0408 */ BSN::FourCC m_platform; + /* 040C */ BSN::FourCC m_locale; + /* 0410 */ BSN::FourCC m_systemLocale; + /* 0414 */ BSN::Array m_components; + + Settings(); +}; + +struct ModuleParam : public BSN::Choice { + union { + /* 0004 */ BSN::String<256> m_string; + /* 0004 */ uint32_t m_int; + /* 0004 */ uint8_t m_value[0x40C]; + }; + + ModuleParam(); +}; + +struct ModuleMessage { + /* 0000 */ uint32_t m_moduleId; + /* 0004 */ BSN::AsciiString<63> m_name; + /* 0048 */ BSN::Array m_params; +}; + +struct ModuleRequest { + /* 0000 */ BSN::AsciiString<63> m_name; + /* 0044 */ uint32_t m_moduleId; + /* 0048 */ BSN::Array m_params; +}; + +struct Complete { + /* 0000 */ uint8_t unk_0000[284]; + /* 011C */ BSN::AsciiString<39> m_accountName; + /* 0148 */ uint32_t m_accountFlags; + /* 014C */ uint32_t m_accountFlags2; +}; + +struct Failure { + /* 0000 */ uint16_t m_error; +}; + +struct Request : public BSN::Choice { + union { + /* 0004 */ BSN::AsciiString<320> m_logon; + /* 0004 */ ModuleMessage m_module; + /* 0004 */ uint8_t m_value[0x108C]; + }; + + Request(); +}; + +struct Response : public BSN::Choice { + union { + /* 0004 */ ModuleRequest m_module; + /* 0004 */ Complete m_complete; + /* 0004 */ Failure m_failure; + /* 0004 */ uint8_t m_value[0x108C]; + }; + + Response(); +}; +} + +namespace Service { +struct State : public BSN::Choice { + union { + /* 0004 */ uint32_t m_recovered; + /* 0004 */ uint8_t m_value[0x4]; + }; + + State(); +}; +} + +namespace Realm { +struct Address { + /* 0000 */ uint8_t m_region; + /* 0001 */ uint8_t m_battlegroup; + /* 0004 */ uint32_t m_id; +}; + +struct CharacterCount { + /* 0000 */ uint8_t m_region; + /* 0001 */ uint8_t m_battlegroup; + /* 0004 */ uint32_t m_id; + /* 0008 */ uint16_t m_count; +}; + +struct Build { + /* 0000 */ BSN::AsciiString<23> m_version; + /* 001C */ uint32_t m_build; + /* 0020 */ IP4::AddressPort m_address; +}; + +struct Info { + /* 0000 */ uint8_t m_flags; + /* 0004 */ BSN::String<255> m_name; + /* 040C */ uint32_t m_type; + /* 0410 */ uint32_t m_category; + /* 0414 */ uint32_t m_otherFlags; + /* 0418 */ float m_population; + /* 041C */ BSN::Optional m_build; +}; + +struct InfoUpdate : public BSN::Choice { + union { + /* 0004 */ Info m_info; + /* 0004 */ uint8_t m_value[0x448]; + }; + + InfoUpdate(); +}; + +struct Update { + /* 0000 */ uint8_t m_region; + /* 0001 */ uint8_t m_battlegroup; + /* 0004 */ uint32_t m_id; + /* 0008 */ InfoUpdate m_info; +}; + +struct ListRequest { + /* 0000 */ bool m_subscribe; + /* 0004 */ uint32_t unk_0004; + /* 0008 */ uint32_t unk_0008; +}; + +struct Request : public BSN::Choice { + union { + /* 0004 */ ListRequest m_list; + /* 0004 */ BSN::Optional
m_join; + /* 0004 */ uint8_t m_value[0xC]; + }; + + Request(); +}; + +struct List : public BSN::Choice { + union { + /* 0004 */ BSN::Array m_characterCounts; + /* 0004 */ uint8_t m_value[0x304]; + }; + + List(); +}; + +struct JoinInfo { + /* 0000 */ BSN::FixedArray m_sessionKey; + /* 0028 */ IP4::AddressPort m_address; +}; + +struct JoinResponse : public BSN::Choice { + union { + /* 0004 */ JoinInfo m_info; + /* 0004 */ uint32_t m_error; + /* 0004 */ uint8_t m_value[0x30]; + }; + + JoinResponse(); +}; + +struct Response : public BSN::Choice { + union { + /* 0004 */ Update m_update; + /* 0004 */ List m_list; + /* 0004 */ JoinResponse m_join; + /* 0004 */ uint8_t m_value[0x454]; + }; + + Response(); +}; +} + +namespace Program { +extern BSN::FourCC WOW; +} + +namespace Toon { +struct FullName { + /* 0000 */ uint32_t m_region; + /* 0004 */ BSN::FourCC m_program; + /* 0008 */ uint32_t m_realm; + /* 000C */ BSN::String<25> m_name; +}; +} + +namespace Presence { +struct AccountName { + /* 0000 */ BSN::String<32> m_givenName; + /* 008C */ BSN::String<32> m_surname; +}; + +struct FieldVal : public BSN::Choice { + union { + /* 0004 */ bool m_bool; + /* 0004 */ BSN::FourCC m_fourCC; + /* 0004 */ int32_t m_int; + /* 0004 */ BSN::String<127> m_string; + /* 0004 */ Toon::FullName m_toonName; + /* 0004 */ AccountName m_accountName; + /* 0004 */ uint8_t m_value[0x208]; + }; + + FieldVal(); +}; + +struct FieldUpdate { + /* 0000 */ uint32_t m_presenceId; + /* 0004 */ uint32_t m_field; + /* 0008 */ FieldVal m_value; +}; + +struct BlockList { + /* 0000 */ BSN::Array m_accounts; + /* 0194 */ BSN::Array m_toons; +}; +} + +namespace Chat { +struct MemberList { + /* 0000 */ BSN::Array m_members; +}; +} + +namespace Friends { +struct FriendInvite { + /* 0000 */ uint32_t m_presenceId; + /* 0004 */ BSN::Optional> m_message; + /* 0210 */ uint8_t unk_0210; + /* 0214 */ int32_t m_time; + + FriendInvite& operator=(const FriendInvite& other); +}; + +struct FriendInviteContainer { + /* 0000 */ BSN::Array m_invites; +}; + +struct FriendList { + /* 0000 */ BSN::Array m_friends; + /* 0194 */ BSN::Array unk_0194; +}; + +struct FriendsOfFriendList { + /* 0000 */ uint32_t m_presenceId; + /* 0004 */ BSN::Array m_friends; +}; +} + +namespace Event { +namespace Creep { +struct Portal : public BSN::Choice { + union { + /* 0004 */ BSN::AsciiString<31> m_portal; + /* 0004 */ uint8_t m_value[0x24]; + }; + + Portal(); +}; + +struct Logoff { + /* 0000 */ uint32_t unk_0000[3]; +}; + +struct Invoke : public BSN::Choice { + union { + /* 0004 */ Authentication::Request m_authentication; + /* 0004 */ Realm::Request m_realm; + /* 0004 */ Logoff m_logoff; + /* 0004 */ Portal m_portal; + /* 0004 */ uint8_t m_value[0xBEFF0]; + }; + + Invoke(); +}; +} + +namespace Larva { +struct Invoke : public BSN::Choice { + union { + /* 0004 */ Authentication::Response m_authentication; + /* 0004 */ Service::State m_service; + /* 0004 */ Realm::Response m_realm; + /* 0004 */ uint8_t m_value[0x27124]; + }; + + Invoke(); +}; +} + +namespace Update { +struct Invoke { + /* 0000 */ BSN::FourCC m_program; + /* 0004 */ BSN::FourCC m_component; + /* 0008 */ BSN::AsciiString<255> m_patch; + /* 010C */ uint32_t unk_010C; +}; +} + +namespace AuthModule { +extern BSN::AsciiString<63> RequestGameAccount; +extern BSN::AsciiString<63> ShowSurveyDialog; +extern BSN::AsciiString<63> FinalizeMatrixCard; +extern BSN::AsciiString<63> RequestToken; +extern BSN::AsciiString<63> CommitMatrixCard; +extern BSN::AsciiString<63> SurveyDialogComplete; +extern BSN::AsciiString<63> RequestMatrixCard; +extern BSN::AsciiString<63> AcceptAgreement; +extern BSN::AsciiString<63> RequestVirtualKeypadPIN; +extern BSN::AsciiString<63> EnterMatrixCard; +extern BSN::AsciiString<63> ClearGameAccounts; +extern BSN::AsciiString<63> RevertMatrixCard; +extern BSN::AsciiString<63> RequestPassword; +extern BSN::AsciiString<63> AddGameAccount; +extern BSN::AsciiString<63> RequestSurveyInfo; +extern BSN::AsciiString<63> DisplayAgreement; +} +} +} + +class Protocol { + public: + template + struct TypeIdOf; + + static const uint8_t s_bytecode[0x2CA4E]; + static const void* const s_codeInfo[0x28D9]; + static BSN::Protocol::Protocol s_protocol; +}; + +template <> +struct Protocol::TypeIdOf { + static const uint32_t s_typeId = 3037; +}; + +template <> +struct Protocol::TypeIdOf { + static const uint32_t s_typeId = 1137; +}; + +template <> +struct Protocol::TypeIdOf { + static const uint32_t s_typeId = 1672; +}; + +template <> +struct Protocol::TypeIdOf { + static const uint32_t s_typeId = 2901; +}; + +template <> +struct Protocol::TypeIdOf { + static const uint32_t s_typeId = 466; +}; + +template <> +struct Protocol::TypeIdOf { + static const uint32_t s_typeId = 3086; +}; + +template <> +struct Protocol::TypeIdOf { + static const uint32_t s_typeId = 3329; +}; + +template <> +struct Protocol::TypeIdOf { + static const uint32_t s_typeId = 3368; +}; + +template <> +struct Protocol::TypeIdOf { + static const uint32_t s_typeId = 3364; +}; + +template <> +struct Protocol::TypeIdOf { + static const uint32_t s_typeId = 371; +}; + +template <> +struct Protocol::TypeIdOf { + static const uint32_t s_typeId = 3105; +}; + +template <> +struct Protocol::TypeIdOf { + static const uint32_t s_typeId = 3092; +}; + +template <> +struct Protocol::TypeIdOf { + static const uint32_t s_typeId = 3097; +}; + +class ProtocolHard { + public: + template + struct TypeInfoOf; +}; + +template <> +struct ProtocolHard::TypeInfoOf { + static int32_t Encode(const Battlenet::IP4::AddressPort& value, BSN::Hard::Encoder& encoder); + static int32_t Encode(const Battlenet::IP4::AddressPort& value, BSN::Hard::SizeEncoder& encoder); + static int32_t Decode(Battlenet::IP4::AddressPort& value, BSN::Hard::Decoder& decoder); +}; + +template <> +struct ProtocolHard::TypeInfoOf { + static int32_t Encode(const Battlenet::Client::DNSInfo& value, BSN::Hard::Encoder& encoder); + static int32_t Encode(const Battlenet::Client::DNSInfo& value, BSN::Hard::SizeEncoder& encoder); +}; + +template <> +struct ProtocolHard::TypeInfoOf { + static int32_t Encode(const Battlenet::Authentication::Component& value, BSN::Hard::Encoder& encoder); +}; + +template <> +struct ProtocolHard::TypeInfoOf { + static int32_t Encode(const Battlenet::Authentication::Settings& value, BSN::Hard::Encoder& encoder); + static int32_t Encode(const Battlenet::Authentication::Settings& value, BSN::Hard::SizeEncoder& encoder); +}; + +#endif diff --git a/WoW/Source/Battlenet/GeneralFunction.cpp b/WoW/Source/Battlenet/GeneralFunction.cpp new file mode 100644 index 0000000..08a75b4 --- /dev/null +++ b/WoW/Source/Battlenet/GeneralFunction.cpp @@ -0,0 +1,250 @@ +#include "WoW/Source/Battlenet/GeneralFunction.h" +#include + +// INLINED +GeneralFunction::Arg::Arg() { + this->m_type = TYPE_NONE; +} + +// INLINED +GeneralFunction::Arg::Arg(const Arg& other) { + this->m_type = TYPE_NONE; + *this = other; +} + +// INLINED +GeneralFunction::Arg::~Arg() { + this->FreeData(); +} + +// INLINED +void GeneralFunction::Arg::FreeData() { + if (this->m_type == TYPE_OBJECT) { + this->m_object->DecRef(); + } + + if (this->m_type == TYPE_CALLBACK) { + this->m_callback->DecRef(); + } + + this->m_type = TYPE_NONE; +} + +// VERIFY: 954766ed auto +// OFFSET: 0x005311E0 +GeneralFunction::Arg& GeneralFunction::Arg::operator=(const Arg& other) { + this->FreeData(); + this->m_type = other.m_type; + + switch (other.m_type) { + case TYPE_BOOL: + this->m_bool = other.m_bool; + break; + case TYPE_INT: + case TYPE_UINT: + this->m_uint = other.m_uint; + break; + case TYPE_REAL: + this->m_real = other.m_real; + break; + case TYPE_FOURCC: + this->m_fourCC[0] = other.m_fourCC[0]; + this->m_fourCC[1] = other.m_fourCC[1]; + this->m_fourCC[2] = other.m_fourCC[2]; + this->m_fourCC[3] = other.m_fourCC[3]; + this->m_fourCC[4] = other.m_fourCC[4]; + break; + case TYPE_STRING: + this->m_string = other.m_string; + break; + case TYPE_OBJECT: + this->m_object = other.m_object; + this->m_object->IncRef(); + break; + case TYPE_CALLBACK: + this->m_callback = other.m_callback; + this->m_callback->IncRef(); + break; + default: + break; + } + + return *this; +} + +// VERIFY: b2a74774 auto +// OFFSET: 0x00530BE0 +int64_t GeneralFunction::Arg::ToInt64() const { + switch (this->m_type) { + case TYPE_BOOL: + return this->m_bool; + case TYPE_INT: + case TYPE_UINT: + return this->m_int; + case TYPE_REAL: + return static_cast(this->m_real); + case TYPE_FOURCC: { + uint32_t value = 0; + + for (const char* c = this->m_fourCC; *c; c++) { + value = (value << 8) | *c; + } + + return value; + } + case TYPE_STRING: + return _strtoi64(this->m_string, nullptr, 0); + default: + return 0; + } +} + +// VERIFY: f35f950c auto +// OFFSET: 0x00530C60 +uint64_t GeneralFunction::Arg::ToUInt64() const { + switch (this->m_type) { + case TYPE_BOOL: + return this->m_bool; + case TYPE_INT: + case TYPE_UINT: + return this->m_uint; + case TYPE_REAL: + return static_cast(this->m_real); + case TYPE_FOURCC: { + uint32_t value = 0; + + for (const char* c = this->m_fourCC; *c; c++) { + value = (value << 8) | *c; + } + + return value; + } + case TYPE_STRING: + return _strtoui64(this->m_string, nullptr, 0); + default: + return 0; + } +} + +// INLINED +const char* GeneralFunction::Arg::ToString() const { + if (this->m_type == TYPE_STRING) { + return this->m_string; + } + + if (this->m_type == TYPE_FOURCC) { + return this->m_fourCC; + } + + return nullptr; +} + +// INLINED +bool GeneralFunction::Arg::ToBool() const { + if (this->m_type == TYPE_BOOL) { + return this->m_bool; + } + + return this->ToUInt64() != 0; +} + +// INLINED +GeneralFunction::Arg& GeneralFunction::Arg::operator=(bool value) { + this->FreeData(); + this->m_type = TYPE_BOOL; + this->m_bool = value; + return *this; +} + +// INLINED +GeneralFunction::Arg& GeneralFunction::Arg::operator=(int64_t value) { + this->FreeData(); + this->m_type = TYPE_INT; + this->m_int = value; + return *this; +} + +// INLINED +GeneralFunction::Arg& GeneralFunction::Arg::operator=(uint64_t value) { + this->FreeData(); + this->m_type = TYPE_UINT; + this->m_uint = value; + return *this; +} + +// INLINED +GeneralFunction::Arg& GeneralFunction::Arg::operator=(const char* value) { + this->FreeData(); + this->m_type = TYPE_STRING; + this->m_string = value; + return *this; +} + +// INLINED +GeneralFunction::Arg& GeneralFunction::Arg::operator=(const BSN::EncodedObject* value) { + this->FreeData(); + this->m_type = TYPE_OBJECT; + this->m_object = value; + value->IncRef(); + return *this; +} + +// INLINED +GeneralFunction::Arg& GeneralFunction::Arg::operator=(Callback* value) { + this->FreeData(); + this->m_type = TYPE_CALLBACK; + this->m_callback = value; + value->IncRef(); + return *this; +} + +// INLINED +const BSN::EncodedObject* GeneralFunction::Arg::ToObject() const { + if (this->m_type == TYPE_OBJECT) { + return this->m_object; + } + + return nullptr; +} + +// INLINED +GeneralFunction::Callback::Callback() { + this->m_refCount = 0; +} + +// INLINED +GeneralFunction::SimpleCallback::SimpleCallback(SimpleCallbackFunc func, void* param) { + this->m_func = func; + this->m_param = param; +} + +// VERIFY: 73ce7bd6 manual +// OFFSET: 0x00530B90 +GeneralFunction::Callback::~Callback() { +} + +// VERIFY: 11b54380 auto +// OFFSET: 0x00530B70 +void GeneralFunction::Callback::IncRef() const { + const_cast(this)->m_refCount++; +} + +// VERIFY: 7a985aa3 manual +// OFFSET: 0x00530B80 +void GeneralFunction::Callback::DecRef() const { + if (const_cast(this)->m_refCount-- == 1) { + this->Destroy(); + } +} + +// VERIFY: 2cab31a0 auto +// OFFSET: 0x00530BC0 +void GeneralFunction::SimpleCallback::Call(int32_t argc, const Arg* args) const { + this->m_func(this->m_param, argc, args); +} + +// VERIFY: 7e8b3875 auto +// OFFSET: 0x00532950 +void GeneralFunction::SimpleCallback::Destroy() const { + delete this; +} diff --git a/WoW/Source/Battlenet/GeneralFunction.h b/WoW/Source/Battlenet/GeneralFunction.h new file mode 100644 index 0000000..d6b2f3a --- /dev/null +++ b/WoW/Source/Battlenet/GeneralFunction.h @@ -0,0 +1,84 @@ +#ifndef WOW_SOURCE_BATTLENET_GENERALFUNCTION_H +#define WOW_SOURCE_BATTLENET_GENERALFUNCTION_H + +#include +#include +#include "WoW/Source/Battlenet/BSN/BSNEncodeInterface.h" + +namespace GeneralFunction { +class Callback; + +class Arg { + public: + enum Type { + TYPE_NONE = 0, + TYPE_BOOL = 1, + TYPE_INT = 2, + TYPE_UINT = 3, + TYPE_REAL = 4, + TYPE_FOURCC = 5, + TYPE_STRING = 6, + TYPE_OBJECT = 7, + TYPE_CALLBACK = 8, + }; + + /* 0000 */ uint32_t m_type; + /* 0008 */ union { + bool m_bool; + int64_t m_int; + uint64_t m_uint; + double m_real; + char m_fourCC[5]; + const char* m_string; + const BSN::EncodedObject* m_object; + Callback* m_callback; + }; + + Arg(); + Arg(const Arg& other); + ~Arg(); + Arg& operator=(const Arg& other); + Arg& operator=(bool value); + Arg& operator=(int64_t value); + Arg& operator=(uint64_t value); + Arg& operator=(const char* value); + Arg& operator=(const BSN::EncodedObject* value); + Arg& operator=(Callback* value); + void FreeData(); + int64_t ToInt64() const; + uint64_t ToUInt64() const; + const char* ToString() const; + bool ToBool() const; + const BSN::EncodedObject* ToObject() const; +}; + +class Callback { + public: + /* 0004 */ uint32_t m_refCount; + + virtual ~Callback(); + virtual void Call(int32_t argc, const Arg* args) const = 0; + virtual void Destroy() const = 0; + virtual void IncRef() const; + virtual void DecRef() const; + + Callback(); +}; + +typedef void (*SimpleCallbackFunc)(void* param, int32_t argc, const Arg* args); + +class SimpleCallback : public Callback { + public: + /* 0008 */ SimpleCallbackFunc m_func; + /* 000C */ void* m_param; + + void Call(int32_t argc, const Arg* args) const override; + void Destroy() const override; + + SimpleCallback(SimpleCallbackFunc func, void* param); +}; + +typedef Arg (*Function)(void* param, int32_t argc, const Arg* args); +} + +#endif diff --git a/WoW/Source/Battlenet/Tumor/BNetStr1.cpp b/WoW/Source/Battlenet/Tumor/BNetStr1.cpp deleted file mode 100644 index 32f1232..0000000 --- a/WoW/Source/Battlenet/Tumor/BNetStr1.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "BNetStr1.h" diff --git a/WoW/Source/Battlenet/Tumor/BNetStr1.h b/WoW/Source/Battlenet/Tumor/BNetStr1.h deleted file mode 100644 index caae280..0000000 --- a/WoW/Source/Battlenet/Tumor/BNetStr1.h +++ /dev/null @@ -1,43 +0,0 @@ -#ifndef WOW_SOURCE_BATTLENET_TUMOR_BNETSTR1_H -#define WOW_SOURCE_BATTLENET_TUMOR_BNETSTR1_H - -#include -#include - -class BNetStr1 { - public: - /* 0000 */ uint32_t unk_0000; - /* 0004 */ uint8_t unk_0004[16]; - /* 0014 */ uint32_t unk_0014; - /* 0018 */ uint8_t unk_0018[4]; - /* 001C */ uint32_t unk_001C; - /* 0020 */ uint32_t unk_0020; - /* 0024 */ uint8_t unk_0024[1812]; - /* 0738 */ uint32_t unk_0738; - /* 073C */ uint32_t unk_073C; - /* 0740 */ uint32_t unk_0740; - /* 0744 */ uint32_t unk_0744; - /* 0748 */ uint32_t unk_0748; - /* 074C */ uint32_t unk_074C; - /* 0750 */ uint8_t unk_0750[8]; - /* 0758 */ uint32_t unk_0758; - /* 075C */ uint32_t unk_075C; - /* 0760 */ uint32_t unk_0760; - /* 0764 */ uint32_t unk_0764; - /* 0768 */ uint8_t unk_0768[8]; - /* 0770 */ uint32_t unk_0770; - /* 0774 */ uint32_t unk_0774; - /* 0778 */ uint32_t unk_0778; - /* 077C */ uint32_t unk_077C; - /* 0780 */ uint32_t unk_0780; - /* 0784 */ uint32_t unk_0784; - /* 0788 */ uint32_t unk_0788; - /* 078C */ uint32_t unk_078C; - /* 0790 */ uint8_t unk_0790[16]; - /* 07A0 */ uint32_t unk_07A0; - /* 07A4 */ uint32_t unk_07A4; - /* 07A8 */ uint32_t unk_07A8; - /* 07AC */ uint32_t unk_07AC; -}; - -#endif diff --git a/WoW/Source/Battlenet/Tumor/CreepTendril.cpp b/WoW/Source/Battlenet/Tumor/CreepTendril.cpp index 9cc7dee..175b003 100644 --- a/WoW/Source/Battlenet/Tumor/CreepTendril.cpp +++ b/WoW/Source/Battlenet/Tumor/CreepTendril.cpp @@ -1 +1,323 @@ -#include "CreepTendril.h" +#include "WoW/Source/Battlenet/Tumor/CreepTendril.h" +#include +#include +#include +#include "Engine/Source/Storm/H/storm.h" + +// STATIC: 0x00DCED30 +uint32_t Battlenet::CreepTendril::s_instances; + +// STATIC: 0x00DCED34 +Battlenet::CreepTendril::CreepInitializeFunc Battlenet::CreepTendril::s_creepInitialize; + +// STATIC: 0x00DCED38 +Battlenet::CreepTendril::CreepTeardownFunc Battlenet::CreepTendril::s_creepTeardown; + +// STATIC: 0x00DCED3C +Battlenet::CreepTendril::CreepCreateFunc Battlenet::CreepTendril::s_creepCreate; + +// STATIC: 0x00DCED40 +Battlenet::CreepTendril::CreepDestroyFunc Battlenet::CreepTendril::s_creepDestroy; + +// STATIC: 0x00DCED44 +Battlenet::Library* Battlenet::CreepTendril::s_creepModule; + +// VERIFY: 6aafdbb2 manual +// OFFSET: 0x009C18D0 +Battlenet::CreepTendril::Host::~Host() { +} + +// VERIFY: db46cbc5 auto +// OFFSET: 0x009C18B0 +void Battlenet::CreepTendril::Host::Log(const char* message) { + this->LogLevel(message, 5); +} + +// VERIFY: 74960614 auto +// OFFSET: 0x009C2460 +bool Battlenet::CreepTendril::Initialize() { + if (Battlenet::CreepTendril::s_creepModule) { + return true; + } + + Battlenet::CreepTendril::s_creepModule = Battlenet::Library::LoadApplicationBundle("Battle.net-prearxan", *Battlenet::g_allocator); + + if (!Battlenet::CreepTendril::s_creepModule) { + Battlenet::CreepTendril::s_creepModule = Battlenet::Library::LoadApplicationBundle("Battle.net", *Battlenet::g_allocator); + + if (!Battlenet::CreepTendril::s_creepModule) { + return false; + } + } + + Battlenet::CreepTendril::s_creepInitialize = reinterpret_cast(Battlenet::CreepTendril::s_creepModule->GetProc(1u)); + + if (Battlenet::CreepTendril::s_creepInitialize) { + Battlenet::CreepTendril::s_creepTeardown = reinterpret_cast(Battlenet::CreepTendril::s_creepModule->GetProc(2u)); + + if (Battlenet::CreepTendril::s_creepTeardown) { + Battlenet::CreepTendril::s_creepCreate = reinterpret_cast(Battlenet::CreepTendril::s_creepModule->GetProc(3u)); + + if (Battlenet::CreepTendril::s_creepCreate) { + if (Battlenet::GetProc(Battlenet::CreepTendril::s_creepModule, reinterpret_cast(Battlenet::CreepTendril::s_creepDestroy), 4) && Battlenet::CreepTendril::s_creepInitialize()) { + return true; + } + } + } + } + + Battlenet::CreepTendril::s_creepModule->Destroy(); + Battlenet::CreepTendril::s_creepModule = nullptr; + return false; +} + +// VERIFY: bd9022bf auto +// OFFSET: 0x009C25D0 +Battlenet::CreepTendril::Instance::Instance(const Authentication::Settings& settings, TumorManager& manager) : Tendril(Battlenet::Event::CREEP, manager) { + this->m_creep = nullptr; + memcpy(&this->m_settings, &settings, sizeof(this->m_settings)); + Battlenet::CreepTendril::s_instances++; + + BSN::Hard::SizeEncoder sizeEncoder; + ProtocolHard::TypeInfoOf::Encode(this->m_settings, sizeEncoder); + + uint32_t size = (sizeEncoder.m_size + 7) >> 3; + BSN::Hard::Encoder encoder; + encoder.SetData(_alloca(size), size); + ProtocolHard::TypeInfoOf::Encode(this->m_settings, encoder); + + this->m_creep = Battlenet::CreepTendril::s_creepCreate(this, encoder.m_data, (encoder.m_position + 7) >> 3); + + this->m_eventHandlers[1] = &Instance::ProcessEventData<1>; + this->m_eventHandlers[2] = &Instance::ProcessEventData<2>; + this->m_eventHandlers[3] = &Instance::ProcessEventData<3>; + this->m_eventHandlers[10] = &Instance::ProcessEventData<10>; + this->m_eventHandlers[11] = &Instance::ProcessEventData<11>; + this->m_eventHandlers[5] = &Instance::ProcessEventData<5>; + this->m_eventHandlers[6] = &Instance::ProcessEventData<6>; + this->m_eventHandlers[9] = &Instance::ProcessEventData<9>; + this->m_eventHandlers[8] = &Instance::ProcessEventData<8>; + this->m_eventHandlers[14] = &Instance::ProcessEventData<14>; + this->m_eventHandlers[15] = &Instance::ProcessEventData<15>; +} + +// VERIFY: 58336dcd auto +// OFFSET: 0x009C2840 +Battlenet::CreepTendril::Instance* Battlenet::CreepTendril::Instance::Create(const Authentication::Settings& settings, TumorManager& manager) { + if (!Battlenet::CreepTendril::s_instances && !Battlenet::CreepTendril::Initialize()) { + return nullptr; + } + + void* memory = Battlenet::g_allocator->Alloc(sizeof(Instance)); + + if (!memory) { + return nullptr; + } + + return new (memory) Instance(settings, manager); +} + +// VERIFY: 3c5d1abe auto +// OFFSET: [0x009C1A40, 0x009C1C50, 0x009C1CF0] +Battlenet::CreepTendril::Instance::~Instance() { + Battlenet::CreepTendril::s_creepDestroy(this->m_creep); + this->m_creep = nullptr; + + if (!--Battlenet::CreepTendril::s_instances && Battlenet::CreepTendril::s_creepModule) { + Battlenet::CreepTendril::s_creepTeardown(); + Battlenet::CreepTendril::s_creepModule->Destroy(); + Battlenet::CreepTendril::s_creepModule = nullptr; + } +} + +// OFFSET: 0x009C1CC0 +void Battlenet::CreepTendril::Instance::Destroy() { + Battlenet::Delete(this); +} + +// VERIFY: f6e9fe2a manual +// OFFSET: 0x009C1B10 +void Battlenet::CreepTendril::Instance::EnumFunctions(EnumFunctionsCallback callback, void* param) { + this->m_creep->EnumFunctions(callback, param); +} + +// VERIFY: 6bc061ba auto +// OFFSET: 0x009C1B50 +void Battlenet::CreepTendril::Instance::DoSubscriptions() { + this->m_eventAdapter->Subscribe(Battlenet::Event::DATAGRAM_CONNECTION_INIT, this->m_tendrilId); + this->m_eventAdapter->Subscribe(Battlenet::Event::S2_LOBBY, this->m_tendrilId); +} + +// VERIFY: 5e829b17 manual +// OFFSET: 0x009C2530 +void Battlenet::CreepTendril::Instance::RecvEvent(const Event::Header& header, const BSN::EncodedObject* data) { + BSN::BSNEncodedObjectPtr object(&header); + object.IncRef(); + this->m_creep->RecvEvent(&object, data); +} + +// VERIFY: eeea3cd7 manual +// OFFSET: 0x009C1D20 +void Battlenet::CreepTendril::Instance::Resolved(uint32_t request, const Client::DNSInfo& info) { + BSN::Hard::SizeEncoder sizeEncoder; + ProtocolHard::TypeInfoOf::Encode(info, sizeEncoder); + + BSN::Hard::Encoder encoder; + encoder.SetData(_alloca(sizeEncoder.m_size), sizeEncoder.m_size); + ProtocolHard::TypeInfoOf::Encode(info, encoder); + + this->m_creep->Resolved(request, encoder.m_data, (encoder.m_position + 7) >> 3); +} + +// VERIFY: ae8ecddb manual +// OFFSET: 0x009C1DB0 +void Battlenet::CreepTendril::Instance::Connected(uint32_t connection, const IP4::AddressPort& address) { + BSN::Hard::SizeEncoder sizeEncoder; + ProtocolHard::TypeInfoOf::Encode(address, sizeEncoder); + + BSN::Hard::Encoder encoder; + encoder.SetData(_alloca(sizeEncoder.m_size), sizeEncoder.m_size); + ProtocolHard::TypeInfoOf::Encode(address, encoder); + + this->m_creep->Connected(connection, encoder.m_data, (encoder.m_position + 7) >> 3); +} + +// VERIFY: 40115e88 manual +// OFFSET: 0x009C1B20 +void Battlenet::CreepTendril::Instance::Disconnected(uint32_t connection) { + this->m_creep->Disconnected(connection); +} + +// VERIFY: d4ecf866 auto +// OFFSET: 0x009C1B30 +bool Battlenet::CreepTendril::Instance::Recv(uint32_t connection, void* data, uint32_t size, uint32_t& used) { + return this->m_creep->Recv(connection, data, size, used); +} + +// VERIFY: 87b09612 manual +// OFFSET: 0x009C1E40 +bool Battlenet::CreepTendril::Instance::RecvDatagram(uint32_t connection, void* data, uint32_t size, const IP4::AddressPort& address) { + BSN::Hard::SizeEncoder sizeEncoder; + ProtocolHard::TypeInfoOf::Encode(address, sizeEncoder); + + uint32_t addressSize = sizeEncoder.m_size; + uint8_t* buffer = static_cast(_alloca(addressSize)); + + BSN::Hard::Encoder encoder; + encoder.SetData(buffer, addressSize); + ProtocolHard::TypeInfoOf::Encode(address, encoder); + + return this->m_creep->RecvDatagram(connection, data, size, buffer, addressSize); +} + +// VERIFY: 48ab284a manual +// OFFSET: 0x009C1B40 +void Battlenet::CreepTendril::Instance::Process(uint32_t time) { + this->m_creep->Process(time); +} + +// VERIFY: e27bead4 manual +// OFFSET: 0x009C1B80 +uint32_t Battlenet::CreepTendril::Instance::Resolve(uint32_t token, const char* hostname) { + return this->m_adapter->Resolve(token, hostname); +} + +// VERIFY: f9b90477 manual +// OFFSET: 0x009C1ED0 +uint32_t Battlenet::CreepTendril::Instance::Connect(const void* address, uint32_t addressSize) { + BSN::Hard::Decoder decoder; + decoder.SetData(address, addressSize); + + IP4::AddressPort decoded; + + if (ProtocolHard::TypeInfoOf::Decode(decoded, decoder)) { + DebugLog("Bad address from Creep"); + return 0; + } + + return this->m_adapter->Connect(decoded, this->m_tendrilId); +} + +// VERIFY: 225d7eb8 manual +// OFFSET: 0x009C1B90 +void Battlenet::CreepTendril::Instance::Disconnect(uint32_t connection) { + this->m_adapter->Disconnect(connection); +} + +// VERIFY: ba4c1f69 auto +// OFFSET: 0x009C1BA0 +bool Battlenet::CreepTendril::Instance::Send(uint32_t connection, const void* data, uint32_t size) { + return this->m_adapter->Send(connection, data, size); +} + +// VERIFY: 2472e52e auto +// OFFSET: 0x009C1BB0 +uint32_t Battlenet::CreepTendril::Instance::OpenDatagram(int32_t port) { + return this->m_adapter->OpenDatagram(port, this->m_tendrilId); +} + +// VERIFY: 08f27f1c manual +// OFFSET: 0x009C1BD0 +void Battlenet::CreepTendril::Instance::CloseDatagram(uint32_t connection) { + this->m_adapter->CloseDatagram(connection); +} + +// VERIFY: d3253092 manual +// OFFSET: 0x009C1F50 +bool Battlenet::CreepTendril::Instance::SendDatagram(uint32_t connection, const void* data, uint32_t size, const void* address, uint32_t addressSize) { + BSN::Hard::Decoder decoder; + decoder.SetData(address, addressSize); + + IP4::AddressPort decoded; + + if (ProtocolHard::TypeInfoOf::Decode(decoded, decoder)) { + DebugLog("Bad address from Creep"); + return false; + } + + return this->m_adapter->SendDatagram(connection, data, size, decoded); +} + +// VERIFY: a3ce1d3b auto +// OFFSET: 0x009C1BE0 +uint64_t Battlenet::CreepTendril::Instance::GetCurrentTime() const { + return this->m_adapter->GetCurrentTime(); +} + +// VERIFY: 2b779f09 auto +// OFFSET: 0x009C1BF0 +uint64_t Battlenet::CreepTendril::Instance::GetCurrentTick() const { + return this->m_adapter->GetCurrentTick(); +} + +// VERIFY: bd8c52da manual +// OFFSET: 0x009C1C00 +void Battlenet::CreepTendril::Instance::LogLevel(const char* message, int32_t level) { + this->m_adapter->LogLevel(message, level); +} + +// VERIFY: e12fdecc manual +// OFFSET: 0x009C1C10 +Battlenet::ApplicationFile* Battlenet::CreepTendril::Instance::OpenApplicationFile(const char* name) { + return this->m_adapter->OpenApplicationFile(name); +} + +// VERIFY: dc3d8a73 manual +// OFFSET: 0x009C1C20 +void Battlenet::CreepTendril::Instance::CloseApplicationFile(ApplicationFile* file) { + this->m_adapter->CloseApplicationFile(file); +} + +// VERIFY: a4b9282f manual +// OFFSET: 0x009C2760 +void Battlenet::CreepTendril::Instance::SendEvent(const BSN::EncodedObject* header, const BSN::EncodedObject* data) { + BSN::BSNEncodedObject decoded; + + if (!decoded.EncodedObject::WalkAndGet(header)) { + DebugLog("Bad event from Creep"); + return; + } + + EventHandler handler = this->m_eventHandlers[decoded.m_data.m_eventType]; + (this->*handler)(decoded.m_data, data); +} diff --git a/WoW/Source/Battlenet/Tumor/CreepTendril.h b/WoW/Source/Battlenet/Tumor/CreepTendril.h index 5447911..6fefb29 100644 --- a/WoW/Source/Battlenet/Tumor/CreepTendril.h +++ b/WoW/Source/Battlenet/Tumor/CreepTendril.h @@ -1,4 +1,117 @@ #ifndef WOW_SOURCE_BATTLENET_TUMOR_CREEPTENDRIL_H #define WOW_SOURCE_BATTLENET_TUMOR_CREEPTENDRIL_H +#include +#include +#include "WoW/Source/Battlenet/BattlenetProtocol.h" +#include "WoW/Source/Battlenet/Tumor/Tendril.h" +#include "WoW/Source/Battlenet/Tumor/TumorManager.h" + +namespace Battlenet { +namespace CreepTendril { +class Host { + public: + virtual ~Host(); + virtual uint32_t Resolve(uint32_t token, const char* hostname) = 0; + virtual uint32_t Connect(const void* address, uint32_t addressSize) = 0; + virtual void Disconnect(uint32_t connection) = 0; + virtual bool Send(uint32_t connection, const void* data, uint32_t size) = 0; + virtual uint32_t OpenDatagram(int32_t port) = 0; + virtual void CloseDatagram(uint32_t connection) = 0; + virtual bool SendDatagram(uint32_t connection, const void* data, uint32_t size, const void* address, uint32_t addressSize) = 0; + virtual uint64_t GetCurrentTime() const = 0; + virtual uint64_t GetCurrentTick() const = 0; + virtual void LogLevel(const char* message, int32_t level) = 0; + virtual void Log(const char* message); + virtual ApplicationFile* OpenApplicationFile(const char* name) = 0; + virtual void CloseApplicationFile(ApplicationFile* file) = 0; + virtual void SendEvent(const BSN::EncodedObject* header, const BSN::EncodedObject* data) = 0; +}; + +class Creep { + public: + virtual void unk_00() = 0; + virtual void unk_04() = 0; + virtual void EnumFunctions(EnumFunctionsCallback callback, void* param) = 0; + virtual void Resolved(uint32_t request, const void* info, uint32_t size) = 0; + virtual void Connected(uint32_t connection, const void* address, uint32_t size) = 0; + virtual void Disconnected(uint32_t connection) = 0; + virtual bool Recv(uint32_t connection, void* data, uint32_t size, uint32_t& used) = 0; + virtual bool RecvDatagram(uint32_t connection, void* data, uint32_t size, const void* address, uint32_t addressSize) = 0; + virtual void RecvEvent(const BSN::EncodedObject* header, const BSN::EncodedObject* data) = 0; + virtual void Process(uint32_t time) = 0; +}; + +typedef bool (*CreepInitializeFunc)(); +typedef void (*CreepTeardownFunc)(); +typedef Creep* (*CreepCreateFunc)(Host* host, const void* settings, uint32_t size); +typedef void (*CreepDestroyFunc)(Creep* creep); + +extern uint32_t s_instances; +extern CreepInitializeFunc s_creepInitialize; +extern CreepTeardownFunc s_creepTeardown; +extern CreepCreateFunc s_creepCreate; +extern CreepDestroyFunc s_creepDestroy; +extern Library* s_creepModule; + +bool Initialize(); + +class Instance : public Tendril, public Host { + public: + typedef int32_t (Instance::*EventHandler)(const Event::Header& header, const BSN::EncodedObject* data); + + static Instance* Create(const Authentication::Settings& settings, TumorManager& manager); + + /* 0020 */ Creep* m_creep; + /* 0024 */ Authentication::Settings m_settings; + /* 0730 */ EventHandler m_eventHandlers[16]; + + void RecvEvent(const Event::Header& header, const BSN::EncodedObject* data) override; + ~Instance() override; + void Destroy() override; + void DoSubscriptions() override; + void Resolved(uint32_t request, const Client::DNSInfo& info) override; + void Connected(uint32_t connection, const IP4::AddressPort& address) override; + void Disconnected(uint32_t connection) override; + bool Recv(uint32_t connection, void* data, uint32_t size, uint32_t& used) override; + bool RecvDatagram(uint32_t connection, void* data, uint32_t size, const IP4::AddressPort& address) override; + void Process(uint32_t time) override; + uint32_t Resolve(uint32_t token, const char* hostname) override; + uint32_t Connect(const void* address, uint32_t addressSize) override; + void Disconnect(uint32_t connection) override; + bool Send(uint32_t connection, const void* data, uint32_t size) override; + uint32_t OpenDatagram(int32_t port) override; + void CloseDatagram(uint32_t connection) override; + bool SendDatagram(uint32_t connection, const void* data, uint32_t size, const void* address, uint32_t addressSize) override; + uint64_t GetCurrentTime() const override; + uint64_t GetCurrentTick() const override; + void LogLevel(const char* message, int32_t level) override; + ApplicationFile* OpenApplicationFile(const char* name) override; + void CloseApplicationFile(ApplicationFile* file) override; + void SendEvent(const BSN::EncodedObject* header, const BSN::EncodedObject* data) override; + + Instance(const Authentication::Settings& settings, TumorManager& manager); + void EnumFunctions(EnumFunctionsCallback callback, void* param); + template + int32_t ProcessEventData(const Event::Header& header, const BSN::EncodedObject* data); +}; +} +} + +// VERIFY: 87aa9a8a manual +// OFFSET: [0x009C2040<1>, 0x009C20A0<2>, 0x009C2100<3>, 0x009C2160<10>, 0x009C21C0<11>, 0x009C2220<5>, 0x009C2280<6>, 0x009C22E0<9>, 0x009C2340<8>, 0x009C23A0<14>, 0x009C2400<15>] +template +int32_t Battlenet::CreepTendril::Instance::ProcessEventData(const Event::Header& header, const BSN::EncodedObject* data) { + if (header.m_target.m_type == 0) { + uint8_t eventType = EVENT_TYPE; + static_cast(this)->SendEvent(eventType, reinterpret_cast(header.m_target.m_value), data); + } else if (header.m_target.m_type == 1) { + uint32_t target = header.m_target.m_value; + uint8_t eventType = EVENT_TYPE; + static_cast(this)->SendEvent(eventType, reinterpret_cast(target), data); + } + + return 0; +} + #endif diff --git a/WoW/Source/Battlenet/Tumor/Tendril.cpp b/WoW/Source/Battlenet/Tumor/Tendril.cpp new file mode 100644 index 0000000..48590f3 --- /dev/null +++ b/WoW/Source/Battlenet/Tumor/Tendril.cpp @@ -0,0 +1,65 @@ +#include "WoW/Source/Battlenet/Tumor/Tendril.h" +#include "WoW/Source/Battlenet/Tumor/TumorManager.h" + +// INLINED +Battlenet::Service::Interface::Interface(TumorManager& manager) { + this->m_manager = &manager; + this->m_eventAdapter = nullptr; + this->m_tendrilId = 0; +} + +// VERIFY: 71c346c6 auto +// OFFSET: 0x00653A10 +void Battlenet::Service::Interface::RecvEvent(const Event::Header& header, const BSN::EncodedObject* data) { +} + +// VERIFY: d97051ab manual +// OFFSET: 0x009C1950 +Battlenet::Service::Interface::~Interface() { + if (this->m_tendrilId) { + this->m_manager->GetTumor()->RemoveTendril(this->m_tendrilId); + } +} + +// VERIFY: 0d162034 auto +// OFFSET: 0x009C1900 +void Battlenet::Service::Interface::Register() { + if (this->m_eventId.m_value) { + Tumor* tumor = this->m_manager->GetTumor(); + tumor->AllocTendrilId(this->m_tendrilId); + this->m_eventAdapter = tumor->AllocEventAdapter(this->m_eventId, *this, this->m_tendrilId); + tumor->Subscribe(this->m_eventId, *this, this->m_tendrilId); + } +} + +// VERIFY: ba55f5d0 manual +// OFFSET: 0x009C1AE0 +void Battlenet::Service::Interface::SendEvent(const uint8_t& eventType, const BSN::FourCC& eventId, const BSN::EncodedObject* data) { + if (this->m_eventAdapter) { + this->m_eventAdapter->SendEvent(eventType, eventId, data); + } +} + +// VERIFY: b8093540 manual +// OFFSET: 0x009C19A0 +Battlenet::Tendril::Tendril(BSN::FourCC eventId, TumorManager& manager) : Service::Interface(manager) { + this->m_eventId = eventId; + + if (this->m_eventId.m_value) { + Tumor* tumor = this->m_manager->GetTumor(); + tumor->AllocTendrilId(this->m_tendrilId); + this->m_eventAdapter = tumor->AllocEventAdapter(this->m_eventId, *this, this->m_tendrilId); + tumor->Subscribe(this->m_eventId, *this, this->m_tendrilId); + } + + this->m_adapter = manager.GetTumor()->AllocAdapter(*this, this->m_tendrilId); +} + +// OFFSET: 0x009C1C60 +Battlenet::Tendril::~Tendril() { +} + +// VERIFY: 84c27b8e auto +// OFFSET: 0x005EEB70 +void Battlenet::Tendril::DoSubscriptions() { +} diff --git a/WoW/Source/Battlenet/Tumor/Tendril.h b/WoW/Source/Battlenet/Tumor/Tendril.h new file mode 100644 index 0000000..be4e875 --- /dev/null +++ b/WoW/Source/Battlenet/Tumor/Tendril.h @@ -0,0 +1,39 @@ +#ifndef WOW_SOURCE_BATTLENET_TUMOR_TENDRIL_H +#define WOW_SOURCE_BATTLENET_TUMOR_TENDRIL_H + +#include +#include +#include "WoW/Source/Battlenet/Tumor/Tumor.h" + +namespace Battlenet { +class TumorManager; + +namespace Service { +class Interface : public EventSubscriber { + public: + /* 0008 */ TumorManager* m_manager; + /* 000C */ EventInterface* m_eventAdapter; + /* 0010 */ uint32_t m_tendrilId; + + void RecvEvent(const Event::Header& header, const BSN::EncodedObject* data) override; + ~Interface() override; + virtual void Destroy() = 0; + virtual void Register(); + virtual void SendEvent(const uint8_t& eventType, const BSN::FourCC& eventId, const BSN::EncodedObject* data); + + Interface(TumorManager& manager); +}; +} + +class Tendril : public Service::Interface, public SystemClient { + public: + /* 0018 */ Tumor::Adapter* m_adapter; + + ~Tendril() override; + virtual void DoSubscriptions(); + + Tendril(BSN::FourCC eventId, TumorManager& manager); +}; +} + +#endif diff --git a/WoW/Source/Battlenet/Tumor/Tumor.cpp b/WoW/Source/Battlenet/Tumor/Tumor.cpp index 84537ab..c660244 100644 --- a/WoW/Source/Battlenet/Tumor/Tumor.cpp +++ b/WoW/Source/Battlenet/Tumor/Tumor.cpp @@ -1 +1,542 @@ -#include "Tumor.h" +#include "WoW/Source/Battlenet/Tumor/Tumor.h" +#include +#include +#include "Engine/Source/Storm/H/storm.h" + +// VERIFY: ee519690 manual +// OFFSET: 0x009BFF90 +Battlenet::Tumor::Tumor(Application& application) { + this->m_application = &application; + this->m_nextTendrilId = 1; + + for (int32_t i = 0; i < 20; i++) { + this->m_eventBindings[i].m_subscriber = nullptr; + this->m_eventBindings[i].m_active = false; + this->m_eventBindings[i].m_tendrilId = 0; + this->m_eventBindings[i].m_eventId.m_value = 0; + } + + for (int32_t i = 0; i < 64; i++) { + this->m_connectionBindings[i].m_connection = 0; + this->m_connectionBindings[i].m_client = nullptr; + this->m_connectionBindings[i].m_active = false; + this->m_connectionBindings[i].m_tendrilId = 0; + } + + for (int32_t i = 0; i < 64; i++) { + this->m_tokenBindings[i].m_token = 0; + this->m_tokenBindings[i].m_request = 0; + this->m_tokenBindings[i].m_client = nullptr; + this->m_tokenBindings[i].m_active = false; + } + + memset(this->m_adapters, 0, sizeof(this->m_adapters)); + memset(this->m_eventAdapters, 0, sizeof(this->m_eventAdapters)); +} + +// VERIFY: 50fa449a manual +// OFFSET: [0x009C0040, 0x009C10E0] +Battlenet::Tumor::~Tumor() { + for (int32_t i = 0; i < 20; i++) { + if (this->m_adapters[i]) { + Battlenet::Delete(this->m_adapters[i]); + this->m_adapters[i] = nullptr; + } + } + + for (int32_t i = 0; i < 20; i++) { + if (this->m_eventAdapters[i]) { + Battlenet::Delete(this->m_eventAdapters[i]); + this->m_eventAdapters[i] = nullptr; + } + } +} + +// VERIFY: cfc39af3 auto +// OFFSET: 0x009C0D30 +bool Battlenet::Tumor::AllocTendrilId(uint32_t& tendrilId) { + tendrilId = this->m_nextTendrilId++; + uint32_t first = tendrilId; + + do { + uint32_t i = 0; + + while (!this->m_eventAdapters[i] || this->m_eventAdapters[i]->m_tendrilId != tendrilId) { + if (++i >= 20) { + return true; + } + } + + tendrilId = this->m_nextTendrilId++; + } while (tendrilId != first); + + return false; +} + +// VERIFY: f13c7f2c manual +// OFFSET: 0x009C0DA0 +void Battlenet::Tumor::Process(uint32_t time) { + for (int32_t i = 0; i < 20; i++) { + if (this->m_adapters[i]) { + static_cast(this->m_adapters[i])->Process(time); + } + } +} + +// VERIFY: 52d8a946 manual +// OFFSET: 0x009C0DE0 +Battlenet::Tumor::ConnectionBinding* Battlenet::Tumor::FindConnectionBinding(uint32_t connection) { + uint32_t i = 0; + + while (!this->m_connectionBindings[i].m_active || this->m_connectionBindings[i].m_connection != connection) { + if (++i >= 64) { + return nullptr; + } + } + + return &this->m_connectionBindings[i]; +} + +// VERIFY: b61bd7a2 manual +// OFFSET: 0x009C0E20 +Battlenet::Tumor::TokenBinding* Battlenet::Tumor::FindTokenBinding(uint32_t token) { + uint32_t i = 0; + + while (!this->m_tokenBindings[i].m_active || this->m_tokenBindings[i].m_token != token) { + if (++i >= 64) { + return nullptr; + } + } + + return &this->m_tokenBindings[i]; +} + +// VERIFY: 679ecf1c manual +// OFFSET: 0x009C0E60 +Battlenet::Tumor::EventBinding* Battlenet::Tumor::AllocEventBinding() { + uint32_t i = 0; + + while (this->m_eventBindings[i].m_active) { + if (++i >= 20) { + DebugLog("Ran out of room in Tumor::m_eventBindings"); + return nullptr; + } + } + + return &this->m_eventBindings[i]; +} + +// VERIFY: ba73fc1f manual +// OFFSET: 0x009C0EA0 +Battlenet::Tumor::ConnectionBinding* Battlenet::Tumor::AllocConnectionBinding() { + uint32_t i = 0; + + while (this->m_connectionBindings[i].m_active) { + if (++i >= 64) { + DebugLog("Ran out of room in Tumor::m_connectionBindings"); + return nullptr; + } + } + + return &this->m_connectionBindings[i]; +} + +// VERIFY: 79a4dbee manual +// OFFSET: 0x009C0EE0 +Battlenet::Tumor::TokenBinding* Battlenet::Tumor::AllocTokenBinding() { + uint32_t i = 0; + + while (this->m_tokenBindings[i].m_active) { + if (++i >= 64) { + DebugLog("Ran out of room in Tumor::m_tokenBindings"); + return nullptr; + } + } + + TokenBinding* binding = &this->m_tokenBindings[i]; + binding->m_token = i; + return binding; +} + +// VERIFY: 629cff03 auto +// OFFSET: 0x009C1190 +void Battlenet::Tumor::Subscribe(BSN::FourCC eventId, EventSubscriber& subscriber, const uint32_t& tendrilId) { + EventBinding* binding = this->AllocEventBinding(); + + if (binding) { + binding->m_eventId = eventId; + binding->m_subscriber = &subscriber; + binding->m_active = true; + binding->m_tendrilId = tendrilId; + } +} + +// VERIFY: 64199477 manual +// OFFSET: 0x009C11C0 +Battlenet::Tumor::Adapter* Battlenet::Tumor::AllocAdapter(SystemClient& client, const uint32_t& tendrilId) { + uint32_t index = 0; + + while (this->m_adapters[index]) { + if (++index >= 20) { + DebugLog("No space in Tumor::m_adapters for new Tendril"); + return nullptr; + } + } + + void* memory = Battlenet::g_allocator->Alloc(sizeof(Adapter)); + Adapter* adapter = memory ? new (memory) Adapter(client, this, index, tendrilId) : nullptr; + this->m_adapters[index] = adapter; + return adapter; +} + +// VERIFY: a039aea5 manual +// OFFSET: 0x009C1250 +Battlenet::Tumor::EventAdapter* Battlenet::Tumor::AllocEventAdapter(BSN::FourCC eventId, EventSubscriber& subscriber, const uint32_t& tendrilId) { + uint32_t index = 0; + + while (this->m_eventAdapters[index]) { + if (++index >= 20) { + DebugLog("No space in Tumor::m_eventAdapters for new Tendril"); + return nullptr; + } + } + + void* memory = Battlenet::g_allocator->Alloc(sizeof(EventAdapter)); + EventAdapter* adapter = memory ? new (memory) EventAdapter(eventId, subscriber, this, index, tendrilId) : nullptr; + this->m_eventAdapters[index] = adapter; + return adapter; +} + +// VERIFY: a2168cb9 manual +// OFFSET: 0x009C12F0 +void Battlenet::Tumor::RemoveTendril(const uint32_t& tendrilId) { + for (int32_t i = 0; i < 20; i++) { + if (this->m_eventAdapters[i] && this->m_eventAdapters[i]->m_tendrilId == tendrilId) { + Battlenet::Delete(this->m_eventAdapters[i]); + this->m_eventAdapters[i] = nullptr; + } + } + + for (int32_t i = 0; i < 20; i++) { + if (this->m_adapters[i] && this->m_adapters[i]->m_tendrilId == tendrilId) { + Battlenet::Delete(this->m_adapters[i]); + this->m_adapters[i] = nullptr; + } + } + + for (int32_t i = 0; i < 20; i++) { + if (this->m_eventBindings[i].m_active && this->m_eventBindings[i].m_tendrilId == tendrilId) { + this->m_eventBindings[i].m_active = false; + } + } + + for (int32_t i = 0; i < 64; i++) { + if (this->m_connectionBindings[i].m_active && this->m_connectionBindings[i].m_tendrilId == tendrilId) { + this->m_connectionBindings[i].m_active = false; + } + } +} + +// VERIFY: 8e36495e manual +// OFFSET: 0x009C1400 +uint32_t Battlenet::Tumor::Connect(uint32_t index, const IP4::AddressPort& address, const uint32_t& tendrilId) { + ConnectionBinding* binding = this->AllocConnectionBinding(); + + if (!binding) { + DebugLog("Couldn't get a connectionId!"); + return static_cast(-1); + } + + uint32_t connection = this->m_application->Connect(address, tendrilId); + binding->m_connection = connection; + binding->m_client = this->m_adapters[index]; + binding->m_active = true; + binding->m_tendrilId = tendrilId; + return connection; +} + +// VERIFY: c1f7add6 manual +// OFFSET: 0x009C1490 +uint32_t Battlenet::Tumor::OpenDatagram(uint32_t index, int32_t port, const uint32_t& tendrilId) { + ConnectionBinding* binding = this->AllocConnectionBinding(); + + if (!binding) { + DebugLog("Couldn't get a connectionId!"); + return static_cast(-1); + } + + uint32_t connection = this->m_application->OpenDatagram(port, tendrilId); + binding->m_connection = connection; + binding->m_client = this->m_adapters[index]; + binding->m_active = true; + binding->m_tendrilId = tendrilId; + return connection; +} + +// VERIFY: b017cd8b auto +// OFFSET: 0x009C1520 +void Battlenet::Tumor::Resolved(uint32_t request, const Client::DNSInfo& info) { + TokenBinding* binding = this->FindTokenBinding(request); + + if (binding) { + binding->m_client->Resolved(binding->m_request, info); + binding->m_token = 0; + binding->m_client = nullptr; + binding->m_active = false; + } +} + +// VERIFY: 697d6e84 auto +// OFFSET: 0x009C1560 +void Battlenet::Tumor::Connected(uint32_t connection, const IP4::AddressPort& address) { + ConnectionBinding* binding = this->FindConnectionBinding(connection); + + if (binding) { + binding->m_client->Connected(connection, address); + } +} + +// VERIFY: dc021d45 auto +// OFFSET: 0x009C1590 +void Battlenet::Tumor::Disconnected(uint32_t connection) { + ConnectionBinding* binding = this->FindConnectionBinding(connection); + + if (binding) { + binding->m_client->Disconnected(connection); + binding->m_connection = 0; + binding->m_client = nullptr; + binding->m_active = false; + } +} + +// VERIFY: 6ac0b5ba manual +// OFFSET: 0x009C15D0 +bool Battlenet::Tumor::Recv(uint32_t connection, void* data, uint32_t size, uint32_t& used) { + ConnectionBinding* binding = this->FindConnectionBinding(connection); + + if (binding) { + return binding->m_client->Recv(connection, data, size, used); + } + + return false; +} + +// VERIFY: 4c7c3bb7 manual +// OFFSET: 0x009C1610 +bool Battlenet::Tumor::RecvDatagram(uint32_t connection, void* data, uint32_t size, const IP4::AddressPort& address) { + ConnectionBinding* binding = this->FindConnectionBinding(connection); + + if (binding) { + return binding->m_client->RecvDatagram(connection, data, size, address); + } + + return false; +} + +// VERIFY: 4e7878b6 manual +// OFFSET: 0x009C1650 +void Battlenet::Tumor::SendEvent(const Event::Header& header, const BSN::EncodedObject* data) { + if (header.m_target.m_type == 0) { + for (int32_t i = 0; i < 20; i++) { + if (this->m_eventBindings[i].m_active && this->m_eventBindings[i].m_eventId.m_value == header.m_target.m_value) { + this->m_eventBindings[i].m_subscriber->RecvEvent(header, data); + } + } + } else if (header.m_target.m_type == 1) { + EventAdapter* adapter = this->m_eventAdapters[header.m_target.m_value]; + + if (adapter) { + static_cast(adapter)->RecvEvent(header, data); + } + } +} + +// INLINED +Battlenet::Tumor::Adapter::Adapter(SystemClient& client, Tumor* tumor, uint32_t index, const uint32_t& tendrilId) { + this->m_tendrilId = tendrilId; + this->m_index = index; + this->m_tumor = tumor; + this->m_client = &client; +} + +// VERIFY: 3658c352 manual +// OFFSET: 0x009C16C0 +uint32_t Battlenet::Tumor::Adapter::Resolve(uint32_t token, const char* hostname) { + Tumor* tumor = this->m_tumor; + uint32_t index = this->m_index; + TokenBinding* binding = tumor->AllocTokenBinding(); + + if (!binding) { + return 0; + } + + binding->m_request = token; + binding->m_client = tumor->m_adapters[index]; + binding->m_active = true; + return tumor->m_application->Resolve(binding->m_token, hostname); +} + +// VERIFY: 15c88fc4 auto +// OFFSET: 0x009C1710 +uint32_t Battlenet::Tumor::Adapter::Connect(const IP4::AddressPort& address, const uint32_t& tendrilId) { + return this->m_tumor->Connect(this->m_index, address, tendrilId); +} + +// VERIFY: 2cff7579 manual +// OFFSET: 0x009C1730 +void Battlenet::Tumor::Adapter::Disconnect(uint32_t connection) { + this->m_tumor->m_application->Disconnect(connection); +} + +// VERIFY: 8a9978de auto +// OFFSET: 0x009C1750 +bool Battlenet::Tumor::Adapter::Send(uint32_t connection, const void* data, uint32_t size) { + return this->m_tumor->m_application->Send(connection, data, size); +} + +// VERIFY: 5d3bbf14 auto +// OFFSET: 0x009C1770 +uint32_t Battlenet::Tumor::Adapter::OpenDatagram(int32_t port, const uint32_t& tendrilId) { + return this->m_tumor->OpenDatagram(this->m_index, port, tendrilId); +} + +// VERIFY: 57407b2a manual +// OFFSET: 0x009C0FD0 +void Battlenet::Tumor::Adapter::CloseDatagram(uint32_t connection) { + this->m_tumor->m_application->CloseDatagram(connection); +} + +// VERIFY: 94a86319 auto +// OFFSET: 0x009C0FF0 +bool Battlenet::Tumor::Adapter::SendDatagram(uint32_t connection, const void* data, uint32_t size, const IP4::AddressPort& address) { + return this->m_tumor->m_application->SendDatagram(connection, data, size, address); +} + +// VERIFY: e14a1641 auto +// OFFSET: 0x009C1010 +uint64_t Battlenet::Tumor::Adapter::GetCurrentTime() const { + return this->m_tumor->m_application->GetCurrentTime(); +} + +// VERIFY: b92489b0 auto +// OFFSET: 0x009C1030 +uint64_t Battlenet::Tumor::Adapter::GetCurrentTick() const { + return this->m_tumor->m_application->GetCurrentTick(); +} + +// VERIFY: 028879f4 manual +// OFFSET: 0x009C1050 +void Battlenet::Tumor::Adapter::LogLevel(const char* message, int32_t level) { + this->m_tumor->m_application->LogLevel(message, level); +} + +// VERIFY: aae911a4 manual +// OFFSET: 0x009C1070 +Battlenet::ApplicationFile* Battlenet::Tumor::Adapter::OpenApplicationFile(const char* name) { + return this->m_tumor->m_application->OpenApplicationFile(name); +} + +// VERIFY: 4a63c7a1 manual +// OFFSET: 0x009C1090 +void Battlenet::Tumor::Adapter::CloseApplicationFile(ApplicationFile* file) { + this->m_tumor->m_application->CloseApplicationFile(file); +} + +// VERIFY: 1cf32261 manual +// OFFSET: [0x009C0F30, 0x009C0F50] +Battlenet::Tumor::Adapter::~Adapter() { +} + +// VERIFY: 7d67d9cc auto +// OFFSET: 0x009C10B0 +void Battlenet::Tumor::Adapter::Destroy() { + Battlenet::Delete(this); +} + +// VERIFY: 570486f7 manual +// OFFSET: 0x009C0C70 +void Battlenet::Tumor::Adapter::Resolved(uint32_t request, const Client::DNSInfo& info) { + this->m_client->Resolved(request, info); +} + +// VERIFY: c288be8e manual +// OFFSET: 0x009C0C80 +void Battlenet::Tumor::Adapter::Connected(uint32_t connection, const IP4::AddressPort& address) { + this->m_client->Connected(connection, address); +} + +// VERIFY: edf04550 manual +// OFFSET: 0x009C0C90 +void Battlenet::Tumor::Adapter::Disconnected(uint32_t connection) { + this->m_client->Disconnected(connection); +} + +// VERIFY: a3a75e38 auto +// OFFSET: 0x009C0CA0 +bool Battlenet::Tumor::Adapter::Recv(uint32_t connection, void* data, uint32_t size, uint32_t& used) { + return this->m_client->Recv(connection, data, size, used); +} + +// VERIFY: 74df147b auto +// OFFSET: 0x009C0CB0 +bool Battlenet::Tumor::Adapter::RecvDatagram(uint32_t connection, void* data, uint32_t size, const IP4::AddressPort& address) { + return this->m_client->RecvDatagram(connection, data, size, address); +} + +// VERIFY: 4033000e manual +// OFFSET: 0x009C0CC0 +void Battlenet::Tumor::Adapter::Process(uint32_t time) { + this->m_client->Process(time); +} + +// INLINED +Battlenet::Tumor::EventAdapter::EventAdapter(BSN::FourCC eventId, EventSubscriber& subscriber, Tumor* tumor, uint32_t index, const uint32_t& tendrilId) { + this->m_eventId = eventId; + this->m_tendrilId = tendrilId; + this->m_tumor = tumor; + this->m_index = index; + this->m_subscriber = &subscriber; +} + +// VERIFY: adedbd5a auto +// OFFSET: 0x009C1790 +void Battlenet::Tumor::EventAdapter::SendEvent(uint8_t eventType, uint32_t adapter, const BSN::EncodedObject* data) { + Event::Header header; + header.m_eventType = eventType; + header.m_source.m_exists = true; + header.m_source.m_adapter = this->m_index; + header.m_source.m_event = this->m_eventId.m_value; + header.m_target.m_type = 1; + header.m_target.m_value = adapter; + this->m_tumor->SendEvent(header, data); +} + +// VERIFY: cce6fea3 auto +// OFFSET: 0x009C17E0 +void Battlenet::Tumor::EventAdapter::SendEvent(uint8_t eventType, BSN::FourCC eventId, const BSN::EncodedObject* data) { + Event::Header header; + header.m_eventType = eventType; + header.m_source.m_exists = true; + header.m_source.m_adapter = this->m_index; + header.m_source.m_event = this->m_eventId.m_value; + header.m_target.m_type = 0; + header.m_target.m_value = eventId.m_value; + this->m_tumor->SendEvent(header, data); +} + +// VERIFY: 5fca2ace auto +// OFFSET: 0x009C0CD0 +void Battlenet::Tumor::EventAdapter::Subscribe(BSN::FourCC eventId, const uint32_t& tendrilId) { + this->m_tumor->Subscribe(eventId, *this, tendrilId); +} + +// VERIFY: f9e9eef3 manual +// OFFSET: 0x009C0F90 +Battlenet::Tumor::EventAdapter::~EventAdapter() { +} + +// VERIFY: f39e6a3a manual +// OFFSET: 0x009C0D00 +void Battlenet::Tumor::EventAdapter::RecvEvent(const Event::Header& header, const BSN::EncodedObject* data) { + this->m_subscriber->RecvEvent(header, data); +} diff --git a/WoW/Source/Battlenet/Tumor/Tumor.h b/WoW/Source/Battlenet/Tumor/Tumor.h index 027e212..6f9a310 100644 --- a/WoW/Source/Battlenet/Tumor/Tumor.h +++ b/WoW/Source/Battlenet/Tumor/Tumor.h @@ -3,19 +3,109 @@ #include #include +#include "WoW/Source/Battlenet/Battlenet.h" namespace Battlenet { -struct Tumor { - /* 0000 */ uint8_t unk_0000; - /* 0001 */ uint8_t unk_0001[4]; - /* 0005 */ uint8_t unk_0005 [16]; - /* 0015 */ uint8_t unk_0015[4]; - /* 0019 */ uint8_t unk_0019 [20]; - /* 002D */ uint8_t unk_002D[4]; - /* 0031 */ uint8_t unk_0031 [76]; - /* 007D */ uint8_t unk_007D[4]; - /* 0081 */ uint8_t unk_0081 [35]; - /* 00A4 */ int32_t unk_00A4; +class Tumor : public SystemClient { + public: + class Adapter : public SystemServer, public SystemClient { + public: + /* 0008 */ uint32_t m_tendrilId; + /* 000C */ uint32_t m_index; + /* 0010 */ Tumor* m_tumor; + /* 0014 */ SystemClient* m_client; + + uint32_t Resolve(uint32_t token, const char* hostname) override; + uint32_t Connect(const IP4::AddressPort& address, const uint32_t& tendrilId) override; + void Disconnect(uint32_t connection) override; + bool Send(uint32_t connection, const void* data, uint32_t size) override; + uint32_t OpenDatagram(int32_t port, const uint32_t& tendrilId) override; + void CloseDatagram(uint32_t connection) override; + bool SendDatagram(uint32_t connection, const void* data, uint32_t size, const IP4::AddressPort& address) override; + uint64_t GetCurrentTime() const override; + uint64_t GetCurrentTick() const override; + void LogLevel(const char* message, int32_t level) override; + ApplicationFile* OpenApplicationFile(const char* name) override; + void CloseApplicationFile(ApplicationFile* file) override; + ~Adapter() override; + virtual void Destroy(); + void Resolved(uint32_t request, const Client::DNSInfo& info) override; + void Connected(uint32_t connection, const IP4::AddressPort& address) override; + void Disconnected(uint32_t connection) override; + bool Recv(uint32_t connection, void* data, uint32_t size, uint32_t& used) override; + bool RecvDatagram(uint32_t connection, void* data, uint32_t size, const IP4::AddressPort& address) override; + void Process(uint32_t time) override; + + Adapter(SystemClient& client, Tumor* tumor, uint32_t index, const uint32_t& tendrilId); + }; + + class EventAdapter : public EventInterface, public EventSubscriber { + public: + /* 000C */ uint32_t m_tendrilId; + /* 0010 */ Tumor* m_tumor; + /* 0014 */ uint32_t m_index; + /* 0018 */ EventSubscriber* m_subscriber; + + void SendEvent(uint8_t eventType, uint32_t adapter, const BSN::EncodedObject* data) override; + void SendEvent(uint8_t eventType, BSN::FourCC eventId, const BSN::EncodedObject* data) override; + void Subscribe(BSN::FourCC eventId, const uint32_t& tendrilId) override; + ~EventAdapter() override; + void RecvEvent(const Event::Header& header, const BSN::EncodedObject* data) override; + + EventAdapter(BSN::FourCC eventId, EventSubscriber& subscriber, Tumor* tumor, uint32_t index, const uint32_t& tendrilId); + }; + + struct EventBinding { + /* 0000 */ BSN::FourCC m_eventId; + /* 0004 */ EventSubscriber* m_subscriber; + /* 0008 */ bool m_active; + /* 000C */ uint32_t m_tendrilId; + }; + + struct ConnectionBinding { + /* 0000 */ uint32_t m_connection; + /* 0004 */ SystemClient* m_client; + /* 0008 */ bool m_active; + /* 000C */ uint32_t m_tendrilId; + }; + + struct TokenBinding { + /* 0000 */ uint32_t m_token; + /* 0004 */ uint32_t m_request; + /* 0008 */ SystemClient* m_client; + /* 000C */ bool m_active; + }; + + /* 0004 */ Adapter* m_adapters[20]; + /* 0054 */ EventAdapter* m_eventAdapters[20]; + /* 00A4 */ uint32_t m_nextTendrilId; + /* 00A8 */ Application* m_application; + /* 00AC */ EventBinding m_eventBindings[20]; + /* 01EC */ ConnectionBinding m_connectionBindings[64]; + /* 05EC */ TokenBinding m_tokenBindings[64]; + + void Resolved(uint32_t request, const Client::DNSInfo& info) override; + void Connected(uint32_t connection, const IP4::AddressPort& address) override; + void Disconnected(uint32_t connection) override; + bool Recv(uint32_t connection, void* data, uint32_t size, uint32_t& used) override; + bool RecvDatagram(uint32_t connection, void* data, uint32_t size, const IP4::AddressPort& address) override; + void Process(uint32_t time) override; + ~Tumor() override; + virtual bool AllocTendrilId(uint32_t& tendrilId); + virtual EventAdapter* AllocEventAdapter(BSN::FourCC eventId, EventSubscriber& subscriber, const uint32_t& tendrilId); + virtual void RemoveTendril(const uint32_t& tendrilId); + virtual void Subscribe(BSN::FourCC eventId, EventSubscriber& subscriber, const uint32_t& tendrilId); + + Tumor(Application& application); + Adapter* AllocAdapter(SystemClient& client, const uint32_t& tendrilId); + ConnectionBinding* FindConnectionBinding(uint32_t connection); + TokenBinding* FindTokenBinding(uint32_t token); + EventBinding* AllocEventBinding(); + ConnectionBinding* AllocConnectionBinding(); + TokenBinding* AllocTokenBinding(); + uint32_t Connect(uint32_t index, const IP4::AddressPort& address, const uint32_t& tendrilId); + uint32_t OpenDatagram(uint32_t index, int32_t port, const uint32_t& tendrilId); + void SendEvent(const Event::Header& header, const BSN::EncodedObject* data); }; } diff --git a/WoW/Source/Battlenet/Tumor/TumorManager.cpp b/WoW/Source/Battlenet/Tumor/TumorManager.cpp index 2c9079c..2608148 100644 --- a/WoW/Source/Battlenet/Tumor/TumorManager.cpp +++ b/WoW/Source/Battlenet/Tumor/TumorManager.cpp @@ -1 +1,225 @@ -#include "TumorManager.h" +#include "WoW/Source/Battlenet/Tumor/TumorManager.h" +#include +#include +#include "Engine/Source/Storm/H/storm.h" +#include "WoW/Source/Battlenet/Tumor/CreepTendril.h" + +// STATIC: 0x00DCEE58 +BSN::FourCC Battlenet::Event::CREEP("Crep"); + +// STATIC: 0x00DCEE5C +BSN::FourCC Battlenet::Event::APP("App"); + +// STATIC: 0x00DCEE60 +BSN::FourCC Battlenet::Event::DATAGRAM_CONNECTION_ACK("DCAC"); + +// STATIC: 0x00DCEE64 +BSN::FourCC Battlenet::Event::S2_LOBBY("S2Lb"); + +// STATIC: 0x00DCEE68 +BSN::FourCC Battlenet::Event::COMSAT_UPDATE("CMSU"); + +// STATIC: 0x00DCEE6C +BSN::FourCC Battlenet::Event::TO_UI("ToUI"); + +// STATIC: 0x00DCEE70 +BSN::FourCC Battlenet::Event::COMSAT_STATE("CMST"); + +// STATIC: 0x00DCEE74 +BSN::FourCC Battlenet::Event::FROM_UI("FmUI"); + +// STATIC: 0x00DCEE78 +BSN::FourCC Battlenet::Event::DATAGRAM_CONNECTION_INIT("DCDI"); + +// VERIFY: 88129388 auto +// OFFSET: 0x009BFDB0 +void Battlenet::TumorManagerRegisterFunction(void* param, const char* name, GeneralFunction::Function func, void* funcParam) { + static_cast(param)->RegisterFunction(name, func, funcParam); +} + +// VERIFY: def51cae auto +// OFFSET: 0x009BFDD0 +Battlenet::Tumor* Battlenet::TumorManager::GetTumor() { + return &this->m_tumor; +} + +// VERIFY: 438ef535 manual +// OFFSET: 0x009BFDE0 +void Battlenet::TumorManager::AddTendril(Tendril* tendril) { + uint32_t i = 0; + + while (this->m_tendrils[i]) { + if (++i >= 20) { + DebugLog("No room for new tendril!"); + return; + } + } + + this->m_tendrils[i] = tendril; + tendril->DoSubscriptions(); +} + +// VERIFY: afb39340 auto +// OFFSET: 0x009BFE30 +void Battlenet::TumorManager::DestroyTendrils() { + for (int32_t i = 0; i < 20; i++) { + if (this->m_tendrils[i]) { + this->m_tendrils[i]->Destroy(); + this->m_tendrils[i] = nullptr; + } + } +} + +// VERIFY: 35a221a0 auto +// OFFSET: 0x009BFE60 +void Battlenet::TumorManager::SendEvent(uint8_t eventType, const uint32_t& adapter, const BSN::EncodedObject* data) { + this->m_eventAdapter->SendEvent(eventType, adapter, data); +} + +// VERIFY: 8aa60d79 auto +// OFFSET: 0x009BFE80 +void Battlenet::TumorManager::SendEvent(uint8_t eventType, const BSN::FourCC& eventId, const BSN::EncodedObject* data) { + this->m_eventAdapter->SendEvent(eventType, eventId, data); +} + +// VERIFY: 6a4672bf manual +// OFFSET: 0x009C0070 +GeneralFunction::Arg Battlenet::TumorManagerSendEvent(void* param, int32_t argc, const GeneralFunction::Arg* args) { + if (argc != 3) { + DebugLog("Usage: SendEvent(eventId, dest, event)"); + return GeneralFunction::Arg(); + } + + const char* target = args[1].ToString(); + BSN::FourCC eventId; + eventId.m_value = 0; + + for (uint8_t c = *target; *target; c = *target) { + target++; + eventId.m_value = c | (eventId.m_value << 8); + } + + const BSN::EncodedObject* data = args[2].m_type == GeneralFunction::Arg::TYPE_OBJECT ? args[2].m_object : nullptr; + static_cast(param)->SendEvent(static_cast(args[0].ToUInt64()), eventId, data); + return GeneralFunction::Arg(); +} + +// VERIFY: af469e54 auto +// OFFSET: 0x009C0110 +Battlenet::TumorManager::TumorManager(Application& application) : m_tumor(application) { + this->m_eventAdapter = nullptr; + this->m_tumor.AllocTendrilId(this->m_tendrilId); + this->m_eventAdapter = this->m_tumor.AllocEventAdapter(Battlenet::Event::APP, application, this->m_tendrilId); + memset(this->m_tendrils, 0, sizeof(this->m_tendrils)); +} + +// VERIFY: 17a2f63a manual +// OFFSET: 0x009C0180 +Battlenet::TumorManager::~TumorManager() { +} + +// VERIFY: e72e8e42 manual +// OFFSET: 0x009C0A10 +Battlenet::TumorManager* Battlenet::TumorManager::Create(Application& application, const Authentication::Settings& settings) { + void* memory = Battlenet::g_allocator->Alloc(sizeof(TumorManagerImplementation)); + TumorManagerImplementation* manager = memory ? new (memory) TumorManagerImplementation(application) : nullptr; + + CreepTendril::Instance* creep = CreepTendril::Instance::Create(settings, *manager); + + if (!creep) { + Battlenet::Delete(manager); + return nullptr; + } + + manager->AddTendril(creep); + manager->m_eventAdapter->Subscribe(Battlenet::Event::APP, manager->m_tendrilId); + manager->m_eventAdapter->Subscribe(Battlenet::Event::TO_UI, manager->m_tendrilId); + manager->RegisterFunction("SendEvent", Battlenet::TumorManagerSendEvent, manager); + creep->EnumFunctions(Battlenet::TumorManagerRegisterFunction, manager); + return manager; +} + +// INLINED +Battlenet::TumorManagerImplementation::TumorManagerImplementation(Application& application) : TumorManager(application) { +} + +// VERIFY: 49eb6e79 manual +// OFFSET: 0x009C0540 +void Battlenet::TumorManagerImplementation::EnumFunctions(EnumFunctionsCallback callback, void* param) { + MapKey key; + FunctionEntry entry = { nullptr, nullptr }; + uint32_t iterator = 0; + + while (this->m_functions.Next(iterator, key, entry)) { + callback(param, key.m_value.GetString(), entry.m_func, entry.m_param); + } +} + +// VERIFY: 6d614d62 manual +// OFFSET: 0x009C05E0 +GeneralFunction::Arg Battlenet::TumorManagerImplementation::CallFunction(const char* name, int32_t argc, GeneralFunction::Arg* args) { + GeneralFunction::Function func = nullptr; + void* param = nullptr; + uint32_t index; + bool found; + + { + MapKey key((String(name))); + + if (this->m_functions.Find(key, index)) { + func = this->m_functions.m_entries[index].m_value.m_func; + param = this->m_functions.m_entries[index].m_value.m_param; + found = true; + } else { + found = false; + } + } + + if (!found) { + return GeneralFunction::Arg(); + } + + return func(param, argc, args); +} + +// VERIFY: 9f1a0722 manual +// OFFSET: 0x009C09C0 +Battlenet::TumorManagerImplementation::~TumorManagerImplementation() { + this->DestroyTendrils(); +} + +// VERIFY: 9227520d manual +// OFFSET: 0x009C0AF0 +void Battlenet::TumorManagerImplementation::RegisterFunction(const char* name, GeneralFunction::Function func, void* param) { + MapKey key((String(name))); + FunctionEntry& entry = this->m_functions[key]; + entry.m_func = func; + entry.m_param = param; +} + +// VERIFY: 08db47a2 manual +// OFFSET: 0x009C0B70 +void Battlenet::TumorManagerImplementation::UnregisterFunction(const char* name, GeneralFunction::Function func, void* param) { + GeneralFunction::Function registeredFunc = nullptr; + void* registeredParam = nullptr; + uint32_t index; + bool found; + + { + MapKey key((String(name))); + + if (this->m_functions.Find(key, index)) { + registeredFunc = this->m_functions.m_entries[index].m_value.m_func; + registeredParam = this->m_functions.m_entries[index].m_value.m_param; + found = true; + } else { + found = false; + } + } + + if (found && registeredFunc == func && registeredParam == param) { + MapKey key(name); + FunctionEntry removed; + this->m_functions.Remove(key, removed); + } +} diff --git a/WoW/Source/Battlenet/Tumor/TumorManager.h b/WoW/Source/Battlenet/Tumor/TumorManager.h index 18bf344..3a92622 100644 --- a/WoW/Source/Battlenet/Tumor/TumorManager.h +++ b/WoW/Source/Battlenet/Tumor/TumorManager.h @@ -1,4 +1,87 @@ #ifndef WOW_SOURCE_BATTLENET_TUMOR_TUMORMANAGER_H #define WOW_SOURCE_BATTLENET_TUMOR_TUMORMANAGER_H +#include +#include +#include "WoW/Source/Battlenet/BattlenetMap.h" +#include "WoW/Source/Battlenet/GeneralFunction.h" +#include "WoW/Source/Battlenet/Tumor/Tumor.h" + +namespace Battlenet { +class Tendril; + +namespace Authentication { +struct Settings; +} + +typedef void (*EnumFunctionsCallback)(void* param, const char* name, GeneralFunction::Function func, void* funcParam); + +class TumorManager { + public: + static TumorManager* Create(Application& application, const Authentication::Settings& settings); + + /* 0004 */ EventInterface* m_eventAdapter; + /* 0008 */ Tendril* m_tendrils[20]; + /* 0058 */ Tumor m_tumor; + /* 0A44 */ uint32_t m_tendrilId; + + virtual void RegisterFunction(const char* name, GeneralFunction::Function func, void* param) = 0; + virtual void UnregisterFunction(const char* name, GeneralFunction::Function func, void* param) = 0; + virtual void EnumFunctions(EnumFunctionsCallback callback, void* param) = 0; + virtual GeneralFunction::Arg CallFunction(const char* name, int32_t argc, GeneralFunction::Arg* args) = 0; + virtual Tumor* GetTumor(); + virtual void SendEvent(uint8_t eventType, const uint32_t& adapter, const BSN::EncodedObject* data); + virtual void SendEvent(uint8_t eventType, const BSN::FourCC& eventId, const BSN::EncodedObject* data); + virtual ~TumorManager(); + + TumorManager(Application& application); + void AddTendril(Tendril* tendril); + void DestroyTendrils(); + template + void SendEvent(const BSN::FourCC& eventId, const T& data); +}; + +class TumorManagerImplementation : public TumorManager { + public: + struct FunctionEntry { + /* 0000 */ GeneralFunction::Function m_func; + /* 0004 */ void* m_param; + }; + + /* 0A48 */ Map m_functions; + + void RegisterFunction(const char* name, GeneralFunction::Function func, void* param) override; + void UnregisterFunction(const char* name, GeneralFunction::Function func, void* param) override; + void EnumFunctions(EnumFunctionsCallback callback, void* param) override; + GeneralFunction::Arg CallFunction(const char* name, int32_t argc, GeneralFunction::Arg* args) override; + ~TumorManagerImplementation() override; + + TumorManagerImplementation(Application& application); +}; + +GeneralFunction::Arg TumorManagerSendEvent(void* param, int32_t argc, const GeneralFunction::Arg* args); +void TumorManagerRegisterFunction(void* param, const char* name, GeneralFunction::Function func, void* funcParam); + +namespace Event { +extern BSN::FourCC CREEP; +extern BSN::FourCC APP; +extern BSN::FourCC DATAGRAM_CONNECTION_ACK; +extern BSN::FourCC S2_LOBBY; +extern BSN::FourCC COMSAT_UPDATE; +extern BSN::FourCC TO_UI; +extern BSN::FourCC COMSAT_STATE; +extern BSN::FourCC FROM_UI; +extern BSN::FourCC DATAGRAM_CONNECTION_INIT; +} +} + +// VERIFY: 889ceaaf manual +// OFFSET: 0x008C6F70 +template +void Battlenet::TumorManager::SendEvent(const BSN::FourCC& eventId, const T& data) { + BSN::BSNEncodedObjectPtr object(&data); + object.IncRef(); + this->SendEvent(6, eventId, &object); +} + #endif diff --git a/WoW/Source/Battlenet/Win64/Battlenet.cpp b/WoW/Source/Battlenet/Win64/Battlenet.cpp new file mode 100644 index 0000000..0450668 --- /dev/null +++ b/WoW/Source/Battlenet/Win64/Battlenet.cpp @@ -0,0 +1,60 @@ +#if defined(WOWDECOMP_ARCH_64) + +#include +#include +#include "WoW/Source/Battlenet/Battlenet.h" + +// OFFSET: 0x009C28B0 +void* Battlenet::WindowsLibrary::GetProc(const char* name) { + return reinterpret_cast(GetProcAddress(static_cast(this->m_module), name)); +} + +// OFFSET: 0x009C28D0 +void* Battlenet::WindowsLibrary::GetProc(uint32_t ordinal) { + if (ordinal > 0xFFFF) { + return nullptr; + } + + return reinterpret_cast(GetProcAddress(static_cast(this->m_module), MAKEINTRESOURCEA(ordinal))); +} + +// OFFSET: 0x009C2900 +Battlenet::Library* Battlenet::Library::Load(const char* path, Allocator& allocator) { + int32_t length = MultiByteToWideChar(CP_UTF8, 0, path, -1, nullptr, 0); + + if (length <= 0) { + return nullptr; + } + + wchar_t* widePath = static_cast(allocator.Alloc(2 * length)); + + if (!widePath) { + return nullptr; + } + + if (MultiByteToWideChar(CP_UTF8, 0, path, -1, widePath, length) > 0) { + HMODULE module = LoadLibraryW(widePath); + + if (module) { + void* memory = allocator.Alloc(sizeof(WindowsLibrary)); + + if (memory) { + WindowsLibrary* library = new (memory) WindowsLibrary(); + library->m_module = module; + library->m_allocator = &allocator; + allocator.Free(widePath); + return library; + } + } + } + + allocator.Free(widePath); + return nullptr; +} + +// OFFSET: 0x009C2A30 +Battlenet::WindowsLibrary::~WindowsLibrary() { + FreeLibrary(static_cast(this->m_module)); +} + +#endif diff --git a/WoW/Source/Client.cpp b/WoW/Source/Client.cpp index c3717e3..f4906a0 100644 --- a/WoW/Source/Client.cpp +++ b/WoW/Source/Client.cpp @@ -6,14 +6,14 @@ #include "_Triage/AreaList.h" #include "WoW/Source/Net/NetClient/NetClient.h" #include "_Triage/SHA1.h" -#include "_Triage/DataPreload.h" #include "_Triage/GameClientCommands.h" -#include "_Triage/StartupReport.h" -#include "_Triage/StreamingSetEnabled.h" #include "Engine/Source/Base/Base.h" #include "Engine/Source/Base/CmdLine.h" +#include "Engine/Source/BlizzardCore/OggDecompress.h" #include "Engine/Source/BlizzardCore/SFile2-Core.h" +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Manifests.h" #include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Streaming.h" +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Tracker.h" #include "Engine/Source/BlizzardCore/Source/System/Time/Time.h" #include "Engine/Source/ConsoleBase/ConsoleCommand.h" #include "Engine/Source/ConsoleBase/ConsoleVar.h" @@ -842,7 +842,7 @@ static void SetInstallPath() { } } -// VERIFY: a6442131 manual +// VERIFY: 835a84bd manual // OFFSET: 0x00403600 static void LoadMFIL(const char* file) { Blizzard::Time::GetElapsedSinceStart(true); @@ -860,12 +860,29 @@ static void LoadMFIL(const char* file) { } if (SFile::IsTrial()) { - RegisterOggDecompressor(); + InitOggDecompression(); } SFile::SetStreamingStatus(s_streamingDiag & 1, (s_streamingDiag >> 1) & 1, (s_streamingDiag >> 2) & 1, (s_streamingDiag >> 3) & 1, 12340); } +// VERIFY: 4b6c1aaa auto +// OFFSET: 0x004036B0 +void StartupReport(bool firstRun) { + uint32_t speedTest; + + if (!SRegLoadValue("World of Warcraft Trial", "SpeedTest", 1, &speedTest)) { + speedTest = 0; + } + + Blizzard::Streaming::FileManifest::SetSpeedTest(speedTest); + StartupReportSetSpeedTest(speedTest); + Tracker::SetLocale(CVar::Lookup("locale")->m_stringValue.m_str); + Tracker::SetBuildnum(12340); + StartupReportSendTelemetry(true, firstRun); + World::SetFrameCntCallback(StartupReportFrameCallback); +} + // VERIFY: 2b64aabf manual // OFFSET: 0x00403B70 static int32_t LoadNewWorld(const void* data, void* param) { @@ -1777,7 +1794,7 @@ void BeginCloseGame() { } } -// VERIFY: 47274a9a auto +// VERIFY: cfa3efeb auto // OFFSET: 0x00406C70 int32_t CommonMain() { StormInitialize(); @@ -1814,7 +1831,7 @@ int32_t CommonMain() { StormDestroy(); if (SFile::IsTrial()) { - ShutdownFileCache(); + ShutdownOggDecompression(); } Blizzard::Time::GetElapsedSinceStart(false); diff --git a/WoW/Source/Client_CVar.cpp b/WoW/Source/Client_CVar.cpp index 7f81c36..5275e7e 100644 --- a/WoW/Source/Client_CVar.cpp +++ b/WoW/Source/Client_CVar.cpp @@ -2,7 +2,7 @@ #include #include #include "Client.h" -#include "_Triage/StreamingSetEnabled.h" +#include "Engine/Source/BlizzardCore/Source/Packages/Streaming/Streaming.h" #include "Engine/Source/BlizzardCore/SFile2-Core.h" #include "Engine/Source/ConsoleBase/ConsoleCommand.h" #include "Engine/Source/ConsoleBase/ConsoleVar.h" diff --git a/WoW/Source/Glue/CGlueMgr.cpp b/WoW/Source/Glue/CGlueMgr.cpp index 5b13646..39c1427 100644 --- a/WoW/Source/Glue/CGlueMgr.cpp +++ b/WoW/Source/Glue/CGlueMgr.cpp @@ -51,7 +51,7 @@ #include "WoW/Source/WowSvcs/WowSvcsClient/AccountData.h" #include "WoW/Source/WowSvcs/WowSvcsClient/ChecksumExecutables.h" #include "WoW/Source/WowSvcs/WowSvcsClient/ClientServices.h" -#include "_Triage/FileDownload.h" +#include "WoW/Source/WowSvcs/WowSvcsClient/FileDownload.h" #include "WoW/Source/WowServices/LoginResponse.h" #include "_Triage/Types.h" #include "Engine/Source/Base/Coordinate.h" @@ -286,6 +286,23 @@ static void WriteConnectionLog(const char* text) { SLogFlush(s_connectionLog); } +// VERIFY: c565c343 auto +// OFFSET: 0x004D8360 +void CGlueMgr::QuitGameAndRunLauncher() { + ClientPostClose(0); + SCreateProcess("Launcher.exe", nullptr, nullptr, nullptr); +} + +// VERIFY: f5c0bd29 auto +// OFFSET: 0x004D8380 +void CGlueMgr::DownloadFeed(const uint8_t* data, uint32_t size) { + if (CGlueMgr::m_patchDownload) { + CGlueMgr::PatchDownloadFeed(data, size); + } else if (CGlueMgr::m_surveyDownload) { + CGlueMgr::SurveyDownloadFeed(data, size); + } +} + // VERIFY: fa4475b8 auto // OFFSET: 0x004D83B0 static int32_t CheckTrialAccountConversion() { @@ -438,6 +455,80 @@ static bool CreateIntroScene(uint8_t classID, uint8_t raceID, C3Vector& position return false; } +// VERIFY: 9fef272c auto +// OFFSET: 0x004DA090 +int32_t CGlueMgr::OnCharRenameResult(void* param, NETMESSAGE msgId, uint32_t time, CDataStore* msg) { + uint8_t result; + WOWGUID guid = { 0 }; + char name[48]; + + msg->Get(result); + + if (!msg->IsRead()) { + msg->Get(guid.m_guid); + msg->GetString(name, sizeof(name)); + } + + FrameScript_SignalEvent(GLUE_EVENT_CLOSE_STATUS_DIALOG, nullptr); + + if (result) { + if (result == 50) { + FrameScript_SignalEvent(GLUE_EVENT_FORCE_RENAME_CHARACTER, "%s", ClientServices::GetErrorToken(50)); + } else { + FrameScript_SignalEvent(GLUE_EVENT_FORCE_RENAME_CHARACTER, "%s", FrameScript_GetText("CHAR_RENAME_FAILED", -1, GENDER_NOT_APPLICABLE)); + } + + return 1; + } + + CCharacterSelection::UpdateCharacterName(guid, name); + + if (CCharacterSelection::s_selectionIndex >= 0 && CCharacterSelection::s_selectionIndex < static_cast(CCharacterSelection::s_characterList.m_count)) { + CharacterSelectionDisplay* display = &CCharacterSelection::s_characterList.m_data[CCharacterSelection::s_selectionIndex]; + + if (display && display->m_characterInfo.m_guid == guid) { + CGlueMgr::EnterWorld(); + } + } + + return 1; +} + +// VERIFY: 60c7823f auto +// OFFSET: 0x004DA190 +int32_t CGlueMgr::OnCharDeclineResult(void* param, NETMESSAGE msgId, uint32_t time, CDataStore* msg) { + WOWGUID guid = { 0 }; + uint32_t result; + + FrameScript_SignalEvent(GLUE_EVENT_CLOSE_STATUS_DIALOG, nullptr); + msg->Get(result); + + if (result) { + FrameScript_SignalEvent(GLUE_EVENT_FORCE_DECLINE_CHARACTER, "%s", "CHAR_DECLINE_FAILED"); + return 1; + } + + msg->Get(guid.m_guid); + CCharacterSelection::UpdateCharacterNameDeclension(guid); + + if (CCharacterSelection::s_selectionIndex >= 0 && CCharacterSelection::s_selectionIndex < static_cast(CCharacterSelection::s_characterList.m_count)) { + CharacterSelectionDisplay* display = &CCharacterSelection::s_characterList.m_data[CCharacterSelection::s_selectionIndex]; + + if (display && display->m_characterInfo.m_guid == guid) { + CGlueMgr::EnterWorld(); + } + } + + return 1; +} + +// VERIFY: a6b0e177 manual +// OFFSET: 0x004DA240 +void CGlueMgr::AcceptChangedOptionWarnings() { + CGlueMgr::m_changedOptionWarnings.Clear(); + CGlueMgr::m_numChangedOptionWarnings = 0; +} + // VERIFY: dccf23d8 manual // OFFSET: 0x004DA360 static void RequestLatestAgreements() { @@ -490,6 +581,69 @@ void CGlueMgr::InitializeFFX() { CGlueMgr::m_deathEffect = new (SMemAlloc(sizeof(EffectDeath), __FILE__, __LINE__, 0)) EffectDeath(); } +// VERIFY: 68028b82 auto +// OFFSET: 0x004D8650 +void CGlueMgr::ProcessAgreements(CGlueMgr::Agreements* agreements) { + if (!agreements) { + return; + } + + bool localized = CheckDataFilesExist(); + + char path[260]; + SStrCopy(path, "data", STORM_MAX_STR); + SStrPack(path, "\\", STORM_MAX_STR); + + if (localized) { + SStrPack(path, s_localeCode, STORM_MAX_STR); + SStrPack(path, "\\", STORM_MAX_STR); + } + + SStrPack(path, "agreements.mpq", STORM_MAX_STR); + + HOSFILE file = OsCreateFile(path, OS_GENERIC_WRITE, 0, OS_CREATE_ALWAYS, OS_FILE_ATTRIBUTE_NORMAL, OS_FILE_TYPE_ANY); + + if (file == OS_INVALID_FILE) { + return; + } + + uint32_t written = 0; + + if (!OsWriteFile(file, agreements->m_data.m_data, agreements->m_data.m_count, &written) || agreements->m_data.m_count != written) { + OsCloseFile(file); + return; + } + + OsCloseFile(file); + + SArchive* archive; + + if (!SFile::OpenArchive(path, 0, 0x800, &archive)) { + OsDeleteFile(path); + return; + } + + SFileImpl* agreement; + + if (SFile::OpenEx(archive, "tos.html", 0, &agreement)) { + ProcessAgreement(agreement, "tos.html", g_readTOSVar, localized); + SFileCloseFile(agreement); + } + + if (SFile::OpenEx(archive, "eula.html", 0, &agreement)) { + ProcessAgreement(agreement, "eula.html", g_readEULAVar, localized); + SFileCloseFile(agreement); + } + + if (SFile::OpenEx(archive, "termination.html", 0, &agreement)) { + ProcessAgreement(agreement, "termination.html", g_readTerminationWithoutNoticeVar, localized); + SFileCloseFile(agreement); + } + + SFile::CloseArchive(archive); + OsDeleteFile(path); +} + // VERIFY: fbc4fd55 auto // OFFSET: 0x004D8860 void CGlueMgr::HandleDisplaySizeChanged(const CSizeEvent& event) { @@ -1732,6 +1886,22 @@ bool CGlueMgr::RenameCharacter(WOWGUID guid, const char* name) { return true; } +// VERIFY: 7551aebf manual +// OFFSET: 0x004D9810 +void CGlueMgr::SetUIDepth(float depth) { + CSimpleFrame* frame = static_cast(CScriptObject::GetScriptObjectByName("GlueParent", CSimpleFrame::GetObjectType())); + + if (frame) { + frame->SetFrameDepth(depth - frame->m_parentDepth, true); + } + + frame = static_cast(CScriptObject::GetScriptObjectByName("OptionsSelectFrame", CSimpleFrame::GetObjectType())); + + if (frame) { + frame->SetFrameDepth(depth - frame->m_parentDepth, true); + } +} + // VERIFY: f70ffd2d auto // OFFSET: 0x004D98A0 CharacterSelectionDisplay* GetCharacterInfo(int32_t index) { @@ -1742,6 +1912,14 @@ CharacterSelectionDisplay* GetCharacterInfo(int32_t index) { return &CCharacterSelection::s_characterList[index]; } +// VERIFY: 86906951 manual +// OFFSET: 0x004D99E0 +void CGlueMgr::CancelLogin() { + if (CGlueMgr::m_idleState == IDLE_LOGIN_SERVER_LOGIN) { + CGlueMgr::StatusDialogClick(); + } +} + // VERIFY: 2b1dadd9 manual // OFFSET: 0x004D9A40 bool CGlueMgr::DeclineCharacter(WOWGUID guid, const char** names) { @@ -2205,6 +2383,52 @@ void CGlueMgr::RaceChange(WOWGUID guid, const CHARACTER_CREATE_INFO* info) { ClientServices::Send2(&msg); } +// VERIFY: 1b14a261 auto +// OFFSET: 0x004D7F90 +void CGlueMgr::LoginEnterPIN(int32_t count, uint8_t* digits) { + FrameScript_SignalEvent(GLUE_EVENT_OPEN_STATUS_DIALOG, "%s", "CANCEL"); + ClientServices::LoginEnterPIN(count, digits); +} + +// VERIFY: 89a8abe0 auto +// OFFSET: 0x004D7FB0 +void CGlueMgr::LoginEnterMatrix(uint8_t value) { + if (CGlueMgr::m_loginState == LOGIN_STATE_MATRIX_WAIT && CGlueMgr::m_matrixRemaining) { + ClientServices::LoginEnterMatrix(value); + } +} + +// VERIFY: 327a11cd manual +// OFFSET: 0x004D7FD0 +void CGlueMgr::LoginRevertMatrix() { + if (CGlueMgr::m_loginState == LOGIN_STATE_MATRIX_WAIT && CGlueMgr::m_matrixRemaining) { + ClientServices::LoginRevertMatrix(); + } +} + +// VERIFY: 697e070f auto +// OFFSET: 0x004D7FF0 +void CGlueMgr::LoginCommitMatrix() { + if (CGlueMgr::m_loginState == LOGIN_STATE_MATRIX_WAIT && CGlueMgr::m_matrixRemaining) { + ClientServices::LoginCommitMatrix(); + + if (!--CGlueMgr::m_matrixRemaining) { + ClientServices::LoginFinalizeMatrix(); + FrameScript_SignalEvent(GLUE_EVENT_OPEN_STATUS_DIALOG, "%s", "CANCEL"); + } + } +} + +// VERIFY: 4fc0fd1e auto +// OFFSET: 0x004D8030 +bool CGlueMgr::LoginGetMatrixCoordinate(uint32_t* x, uint32_t* y) { + if (CGlueMgr::m_loginState != LOGIN_STATE_MATRIX_WAIT || !CGlueMgr::m_matrixRemaining) { + return false; + } + + return ClientServices::LoginConnection()->GetMatrixCoordinates(CGlueMgr::m_matrixChallengeCount - CGlueMgr::m_matrixRemaining, x, y); +} + // VERIFY: 24156984 auto // OFFSET: 0x004D8080 void CGlueMgr::LoginEnterToken(const char* token) { diff --git a/WoW/Source/Glue/CGlueMgr.h b/WoW/Source/Glue/CGlueMgr.h index 8dc0a29..4bfa2ab 100644 --- a/WoW/Source/Glue/CGlueMgr.h +++ b/WoW/Source/Glue/CGlueMgr.h @@ -1,6 +1,7 @@ #ifndef WOW_SOURCE_GLUE_CGLUEMGR_H #define WOW_SOURCE_GLUE_CGLUEMGR_H +#include #include #include "WoW/Source/Object/WGUID.h" #include "Engine/Source/Os/OsURLDownload.h" @@ -11,6 +12,7 @@ struct CVar; class SFileImpl; +struct SArchive; class CDataStore; struct CHARACTER_CREATE_INFO; class CHARACTER_INFO; @@ -97,6 +99,11 @@ class CGlueMgr { static FileDownload* m_surveyDownload; static FileDownload* m_patchDownload; static float m_patchDownloadProgress; + static uint32_t m_patchLastUpdate; + static uint32_t m_patchStartTime; + static uint8_t* m_surveyData; + static uint16_t m_surveyDataSize; + static bool m_deleteLocalPatch; static uint8_t m_ffxActive; static FFX::Effect* m_deathEffect; static FFX::Effect* m_glowEffect; @@ -107,6 +114,7 @@ class CGlueMgr { static volatile long m_scandllStatus; static SThread m_scandllThread; + static void AcceptChangedOptionWarnings(); static void AcceptContest(); static void AcceptEULA(); static void AcceptScanning(); @@ -118,6 +126,24 @@ class CGlueMgr { static void CreateCharacter(const CHARACTER_CREATE_INFO* info); static void CustomizeCharacter(WOWGUID guid, const CHARACTER_CREATE_INFO* info); static bool AreScriptFunctionsLoaded(); + static void CancelLogin(); + static void DownloadFeed(const uint8_t* data, uint32_t size); + static size_t GetPatchFolder(char* buffer, uint32_t size); + static void LoginCommitMatrix(); + static void LoginEnterMatrix(uint8_t value); + static void LoginEnterPIN(int32_t count, uint8_t* digits); + static bool LoginGetMatrixCoordinate(uint32_t* x, uint32_t* y); + static void LoginRevertMatrix(); + static void PatchDownloadApply(); + static void PatchDownloadCancel(); + static bool PatchDownloadDeleteCommand(const char* path); + static bool PatchDownloadExecuteCommand(const char* path, const char* arguments); + static bool PatchDownloadExecutePrepatch(SArchive* archive); + static bool PatchDownloadExtractCommand(SArchive* archive, const char* name); + static void PatchDownloadFeed(const uint8_t* data, uint32_t size); + static void PatchFailed(int32_t reason, uint32_t data); + static void QuitGameAndRunLauncher(); + static void SurveyDownloadFeed(const uint8_t* data, uint32_t size); static bool DeclineCharacter(WOWGUID guid, const char** names); static void DeleteCharacter(WOWGUID guid); static void EnterWorld(); diff --git a/WoW/Source/Glue/GlueScriptEvents_Scripts.cpp b/WoW/Source/Glue/GlueScriptEvents_Scripts.cpp index 47130ea..5f77a72 100644 --- a/WoW/Source/Glue/GlueScriptEvents_Scripts.cpp +++ b/WoW/Source/Glue/GlueScriptEvents_Scripts.cpp @@ -12,6 +12,7 @@ #include "Engine/Source/FrameXML/LoadXML.h" #include "Engine/Source/Gx/CGxDevice/CGxDevice.h" #include "Engine/Source/Os/Processor.h" +#include "Engine/Source/Os/System.h" #include "Engine/Source/Services/AsyncFile.h" #include "Engine/Source/ShaderEffect/ShadowCache.h" #include "Engine/Source/Storm/H/storm.h" @@ -37,33 +38,17 @@ #include "WoW/Source/WowSvcs/WowSvcsClient/AccountData.h" int32_t Script_GetLocale(lua_State* L); -int32_t Script_QuitGameAndRunLauncher(lua_State* L); int32_t Script_PlayCreditsMusic(lua_State* L); int32_t Script_PatchDownloadProgress(lua_State* L); -int32_t Script_PatchDownloadCancel(lua_State* L); -int32_t Script_PatchDownloadApply(lua_State* L); -int32_t Script_LaunchAddOnURL(lua_State* L); int32_t Script_GetAddOnEnableState(lua_State* L); -int32_t Script_EnableAddOn(lua_State* L); -int32_t Script_EnableAllAddOns(lua_State* L); -int32_t Script_DisableAddOn(lua_State* L); int32_t Script_ResetAddOns(lua_State* L); int32_t Script_GetBillingTimeRemaining(lua_State* L); int32_t Script_GetBillingPlan(lua_State* L); int32_t Script_GetBillingTimeRested(lua_State* L); -int32_t Script_SurveyNotificationDone(lua_State* L); -int32_t Script_PINEntered(lua_State* L); -int32_t Script_MatrixEntered(lua_State* L); -int32_t Script_MatrixRevert(lua_State* L); -int32_t Script_MatrixCommit(lua_State* L); -int32_t Script_GetMatrixCoordinates(lua_State* L); int32_t Script_IsLinuxClient(lua_State* L); -int32_t Script_CancelLogin(lua_State* L); -int32_t Script_AcceptChangedOptionWarnings(lua_State* L); int32_t Script_RestoreVideoResolutionDefaults(lua_State* L); int32_t Script_RestoreVideoEffectsDefaults(lua_State* L); int32_t Script_RestoreVideoStereoDefaults(lua_State* L); -int32_t Script_IsStreamingMode(lua_State* L); // VERIFY: 51aeb88d auto // OFFSET: 0x004DBE60 @@ -107,7 +92,7 @@ static int32_t Script_SetUsesToken(lua_State* L) { return 0; } -// VERIFY: b27386e0 auto +// VERIFY: 90f2304e auto // OFFSET: 0x004DBF80 static int32_t Script_SetSavedAccountList(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -744,7 +729,7 @@ static int32_t Script_GetCVarMax(lua_State* L) { return 1; } -// VERIFY: 50da2212 auto +// VERIFY: fec93d6e auto // OFFSET: 0x004DE090 static int32_t Script_GetCVarAbsoluteMin(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -768,7 +753,7 @@ static int32_t Script_GetCVarAbsoluteMin(lua_State* L) { return 1; } -// VERIFY: 66589bae manual +// VERIFY: e499875e auto // OFFSET: 0x004DE130 static int32_t Script_GetCVarAbsoluteMax(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -964,7 +949,7 @@ static int32_t Script_PatchDownloadProgress(lua_State* L) { return 1; } -// VERIFY: 203a3cde auto +// VERIFY: e963f241 auto // OFFSET: 0x004DC150 static int32_t Script_PlayCreditsMusic(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -1019,7 +1004,7 @@ static int32_t Script_Screenshot(lua_State* L) { return 0; } -// VERIFY: 10a06b79 manual +// VERIFY: 0aa14818 auto // OFFSET: 0x004DC7C0 static int32_t Script_GetAddOnEnableState(lua_State* L) { if ((!lua_isstring(L, 1) && lua_type(L, 1)) || !lua_isnumber(L, 2)) { @@ -1039,7 +1024,7 @@ static int32_t Script_GetAddOnEnableState(lua_State* L) { return 1; } -// VERIFY: d6099889 auto +// VERIFY: 88319ee9 auto // OFFSET: 0x004DC1C0 static int32_t Script_LaunchURL(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -1051,7 +1036,7 @@ static int32_t Script_LaunchURL(lua_State* L) { return 0; } -// VERIFY: 4a86e3b0 auto +// VERIFY: ca947a95 auto // OFFSET: 0x004DCD60 static int32_t Script_GetCreditsText(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -1090,7 +1075,7 @@ static int32_t Script_TokenEntered(lua_State* L) { return 0; } -// VERIFY: 516d9613 manual +// VERIFY: 4fe1a04b auto // OFFSET: 0x004DC560 static int32_t Script_GetAddOnInfo(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -1176,7 +1161,7 @@ static int32_t Script_IsAddonVersionCheckEnabled(lua_State* L) { return 1; } -// VERIFY: c57b30ea auto +// VERIFY: a66ac9ee auto // OFFSET: 0x004DE250 static int32_t Script_SetRealmSplitState(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -1197,7 +1182,6 @@ static int32_t Script_SetRealmSplitState(lua_State* L) { return 0; } -// STATIC: 0x00AC3E00 // VERIFY: 042aa045 auto // OFFSET: 0x004DBE10 static int32_t Script_IsShiftKeyDown(lua_State* L) { @@ -1222,7 +1206,7 @@ static int32_t Script_SetAddonVersionCheck(lua_State* L) { return 0; } -// VERIFY: d426a464 auto +// VERIFY: 438aa8da auto // OFFSET: 0x004DCF70 static int32_t Script_GetNumDeclensionSets(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -1248,7 +1232,7 @@ static int32_t Script_GetNumDeclensionSets(lua_State* L) { return 1; } -// VERIFY: b3444eb1 auto +// VERIFY: e08d08fe auto // OFFSET: 0x004DD020 static int32_t Script_DeclineName(lua_State* L) { if (!lua_isstring(L, 1) || !lua_isnumber(L, 3)) { @@ -1287,7 +1271,7 @@ static int32_t Script_DeclineName(lua_State* L) { return 5; } -// VERIFY: 30f2d4b2 auto +// VERIFY: 93189456 auto // OFFSET: 0x004DD130 static int32_t Script_GetNumGameAccounts(lua_State* L) { Login* login = ClientServices::LoginConnection(); @@ -1406,6 +1390,206 @@ static int32_t Script_GetAddOnDependencies(lua_State* L) { return dependencies->m_count; } +// VERIFY: 44b9454f auto +// OFFSET: 0x004DC060 +static int32_t Script_QuitGameAndRunLauncher(lua_State* L) { + CGlueMgr::QuitGameAndRunLauncher(); + return 0; +} + +// VERIFY: 30f9beb4 manual +// OFFSET: 0x004DC2D0 +static int32_t Script_PINEntered(lua_State* L) { + uint8_t digits[10]; + int32_t count = 0; + + for (int32_t i = 1; i < 11; i++) { + if (lua_type(L, i) <= LUA_TNIL) { + break; + } + + if (!lua_isnumber(L, i)) { + luaL_error(L, "Usage: PINEntered(4-10 key positions) - non-numeric arg #%d", count + 1); + } + + digits[i - 1] = static_cast(lua_tonumber(L, i)); + count++; + } + + if (static_cast(count - 4) > 6) { + luaL_error(L, "Usage: PINEntered(4-10 key positions) - bad number of args %d", count); + } + + CGlueMgr::LoginEnterPIN(count, digits); + return 0; +} + +// VERIFY: 7ff32db5 manual +// OFFSET: 0x004DC3A0 +static int32_t Script_MatrixEntered(lua_State* L) { + if (!lua_isnumber(L, 1)) { + luaL_error(L, "Usage: MatrixEntered(number)"); + } + + double value = lua_tonumber(L, 1); + + if (value > 9) { + luaL_error(L, "MatrixEntered: number must be 0 to 9"); + } + + CGlueMgr::LoginEnterMatrix(static_cast(value)); + return 0; +} + +// VERIFY: 587d557c auto +// OFFSET: 0x004DC420 +static int32_t Script_MatrixRevert(lua_State* L) { + CGlueMgr::LoginRevertMatrix(); + return 0; +} + +// VERIFY: f7d16787 auto +// OFFSET: 0x004DC430 +static int32_t Script_MatrixCommit(lua_State* L) { + CGlueMgr::LoginCommitMatrix(); + return 0; +} + +// VERIFY: dd9ba17d auto +// OFFSET: 0x004DC440 +static int32_t Script_GetMatrixCoordinates(lua_State* L) { + uint32_t x; + uint32_t y; + + if (CGlueMgr::LoginGetMatrixCoordinate(&x, &y)) { + lua_pushnumber(L, 1.0); + lua_pushnumber(L, x); + lua_pushnumber(L, y); + } else { + lua_pushnil(L); + lua_pushnil(L); + lua_pushnil(L); + } + + return 3; +} + +// VERIFY: da79f55e auto +// OFFSET: 0x004DC540 +static int32_t Script_PatchDownloadCancel(lua_State* L) { + CGlueMgr::PatchDownloadCancel(); + return 0; +} + +// VERIFY: d348a87d auto +// OFFSET: 0x004DC550 +static int32_t Script_PatchDownloadApply(lua_State* L) { + CGlueMgr::PatchDownloadApply(); + return 0; +} + +// VERIFY: b3ad3e87 manual +// OFFSET: 0x004DC720 +static int32_t Script_LaunchAddOnURL(lua_State* L) { + if (!lua_isnumber(L, 1)) { + luaL_error(L, "Usage: LaunchAddOnURL(index)"); + } + + const char* name = GetAddOnByIndex(static_cast(static_cast(lua_tonumber(L, 1))) - 1); + + if (!name) { + luaL_error(L, "AddOn index must be in the range of 1 to %d", GetNumAddOns()); + } + + const char* url = GetAddOnURL(name); + + if (url) { + OsLaunchURL(url); + } + + return 0; +} + +// VERIFY: 8d79714e auto +// OFFSET: 0x004DC8A0 +static int32_t Script_EnableAddOn(lua_State* L) { + if ((!lua_isstring(L, 1) && lua_type(L, 1)) || !lua_isnumber(L, 2)) { + luaL_error(L, "Usage: EnableAddOn(\"character\", index)"); + } + + const char* character = lua_tolstring(L, 1, nullptr); + const char* name = GetAddOnByIndex(static_cast(static_cast(lua_tonumber(L, 2))) - 1); + + if (!name) { + luaL_error(L, "AddOn index must be in the range of 1 to %d", GetNumAddOns()); + } + + SetAddOnEnableState(name, character, 2); + return 0; +} + +// VERIFY: 42d43910 auto +// OFFSET: 0x004DC960 +static int32_t Script_EnableAllAddOns(lua_State* L) { + const char* character = lua_tolstring(L, 1, nullptr); + + for (uint32_t i = 0; i < GetNumAddOns(); i++) { + SetAddOnEnableState(GetAddOnByIndex(i), character, 2); + } + + return 0; +} + +// VERIFY: 92fdab84 auto +// OFFSET: 0x004DC9B0 +static int32_t Script_DisableAddOn(lua_State* L) { + if ((!lua_isstring(L, 1) && lua_type(L, 1)) || !lua_isnumber(L, 2)) { + luaL_error(L, "Usage: DisableAddOn(\"character\", index)"); + } + + const char* character = lua_tolstring(L, 1, nullptr); + const char* name = GetAddOnByIndex(static_cast(static_cast(lua_tonumber(L, 2))) - 1); + + if (!name) { + luaL_error(L, "AddOn index must be in the range of 1 to %d", GetNumAddOns()); + } + + SetAddOnEnableState(name, character, 0); + return 0; +} + +// VERIFY: 2c62788c auto +// OFFSET: 0x004DCCC0 +static int32_t Script_SurveyNotificationDone(lua_State* L) { + if (StringToBOOL(L, 1, 0)) { + CGlueMgr::SurveySendResults(); + } + + CGlueMgr::SurveyDownloadEnd(); + return 1; +} + +// VERIFY: 38032ddb auto +// OFFSET: 0x004DCE60 +static int32_t Script_CancelLogin(lua_State* L) { + CGlueMgr::CancelLogin(); + return 0; +} + +// VERIFY: 121c3b3a auto +// OFFSET: 0x004DCF20 +static int32_t Script_AcceptChangedOptionWarnings(lua_State* L) { + CGlueMgr::AcceptChangedOptionWarnings(); + return 0; +} + +// VERIFY: a8e471a8 auto +// OFFSET: 0x004DD430 +static int32_t Script_IsStreamingMode(lua_State* L) { + return SFile::IsStreamingMode(); +} + +// STATIC: 0x00AC3E00 static FrameScript_Method s_scriptFunctions[] = { { "IsShiftKeyDown", &Script_IsShiftKeyDown }, { "GetBuildInfo", &Script_GetBuildInfo }, diff --git a/WoW/Source/Glue/PatchDownloadGlue.cpp b/WoW/Source/Glue/PatchDownloadGlue.cpp index bc084cc..973bb0d 100644 --- a/WoW/Source/Glue/PatchDownloadGlue.cpp +++ b/WoW/Source/Glue/PatchDownloadGlue.cpp @@ -1,8 +1,381 @@ #include "PatchDownloadGlue.h" +#include +#include "Engine/Source/BlizzardCore/SFile2-Core.h" +#include "Engine/Source/FrameScript/FrameScript.h" +#include "Engine/Source/Os/OsFile.h" +#include "Engine/Source/Os/TimeManager.h" +#include "Engine/Source/Storm/H/storm.h" #include "WoW/Source/Glue/CGlueMgr.h" +#include "WoW/Source/WowServices/BattlenetLogin.h" +#include "WoW/Source/WowServices/Login.h" +#include "WoW/Source/WowSvcs/WowSvcsClient/ClientServices.h" +#include "WoW/Source/WowSvcs/WowSvcsClient/FileDownload.h" + +// STATIC: 0x009F6498 +static const uint8_t s_patchExponent[4] = { + 0x01, 0x00, 0x01, 0x00, +}; + +// STATIC: 0x00AC4538 +static uint8_t s_patchModulus[256] = { + 0x4F, 0x6F, 0xD4, 0x65, 0x56, 0x85, 0x88, 0xD9, 0xAA, 0xE6, 0xF7, 0x05, 0x72, 0xBB, 0x2A, 0x20, + 0xE0, 0x24, 0x38, 0x2B, 0x77, 0xB3, 0x3D, 0xC2, 0xD3, 0x2D, 0x52, 0x5C, 0xB7, 0xA3, 0x0F, 0xE6, + 0x0F, 0x80, 0x93, 0x8D, 0x5C, 0xC4, 0x81, 0x5E, 0x9D, 0x58, 0x8E, 0xCA, 0xA6, 0x6F, 0x27, 0x36, + 0x52, 0x58, 0x0D, 0xCE, 0x65, 0xE2, 0xB5, 0x7A, 0xD2, 0x39, 0x74, 0x8A, 0xAC, 0xAA, 0xC1, 0x0E, + 0xE5, 0x67, 0x2B, 0x79, 0xC1, 0xFE, 0x08, 0x96, 0x54, 0x18, 0x2A, 0x34, 0x31, 0xA4, 0x06, 0x20, + 0x4B, 0x12, 0xD2, 0x47, 0x63, 0x53, 0x36, 0x38, 0x19, 0x88, 0x8E, 0x50, 0x2F, 0x2F, 0xD1, 0x68, + 0xC8, 0x5C, 0x9D, 0x3B, 0xDE, 0xFE, 0x56, 0x21, 0xD1, 0x59, 0x4D, 0x1C, 0x32, 0x1B, 0x70, 0x4B, + 0x40, 0xE2, 0x5E, 0x0C, 0x0E, 0x4B, 0x84, 0xD5, 0xD7, 0x52, 0x00, 0x50, 0x65, 0x81, 0xCE, 0x17, + 0x53, 0x25, 0x49, 0x9E, 0x40, 0xE9, 0x04, 0x94, 0x2C, 0xA7, 0x93, 0x5C, 0x5D, 0x54, 0xC8, 0xF9, + 0x6E, 0xD0, 0x69, 0xFC, 0xE5, 0x8F, 0xC0, 0xB6, 0x76, 0xF2, 0xEB, 0x34, 0x67, 0x9F, 0xF8, 0xD0, + 0x34, 0xB9, 0xEA, 0x9E, 0x80, 0xD0, 0x29, 0x8D, 0xB4, 0xB2, 0xEB, 0x3E, 0xF4, 0x4F, 0xD0, 0x84, + 0x43, 0x15, 0xF4, 0x19, 0xE3, 0xC6, 0x52, 0xA2, 0x18, 0x40, 0x08, 0x07, 0x21, 0xF4, 0x20, 0xEC, + 0xE6, 0x5A, 0x9C, 0x2B, 0x08, 0xF6, 0x17, 0x97, 0x72, 0xA6, 0xD7, 0xAB, 0x64, 0x0B, 0x04, 0x95, + 0x93, 0x0D, 0xCC, 0x8F, 0x02, 0x30, 0x91, 0xA2, 0xEE, 0x30, 0xE6, 0x5F, 0x2F, 0xD4, 0x13, 0xB5, + 0x5D, 0xCA, 0x5D, 0xCF, 0x7D, 0xC3, 0x6F, 0x6B, 0x9D, 0xBC, 0x6D, 0x86, 0x4C, 0x91, 0xC5, 0x51, + 0xE8, 0xFD, 0xA6, 0x33, 0x10, 0xD1, 0x12, 0x8F, 0x05, 0x80, 0xDA, 0x42, 0x57, 0x0C, 0xEB, 0xC0, +}; + +// STATIC: 0x00B6A990 +float CGlueMgr::m_patchDownloadProgress; + +// STATIC: 0x00B6A994 +uint32_t CGlueMgr::m_patchLastUpdate; + +// STATIC: 0x00B6A998 +uint32_t CGlueMgr::m_patchStartTime; // STATIC: 0x00B6B25C FileDownload* CGlueMgr::m_patchDownload; -// STATIC: 0x00B6A990 -float CGlueMgr::m_patchDownloadProgress; +// STATIC: 0x00B6B260 +bool CGlueMgr::m_deleteLocalPatch; + +// VERIFY: 434eb4cd auto +// OFFSET: 0x004E4F70 +bool CGlueMgr::PatchDownloadExtractCommand(SArchive* archive, const char* name) { + void* data; + uint32_t size; + + if (!SFileLoadFileEx(archive, name, &data, &size, 0, 0, nullptr) || !data) { + return false; + } + + HOSFILE file = OsCreateFile(name, OS_GENERIC_WRITE, 0, OS_CREATE_ALWAYS, OS_FILE_ATTRIBUTE_NORMAL, OS_FILE_TYPE_ANY); + + if (file == OS_INVALID_FILE) { + SFileUnloadFile(data); + return false; + } + + uint32_t written; + OsWriteFile(file, data, size, &written); + SFileUnloadFile(data); + OsCloseFile(file); + + return true; +} + +// VERIFY: 81f1800c auto +// OFFSET: 0x004E5000 +bool CGlueMgr::PatchDownloadDeleteCommand(const char* path) { + if (OsFileExists(path)) { + if (SStrCmpI(path, "wow-patch.mpq", STORM_MAX_STR)) { + OsDeleteFile(path); + return true; + } + + CGlueMgr::m_deleteLocalPatch = true; + return true; + } + + if (OsDirectoryExists(path)) { + OsRemoveDirectory(path); + } + + return true; +} + +// VERIFY: 068cd41b auto +// OFFSET: 0x004E5070 +bool CGlueMgr::PatchDownloadExecutePrepatch(SArchive* archive) { + bool result = true; + void* data = nullptr; + uint32_t size; + + SFileLoadFileEx(archive, "prepatch.lst", &data, &size, 1, 0, nullptr); + + if (!data) { + return false; + } + + const char* cursor = static_cast(data); + + while (*cursor && result) { + char line[260]; + SStrTokenize(&cursor, line, sizeof(line), "\r\n", nullptr); + + if (!SStrCmp(line, "extract ", SStrLen("extract "))) { + result = CGlueMgr::PatchDownloadExtractCommand(archive, &line[SStrLen("extract ")]); + } else if (!SStrCmp(line, "execute ", SStrLen("execute "))) { + result = CGlueMgr::PatchDownloadExecuteCommand(&line[SStrLen("execute ")], ""); + } else if (!SStrCmp(line, "delete ", SStrLen("delete "))) { + result = CGlueMgr::PatchDownloadDeleteCommand(&line[SStrLen("delete ")]); + } + + if (!cursor) { + break; + } + } + + SFileUnloadFile(data); + return result; +} + +// VERIFY: 0f7aecd2 auto +// OFFSET: 0x004E51C0 +void CGlueMgr::PatchDownloadFeed(const uint8_t* data, uint32_t size) { + if (CGlueMgr::m_patchDownload) { + CGlueMgr::m_patchDownload->Proceed(data, size); + } +} + +// VERIFY: 60c4342c auto +// OFFSET: 0x004E51E0 +size_t CGlueMgr::GetPatchFolder(char* buffer, uint32_t size) { + return SStrCopy(buffer, OsFileGetDownloadFolder(), size); +} + +// VERIFY: 95e3f756 auto +// OFFSET: 0x004E5200 +void CGlueMgr::PatchDownloadStart() { + FrameScript_SignalEvent(GLUE_EVENT_CLOSE_STATUS_DIALOG, nullptr); + CGlueMgr::m_idleState = IDLE_12; + CGlueMgr::m_showedDisconnect = 0; + CGlueMgr::SetScreen("patchdownload"); + CGlueMgr::m_patchStartTime = OsGetAsyncTimeMs(); + CGlueMgr::m_patchLastUpdate = OsGetAsyncTimeMs(); + + if (CGlueMgr::m_patchDownload) { + delete CGlueMgr::m_patchDownload; + } + + if (ClientServices::LoginConnection()->GetLoginServerType() == 1) { + CGlueMgr::m_patchDownload = new (__FILE__, __LINE__) BattlenetFileDownload; + } else { + CGlueMgr::m_patchDownload = new (__FILE__, __LINE__) GruntFileDownload; + } + + Login* login = ClientServices::LoginConnection(); + uint64_t size = login->m_fileSize; + const char* name = ClientServices::LoginConnection()->m_fileName; + + if (!SStrCmpI(name, "Patch", STORM_MAX_STR)) { + name = "wow-patch.mpq"; + } + + char path[260]; + SStrCopy(path, OsFileGetDownloadFolder(), sizeof(path)); + OsCreateDirectory(path, 1); + SStrPack(path, "/", sizeof(path)); + SStrPack(path, name, sizeof(path)); + + ClientServices::StartDownload(); + + uint64_t offset; + bool accept = CGlueMgr::m_patchDownload->Initialize(path, ClientServices::LoginConnection()->m_fileMD5, size, offset); + + if (!ClientServices::LoginConnection()->GetLoginServerType()) { + ClientServices::FileAccept(accept, offset); + } +} + +// VERIFY: a565d49b auto +// OFFSET: 0x004E53A0 +void CGlueMgr::PatchDownloadCancel() { + CGlueMgr::m_patchDownload->StopDownload(); + + if (CGlueMgr::m_patchDownload) { + delete CGlueMgr::m_patchDownload; + } + + CGlueMgr::m_patchDownload = nullptr; + + if (!ClientServices::LoginConnection()->GetLoginServerType()) { + ClientServices::LoginConnection()->FileComplete(false); + } + + CGlueMgr::m_idleState = IDLE_NONE; + CGlueMgr::m_showedDisconnect = 0; + ClientServices::LoginConnection()->Logoff(); + CGlueMgr::SetScreen("login"); +} + +// VERIFY: 70646025 manual +// OFFSET: 0x004E5420 +void CGlueMgr::PatchFailed(int32_t reason, uint32_t data) { + ClientServices::LoginConnection()->Logoff(); + CGlueMgr::m_idleState = IDLE_NONE; + CGlueMgr::m_showedDisconnect = 0; + CGlueMgr::SetScreen("login"); + + char buffer[1024]; + const char* text; + + if (reason == 2) { + uint32_t megabytes = data; + + if (megabytes < 2) { + megabytes = 2; + } + + SStrPrintf(buffer, sizeof(buffer), FrameScript_GetText("PATCH_FAILED_DISK_FULL", -1, GENDER_NOT_APPLICABLE), megabytes); + text = buffer; + } else { + text = FrameScript_GetText("PATCH_FAILED_MESSAGE", -1, GENDER_NOT_APPLICABLE); + } + + FrameScript_SignalEvent(GLUE_EVENT_OPEN_STATUS_DIALOG, "%s%s", "OKAY", text); +} + +// VERIFY: f78c1cd2 manual +// OFFSET: 0x004E54D0 +void CGlueMgr::PatchDownloadIdle() { + switch (CGlueMgr::m_patchDownload->GetStatus()) { + case 2: { + CGlueMgr::m_patchDownloadProgress = 1.0f; + FrameScript_SignalEvent(GLUE_EVENT_PATCH_DOWNLOADED, nullptr); + + if (CGlueMgr::m_patchDownload->Accepted()) { + ClientServices::LoginConnection()->FileComplete(true); + } + + CGlueMgr::m_patchDownload->CompleteDownload(); + + if (CGlueMgr::m_patchDownload->GetStatus() == 3) { + uint32_t data; + int32_t reason = CGlueMgr::m_patchDownload->GetReason(&data); + CGlueMgr::PatchFailed(reason, data); + } else { + CGlueMgr::m_idleState = IDLE_NONE; + CGlueMgr::m_showedDisconnect = 0; + } + + if (CGlueMgr::m_patchDownload) { + delete CGlueMgr::m_patchDownload; + } + + CGlueMgr::m_patchDownload = nullptr; + break; + } + + case 3: { + if (CGlueMgr::m_patchDownload->Accepted()) { + ClientServices::LoginConnection()->FileComplete(false); + } + + CGlueMgr::m_patchDownload->Destroy(true); + + uint32_t data; + int32_t reason = CGlueMgr::m_patchDownload->GetReason(&data); + CGlueMgr::PatchFailed(reason, data); + + if (CGlueMgr::m_patchDownload) { + delete CGlueMgr::m_patchDownload; + } + + CGlueMgr::m_patchDownload = nullptr; + break; + } + + case 4: { + if (CGlueMgr::m_patchDownload) { + delete CGlueMgr::m_patchDownload; + } + + CGlueMgr::m_patchDownload = nullptr; + CGlueMgr::m_idleState = IDLE_LOGIN_SERVER_LOGIN; + CGlueMgr::m_showedDisconnect = 0; + + Login* login = ClientServices::LoginConnection(); + const char* password = ClientServices::LoginConnection()->m_password; + + char username[1280]; + char passwordCopy[1280]; + SStrCopy(username, login->m_rawUsername, sizeof(username)); + SStrCopy(passwordCopy, password, sizeof(passwordCopy)); + + BattlenetLogin::s_monolithicComponent = true; + ClientServices::Logon(username, passwordCopy); + break; + } + + default: { + uint32_t now = OsGetAsyncTimeMs(); + + if (now - CGlueMgr::m_patchLastUpdate > 250) { + CGlueMgr::m_patchLastUpdate = now; + CGlueMgr::m_patchDownloadProgress = CGlueMgr::m_patchDownload->GetProgress(); + FrameScript_SignalEvent(GLUE_EVENT_PATCH_UPDATE_PROGRESS, nullptr); + + if (!ClientServices::LoginConnection()->GetLoginServerType() && !ClientServices::LoginConnection()->IsLoggedOn()) { + CGlueMgr::PatchDownloadCancel(); + FrameScript_SignalEvent(GLUE_EVENT_OPEN_STATUS_DIALOG, "%s%s", "OKAY", FrameScript_GetText("DISCONNECTED", -1, GENDER_NOT_APPLICABLE)); + } + } + + break; + } + } +} + +// VERIFY: 8c2017c4 manual +// OFFSET: 0x004E5730 +void CGlueMgr::PatchDownloadApply() { + char currentDirectory[260]; + OsGetCurrentDirectory(sizeof(currentDirectory), currentDirectory); + + char folder[260]; + SStrCopy(folder, OsFileGetDownloadFolder(), sizeof(folder)); + OsSetCurrentDirectory(folder); + + bool success = false; + SArchive* archive = nullptr; + int32_t opened = SFileOpenArchive("wow-patch.mpq", 100, 0, &archive); + int32_t reason = 0; + CGlueMgr::m_deleteLocalPatch = false; + + if (opened) { + uint32_t authResult; + SFileAuthenticateArchiveEx(archive, &authResult, s_patchModulus, sizeof(s_patchModulus), s_patchExponent, sizeof(s_patchExponent)); + + if (authResult >= 5) { + success = CGlueMgr::PatchDownloadExecutePrepatch(archive); + + if (!success) { + reason = 6; + } + } else { + reason = 5; + } + + SFileCloseArchive(archive); + archive = nullptr; + + if (success) { + if (CGlueMgr::m_deleteLocalPatch) { + OsDeleteFile("wow-patch.mpq"); + } + + OsSetCurrentDirectory(currentDirectory); + CGlueMgr::QuitGame(); + return; + } + } else { + reason = SErrGetLastError() == 2 ? 4 : 5; + } + + CGlueMgr::PatchFailed(reason, 0); + OsDeleteFile("wow-patch.mpq"); + OsSetCurrentDirectory(currentDirectory); +} diff --git a/WoW/Source/Glue/SurveyDownloadGlue.cpp b/WoW/Source/Glue/SurveyDownloadGlue.cpp index 9f83283..0be4aed 100644 --- a/WoW/Source/Glue/SurveyDownloadGlue.cpp +++ b/WoW/Source/Glue/SurveyDownloadGlue.cpp @@ -1,5 +1,43 @@ #include "SurveyDownloadGlue.h" +#include +#include +#include "Engine/Source/BlizzardCore/SFile2-Core.h" +#include "Engine/Source/FrameScript/FrameScript.h" +#include "Engine/Source/Gx/CGxDevice/CGxDevice.h" +#include "Engine/Source/Os/OsFile.h" +#include "Engine/Source/Os/OsLibrary.h" +#include "Engine/Source/Storm/H/storm.h" #include "WoW/Source/Glue/CGlueMgr.h" +#include "WoW/Source/WowServices/Login.h" +#include "WoW/Source/WowServices/LoginResponse.h" +#include "WoW/Source/WowSvcs/WowSvcsClient/ClientServices.h" +#include "WoW/Source/WowSvcs/WowSvcsClient/FileDownload.h" +#include "ThirdParty/zlib/zlib.h" + +// STATIC: 0x009F6418 +static const uint8_t s_surveyExponent[4] = { + 0x01, 0x00, 0x01, 0x00, +}; + +// STATIC: 0x00AC4430 +static uint8_t s_surveyModulus[256] = { + 0x9D, 0x6B, 0x29, 0x8C, 0x12, 0x0B, 0x73, 0x4D, 0x94, 0x5F, 0x17, 0xB5, 0xB2, 0xC8, 0x21, 0xB2, + 0x52, 0xE8, 0x01, 0x96, 0x39, 0x3D, 0xE2, 0xD5, 0xB8, 0xE3, 0x28, 0x0D, 0x30, 0x49, 0x57, 0x2B, + 0x32, 0x25, 0xD7, 0xF9, 0x29, 0x2E, 0x1B, 0xF5, 0x19, 0xF2, 0xA9, 0xBB, 0x3E, 0x4D, 0x1F, 0xC5, + 0xBD, 0x9A, 0xBE, 0x14, 0x09, 0xB3, 0xB3, 0xDB, 0x44, 0x6C, 0x31, 0xCF, 0xC6, 0xFA, 0x9A, 0x5A, + 0x02, 0xCB, 0xAC, 0xC5, 0x78, 0x3C, 0x68, 0x27, 0x52, 0xCE, 0xD5, 0x4E, 0x92, 0x1C, 0x6C, 0x23, + 0x82, 0xF5, 0xF4, 0x61, 0x26, 0x98, 0xB3, 0x52, 0x42, 0xE3, 0xC9, 0x29, 0xA5, 0x65, 0x2B, 0xF8, + 0xCD, 0xED, 0x7C, 0x8B, 0x70, 0x80, 0x47, 0x0B, 0x6A, 0x8A, 0x95, 0xD9, 0xD4, 0xFA, 0xE3, 0x9D, + 0x35, 0x0B, 0xEC, 0x67, 0x09, 0x70, 0x7F, 0xE0, 0x40, 0xD7, 0xCF, 0xE3, 0xE1, 0x88, 0x82, 0xD2, + 0x09, 0x36, 0x09, 0xF9, 0xE2, 0xE7, 0x86, 0x3F, 0x10, 0x7B, 0xF0, 0xAE, 0xC6, 0x47, 0x8C, 0x1E, + 0x05, 0x14, 0xE8, 0x4C, 0x48, 0xE4, 0x3C, 0x73, 0xE9, 0xC7, 0x3B, 0xAD, 0xFF, 0xE2, 0xD3, 0xA4, + 0xBD, 0x8D, 0xFC, 0x3D, 0x7C, 0x80, 0xEB, 0xD6, 0x45, 0x31, 0x76, 0xE8, 0xF4, 0x14, 0x06, 0xB1, + 0xF5, 0xD8, 0x19, 0x65, 0x3D, 0x75, 0xF8, 0xDC, 0x1C, 0x6A, 0xF7, 0xD4, 0x60, 0x7C, 0xE6, 0x74, + 0xEB, 0x9C, 0xDD, 0x89, 0x27, 0xA6, 0xA2, 0x2D, 0x71, 0x21, 0x0F, 0x92, 0x57, 0x3F, 0x3B, 0x30, + 0x04, 0x10, 0x74, 0x93, 0x26, 0xED, 0x89, 0x39, 0x71, 0x32, 0x48, 0x67, 0xA3, 0x2F, 0x2B, 0x71, + 0xB0, 0xC0, 0x3B, 0x7F, 0xC0, 0xDC, 0xE1, 0x89, 0xB1, 0xF2, 0x9F, 0xAD, 0xC6, 0x69, 0xED, 0xA2, + 0x30, 0xDE, 0x11, 0x6A, 0xAA, 0x2D, 0xB3, 0x8A, 0x2C, 0x47, 0xA7, 0x1E, 0x0D, 0x75, 0x8B, 0x9C, +}; // STATIC: 0x00B6B248 uint32_t CGlueMgr::m_surveyTimer; @@ -9,3 +47,245 @@ uint8_t CGlueMgr::m_executedSurvey; // STATIC: 0x00B6B250 FileDownload* CGlueMgr::m_surveyDownload; + +// STATIC: 0x00B6B254 +uint8_t* CGlueMgr::m_surveyData; + +// STATIC: 0x00B6B258 +uint16_t CGlueMgr::m_surveyDataSize; + +// VERIFY: 01b93246 auto +// OFFSET: 0x004E4880 +void CGlueMgr::SurveyDownloadFeed(const uint8_t* data, uint32_t size) { + if (CGlueMgr::m_surveyDownload) { + CGlueMgr::m_surveyDownload->Proceed(data, size); + } +} + +// VERIFY: 58660bf2 auto +// OFFSET: 0x004E48A0 +void CGlueMgr::SurveySendResults() { + if (CGlueMgr::m_surveyData && CGlueMgr::m_surveyDataSize) { + DebugLog("Sending survey result\n"); + ClientServices::SendSurveyData(CGlueMgr::m_surveyDataSize, CGlueMgr::m_surveyData); + } +} + +// VERIFY: 65419e70 auto +// OFFSET: 0x004E48E0 +void CGlueMgr::SurveyDownloadStart() { + if (ClientServices::LoginConnection()->GetLoginServerType()) { + return; + } + + char path[260]; + CGlueMgr::GetPatchFolder(path, sizeof(path)); + SStrPack(path, "/", sizeof(path)); + SStrPack(path, "Cache", sizeof(path)); + OsCreateDirectory(path, 1); + + CGlueMgr::m_idleState = IDLE_12; + CGlueMgr::m_showedDisconnect = 0; + + if (CGlueMgr::m_surveyDownload) { + delete CGlueMgr::m_surveyDownload; + } + + CGlueMgr::m_surveyDownload = new (__FILE__, __LINE__) GruntFileDownload; + + Login* login = ClientServices::LoginConnection(); + uint64_t size = login->m_fileSize; + + char fileName[260]; + CGlueMgr::GetPatchFolder(fileName, sizeof(fileName)); + SStrPack(fileName, "/", sizeof(fileName)); + SStrPack(fileName, "Cache\\Survey.mpq", sizeof(fileName)); + + uint64_t offset; + bool accept = CGlueMgr::m_surveyDownload->Initialize(fileName, ClientServices::LoginConnection()->m_fileMD5, size, offset); + ClientServices::FileAccept(accept, offset); +} + +// VERIFY: 13cc02a9 manual +// OFFSET: 0x004E4A40 +void CGlueMgr::SurveyDownloadCancel() { + CGlueMgr::m_surveyDownload->StopDownload(); + + if (CGlueMgr::m_surveyDownload) { + delete CGlueMgr::m_surveyDownload; + } + + CGlueMgr::m_surveyDownload = nullptr; + ClientServices::LoginConnection()->FileComplete(false); + CGlueMgr::m_idleState = IDLE_NONE; + CGlueMgr::m_showedDisconnect = 0; + ClientServices::LoginConnection()->Logoff(); +} + +// VERIFY: fdd18e3f auto +// OFFSET: 0x004E4AA0 +void CGlueMgr::SurveyDownloadIdle() { + int32_t status = CGlueMgr::m_surveyDownload->GetStatus(); + + if (status == 2) { + if (CGlueMgr::m_surveyDownload->Accepted()) { + ClientServices::LoginConnection()->FileComplete(true); + } + + CGlueMgr::m_surveyDownload->CompleteDownload(); + } else { + if (status != 3) { + return; + } + + if (CGlueMgr::m_surveyDownload->Accepted()) { + ClientServices::LoginConnection()->FileComplete(false); + } + + CGlueMgr::m_surveyDownload->Destroy(true); + } + + CGlueMgr::m_showedDisconnect = 0; + CGlueMgr::m_idleState = IDLE_13; +} + +// VERIFY: 47cdb6c7 manual +// OFFSET: 0x004E4B30 +bool CGlueMgr::SurveyExecute() { + char currentDirectory[260]; + OsGetCurrentDirectory(sizeof(currentDirectory), currentDirectory); + + char patchFolder[260]; + CGlueMgr::GetPatchFolder(patchFolder, sizeof(patchFolder)); + OsSetCurrentDirectory(patchFolder); + + SArchive* archive = nullptr; + HOSFILE file = OS_INVALID_FILE; + uint32_t written = 0; + void* dll = nullptr; + uint32_t dllSize = 0; + void* library = nullptr; + bool success = false; + + SFileOpenArchive("Cache\\Survey.mpq", 100, 0, &archive); + + if (archive) { + uint32_t authResult; + SFileAuthenticateArchiveEx(archive, &authResult, s_surveyModulus, sizeof(s_surveyModulus), s_surveyExponent, sizeof(s_surveyExponent)); + + if (authResult >= 5) { + file = OsCreateFile("Cache\\Survey.dll", OS_GENERIC_WRITE, 0, OS_CREATE_ALWAYS, OS_FILE_ATTRIBUTE_NORMAL, OS_FILE_TYPE_ANY); + + if (file != OS_INVALID_FILE && SFileLoadFileEx(archive, "Survey.dll", &dll, &dllSize, 0, 0, nullptr) && dll) { + OsWriteFile(file, dll, dllSize, &written); + + if (written == dllSize) { + OsCloseFile(file); + file = OS_INVALID_FILE; + DebugLog("Cache\\Survey.dll"); + library = OsLoadLibrary("Cache\\Survey.dll"); + + int32_t (*extraWork)(uint16_t* data) = library ? reinterpret_cast(OsGetLibraryEntryPoint(library, "ExtraWork")) : nullptr; + uint16_t* data = extraWork ? static_cast(SMemAlloc(0x1004, __FILE__, __LINE__, 0)) : nullptr; + + if (data) { + memset(data, 0, 0x1004); + + uint32_t desktopWidth = 0; + uint32_t desktopHeight = 0; + uint32_t desktopBpp = 0; + uint32_t width = 0; + uint32_t height = 0; + uint32_t bpp = 0; + + if (g_theGxDevicePtr) { + g_theGxDevicePtr->GetSurveyModeInfo(desktopWidth, desktopHeight, desktopBpp, width, height, bpp); + } + + data[0] = 4; + data[1] = 32; + reinterpret_cast(data)[1] = SFile::s_locale; + reinterpret_cast(data)[2] = ClientServices::GetSurveyId(); + reinterpret_cast(data)[3] = desktopWidth; + reinterpret_cast(data)[4] = desktopHeight; + reinterpret_cast(data)[5] = desktopBpp; + reinterpret_cast(data)[6] = width; + reinterpret_cast(data)[7] = height; + reinterpret_cast(data)[8] = bpp; + + if (extraWork(data) && data[1] <= 0x1000) { + uLongf compressedSize = 0x2000; + uint8_t* compressed = static_cast(SMemAlloc(0x2000, __FILE__, __LINE__, 0)); + + if (compressed) { + if (!compress2(compressed, &compressedSize, reinterpret_cast(data + 2), data[1], 9) && compressedSize <= 1000) { + CGlueMgr::m_surveyDataSize = static_cast(compressedSize); + CGlueMgr::m_surveyData = static_cast(SMemAlloc(CGlueMgr::m_surveyDataSize, __FILE__, __LINE__, 0)); + + if (CGlueMgr::m_surveyData) { + memcpy(CGlueMgr::m_surveyData, compressed, CGlueMgr::m_surveyDataSize); + } + + success = true; + } + + SMemFree(compressed, __FILE__, __LINE__, 0); + } + } + + delete data; + } + } + } + } + } + + if (!success) { + ClientServices::SendSurveyFailed(); + } + + if (library) { + OsFreeLibrary(library); + } + + if (dll) { + SFileUnloadFile(dll); + } + + if (file != OS_INVALID_FILE) { + OsCloseFile(file); + } + + if (OsFileExists("Cache\\Survey.dll")) { + OsDeleteFile("Cache\\Survey.dll"); + } + + if (archive) { + SFileCloseArchive(archive); + } + + OsSetCurrentDirectory(currentDirectory); + return success; +} + +// VERIFY: d2090c19 manual +// OFFSET: 0x004E4E80 +void CGlueMgr::SurveyDownloadEnd() { + CGlueMgr::m_executedSurvey = 0; + + if (CGlueMgr::m_surveyData) { + SMemFree(CGlueMgr::m_surveyData, __FILE__, __LINE__, 0); + } + + CGlueMgr::m_surveyData = nullptr; + CGlueMgr::m_surveyDataSize = 0; + + if (CGlueMgr::m_surveyDownload) { + delete CGlueMgr::m_surveyDownload; + CGlueMgr::m_surveyDownload = nullptr; + } + + ClientServices::CreateLoginResponse()->UpdateLoginStatus(LOGIN_STATE_AUTHENTICATED, LOGIN_OK, nullptr, 0); + CGlueMgr::m_showedDisconnect = 0; + CGlueMgr::m_idleState = IDLE_LOGIN_SERVER_LOGIN; +} diff --git a/WoW/Source/Glue/Win64/PatchDownloadGlue.cpp b/WoW/Source/Glue/Win64/PatchDownloadGlue.cpp new file mode 100644 index 0000000..1672829 --- /dev/null +++ b/WoW/Source/Glue/Win64/PatchDownloadGlue.cpp @@ -0,0 +1,36 @@ +#if defined(WOWDECOMP_ARCH_64) + +#include +#include +#include +#include "WoW/Source/Glue/CGlueMgr.h" +#include "Engine/Source/BlizzardCore/Source/System/Process/Process.h" +#include "Engine/Source/BlizzardCore/Source/System/Unicode/Unicode.h" + +// OFFSET: 0x004620A0 +static bool ShellExecuteRunAs(const char* path, const char* arguments) { + if (!arguments) { + arguments = ""; + } + + Blizzard::StringConversion_CodepageToUTF8::ToNative nativeArguments(arguments); + Blizzard::StringConversion_CodepageToUTF8::ToNative nativePath(path); + Blizzard::StringConversion_CodepageToUTF8::ToNative verb("runas"); + + return reinterpret_cast(ShellExecuteA(nullptr, verb.m_data, nativePath.m_data, nativeArguments.m_data, nullptr, SW_SHOWNORMAL)) > 32; +} + +// OFFSET: 0x00462190 +bool CGlueMgr::PatchDownloadExecuteCommand(const char* path, const char* arguments) { + OSVERSIONINFOA versionInfo; + versionInfo.dwOSVersionInfoSize = sizeof(versionInfo); + GetVersionExA(&versionInfo); + + if (versionInfo.dwMajorVersion < 6) { + return Blizzard::Process::LaunchChildProcessWithArguments(path, arguments, nullptr, nullptr); + } + + return ShellExecuteRunAs(path, arguments); +} + +#endif diff --git a/WoW/Source/Magic/MagicClient/Spell_C_Scripts.cpp b/WoW/Source/Magic/MagicClient/Spell_C_Scripts.cpp index e3736bb..fabee4e 100644 --- a/WoW/Source/Magic/MagicClient/Spell_C_Scripts.cpp +++ b/WoW/Source/Magic/MagicClient/Spell_C_Scripts.cpp @@ -194,7 +194,7 @@ static int32_t Script_SpellStopCasting(lua_State* L) { return 1; } -// VERIFY: 07d2d114 manual +// VERIFY: 3c719e98 auto // OFFSET: 0x008021D0 static int32_t Script_CancelItemTempEnchantment(lua_State* L) { CGPlayer_C* player = ClntObjMgrGetActivePlayerObj(); @@ -221,7 +221,7 @@ static int32_t Script_CancelItemTempEnchantment(lua_State* L) { return 0; } -// VERIFY: 36933267 auto +// VERIFY: e1fc05d2 auto // OFFSET: 0x00804220 static int32_t Script_CancelUnitBuff(lua_State* L) { ScriptAuraInfo info; diff --git a/WoW/Source/Object/ObjectClient/UnitCombatLog_C_Scripts.cpp b/WoW/Source/Object/ObjectClient/UnitCombatLog_C_Scripts.cpp index d51036b..52be208 100644 --- a/WoW/Source/Object/ObjectClient/UnitCombatLog_C_Scripts.cpp +++ b/WoW/Source/Object/ObjectClient/UnitCombatLog_C_Scripts.cpp @@ -41,7 +41,7 @@ static int32_t Script_CombatLogClearEntries(lua_State* L) { return 0; } -// VERIFY: 04498be3 auto +// VERIFY: 07fafbfd auto // OFFSET: 0x0074D5B0 static int32_t Script_CombatLogSetRetentionTime(lua_State* L) { if (!lua_isnumber(L, 1)) { diff --git a/WoW/Source/SoundInterface/SoundInterface2_Scripts.cpp b/WoW/Source/SoundInterface/SoundInterface2_Scripts.cpp index 6c4e94b..73dcc9b 100644 --- a/WoW/Source/SoundInterface/SoundInterface2_Scripts.cpp +++ b/WoW/Source/SoundInterface/SoundInterface2_Scripts.cpp @@ -175,7 +175,7 @@ static int32_t Script_VoiceChat_StopCapture(lua_State* L) { return 0; } -// VERIFY: ec24934e manual +// VERIFY: e09b1c70 auto // OFFSET: 0x00985D60 static int32_t Script_VoiceChat_RecordLoopbackSound(lua_State* L) { if (!lua_isnumber(L, 1)) { diff --git a/WoW/Source/UIUtil/InputControl_Scripts.cpp b/WoW/Source/UIUtil/InputControl_Scripts.cpp index 78eef98..f1cbfb8 100644 --- a/WoW/Source/UIUtil/InputControl_Scripts.cpp +++ b/WoW/Source/UIUtil/InputControl_Scripts.cpp @@ -588,7 +588,7 @@ static int32_t Script_IsVehicleAimPowerAdjustable(lua_State* L) { return 1; } -// VERIFY: 3bf17f31 auto +// VERIFY: 2474fdc2 auto // OFFSET: 0x005FD550 static int32_t Script_SetMouselookOverrideBinding(lua_State* L) { CGInputControl* inputControl = CGInputControl::s_inputControl; diff --git a/WoW/Source/UIUtil/Tooltip_Scripts.cpp b/WoW/Source/UIUtil/Tooltip_Scripts.cpp index 970f997..fba2767 100644 --- a/WoW/Source/UIUtil/Tooltip_Scripts.cpp +++ b/WoW/Source/UIUtil/Tooltip_Scripts.cpp @@ -2378,7 +2378,7 @@ static int32_t Script_SetExistingSocketGem(lua_State* L) { return 0; } -// VERIFY: c26318ae manual +// VERIFY: e89f31ca auto // OFFSET: 0x006304A0 static int32_t Script_SetGuildBankItem(lua_State* L) { CGTooltip* tooltip = static_cast(FrameScript_GetObjectThis(L, CGTooltip::GetObjectType())); diff --git a/WoW/Source/Ui/AchievementInfo_Scripts.cpp b/WoW/Source/Ui/AchievementInfo_Scripts.cpp index e7498a9..0fd9828 100644 --- a/WoW/Source/Ui/AchievementInfo_Scripts.cpp +++ b/WoW/Source/Ui/AchievementInfo_Scripts.cpp @@ -56,7 +56,7 @@ static int32_t Script_GetPreviousAchievement(lua_State* L) { return 1; } -// VERIFY: 5a4740c3 auto +// VERIFY: 1f10113f auto // OFFSET: 0x005B18E0 static int32_t Script_GetAchievementCategory(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -74,7 +74,7 @@ static int32_t Script_GetAchievementCategory(lua_State* L) { return 1; } -// VERIFY: 01bbd72e auto +// VERIFY: fd1ca539 auto // OFFSET: 0x005B1970 static int32_t Script_GetAchievementNumRewards(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -93,7 +93,7 @@ static int32_t Script_GetAchievementNumRewards(lua_State* L) { return 1; } -// VERIFY: 05270d3b auto +// VERIFY: 0f6732e2 auto // OFFSET: 0x005B1A00 static int32_t Script_GetAchievementReward(lua_State* L) { if (!lua_isnumber(L, 1) || !lua_isnumber(L, 2)) { @@ -449,7 +449,7 @@ static int32_t Script_GetStatisticsCategoryList(lua_State* L) { return 1; } -// VERIFY: c18efdb4 auto +// VERIFY: 3a8c4c7a auto // OFFSET: 0x005B1720 static int32_t Script_GetAchievementInfoFromCriteria(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -1018,7 +1018,7 @@ static int32_t Script_GetAchievementComparisonInfo(lua_State* L) { return 5; } -// VERIFY: 17abec08 auto +// VERIFY: 9a10a883 auto // OFFSET: 0x005B4870 static int32_t Script_AddTrackedAchievement(lua_State* L) { int32_t id = static_cast(lua_tonumber(L, 1)); @@ -1032,7 +1032,7 @@ static int32_t Script_AddTrackedAchievement(lua_State* L) { return 0; } -// VERIFY: 10b17561 auto +// VERIFY: 7eb57b4e auto // OFFSET: 0x005B48D0 static int32_t Script_RemoveTrackedAchievement(lua_State* L) { int32_t id = static_cast(lua_tonumber(L, 1)); diff --git a/WoW/Source/Ui/ActionBarFrame_Scripts.cpp b/WoW/Source/Ui/ActionBarFrame_Scripts.cpp index f56ae1e..06ff928 100644 --- a/WoW/Source/Ui/ActionBarFrame_Scripts.cpp +++ b/WoW/Source/Ui/ActionBarFrame_Scripts.cpp @@ -142,7 +142,7 @@ static int32_t Script_GetActionInfo(lua_State* L) { return 2; } -// VERIFY: 45a7ef5a manual +// VERIFY: 850abda9 auto // OFFSET: 0x005A91C0 static int32_t Script_GetActionCooldown(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -230,7 +230,7 @@ static int32_t Script_UseAction(lua_State* L) { return 0; } -// VERIFY: b345a40c auto +// VERIFY: 9530d833 auto // OFFSET: 0x005A7D90 static int32_t Script_GetActionText(lua_State* L) { if (!lua_isnumber(L, 1)) { diff --git a/WoW/Source/Ui/ArenaTeamInfo_Scripts.cpp b/WoW/Source/Ui/ArenaTeamInfo_Scripts.cpp index 9cf6b41..cef8296 100644 --- a/WoW/Source/Ui/ArenaTeamInfo_Scripts.cpp +++ b/WoW/Source/Ui/ArenaTeamInfo_Scripts.cpp @@ -225,7 +225,7 @@ static int32_t Script_SetArenaTeamRosterSelection(lua_State* L) { return 0; } -// VERIFY: d74e026b manual +// VERIFY: 35145502 auto // OFFSET: 0x005A3410 static int32_t Script_GetArenaTeamRosterSelection(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -300,7 +300,7 @@ static int32_t Script_CloseArenaTeamRoster(lua_State* L) { return 0; } -// VERIFY: fa985c25 manual +// VERIFY: 1e8f2585 auto // OFFSET: 0x005A3CF0 static int32_t Script_ArenaTeamRoster(lua_State* L) { if (!lua_isnumber(L, 1)) { diff --git a/WoW/Source/Ui/AuctionHouse_Scripts.cpp b/WoW/Source/Ui/AuctionHouse_Scripts.cpp index cf1ec58..0c124ef 100644 --- a/WoW/Source/Ui/AuctionHouse_Scripts.cpp +++ b/WoW/Source/Ui/AuctionHouse_Scripts.cpp @@ -60,7 +60,7 @@ static const AuctionInvType s_auctionInvTypes[14] = { { 23, "INVTYPE_HOLDABLE", 1, 1 }, }; -// VERIFY: 06078343 auto +// VERIFY: 95a282d9 auto // OFFSET: 0x0059B0B0 static int32_t Script_SetAuctionsTabShowing(lua_State* L) { if (lua_type(L, 1) != LUA_TBOOLEAN) { @@ -190,7 +190,7 @@ static int32_t Script_GetAuctionInvTypes(lua_State* L) { return 28; } -// VERIFY: 0a1271c4 manual +// VERIFY: a694c251 auto // OFFSET: 0x0059C9F0 static int32_t Script_CanCancelAuction(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -262,7 +262,7 @@ static int32_t Script_CancelAuction(lua_State* L) { return 0; } -// VERIFY: 370de460 manual +// VERIFY: c9d2ca3b auto // OFFSET: 0x0059C1A0 static int32_t Script_GetNumAuctionItems(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -385,7 +385,7 @@ static int32_t Script_GetAuctionSort(lua_State* L) { return 2; } -// VERIFY: 4d5b346c auto +// VERIFY: a7708e62 auto // OFFSET: 0x0059AE70 static int32_t Script_SortAuctionClearSort(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -406,7 +406,7 @@ static int32_t Script_SortAuctionClearSort(lua_State* L) { return 0; } -// VERIFY: 6ce803e7 auto +// VERIFY: bf332834 auto // OFFSET: 0x0059AF10 static int32_t Script_SortAuctionSetSort(lua_State* L) { if (!lua_isstring(L, 1) || !lua_isstring(L, 2)) { @@ -660,7 +660,7 @@ static int32_t Script_SetSelectedAuctionItem(lua_State* L) { return 0; } -// VERIFY: e4d0be72 auto +// VERIFY: f95e702d auto // OFFSET: 0x0059C920 static int32_t Script_GetSelectedAuctionItem(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -683,7 +683,7 @@ static int32_t Script_GetSelectedAuctionItem(lua_State* L) { return 1; } -// VERIFY: ef011e51 auto +// VERIFY: 7cc1108f auto // OFFSET: 0x0059CAB0 static int32_t Script_SortAuctionApplySort(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -705,7 +705,7 @@ static int32_t Script_SortAuctionApplySort(lua_State* L) { return 0; } -// VERIFY: 9e0b91e7 manual +// VERIFY: 3de5ed5e auto // OFFSET: 0x0059D270 static int32_t Script_CalculateAuctionDeposit(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -989,7 +989,7 @@ static int32_t Script_PlaceAuctionBid(lua_State* L) { return 0; } -// VERIFY: 53a2205e auto +// VERIFY: bd9b02e3 auto // OFFSET: 0x0059DD00 static int32_t Script_SortAuctionItems(lua_State* L) { if (!lua_isstring(L, 1) || !lua_isstring(L, 2)) { @@ -1071,7 +1071,7 @@ static int32_t Script_GetAuctionSellItemInfo(lua_State* L) { return 9; } -// VERIFY: 968d4e95 manual +// VERIFY: 6bd4bdb4 auto // OFFSET: 0x0059F990 static int32_t Script_StartAuction(lua_State* L) { if (!lua_isnumber(L, 1) || !lua_isnumber(L, 2) || !lua_isnumber(L, 3)) { diff --git a/WoW/Source/Ui/BattlefieldInfo_Scripts.cpp b/WoW/Source/Ui/BattlefieldInfo_Scripts.cpp index 9666550..72d129c 100644 --- a/WoW/Source/Ui/BattlefieldInfo_Scripts.cpp +++ b/WoW/Source/Ui/BattlefieldInfo_Scripts.cpp @@ -481,7 +481,7 @@ static int32_t Script_GetNumBattlefieldFlagPositions(lua_State* L) { return 1; } -// VERIFY: 15310d8d manual +// VERIFY: e121516b auto // OFFSET: 0x00549F60 static int32_t Script_GetBattlefieldStatData(lua_State* L) { if (!lua_isnumber(L, 1) || !lua_isnumber(L, 2)) { @@ -504,7 +504,7 @@ static int32_t Script_GetBattlefieldStatData(lua_State* L) { return 1; } -// VERIFY: a4ccae58 manual +// VERIFY: 6e90bb54 auto // OFFSET: 0x0054C170 static int32_t Script_GetBattlefieldStatInfo(lua_State* L) { if (!lua_isnumber(L, 1)) { diff --git a/WoW/Source/Ui/BattlenetAPI.cpp b/WoW/Source/Ui/BattlenetAPI.cpp new file mode 100644 index 0000000..07ae4f9 --- /dev/null +++ b/WoW/Source/Ui/BattlenetAPI.cpp @@ -0,0 +1,443 @@ +#include "BattlenetAPI.h" +#include "WoW/Source/Battlenet/Tumor/TumorManager.h" +#include "WoW/Source/WowServices/BattlenetLogin.h" + +// VERIFY: 47bdd12c manual +// OFFSET: 0x005312E0 +uint16_t BattlenetAPI::SendChatWhisper(uint32_t presenceId, const char* message) { + GeneralFunction::Arg args[2]; + args[0] = static_cast(presenceId); + args[1] = message; + return static_cast(g_tumorManager->CallFunction("BattlenetAPI_SendChatWhisper", 2, args).ToUInt64()); +} + +// VERIFY: 1f7f4d30 manual +// OFFSET: 0x005313A0 +uint16_t BattlenetAPI::LeaveChatConversation(uint8_t channel) { + GeneralFunction::Arg arg; + arg = static_cast(channel); + return static_cast(g_tumorManager->CallFunction("BattlenetAPI_LeaveChatConversation", 1, &arg).ToUInt64()); +} + +// VERIFY: 0c9531cb manual +// OFFSET: 0x00531430 +uint16_t BattlenetAPI::SendChatMessage(uint8_t channel, const char* message) { + GeneralFunction::Arg args[2]; + args[0] = static_cast(channel); + args[1] = message; + return static_cast(g_tumorManager->CallFunction("BattlenetAPI_SendChatMessage", 2, args).ToUInt64()); +} + +// VERIFY: c2328de4 manual +// OFFSET: 0x005314F0 +uint32_t BattlenetAPI::GetNumChatMembers(uint8_t channel) { + GeneralFunction::Arg arg; + arg = static_cast(channel); + return static_cast(g_tumorManager->CallFunction("BattlenetAPI_GetNumChatMembers", 1, &arg).ToUInt64()); +} + +// VERIFY: 67a310d6 manual +// OFFSET: 0x00531580 +uint16_t BattlenetAPI::SetFriendNote(uint32_t presenceId, const char* note) { + GeneralFunction::Arg args[2]; + args[0] = static_cast(presenceId); + args[1] = note; + return static_cast(g_tumorManager->CallFunction("BattlenetAPI_SetFriendNote", 2, args).ToUInt64()); +} + +// VERIFY: c29a1cce manual +// OFFSET: 0x00531640 +uint16_t BattlenetAPI::SendRIDFriendInviteByEmail(const char* email, const char* note, GeneralFunction::Callback* callback) { + GeneralFunction::Arg args[3]; + args[0] = email; + args[1] = note; + args[2] = callback; + return static_cast(g_tumorManager->CallFunction("BattlenetAPI_SendRIDFriendInviteByEmail", 3, args).ToUInt64()); +} + +// VERIFY: 245a930e manual +// OFFSET: 0x00531700 +uint16_t BattlenetAPI::SendRIDFriendInviteByPresenceId(uint32_t presenceId, const char* note, GeneralFunction::Callback* callback) { + GeneralFunction::Arg args[3]; + args[0] = static_cast(presenceId); + args[1] = note; + args[2] = callback; + return static_cast(g_tumorManager->CallFunction("BattlenetAPI_SendRIDFriendInviteByPresenceId", 3, args).ToUInt64()); +} + +// VERIFY: 5e24d7f3 manual +// OFFSET: 0x005317D0 +uint16_t BattlenetAPI::RemoveFriend(uint32_t presenceId) { + GeneralFunction::Arg arg; + arg = static_cast(presenceId); + return static_cast(g_tumorManager->CallFunction("BattlenetAPI_RemoveFriend", 1, &arg).ToUInt64()); +} + +// VERIFY: ecba5662 manual +// OFFSET: 0x00531860 +uint16_t BattlenetAPI::AcceptFriendInvite(uint32_t presenceId) { + GeneralFunction::Arg arg; + arg = static_cast(presenceId); + return static_cast(g_tumorManager->CallFunction("BattlenetAPI_AcceptFriendInvite", 1, &arg).ToUInt64()); +} + +// VERIFY: 8cb68fd4 manual +// OFFSET: 0x005318F0 +uint16_t BattlenetAPI::DeclineFriendInvite(uint32_t presenceId) { + GeneralFunction::Arg arg; + arg = static_cast(presenceId); + return static_cast(g_tumorManager->CallFunction("BattlenetAPI_DeclineFriendInvite", 1, &arg).ToUInt64()); +} + +// VERIFY: a84e6f9a manual +// OFFSET: 0x00531980 +uint16_t BattlenetAPI::ReportFriendInvite(uint32_t presenceId) { + GeneralFunction::Arg arg; + arg = static_cast(presenceId); + return static_cast(g_tumorManager->CallFunction("BattlenetAPI_ReportFriendInvite", 1, &arg).ToUInt64()); +} + +// VERIFY: 9940bbeb manual +// OFFSET: 0x00531A10 +uint16_t BattlenetAPI::GetFriendsOfFriend(uint32_t presenceId, GeneralFunction::Callback* callback) { + GeneralFunction::Arg args[2]; + args[0] = static_cast(presenceId); + args[1] = callback; + return static_cast(g_tumorManager->CallFunction("BattlenetAPI_GetFriendsOfFriend", 2, args).ToUInt64()); +} + +// VERIFY: 65d4abfb manual +// OFFSET: 0x00531AD0 +uint32_t BattlenetAPI::RegisterPresenceUpdateCallback(uint32_t presenceId, uint32_t field, GeneralFunction::Callback* callback) { + GeneralFunction::Arg args[3]; + args[0] = static_cast(presenceId); + args[1] = static_cast(field); + args[2] = callback; + return static_cast(g_tumorManager->CallFunction("BattlenetAPI_RegisterPresenceUpdateCallback", 3, args).ToUInt64()); +} + +// VERIFY: b965982b manual +// OFFSET: 0x00531BA0 +uint32_t BattlenetAPI::GetPresenceIDForCurrentAccount() { + return static_cast(g_tumorManager->CallFunction("BattlenetAPI_GetPresenceIDForCurrentAccount", 0, nullptr).ToUInt64()); +} + +// VERIFY: 730cce7c manual +// OFFSET: 0x00531C00 +uint32_t BattlenetAPI::GetPresenceIDForCurrentToon() { + return static_cast(g_tumorManager->CallFunction("BattlenetAPI_GetPresenceIDForCurrentToon", 0, nullptr).ToUInt64()); +} + +// VERIFY: 210a9c9d manual +// OFFSET: 0x00531C60 +uint32_t BattlenetAPI::GetAccountPresenceId(uint32_t presenceId) { + GeneralFunction::Arg arg; + arg = static_cast(presenceId); + return static_cast(g_tumorManager->CallFunction("BattlenetAPI_GetAccountPresenceId", 1, &arg).ToUInt64()); +} + +// VERIFY: 66cae904 manual +// OFFSET: 0x00531CF0 +const char* BattlenetAPI::GetNameForPresenceId(uint32_t presenceId, bool full) { + GeneralFunction::Arg args[2]; + args[0] = static_cast(presenceId); + args[1] = full; + return g_tumorManager->CallFunction("BattlenetAPI_GetNameForPresenceId", 2, args).ToString(); +} + +// VERIFY: 0a05bad6 manual +// OFFSET: 0x00531DB0 +const char* BattlenetAPI::GetExactNameForPresenceId(uint32_t presenceId, bool full) { + GeneralFunction::Arg args[2]; + args[0] = static_cast(presenceId); + args[1] = full; + return g_tumorManager->CallFunction("BattlenetAPI_GetExactNameForPresenceId", 2, args).ToString(); +} + +// VERIFY: 19def57a manual +// OFFSET: 0x00531E70 +const char* BattlenetAPI::GetToonNameForPresenceId(uint32_t presenceId, bool full) { + GeneralFunction::Arg args[2]; + args[0] = static_cast(presenceId); + args[1] = full; + return g_tumorManager->CallFunction("BattlenetAPI_GetToonNameForPresenceId", 2, args).ToString(); +} + +// VERIFY: 76fcefe5 manual +// OFFSET: 0x00531F30 +uint32_t BattlenetAPI::GetNumToons(uint32_t presenceId) { + GeneralFunction::Arg arg; + arg = static_cast(presenceId); + return static_cast(g_tumorManager->CallFunction("BattlenetAPI_GetNumToons", 1, &arg).ToUInt64()); +} + +// VERIFY: 460cf366 manual +// OFFSET: 0x00531FC0 +uint32_t BattlenetAPI::GetToon(uint32_t presenceId, uint32_t index) { + GeneralFunction::Arg args[2]; + args[0] = static_cast(presenceId); + args[1] = static_cast(index); + return static_cast(g_tumorManager->CallFunction("BattlenetAPI_GetToon", 2, args).ToUInt64()); +} + +// VERIFY: e101be0a manual +// OFFSET: 0x00532070 +uint32_t BattlenetAPI::GetFocusedToon(uint32_t presenceId) { + GeneralFunction::Arg arg; + arg = static_cast(presenceId); + return static_cast(g_tumorManager->CallFunction("BattlenetAPI_GetFocusedToon", 1, &arg).ToUInt64()); +} + +// VERIFY: a79c3fbd manual +// OFFSET: 0x00532100 +uint16_t BattlenetAPI::AddRIDBlock(uint32_t presenceId) { + GeneralFunction::Arg arg; + arg = static_cast(presenceId); + return static_cast(g_tumorManager->CallFunction("BattlenetAPI_AddRIDBlock", 1, &arg).ToUInt64()); +} + +// VERIFY: 1f3eb23f manual +// OFFSET: 0x00532190 +uint16_t BattlenetAPI::AddCIDBlock(uint32_t presenceId) { + GeneralFunction::Arg arg; + arg = static_cast(presenceId); + return static_cast(g_tumorManager->CallFunction("BattlenetAPI_AddCIDBlock", 1, &arg).ToUInt64()); +} + +// VERIFY: bf8a1772 manual +// OFFSET: 0x00532220 +uint16_t BattlenetAPI::RemoveRIDBlock(uint32_t presenceId) { + GeneralFunction::Arg arg; + arg = static_cast(presenceId); + return static_cast(g_tumorManager->CallFunction("BattlenetAPI_RemoveRIDBlock", 1, &arg).ToUInt64()); +} + +// VERIFY: f3c6ff02 manual +// OFFSET: 0x005322B0 +uint16_t BattlenetAPI::RemoveCIDBlock(uint32_t presenceId) { + GeneralFunction::Arg arg; + arg = static_cast(presenceId); + return static_cast(g_tumorManager->CallFunction("BattlenetAPI_RemoveCIDBlock", 1, &arg).ToUInt64()); +} + +// VERIFY: 60f4858d manual +// OFFSET: 0x00532340 +uint16_t BattlenetAPI::ReportPlayer(uint32_t presenceId, int32_t reason, const char* note) { + GeneralFunction::Arg args[3]; + args[0] = static_cast(presenceId); + args[1] = static_cast(reason); + args[2] = note; + return static_cast(g_tumorManager->CallFunction("BattlenetAPI_ReportPlayer", 3, args).ToUInt64()); +} + +// VERIFY: 654a4514 manual +// OFFSET: 0x00532400 +void BattlenetAPI::SetSetting(const char* name, GeneralFunction::Arg value, bool notify) { + GeneralFunction::Arg args[3]; + args[0] = name; + args[1] = value; + args[2] = notify; + g_tumorManager->CallFunction("BattlenetAPI_SetSetting", 3, args); +} + +// VERIFY: 75a56b4f manual +// OFFSET: 0x00532500 +const char* BattlenetAPI::GetErrorString(uint16_t error) { + GeneralFunction::Arg arg; + arg = static_cast(error); + return g_tumorManager->CallFunction("BattlenetAPI_GetErrorString", 1, &arg).ToString(); +} + +// VERIFY: 910a8d74 manual +// OFFSET: 0x005325A0 +uint32_t BattlenetAPI::RegisterEvent(const char* name, GeneralFunction::Callback* callback) { + GeneralFunction::Arg args[2]; + args[0] = name; + args[1] = callback; + return static_cast(g_tumorManager->CallFunction("BattlenetAPI_RegisterEvent", 2, args).ToUInt64()); +} + +// VERIFY: a4abcd2e manual +// OFFSET: 0x00532650 +void BattlenetAPI::SetAccountNameFormatString(const char* format) { + GeneralFunction::Arg arg; + arg = format; + g_tumorManager->CallFunction("BattlenetAPI_SetAccountNameFormatString", 1, &arg); +} + +// VERIFY: fc61362b manual +// OFFSET: 0x00532E10 +uint16_t BattlenetAPI::CreateChatConversation(const Battlenet::Toon::FullName* first, const Battlenet::Toon::FullName* second, GeneralFunction::Callback* callback) { + GeneralFunction::Arg args[3]; + + BSN::BSNEncodedObjectPtr firstObject(first); + firstObject.IncRef(); + args[0] = &firstObject; + + BSN::BSNEncodedObjectPtr secondObject(second); + secondObject.IncRef(); + args[1] = &secondObject; + + args[2] = callback; + return static_cast(g_tumorManager->CallFunction("BattlenetAPI_CreateChatConversation", 3, args).ToUInt64()); +} + +// VERIFY: 24a8a358 manual +// OFFSET: 0x00532FD0 +uint16_t BattlenetAPI::SendChatConversationInvite(uint8_t channel, const Battlenet::Toon::FullName* toon, GeneralFunction::Callback* callback) { + GeneralFunction::Arg args[3]; + args[0] = static_cast(channel); + + BSN::BSNEncodedObjectPtr toonObject(toon); + toonObject.IncRef(); + args[1] = &toonObject; + + args[2] = callback; + return static_cast(g_tumorManager->CallFunction("BattlenetAPI_SendChatConversationInvite", 3, args).ToUInt64()); +} + +// VERIFY: ea67e7f3 manual +// OFFSET: 0x00533130 +int32_t BattlenetAPI::GetChatChannelType(uint8_t channel) { + GeneralFunction::Arg arg; + arg = static_cast(channel); + return static_cast(g_tumorManager->CallFunction("BattlenetAPI_GetChatChannelType", 1, &arg).ToInt64()); +} + +// VERIFY: 99bd6eb2 manual +// OFFSET: 0x005331C0 +Battlenet::Chat::MemberList BattlenetAPI::GetChatMemberList(uint8_t channel) { + GeneralFunction::Arg arg; + arg = static_cast(channel); + BSN::BSNEncodedObject memberList(g_tumorManager->CallFunction("BattlenetAPI_GetChatMemberList", 1, &arg).ToObject()); + return memberList.m_data; +} + +// VERIFY: 738a2741 manual +// OFFSET: 0x00533280 +bool BattlenetAPI::IsRIDFriend(uint32_t presenceId) { + GeneralFunction::Arg arg; + arg = static_cast(presenceId); + return g_tumorManager->CallFunction("BattlenetAPI_IsRIDFriend", 1, &arg).ToBool(); +} + +// VERIFY: f22d0ef8 manual +// OFFSET: 0x00533320 +bool BattlenetAPI::IsCIDFriend(uint32_t presenceId) { + GeneralFunction::Arg arg; + arg = static_cast(presenceId); + return g_tumorManager->CallFunction("BattlenetAPI_IsCIDFriend", 1, &arg).ToBool(); +} + +// VERIFY: 198d8bb9 manual +// OFFSET: 0x005333C0 +bool BattlenetAPI::HasRIDFriendship(uint32_t presenceId) { + GeneralFunction::Arg arg; + arg = static_cast(presenceId); + return g_tumorManager->CallFunction("BattlenetAPI_HasRIDFriendship", 1, &arg).ToBool(); +} + +// VERIFY: 6968d226 manual +// OFFSET: 0x00533460 +Battlenet::Friends::FriendInvite BattlenetAPI::GetFriendInvite(uint32_t presenceId) { + GeneralFunction::Arg arg; + arg = static_cast(presenceId); + BSN::BSNEncodedObject invite(g_tumorManager->CallFunction("BattlenetAPI_GetFriendInvite", 1, &arg).ToObject()); + return invite.m_data; +} + +// VERIFY: 0dd03862 manual +// OFFSET: 0x00533560 +bool BattlenetAPI::UnregisterPresenceUpdateCallback(uint32_t handle) { + GeneralFunction::Arg arg; + arg = static_cast(handle); + return g_tumorManager->CallFunction("BattlenetAPI_UnregisterPresenceUpdateCallback", 1, &arg).ToBool(); +} + +// VERIFY: 81ff8cb8 manual +// OFFSET: 0x00533600 +bool BattlenetAPI::SetPresenceValue(uint32_t field, const Battlenet::Presence::FieldVal* value) { + GeneralFunction::Arg args[2]; + args[0] = static_cast(field); + + BSN::BSNEncodedObjectPtr valueObject(value); + valueObject.IncRef(); + args[1] = &valueObject; + + return g_tumorManager->CallFunction("BattlenetAPI_SetPresenceValue", 2, args).ToBool(); +} + +// VERIFY: 0b35f414 manual +// OFFSET: 0x00533740 +Battlenet::Presence::FieldVal BattlenetAPI::GetPresenceValue(uint32_t presenceId, uint32_t field) { + GeneralFunction::Arg args[2]; + args[0] = static_cast(presenceId); + args[1] = static_cast(field); + BSN::BSNEncodedObject value(g_tumorManager->CallFunction("BattlenetAPI_GetPresenceValue", 2, args).ToObject()); + return value.m_data; +} + +// VERIFY: d7d36627 manual +// OFFSET: 0x00533880 +uint32_t BattlenetAPI::GetPresenceIDForToon(const Battlenet::Toon::FullName* toon) { + GeneralFunction::Arg arg; + + BSN::BSNEncodedObjectPtr toonObject(toon); + toonObject.IncRef(); + arg = &toonObject; + + return static_cast(g_tumorManager->CallFunction("BattlenetAPI_GetPresenceIDForToon", 1, &arg).ToUInt64()); +} + +// VERIFY: 46fb4745 manual +// OFFSET: 0x00533980 +bool BattlenetAPI::IsSelf(uint32_t presenceId) { + GeneralFunction::Arg arg; + arg = static_cast(presenceId); + return g_tumorManager->CallFunction("BattlenetAPI_IsSelf", 1, &arg).ToBool(); +} + +// VERIFY: 768550a9 manual +// OFFSET: 0x00533A20 +Battlenet::Presence::BlockList BattlenetAPI::GetBlockList() { + BSN::BSNEncodedObject blockList(g_tumorManager->CallFunction("BattlenetAPI_GetBlockList", 0, nullptr).ToObject()); + return blockList.m_data; +} + +// VERIFY: 33c87192 manual +// OFFSET: 0x00533AA0 +bool BattlenetAPI::IsRIDBlock(uint32_t presenceId) { + GeneralFunction::Arg arg; + arg = static_cast(presenceId); + return g_tumorManager->CallFunction("BattlenetAPI_IsRIDBlock", 1, &arg).ToBool(); +} + +// VERIFY: 49652734 manual +// OFFSET: 0x00533B40 +bool BattlenetAPI::IsCIDBlock(uint32_t presenceId) { + GeneralFunction::Arg arg; + arg = static_cast(presenceId); + return g_tumorManager->CallFunction("BattlenetAPI_IsCIDBlock", 1, &arg).ToBool(); +} + +// VERIFY: bd641ff4 manual +// OFFSET: 0x00533BE0 +GeneralFunction::Arg BattlenetAPI::GetSetting(const char* name) { + GeneralFunction::Arg arg; + arg = name; + return g_tumorManager->CallFunction("BattlenetAPI_GetSetting", 1, &arg); +} + +// VERIFY: f2e9a292 manual +// OFFSET: 0x00533C40 +bool BattlenetAPI::IsRIDEnabled() { + return g_tumorManager->CallFunction("BattlenetAPI_IsRIDEnabled", 0, nullptr).ToBool(); +} + +// VERIFY: 2090a458 manual +// OFFSET: 0x00533CA0 +bool BattlenetAPI::UnregisterEvent(uint32_t handle) { + GeneralFunction::Arg arg; + arg = static_cast(handle); + return g_tumorManager->CallFunction("BattlenetAPI_UnregisterEvent", 1, &arg).ToBool(); +} diff --git a/WoW/Source/Ui/BattlenetAPI.h b/WoW/Source/Ui/BattlenetAPI.h new file mode 100644 index 0000000..7a33ebb --- /dev/null +++ b/WoW/Source/Ui/BattlenetAPI.h @@ -0,0 +1,62 @@ +#ifndef WOW_SOURCE_UI_BATTLENETAPI_H +#define WOW_SOURCE_UI_BATTLENETAPI_H + +#include +#include +#include "WoW/Source/Battlenet/BattlenetProtocol.h" +#include "WoW/Source/Battlenet/GeneralFunction.h" + +namespace BattlenetAPI { +uint16_t AcceptFriendInvite(uint32_t presenceId); +uint16_t AddCIDBlock(uint32_t presenceId); +uint16_t AddRIDBlock(uint32_t presenceId); +uint16_t CreateChatConversation(const Battlenet::Toon::FullName* first, const Battlenet::Toon::FullName* second, GeneralFunction::Callback* callback); +uint16_t DeclineFriendInvite(uint32_t presenceId); +uint32_t GetAccountPresenceId(uint32_t presenceId); +Battlenet::Presence::BlockList GetBlockList(); +Battlenet::Chat::MemberList GetChatMemberList(uint8_t channel); +int32_t GetChatChannelType(uint8_t channel); +const char* GetErrorString(uint16_t error); +const char* GetExactNameForPresenceId(uint32_t presenceId, bool full); +uint32_t GetFocusedToon(uint32_t presenceId); +Battlenet::Friends::FriendInvite GetFriendInvite(uint32_t presenceId); +uint16_t GetFriendsOfFriend(uint32_t presenceId, GeneralFunction::Callback* callback); +const char* GetNameForPresenceId(uint32_t presenceId, bool full); +uint32_t GetNumChatMembers(uint8_t channel); +uint32_t GetNumToons(uint32_t presenceId); +uint32_t GetPresenceIDForCurrentAccount(); +uint32_t GetPresenceIDForCurrentToon(); +uint32_t GetPresenceIDForToon(const Battlenet::Toon::FullName* toon); +Battlenet::Presence::FieldVal GetPresenceValue(uint32_t presenceId, uint32_t field); +GeneralFunction::Arg GetSetting(const char* name); +uint32_t GetToon(uint32_t presenceId, uint32_t index); +const char* GetToonNameForPresenceId(uint32_t presenceId, bool full); +bool HasRIDFriendship(uint32_t presenceId); +bool IsCIDBlock(uint32_t presenceId); +bool IsCIDFriend(uint32_t presenceId); +bool IsRIDBlock(uint32_t presenceId); +bool IsRIDEnabled(); +bool IsRIDFriend(uint32_t presenceId); +bool IsSelf(uint32_t presenceId); +uint16_t LeaveChatConversation(uint8_t channel); +uint32_t RegisterEvent(const char* name, GeneralFunction::Callback* callback); +uint32_t RegisterPresenceUpdateCallback(uint32_t presenceId, uint32_t field, GeneralFunction::Callback* callback); +uint16_t RemoveCIDBlock(uint32_t presenceId); +uint16_t RemoveFriend(uint32_t presenceId); +uint16_t RemoveRIDBlock(uint32_t presenceId); +uint16_t ReportFriendInvite(uint32_t presenceId); +uint16_t ReportPlayer(uint32_t presenceId, int32_t reason, const char* note); +uint16_t SendChatConversationInvite(uint8_t channel, const Battlenet::Toon::FullName* toon, GeneralFunction::Callback* callback); +uint16_t SendChatMessage(uint8_t channel, const char* message); +uint16_t SendChatWhisper(uint32_t presenceId, const char* message); +uint16_t SendRIDFriendInviteByEmail(const char* email, const char* note, GeneralFunction::Callback* callback); +uint16_t SendRIDFriendInviteByPresenceId(uint32_t presenceId, const char* note, GeneralFunction::Callback* callback); +void SetAccountNameFormatString(const char* format); +uint16_t SetFriendNote(uint32_t presenceId, const char* note); +bool SetPresenceValue(uint32_t field, const Battlenet::Presence::FieldVal* value); +void SetSetting(const char* name, GeneralFunction::Arg value, bool notify); +bool UnregisterEvent(uint32_t handle); +bool UnregisterPresenceUpdateCallback(uint32_t handle); +} + +#endif diff --git a/WoW/Source/Ui/BattlenetUI.cpp b/WoW/Source/Ui/BattlenetUI.cpp index ce78279..23b8bfd 100644 --- a/WoW/Source/Ui/BattlenetUI.cpp +++ b/WoW/Source/Ui/BattlenetUI.cpp @@ -1,27 +1,474 @@ #include "BattlenetUI.h" +#include +#include +#include +#include "Engine/Source/ConsoleBase/ConsoleVar.h" #include "Engine/Source/FrameScript/FrameScript.h" +#include "Engine/Source/Storm/H/storm.h" +#include "WoW/Source/Battlenet/Tumor/TumorManager.h" +#include "WoW/Source/Ui/CGAutoCompleteName.h" +#include "WoW/Source/Ui/ChatFrame.h" +#include "WoW/Source/Ui/GameUI.h" #include "WoW/Source/WowServices/BattlenetLogin.h" #include "WoW/Source/WowServices/Login.h" #include "WoW/Source/WowSvcs/WowSvcsClient/ClientServices.h" +// STATIC: 0x00ACC8B0 +BattlenetUI::EventCallback BattlenetUI::s_eventCallbacks[26] = { + { "BattlenetEvent_NewPresence", BattlenetUI::NewPresenceCB, 0 }, + { "BattlenetEvent_ToonOnline", BattlenetUI::SelfToonOnlineCB, 0 }, + { "BattlenetEvent_ToonOffine", BattlenetUI::SelfToonOfflineCB, 0 }, + { "BattlenetEvent_FriendListInitialized", BattlenetUI::FriendListInitializedCB, 0 }, + { "BattlenetEvent_FriendAdded", BattlenetUI::FriendAddedCB, 0 }, + { "BattlenetEvent_FriendRemoved", BattlenetUI::FriendRemovedCB, 0 }, + { "BattlenetEvent_InviteListInitialized", BattlenetUI::FriendInviteListInitializedCB, 0 }, + { "BattlenetEvent_InviteAdded", BattlenetUI::FriendInviteAddedCB, 0 }, + { "BattlenetEvent_InviteRemoved", BattlenetUI::FriendInviteRemovedCB, 0 }, + { "BattlenetEvent_ChatWhisperSent", BattlenetUI::ChatWhisperSentCB, 0 }, + { "BattlenetEvent_ChatWhisperReceived", BattlenetUI::ChatWhisperReceivedCB, 0 }, + { "BattlenetEvent_ChatWhisperUndeliverable", BattlenetUI::ChatWhisperUndeliverableCB, 0 }, + { "BattlenetEvent_ChannelJoined", BattlenetUI::ChatChannelJoinedCB, 0 }, + { "BattlenetEvent_ChannelLeft", BattlenetUI::ChatChannelLeftCB, 0 }, + { "BattlenetEvent_ChannelClosed", BattlenetUI::ChatChannelClosedCB, 0 }, + { "BattlenetEvent_ChatMessage", BattlenetUI::ChatChannelMessageReceivedCB, 0 }, + { "BattlenetEvent_ChatMessageUndeliverable", BattlenetUI::ChatChannelMessageUndeliverableCB, 0 }, + { "BattlenetEvent_ChatMessageBlocked", BattlenetUI::ChatChannelMessageBlockedCB, 0 }, + { "BattlenetEvent_ChannelMemberJoined", BattlenetUI::ChatChannelMemberJoinedCB, 0 }, + { "BattlenetEvent_ChannelMemberLeft", BattlenetUI::ChatChannelMemberLeftCB, 0 }, + { "BattlenetEvent_ChannelMemberUpdated", BattlenetUI::ChatChannelMemberUpdatedCB, 0 }, + { "BattlenetEvent_BlockListInitialized", BattlenetUI::BlockListInitializedCB, 0 }, + { "BattlenetEvent_BlockAdded", BattlenetUI::BlockAddedCB, 0 }, + { "BattlenetEvent_BlockRemoved", BattlenetUI::BlockRemovedCB, 0 }, + { "BattlenetEvent_SystemMessage", BattlenetUI::SystemMessageCB, 0 }, + { "BattlenetEvent_SettingChanged", BattlenetUI::SettingChangedCB, 0 }, +}; + +// STATIC: 0x00ACC9E8 +BattlenetUI::PresenceCallback BattlenetUI::s_presenceCallbacks[NUM_BN_PRESENCE_FIELDS] = { + { 0x10002, BattlenetUI::OnlinePresenceChangedCB, 0 }, + { 0x10003, BattlenetUI::OnlineTimeChangedCB, 0 }, + { 0x10007, BattlenetUI::LastOnlineChangedCB, 0 }, + { 0x10010, BattlenetUI::FriendInfoChangedCB, 0 }, + { 0x10011, BattlenetUI::FriendInfoChangedCB, 0 }, + { 0x1000C, BattlenetUI::CustomMessageChangedCB, 0 }, + { 0x1000D, BattlenetUI::IgnoredFieldCB, 0 }, + { 0x1000E, BattlenetUI::ToonNameUpdateCB, 0 }, + { 0x10005, BattlenetUI::FriendInfoChangedCB, 0 }, + { 0x10004, BattlenetUI::FriendInfoChangedCB, 0 }, + { 0x10009, BattlenetUI::FriendInfoChangedCB, 0 }, + { 0x10008, BattlenetUI::FriendInfoChangedCB, 0 }, + { 0x30001, BattlenetUI::FriendInfoChangedCB, 0 }, + { 0x30002, BattlenetUI::FriendInfoChangedCB, 0 }, + { 0x30003, BattlenetUI::FriendInfoChangedCB, 0 }, + { 0x30004, BattlenetUI::FriendInfoChangedCB, 0 }, + { 0x30005, BattlenetUI::FriendInfoChangedCB, 0 }, + { 0x30006, BattlenetUI::FriendInfoChangedCB, 0 }, + { 0x1000A, BattlenetUI::FriendInfoChangedCB, 0 }, + { 0x1000B, BattlenetUI::IgnoredFieldCB, 0 }, + { 0x40001, BattlenetUI::FactionUpdateCB, 0 }, +}; + +// STATIC: 0x00ACCCB0 +BattlenetUI::FriendInviteSentCB BattlenetUI::s_friendInviteSentCB; + +// STATIC: 0x00ACCCB8 +int32_t BattlenetUI::s_broadcastCount = 2; + // STATIC: 0x00BD1B00 -int32_t BattlenetUI::unk_BD1B00; +uint32_t BattlenetUI::s_selfRealm; + +// STATIC: 0x00BD1B04 +bool BattlenetUI::s_initialized; // STATIC: 0x00BD1B05 -uint8_t BattlenetUI::m_friendListLoaded; +bool BattlenetUI::m_friendListLoaded; // STATIC: 0x00BD1B08 -BattlenetInviteList* BattlenetUI::m_friendInvites; +BSN::BSNEncodedObject* BattlenetUI::m_friendInvites; + +// STATIC: 0x00BD1B0C +BSN::BSNEncodedObject* BattlenetUI::s_friendsOfFriend; + +// STATIC: 0x00BD1B10 +GeneralFunction::Callback* BattlenetUI::s_createConversationCB; + +// STATIC: 0x00BD1B14 +GeneralFunction::Callback* BattlenetUI::s_inviteToConversationCB; + +// STATIC: 0x00BD1B18 +GeneralFunction::Callback* BattlenetUI::s_friendsOfFriendCB; + +// STATIC: 0x00BD1B1C +uint32_t BattlenetUI::s_selectedFriend; + +// STATIC: 0x00BD1B20 +uint32_t BattlenetUI::s_selectedBlock; // STATIC: 0x00BD1B24 -TSGrowableArray BattlenetUI::m_friends; +uint32_t BattlenetUI::s_selectedToonBlock; -// VERIFY: 02cceac3 auto +// STATIC: 0x00BD1B28 +BSN::Array BattlenetUI::m_friends; + +// STATIC: 0x00BE5D0C +char BattlenetUI::s_programString[16]; + +// STATIC: 0x00BE5D1C +float BattlenetUI::s_broadcastTime; + +// STATIC: 0x00BE5D20 +char BattlenetUI::s_displayName[72]; + +// VERIFY: d9b6deb2 manual +// OFFSET: 0x00530D00 +char* FilterChatLinks(const char* source, char* dest, uint32_t size) { + if (!source || !dest || !size) { + SErrDisplayAppFatalMessage("", "", 0); + } + + char* out = dest; + const char* end = &source[SStrLen(source)]; + + if (source < end) { + do { + if (out >= &dest[size - 1]) { + break; + } + + if (*source == '|') { + switch (source[1]) { + case 'T': + case 'r': + case 't': + source += 2; + break; + + case 'c': + source += 10; + break; + + default: + break; + } + } + + if (source >= end) { + break; + } + + *out++ = *source++; + } while (source < end); + } + + *out = '\0'; + return dest; +} + +// VERIFY: af1ed3d3 auto +// OFFSET: 0x00530DC0 +static int32_t CountFormatStrings(const char* format) { + if (!format) { + return 0; + } + + int32_t length = SStrLen(format); + bool inFormat = false; + int32_t count = 0; + + for (int32_t i = 0; i < length; i++) { + switch (format[i]) { + case ' ': + case '#': + case '$': + case '+': + case '-': + case '.': + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + break; + + case '%': + inFormat = !inFormat; + break; + + case 'S': + case 's': + if (inFormat) { + count++; + inFormat = false; + } + + break; + + default: + if (inFormat) { + return -1; + } + + break; + } + } + + return count; +} + +// VERIFY: 3d11db98 auto +// OFFSET: 0x00530E90 +int32_t BattlenetUI::QSortFriendInviteListByTimeCB(const void* a, const void* b) { + int32_t time1 = static_cast(a)->m_time; + int32_t time2 = static_cast(b)->m_time; + + if (time1 > time2) { + return -1; + } + + return time1 < time2; +} + +// VERIFY: 5e47b873 auto +// OFFSET: 0x005326D0 +void BattlenetUI::SendScriptEvent(uint32_t event, const char* format, ...) { + va_list args; + va_start(args, format); + + if (CGGameUI::m_initialized) { + vFrameScript_SignalEvent(event, format, args); + } +} + +// VERIFY: 0ddbd7df auto +// OFFSET: 0x00532700 +int32_t BattlenetUI::FindFriendIndex(uint32_t presenceId) { + for (uint32_t i = 0; i < BattlenetUI::m_friends.m_count; i++) { + if (BattlenetUI::m_friends[i].m_presenceID == presenceId) { + return i; + } + } + + return -1; +} + +// VERIFY: f5ec582e auto +// OFFSET: 0x00532750 +BattlenetUIFriend* BattlenetUI::FindFriend(uint32_t presenceId) { + for (uint32_t i = 0; i < BattlenetUI::m_friends.m_count; i++) { + BattlenetUIFriend& entry = BattlenetUI::m_friends[i]; + + if (entry.m_presenceID == presenceId) { + return &entry; + } + } + + return nullptr; +} + +// VERIFY: 9eaa7f3c auto +// OFFSET: 0x00532800 +int32_t BattlenetUI::QSortDisambiguateFriendListCB(const void* a, const void* b) { + const BattlenetUIFriend* friend1 = static_cast(a); + const BattlenetUIFriend* friend2 = static_cast(b); + + int32_t result = SStrCmpUTF8I(friend1->m_givenName.m_data, friend2->m_givenName.m_data, 40); + + if (!result) { + result = SStrCmpUTF8I(friend1->m_sortSurname.m_data, friend2->m_sortSurname.m_data, 40); + + if (!result) { + return friend1->m_program - friend2->m_program; + } + } + + return result; +} + +// VERIFY: 98854ef8 auto +// OFFSET: 0x00532850 +void BattlenetUI::SortFriendInviteList() { + if (!BattlenetUI::m_friendInvites) { + SErrDisplayAppFatalMessage("", "", 0); + } + + BSN::Array& invites = BattlenetUI::m_friendInvites->m_data.m_invites; + + if (invites.m_count > 1) { + qsort(invites.m_data, invites.m_count, sizeof(Battlenet::Friends::FriendInvite), BattlenetUI::QSortFriendInviteListByTimeCB); + } +} + +// VERIFY: 96eab942 auto // OFFSET: 0x00532890 void BattlenetUI_LeaveRealm() { - BattlenetUI::m_friendListLoaded = 0; + BattlenetUI::m_friendListLoaded = false; BattlenetUI::m_friends.m_count = 0; - BattlenetUI::unk_BD1B00 = 0; + BattlenetUI::s_selfRealm = 0; +} + +// VERIFY: 1faee593 manual +// OFFSET: 0x005328B0 +void BattlenetUI::SetDisconnectedFromBattlenet(bool disconnected) { + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_DISCONNECTED, "%b", disconnected); + + for (AUTOCOMPLETE_NAMENODE* node = CGAutoCompleteName::m_list.Head(); node;) { + AUTOCOMPLETE_NAMENODE* next = CGAutoCompleteName::m_list.Next(node); + + if (node->m_presenceId) { + CGAutoCompleteName::m_list.DeleteNode(node); + } + + node = next; + } +} + +// VERIFY: 9dde2faf auto +// OFFSET: 0x005328D0 +void BattlenetUI::SetBattlenetConnectionRecovered() { + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_CONNECTED, nullptr); +} + +// VERIFY: ad919403 manual +// OFFSET: 0x00533D40 +bool BattlenetUI::AddToFriendList(uint32_t presenceId) { + if (BattlenetUI::FindFriendIndex(presenceId) >= 0) { + return true; + } + + BattlenetUIFriend* entry = BattlenetUI::m_friends.New(); + entry->m_presenceID = presenceId; + + Battlenet::Presence::FieldVal accountName = BattlenetAPI::GetPresenceValue(presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_ACCOUNT_NAME].m_field); + + if (accountName.m_tag == 18) { + SStrPrintf(entry->m_name.m_data, sizeof(entry->m_name.m_data), FrameScript_GetText("BATTLENET_NAME_FORMAT", -1, GENDER_NOT_APPLICABLE), entry->m_givenName.m_data, entry->m_surname.m_data); + entry->m_givenName = accountName.m_accountName.m_givenName.m_data; + entry->m_surname = accountName.m_accountName.m_surname.m_data; + entry->m_sortSurname = accountName.m_accountName.m_surname.m_data; + } else { + entry->m_name = ""; + entry->m_givenName = ""; + entry->m_surname = ""; + entry->m_sortSurname = ""; + } + + Battlenet::Presence::FieldVal program = BattlenetAPI::GetPresenceValue(entry->m_presenceID, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_PROGRAM].m_field); + entry->m_program = program.m_tag != 5 ? 0 : program.m_fourCC.m_value; + + return true; +} + +// VERIFY: 1797aa8b auto +// OFFSET: 0x00533F10 +int32_t BattlenetUI::UpdateAutoComplete(uint32_t& presenceId, uint32_t flags, int32_t add, const char* name) { + if (BattlenetAPI::IsSelf(presenceId)) { + return CGAutoCompleteName::RemoveFlags(presenceId, 0x7FFFFFFF); + } + + const char* displayName = name; + + if (BattlenetAPI::HasRIDFriendship(presenceId) && !BattlenetAPI::IsRIDFriend(presenceId)) { + presenceId = BattlenetAPI::GetAccountPresenceId(presenceId); + BattlenetUIFriend* entry = BattlenetUI::FindFriend(presenceId); + + if (entry) { + displayName = entry->m_name.m_data; + } + } + + int32_t result = CGAutoCompleteName::AddFlags(presenceId, flags, add, displayName); + + if (displayName && *displayName) { + return CGAutoCompleteName::SetName(presenceId, displayName, true); + } + + return result; +} + +// VERIFY: 4e033cce auto +// OFFSET: 0x00533FA0 +uint32_t BattlenetUI::GetSelfRealmID() { + if (!BattlenetUI::s_selfRealm) { + Battlenet::Presence::FieldVal toon = BattlenetAPI::GetPresenceValue(BattlenetAPI::GetPresenceIDForCurrentToon(), BattlenetUI::s_presenceCallbacks[BN_PRESENCE_TOON_NAME].m_field); + + if (toon.m_tag == 17) { + BattlenetUI::s_selfRealm = toon.m_toonName.m_realm; + return BattlenetUI::s_selfRealm; + } + } + + return BattlenetUI::s_selfRealm; +} + +// VERIFY: 4a0688b2 manual +// OFFSET: 0x00533FF0 +int32_t BattlenetUI::QSortFriendListCB(const void* a, const void* b) { + const BattlenetUIFriend* friend1 = static_cast(a); + const BattlenetUIFriend* friend2 = static_cast(b); + + Battlenet::Presence::FieldVal online1 = BattlenetAPI::GetPresenceValue(friend1->m_presenceID, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_ONLINE].m_field); + Battlenet::Presence::FieldVal online2 = BattlenetAPI::GetPresenceValue(friend2->m_presenceID, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_ONLINE].m_field); + + bool isOnline1 = false; + bool isOnline2 = false; + + if (online1.m_tag == 1) { + isOnline1 = online1.m_bool != 0; + } + + if (online2.m_tag == 1) { + isOnline2 = online2.m_bool != 0; + } + + if (isOnline1) { + if (!isOnline2) { + return -1; + } + } else if (isOnline2) { + return 1; + } + + return SStrCmpUTF8I(friend1->m_name.m_data, friend2->m_name.m_data, 72); +} + +// VERIFY: bea02848 manual +// OFFSET: 0x00534090 +void BattlenetUI::DisambiguateFriendList() { + if (BattlenetUI::m_friends.m_count > 1) { + qsort(BattlenetUI::m_friends.m_data, BattlenetUI::m_friends.m_count, sizeof(BattlenetUIFriend), BattlenetUI::QSortDisambiguateFriendListCB); + } + + uint32_t duplicates = 0; + + for (uint32_t i = 0; i < BattlenetUI::m_friends.m_count; i++) { + if (i != BattlenetUI::m_friends.m_count - 1 + && !SStrCmpUTF8I(BattlenetUI::m_friends[i].m_givenName.m_data, BattlenetUI::m_friends[i + 1].m_givenName.m_data, 40) + && !SStrCmpUTF8I(BattlenetUI::m_friends[i].m_sortSurname.m_data, BattlenetUI::m_friends[i + 1].m_sortSurname.m_data, 40)) { + if (++duplicates == 1) { + BattlenetUI::m_friends[i].m_surname = BattlenetUI::m_friends[i].m_sortSurname; + BattlenetUI::m_friends[i].m_surname += " 1"; + } + + char suffix[16]; + SStrPrintf(suffix, sizeof(suffix), " %d", duplicates + 1); + BattlenetUI::m_friends[i + 1].m_surname = BattlenetUI::m_friends[i + 1].m_sortSurname; + BattlenetUI::m_friends[i + 1].m_surname += suffix; + } else { + if (!duplicates) { + BattlenetUI::m_friends[i].m_surname = BattlenetUI::m_friends[i].m_sortSurname; + } + + duplicates = 0; + } + + BattlenetUIFriend& entry = BattlenetUI::m_friends[i]; + SStrPrintf(entry.m_name.m_data, sizeof(entry.m_name.m_data), FrameScript_GetText("BATTLENET_NAME_FORMAT", -1, GENDER_NOT_APPLICABLE), entry.m_givenName.m_data, entry.m_surname.m_data); + } } // VERIFY: f8478297 auto @@ -31,7 +478,1490 @@ bool BattlenetUI_IsAvailable() { return login && login->GetLoginServerType() == 1 && !login->IsTrialAccount() && BattlenetAPI::IsRIDEnabled() && static_cast(login)->IsConnected(); } -// VERIFY: ac1af170 auto +// VERIFY: 9732c054 manual +// OFFSET: 0x00534320 +void BattlenetUI::Uninit() { + BattlenetUI::s_initialized = false; + + for (uint32_t i = 0; i < 26; i++) { + BattlenetAPI::UnregisterEvent(BattlenetUI::s_eventCallbacks[i].m_handle); + BattlenetUI::s_eventCallbacks[i].m_handle = 0; + } + + for (uint32_t i = 0; i < NUM_BN_PRESENCE_FIELDS; i++) { + BattlenetAPI::UnregisterPresenceUpdateCallback(BattlenetUI::s_presenceCallbacks[i].m_handle); + BattlenetUI::s_presenceCallbacks[i].m_handle = 0; + } + + if (BattlenetUI::s_inviteToConversationCB) { + BattlenetUI::s_inviteToConversationCB->DecRef(); + BattlenetUI::s_inviteToConversationCB = nullptr; + } + + if (BattlenetUI::s_createConversationCB) { + BattlenetUI::s_createConversationCB->DecRef(); + BattlenetUI::s_createConversationCB = nullptr; + } + + if (BattlenetUI::s_friendsOfFriendCB) { + BattlenetUI::s_friendsOfFriendCB->DecRef(); + BattlenetUI::s_friendsOfFriendCB = nullptr; + } + + if (BattlenetUI::m_friendInvites) { + BattlenetUI::m_friendInvites->m_data.m_invites.m_count = 0; + delete BattlenetUI::m_friendInvites; + BattlenetUI::m_friendInvites = nullptr; + } + + if (BattlenetUI::s_friendsOfFriend) { + BattlenetUI::s_friendsOfFriend->m_data.m_friends.m_count = 0; + delete BattlenetUI::s_friendsOfFriend; + BattlenetUI::s_friendsOfFriend = nullptr; + } +} + +// VERIFY: 64e9664d manual +// OFFSET: 0x005346F0 +int32_t BattlenetUI::BNGetFriendInfoHelper(lua_State* L, uint32_t index) { + if (index >= BattlenetUI::m_friends.m_count) { + return 0; + } + + uint32_t presenceId = BattlenetUI::m_friends.m_data[index].m_presenceID; + lua_pushnumber(L, presenceId); + + Battlenet::Presence::FieldVal toon = BattlenetAPI::GetPresenceValue(presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_TOON_NAME].m_field); + Battlenet::Presence::FieldVal online = BattlenetAPI::GetPresenceValue(presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_ONLINE].m_field); + Battlenet::Presence::FieldVal lastOnline = BattlenetAPI::GetPresenceValue(presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_LAST_ONLINE].m_field); + Battlenet::Presence::FieldVal afk = BattlenetAPI::GetPresenceValue(presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_AFK].m_field); + Battlenet::Presence::FieldVal dnd = BattlenetAPI::GetPresenceValue(presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_DND].m_field); + Battlenet::Presence::FieldVal broadcast = BattlenetAPI::GetPresenceValue(presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_BROADCAST].m_field); + Battlenet::Presence::FieldVal note = BattlenetAPI::GetPresenceValue(presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_NOTE].m_field); + + lua_pushstring(L, BattlenetUI::m_friends[index].m_givenName.m_data); + lua_pushstring(L, BattlenetUI::m_friends[index].m_surname.m_data); + + if (toon.m_tag == 17) { + uint32_t toonId = BattlenetAPI::GetPresenceIDForToon(&toon.m_toonName); + const char* toonName = BattlenetAPI::GetToonNameForPresenceId(presenceId, false); + + if (!toonName) { + toonName = toon.Get<17, Battlenet::Toon::FullName>().m_name.m_data; + } + + lua_pushstring(L, toonName); + lua_pushnumber(L, toonId); + + BSN::FourCC program = toon.Get<17, Battlenet::Toon::FullName>().m_program; + program.ToString(BattlenetUI::s_programString, sizeof(BattlenetUI::s_programString)); + lua_pushstring(L, BattlenetUI::s_programString); + } else { + lua_pushnil(L); + lua_pushnil(L); + lua_pushnil(L); + } + + bool isOnline = false; + + if (online.m_tag == 1) { + isOnline = online.m_bool != 0; + } + + lua_pushboolean(L, isOnline); + + uint32_t lastOnlineTime = 0; + + if (lastOnline.m_tag == 6) { + lastOnlineTime = lastOnline.m_int; + } + + lua_pushnumber(L, lastOnlineTime); + + uint8_t isAFK = 0; + + if (afk.m_tag == 11) { + isAFK = afk.m_bool; + } + + lua_pushboolean(L, isAFK); + + uint8_t isDND = 0; + + if (dnd.m_tag == 11) { + isDND = dnd.m_bool; + } + + lua_pushboolean(L, isDND); + + if (broadcast.m_tag == 13) { + lua_pushstring(L, broadcast.m_string.m_data); + } else { + lua_pushnil(L); + } + + if (note.m_tag == 13) { + lua_pushstring(L, note.m_string.m_data); + } else { + lua_pushnil(L); + } + + lua_pushboolean(L, BattlenetAPI::IsRIDFriend(presenceId)); + + afk = BattlenetAPI::GetPresenceValue(presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_BROADCAST_TIME].m_field); + lua_pushnumber(L, afk.m_tag == 6 ? afk.m_int : 0.0); + + return 14; +} + +// VERIFY: 51d722d8 manual +// OFFSET: 0x00534B60 +int32_t BattlenetUI::BNGetToonInfoHelper(lua_State* L, uint32_t presenceId) { + lua_pushboolean(L, BattlenetAPI::GetFocusedToon(BattlenetAPI::GetAccountPresenceId(presenceId)) == presenceId); + + Battlenet::Presence::FieldVal toon = BattlenetAPI::GetPresenceValue(presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_TOON_NAME].m_field); + + if (toon.m_tag == 17) { + const char* toonName = BattlenetAPI::GetToonNameForPresenceId(presenceId, false); + + if (!toonName) { + toonName = toon.Get<17, Battlenet::Toon::FullName>().m_name.m_data; + } + + lua_pushstring(L, toonName); + + BSN::FourCC program = toon.Get<17, Battlenet::Toon::FullName>().m_program; + program.ToString(BattlenetUI::s_programString, sizeof(BattlenetUI::s_programString)); + lua_pushstring(L, BattlenetUI::s_programString); + } else { + lua_pushstring(L, ""); + lua_pushstring(L, ""); + } + + Battlenet::Presence::FieldVal realm = BattlenetAPI::GetPresenceValue(presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_REALM_NAME].m_field); + lua_pushstring(L, realm.m_tag == 13 ? realm.m_string.m_data : ""); + + Battlenet::Presence::FieldVal value = BattlenetAPI::GetPresenceValue(presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_FACTION].m_field); + lua_pushnumber(L, value.m_tag == 1 ? value.m_bool : -1.0); + + Battlenet::Presence::FieldVal race = BattlenetAPI::GetPresenceValue(presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_RACE].m_field); + lua_pushstring(L, race.m_tag == 13 ? race.m_string.m_data : ""); + + Battlenet::Presence::FieldVal classValue = BattlenetAPI::GetPresenceValue(presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_CLASS].m_field); + lua_pushstring(L, classValue.m_tag == 13 ? classValue.m_string.m_data : ""); + + Battlenet::Presence::FieldVal guild = BattlenetAPI::GetPresenceValue(presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_GUILD].m_field); + lua_pushstring(L, guild.m_tag == 13 ? guild.m_string.m_data : ""); + + Battlenet::Presence::FieldVal area = BattlenetAPI::GetPresenceValue(presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_AREA].m_field); + lua_pushstring(L, area.m_tag == 13 ? area.m_string.m_data : ""); + + value = BattlenetAPI::GetPresenceValue(presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_LEVEL].m_field); + + if (value.m_tag == 1) { + char level[8]; + SStrPrintf(level, sizeof(level), "%u", value.m_bool); + lua_pushstring(L, level); + } else { + lua_pushstring(L, ""); + } + + Battlenet::Presence::FieldVal gameText = BattlenetAPI::GetPresenceValue(presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_GAME_TEXT].m_field); + lua_pushstring(L, gameText.m_tag == 13 ? gameText.m_string.m_data : ""); + + Battlenet::Presence::FieldVal broadcast = BattlenetAPI::GetPresenceValue(presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_BROADCAST].m_field); + lua_pushstring(L, broadcast.m_tag == 13 ? broadcast.m_string.m_data : ""); + + value = BattlenetAPI::GetPresenceValue(presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_BROADCAST_TIME].m_field); + lua_pushnumber(L, value.m_tag == 6 ? value.m_int : 0.0); + + value = BattlenetAPI::GetPresenceValue(presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_ONLINE].m_field); + + bool isOnline = false; + + if (value.m_tag == 1) { + isOnline = value.m_bool != 0; + } + + lua_pushboolean(L, isOnline); + + return 14; +} + +// VERIFY: eb18a89b auto +// OFFSET: 0x00537B90 +void BattlenetUI::SelfToonOnlineCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + uint32_t presenceId = static_cast(args[0].ToUInt64()); + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_SELF_ONLINE, "%u", presenceId); + DebugLog("BNUI Self Toon Online, ID %u", presenceId); +} + +// VERIFY: 8aafec95 auto +// OFFSET: 0x00537C00 +void BattlenetUI::SelfToonOfflineCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_SELF_OFFLINE, nullptr); + DebugLog("BNUI: Self Toon Offline"); +} + +// VERIFY: 03c80fe7 auto +// OFFSET: 0x00537C60 +const char* BattlenetUI::GetNameForPresenceIdHelper(uint32_t presenceId) { + uint32_t accountId = presenceId; + + if (BattlenetAPI::HasRIDFriendship(presenceId)) { + if (!BattlenetAPI::IsRIDFriend(presenceId)) { + accountId = BattlenetAPI::GetAccountPresenceId(presenceId); + } + + BattlenetUIFriend* entry = BattlenetUI::FindFriend(accountId); + + if (entry) { + return entry->m_name.m_data; + } + + return BattlenetAPI::GetNameForPresenceId(accountId, false); + } + + if (BattlenetAPI::IsSelf(presenceId)) { + return BattlenetAPI::GetNameForPresenceId(presenceId, false); + } + + uint32_t realm = BattlenetUI::GetSelfRealmID(); + + if (!realm) { + return BattlenetAPI::GetNameForPresenceId(presenceId, false); + } + + Battlenet::Presence::FieldVal toon = BattlenetAPI::GetPresenceValue(presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_TOON_NAME].m_field); + + if (toon.m_tag != 17 || (realm == toon.m_toonName.m_realm && toon.m_toonName.m_program.m_value == Battlenet::Program::WOW.m_value)) { + return BattlenetAPI::GetNameForPresenceId(presenceId, false); + } + + SStrPrintf(BattlenetUI::s_displayName, sizeof(BattlenetUI::s_displayName), "%s*", BattlenetAPI::GetNameForPresenceId(presenceId, false)); + return BattlenetUI::s_displayName; +} + +// VERIFY: e675c286 manual +// OFFSET: 0x00537D40 +void BattlenetUI::FriendInviteSentCB::Call(int32_t argc, const GeneralFunction::Arg* args) const { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + UIErrors error = ERR_BN_FRIEND_REQUEST_SENT; + uint16_t result = static_cast(args[0].ToUInt64()); + + if (result == 604) { + error = ERR_BN_FRIEND_ALREADY; + } else if (result == 617) { + error = ERR_BN_FRIEND_SELF; + } else if (result == 623) { + error = ERR_BN_FRIEND_BLOCKED; + } + + CGGameUI::DisplayError(error); + + DebugLog("BNUI: Friend Invite Send Result: %s", result ? "failure" : "success"); +} + +// VERIFY: 0926afe1 auto +// OFFSET: 0x005EEB70 +void BattlenetUI::FriendInviteSentCB::Destroy() const { +} + +// VERIFY: 4c0454a7 auto +// OFFSET: 0x005EEB70 +void BattlenetUI::IgnoredFieldCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { +} + +// VERIFY: 8eee8765 auto +// OFFSET: 0x00537DF0 +void BattlenetUI::FriendInviteListInitializedCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + if (!BattlenetUI::s_initialized || !BattlenetUI::m_friendInvites) { + SErrDisplayAppFatalMessage("", "", 0); + } + + BattlenetUI::m_friendInvites->m_data.m_invites.m_count = 0; + BattlenetUI::m_friendInvites->WalkAndGet(args[0].ToObject()); + BattlenetUI::SortFriendInviteList(); + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_FRIEND_INVITE_LIST_INITIALIZED, "%d", BattlenetUI::m_friendInvites->m_data.m_invites.m_count); + + if (s_cvShowToastFriendRequest && s_cvShowToastFriendRequest->m_intValue) { + CGChat::AddChatMessage("FRIEND_PENDING", CHAT_MSG_BN_INLINE_TOAST_ALERT, nullptr, 0, nullptr, nullptr, nullptr, WOWGUID(), 0, WOWGUID(), 0, false, nullptr); + } + + DebugLog("BNUI: Friend Invite List Initialized"); +} + +// VERIFY: 1fc21d99 auto +// OFFSET: 0x00537F00 +void BattlenetUI::FriendInviteAddedCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + if (!BattlenetUI::s_initialized || !BattlenetUI::m_friendInvites) { + SErrDisplayAppFatalMessage("", "", 0); + } + + uint32_t presenceId = static_cast(args[0].ToUInt64()); + + if (!presenceId) { + SErrDisplayAppFatalMessage("", "", 0); + } + + Battlenet::Friends::FriendInvite invite = BattlenetAPI::GetFriendInvite(presenceId); + + if (!invite.m_presenceId) { + SErrDisplayAppFatalMessage("", "", 0); + } + + *BattlenetUI::m_friendInvites->m_data.m_invites.New() = invite; + BattlenetUI::SortFriendInviteList(); + + Battlenet::Presence::FieldVal onlineTime = BattlenetAPI::GetPresenceValue(BattlenetAPI::GetPresenceIDForCurrentToon(), BattlenetUI::s_presenceCallbacks[BN_PRESENCE_ONLINE_TIME].m_field); + + if (onlineTime.m_tag != 6 || invite.m_time < onlineTime.Get<6, int32_t>()) { + return; + } + + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_FRIEND_INVITE_ADDED, "%u", presenceId); + + if (s_cvShowToastFriendRequest && s_cvShowToastFriendRequest->m_intValue) { + CGChat::AddChatMessage("FRIEND_REQUEST", CHAT_MSG_BN_INLINE_TOAST_ALERT, nullptr, 0, nullptr, nullptr, nullptr, WOWGUID(), 0, WOWGUID(), 0, false, nullptr); + } + + DebugLog("BNUI: Friend Invite Added. ID %u", presenceId); +} + +// VERIFY: 7069b0c1 manual +// OFFSET: 0x00538060 +void BattlenetUI::FriendInviteRemovedCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + uint32_t presenceId; + + if (!BattlenetUI::s_initialized || !BattlenetUI::m_friendInvites || (presenceId = static_cast(args[0].ToUInt64())) == 0) { + SErrDisplayAppFatalMessage("", "", 0); + } + + BSN::Array& invites = BattlenetUI::m_friendInvites->m_data.m_invites; + int32_t index = 0; + + for (; static_cast(index) < invites.m_count; index++) { + if (invites[index].m_presenceId == presenceId) { + if (index >= 0) { + invites.Remove(index); + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_FRIEND_INVITE_REMOVED, "%d%u", index, presenceId); + } + + break; + } + } + + DebugLog("BNUI: Friend Invite Removed. index %d, ID %u", index, presenceId); +} + +// VERIFY: 6a08abf9 auto +// OFFSET: 0x00538160 +void BattlenetUI::FriendInfoChangedCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + if (!BattlenetUI::s_initialized) { + SErrDisplayAppFatalMessage("", "", 0); + } + + BSN::BSNEncodedObject update(args[0].ToObject()); + const char* name = BattlenetUI::GetNameForPresenceIdHelper(update.m_data.m_presenceId); + + if (update.m_data.m_field == BattlenetUI::s_presenceCallbacks[BN_PRESENCE_ACCOUNT_NAME].m_field) { + if (!BattlenetAPI::HasRIDFriendship(update.m_data.m_presenceId) || BattlenetAPI::IsRIDFriend(update.m_data.m_presenceId)) { + CGAutoCompleteName::SetName(update.m_data.m_presenceId, name, true); + } else { + CGAutoCompleteName::RemoveFlags(update.m_data.m_presenceId, 0x7FFFFFFF); + } + } + + int32_t index = BattlenetUI::FindFriendIndex(update.m_data.m_presenceId); + + if (index >= 0) { + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_FRIEND_INFO_CHANGED, "%d", index + 1); + } +} + +// VERIFY: 3e8839d1 auto +// OFFSET: 0x00538290 +void BattlenetUI::FactionUpdateCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + BSN::BSNEncodedObject update(args[0].ToObject()); + + if (!BattlenetAPI::IsSelf(update.m_data.m_presenceId)) { + BattlenetUI::UpdateAutoComplete(update.m_data.m_presenceId, 0x20, 0, nullptr); + } +} + +// VERIFY: 63f6b0df auto +// OFFSET: 0x00538320 +void BattlenetUI::NewPresenceCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + if (!BattlenetUI::s_initialized) { + SErrDisplayAppFatalMessage("", "", 0); + } + + uint32_t presenceId = static_cast(args[0].ToUInt64()); + + if (!BattlenetUI::m_friendListLoaded) { + DebugLog("BNUI: New Presence ID %u before Friend List initialized.", presenceId); + return; + } + + Battlenet::Presence::FieldVal toon = BattlenetAPI::GetPresenceValue(presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_TOON_NAME].m_field); + + if (toon.m_tag == 17) { + if (BattlenetAPI::HasRIDFriendship(presenceId)) { + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_FRIEND_TOON_ONLINE, "%u", presenceId); + DebugLog("BNUI: >> TOON %s is now ONLINE. ID %u (new presence)", BattlenetUI::GetNameForPresenceIdHelper(presenceId), presenceId); + } else { + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_NEW_PRESENCE, "%u%s", presenceId, toon.m_toonName.m_name.m_data); + DebugLog("BNUI: New Presence ID %u, name %s", presenceId, toon.m_toonName.m_name.m_data); + } + } else { + const char* name = BattlenetUI::GetNameForPresenceIdHelper(presenceId); + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_NEW_PRESENCE, "%u%s", presenceId, name); + DebugLog("BNUI: New Non-Toon Presence ID %u, name %s", presenceId, name); + } +} + +// VERIFY: 9bb49d4e auto +// OFFSET: 0x00538460 +void BattlenetUI::ToonNameUpdateCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + if (!BattlenetUI::s_initialized) { + SErrDisplayAppFatalMessage("", "", 0); + } + + BSN::BSNEncodedObject update(args[0].ToObject()); + bool friendship = BattlenetAPI::HasRIDFriendship(update.m_data.m_presenceId); + + if (update.m_data.m_value.m_tag == 17) { + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_TOON_NAME_UPDATED, "%u%s%b", update.m_data.m_presenceId, update.m_data.m_value.m_toonName.m_name.m_data, friendship); + DebugLog("BNUI: Toon Name Updated, %s friend. ID %u, name %s", friendship ? "" : "non", update.m_data.m_presenceId, update.m_data.m_value.m_toonName.m_name.m_data); + } + + if (!BattlenetAPI::IsSelf(update.m_data.m_presenceId)) { + BattlenetUI::UpdateAutoComplete(update.m_data.m_presenceId, 0x20, 0, nullptr); + } +} + +// VERIFY: bf4a6401 auto +// OFFSET: 0x00538580 +void BattlenetUI::OnlineTimeChangedCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + if (!BattlenetUI::s_initialized) { + SErrDisplayAppFatalMessage("", "", 0); + } + + BSN::BSNEncodedObject update(args[0].ToObject()); + + if (BattlenetAPI::IsSelf(update.m_data.m_presenceId) || update.m_data.m_value.m_tag != 6) { + return; + } + + int32_t onlineTime = update.m_data.m_value.m_int; + bool ridFriend = BattlenetAPI::IsRIDFriend(update.m_data.m_presenceId); + bool cidFriend = BattlenetAPI::IsCIDFriend(update.m_data.m_presenceId); + + if (!ridFriend && !cidFriend) { + return; + } + + Battlenet::Presence::FieldVal selfTime = BattlenetAPI::GetPresenceValue(BattlenetAPI::GetPresenceIDForCurrentToon(), BattlenetUI::s_presenceCallbacks[BN_PRESENCE_ONLINE_TIME].m_field); + + if (selfTime.m_tag != 6) { + return; + } + + int32_t selfOnlineTime = selfTime.Get<6, int32_t>(); + + if (selfOnlineTime && onlineTime && onlineTime > selfOnlineTime) { + if (ridFriend) { + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_FRIEND_ACCOUNT_ONLINE, "%u", update.m_data.m_presenceId); + + if (s_cvShowToastOnline && s_cvShowToastOnline->m_intValue) { + ChatConversation conversation; + conversation.m_presenceID = update.m_data.m_presenceId; + conversation.m_inactive = 1; + CGChat::AddChatMessage("FRIEND_ONLINE", CHAT_MSG_BN_INLINE_TOAST_ALERT, BattlenetUI::GetNameForPresenceIdHelper(update.m_data.m_presenceId), 0, nullptr, nullptr, nullptr, WOWGUID(), 0, WOWGUID(), 0, false, &conversation); + } + + DebugLog("BNUI: >> ACCOUNT %s Online Time changed. ID %u", BattlenetUI::GetNameForPresenceIdHelper(update.m_data.m_presenceId), update.m_data.m_presenceId); + } else if (cidFriend) { + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_FRIEND_TOON_ONLINE, "%u", update.m_data.m_presenceId); + DebugLog("BNUI: >> TOON %s is now ONLINE. ID %u", BattlenetUI::GetNameForPresenceIdHelper(update.m_data.m_presenceId), update.m_data.m_presenceId); + } + } + + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_FRIEND_INFO_CHANGED, nullptr); +} + +// VERIFY: a04df2e0 auto +// OFFSET: 0x00538790 +void BattlenetUI::LastOnlineChangedCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + if (!BattlenetUI::s_initialized) { + SErrDisplayAppFatalMessage("", "", 0); + } + + BSN::BSNEncodedObject update(args[0].ToObject()); + + if (update.m_data.m_value.m_tag == 6) { + DebugLog("BNUI: Last Online for ID %u is now %d", update.m_data.m_presenceId, update.m_data.m_value.m_int); + } else { + DebugLog("BNUI: Last Online for ID %u changed", update.m_data.m_presenceId); + } +} + +// VERIFY: 6cd97fa7 manual +// OFFSET: 0x00538850 +void BattlenetUI::CustomMessageChangedCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + if (!BattlenetUI::s_initialized) { + SErrDisplayAppFatalMessage("", "", 0); + } + + BSN::BSNEncodedObject update(args[0].ToObject()); + uint32_t toonId = BattlenetAPI::GetPresenceIDForCurrentToon(); + + Battlenet::Presence::FieldVal value = BattlenetAPI::GetPresenceValue(toonId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_ONLINE_TIME].m_field); + int32_t onlineTime = 0; + + if (value.m_tag == 6) { + onlineTime = value.m_int; + } + + const char* message = update.m_data.m_value.m_tag == 13 ? update.m_data.m_value.m_string.m_data : ""; + int32_t broadcastTime = 0; + + value = BattlenetAPI::GetPresenceValue(update.m_data.m_presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_BROADCAST_TIME].m_field); + + if (value.m_tag == 6) { + broadcastTime = value.m_int; + } + + char text[512]; + + if (toonId != update.m_data.m_presenceId) { + if (BattlenetAPI::IsRIDFriend(update.m_data.m_presenceId)) { + if (!onlineTime || broadcastTime < onlineTime) { + return; + } + + Battlenet::Presence::FieldVal friendTime = BattlenetAPI::GetPresenceValue(update.m_data.m_presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_ONLINE_TIME].m_field); + + if (friendTime.m_tag == 6 && broadcastTime < friendTime.Get<6, int32_t>()) { + return; + } + + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_CUSTOM_MESSAGE_CHANGED, "%u", update.m_data.m_presenceId); + + if (s_cvShowToastBroadcast && s_cvShowToastBroadcast->m_intValue) { + FilterChatLinks(message, text, 509); + + ChatConversation conversation; + conversation.m_presenceID = update.m_data.m_presenceId; + conversation.m_inactive = 1; + CGChat::AddChatMessage(text, CHAT_MSG_BN_INLINE_TOAST_BROADCAST, BattlenetUI::GetNameForPresenceIdHelper(update.m_data.m_presenceId), 0, nullptr, nullptr, nullptr, WOWGUID(), 0, WOWGUID(), 0, false, &conversation); + } + } + + DebugLog("BNUI: Custom Message Changed"); + return; + } + + if (onlineTime && broadcastTime >= onlineTime) { + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_CUSTOM_MESSAGE_CHANGED, nullptr); + FilterChatLinks(message, text, 509); + CGChat::AddChatMessage(text, CHAT_MSG_BN_INLINE_TOAST_BROADCAST_INFORM, nullptr, 0, nullptr, nullptr, nullptr, WOWGUID(), 0, WOWGUID(), 0, false, nullptr); + } else { + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_CUSTOM_MESSAGE_LOADED, nullptr); + } +} + +// VERIFY: 4b72e85c manual +// OFFSET: 0x00538AB0 +void BattlenetUI::ChatWhisperSentCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + uint32_t presenceId = static_cast(args[0].ToUInt64()); + const char* message = args[1].ToString(); + + if (!message) { + message = ""; + } + + BattlenetUI::UpdateAutoComplete(presenceId, 0x30, 1, BattlenetUI::GetNameForPresenceIdHelper(presenceId)); + + Battlenet::Presence::FieldVal toon = BattlenetAPI::GetPresenceValue(presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_TOON_NAME].m_field); + const char* flags = nullptr; + Battlenet::Presence::FieldVal afk = BattlenetAPI::GetPresenceValue(presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_AFK].m_field); + Battlenet::Presence::FieldVal dnd = BattlenetAPI::GetPresenceValue(presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_DND].m_field); + + if (afk.m_tag == 11 && afk.m_bool) { + flags = "AFK"; + } else if (dnd.m_tag == 11 && dnd.m_bool) { + flags = "DND"; + } + + char text[1024]; + FilterChatLinks(message, text, 1021); + + ChatConversation conversation; + conversation.m_presenceID = presenceId; + conversation.m_inactive = 1; + CGChat::AddChatMessage(text, CHAT_MSG_BN_WHISPER_INFORM, BattlenetUI::GetNameForPresenceIdHelper(presenceId), 0, nullptr, nullptr, flags, WOWGUID(), 0, WOWGUID(), 0, false, &conversation); + + DebugLog("BNUI: Whisper Sent to %s, ID %u. %s", toon.m_tag == 17 ? toon.m_toonName.m_name.m_data : "unknown", presenceId, message); +} + +// VERIFY: 869184a5 manual +// OFFSET: 0x00538C40 +void BattlenetUI::ChatWhisperReceivedCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + uint32_t presenceId = static_cast(args[0].ToUInt64()); + const char* message = args[1].ToString(); + + if (!message) { + message = ""; + } + + BattlenetUI::UpdateAutoComplete(presenceId, 0x30, 1, BattlenetUI::GetNameForPresenceIdHelper(presenceId)); + + Battlenet::Presence::FieldVal toon = BattlenetAPI::GetPresenceValue(presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_TOON_NAME].m_field); + const char* flags = nullptr; + Battlenet::Presence::FieldVal afk = BattlenetAPI::GetPresenceValue(presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_AFK].m_field); + Battlenet::Presence::FieldVal dnd = BattlenetAPI::GetPresenceValue(presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_DND].m_field); + + if (afk.m_tag == 11 && afk.m_bool) { + flags = "AFK"; + } else if (dnd.m_tag == 11 && dnd.m_bool) { + flags = "DND"; + } + + char text[1024]; + FilterChatLinks(message, text, 1021); + + ChatConversation conversation; + conversation.m_presenceID = presenceId; + conversation.m_inactive = 1; + CGChat::AddChatMessage(text, CHAT_MSG_BN_WHISPER, BattlenetUI::GetNameForPresenceIdHelper(presenceId), 0, nullptr, nullptr, flags, WOWGUID(), 0, WOWGUID(), 0, false, &conversation); + + DebugLog("BNUI: Whisper Received From %s, ID %u. %s", toon.m_tag == 17 ? toon.m_toonName.m_name.m_data : "unknown", presenceId, message); +} + +// VERIFY: 3c7d99a1 manual +// OFFSET: 0x00538DD0 +void BattlenetUI::ChatChannelJoinedCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + uint8_t channel = static_cast(args[0].ToUInt64()); + int32_t type = static_cast(args[1].ToInt64()); + + if (channel >= 6) { + SErrDisplayAppFatalMessage("", "", 0); + } + + Battlenet::Chat::MemberList members = BattlenetAPI::GetChatMemberList(channel); + uint32_t count = members.m_members.m_count; + + for (uint32_t i = 0; i < count; i++) { + uint32_t presenceId = members.m_members.m_data[i]; + BattlenetUI::UpdateAutoComplete(presenceId, 0x30, 1, BattlenetUI::GetNameForPresenceIdHelper(presenceId)); + } + + if (type == 2) { + ChatConversation conversation; + conversation.m_presenceID = BattlenetAPI::GetPresenceIDForCurrentAccount(); + conversation.m_index = channel; + conversation.m_inactive = 0; + CGChat::AddChatMessage("YOU_JOINED_CONVERSATION", CHAT_MSG_BN_CONVERSATION_NOTICE, BattlenetUI::GetNameForPresenceIdHelper(BattlenetAPI::GetPresenceIDForCurrentAccount()), 0, nullptr, nullptr, nullptr, WOWGUID(), 0, WOWGUID(), 0, false, &conversation); + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_CHAT_CHANNEL_JOINED, "%d", channel + 1); + + if (s_cvShowToastConversation && s_cvShowToastConversation->m_intValue) { + uint32_t accountId = BattlenetAPI::GetPresenceIDForCurrentAccount(); + uint32_t toonId = BattlenetAPI::GetPresenceIDForCurrentToon(); + const char* delimiter = FrameScript_GetText("PLAYER_LIST_DELIMITER", -1, GENDER_NOT_APPLICABLE); + char text[3000]; + bool first = true; + + for (uint32_t i = 0; i < count; i++) { + uint32_t presenceId = members.m_members.m_data[i]; + + if (presenceId != accountId && presenceId != toonId) { + if (first) { + SStrCopyUTF8(text, BattlenetUI::GetNameForPresenceIdHelper(presenceId), sizeof(text), sizeof(text)); + first = false; + } else { + SStrPrintf(text, sizeof(text), "%s%s%s", text, delimiter, BattlenetUI::GetNameForPresenceIdHelper(presenceId)); + } + } + } + + CGChat::AddChatMessage(text, CHAT_MSG_BN_INLINE_TOAST_CONVERSATION, BattlenetUI::GetNameForPresenceIdHelper(BattlenetAPI::GetPresenceIDForCurrentAccount()), 0, nullptr, nullptr, nullptr, WOWGUID(), 0, WOWGUID(), 0, false, &conversation); + } + } + + DebugLog("BNUI: Chat Channel Joined. channel %d", channel + 1); +} + +// VERIFY: a5450f66 auto +// OFFSET: 0x00539020 +void BattlenetUI::ChatChannelLeftCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + uint8_t channel = static_cast(args[0].ToUInt64()); + + if (channel >= 6) { + SErrDisplayAppFatalMessage("", "", 0); + } + + ChatConversation conversation; + conversation.m_presenceID = BattlenetAPI::GetPresenceIDForCurrentAccount(); + conversation.m_index = channel; + conversation.m_inactive = 0; + CGChat::AddChatMessage("YOU_LEFT_CONVERSATION", CHAT_MSG_BN_CONVERSATION_NOTICE, BattlenetUI::GetNameForPresenceIdHelper(BattlenetAPI::GetPresenceIDForCurrentAccount()), 0, nullptr, nullptr, nullptr, WOWGUID(), 0, WOWGUID(), 0, false, &conversation); + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_CHAT_CHANNEL_LEFT, "%d", channel + 1); + DebugLog("BNUI: Chat Channel Left. Channel %d", channel + 1); +} + +// VERIFY: 169ab59f auto +// OFFSET: 0x00539100 +void BattlenetUI::ChatChannelClosedCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + uint8_t channel = static_cast(args[0].ToUInt64()); + uint32_t presenceId = static_cast(args[1].ToUInt64()); + + if (channel >= 6) { + SErrDisplayAppFatalMessage("", "", 0); + } + + ChatConversation conversation; + conversation.m_index = channel; + conversation.m_presenceID = presenceId; + conversation.m_inactive = 0; + CGChat::AddChatMessage("CONVERSATION_CONVERTED_TO_WHISPER", CHAT_MSG_BN_CONVERSATION_NOTICE, BattlenetUI::GetNameForPresenceIdHelper(presenceId), 0, nullptr, nullptr, nullptr, WOWGUID(), 0, WOWGUID(), 0, false, &conversation); + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_CHAT_CHANNEL_CLOSED, "%d%s", channel + 1, BattlenetUI::GetNameForPresenceIdHelper(presenceId)); + DebugLog("BNUI: Chat Channel Closed channel, index %d, remaining ID %u", channel + 1, presenceId); +} + +// VERIFY: bbcce2b9 manual +// OFFSET: 0x005391F0 +void BattlenetUI::ChatChannelMessageReceivedCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + uint8_t channel = static_cast(args[0].ToUInt64()); + uint32_t presenceId = static_cast(args[1].ToUInt64()); + const char* message = args[2].ToString(); + + if (!message) { + message = ""; + } + + if (channel >= 6) { + SErrDisplayAppFatalMessage("", "", 0); + } + + char text[1024]; + FilterChatLinks(message, text, 1021); + BattlenetUI::UpdateAutoComplete(presenceId, 0x30, 1, BattlenetUI::GetNameForPresenceIdHelper(presenceId)); + + ChatConversation conversation; + conversation.m_index = channel; + conversation.m_presenceID = presenceId; + conversation.m_inactive = 0; + CGChat::AddChatMessage(text, CHAT_MSG_BN_CONVERSATION, BattlenetUI::GetNameForPresenceIdHelper(presenceId), 0, nullptr, nullptr, nullptr, WOWGUID(), 0, WOWGUID(), 0, false, &conversation); + DebugLog("BNUI: Chat Channel Message Recieved. channel %d, ID %u, msg: %s", channel + 1, presenceId, message); +} + +// VERIFY: 808d4862 auto +// OFFSET: 0x00539320 +void BattlenetUI::ChatChannelMessageBlockedCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + uint8_t channel = static_cast(args[0].ToUInt64()); + uint32_t presenceId = static_cast(args[1].ToUInt64()); + + if (channel >= 6) { + SErrDisplayAppFatalMessage("", "", 0); + } + + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_CHAT_CHANNEL_MESSAGE_BLOCKED, "%d%u", channel + 1, presenceId); + DebugLog("BNUI: Chat Channel Message Blocked. channel %d, id %u", channel + 1, presenceId); +} + +// VERIFY: c2ba753f auto +// OFFSET: 0x005393C0 +void BattlenetUI::ChatChannelMemberJoinedCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + uint8_t channel = static_cast(args[0].ToUInt64()); + uint32_t presenceId = static_cast(args[1].ToUInt64()); + + if (channel >= 6) { + SErrDisplayAppFatalMessage("", "", 0); + } + + BattlenetUI::UpdateAutoComplete(presenceId, 0x30, 1, BattlenetUI::GetNameForPresenceIdHelper(presenceId)); + + ChatConversation conversation; + conversation.m_index = channel; + conversation.m_presenceID = presenceId; + conversation.m_inactive = 0; + CGChat::AddChatMessage("MEMBER_JOINED", CHAT_MSG_BN_CONVERSATION_NOTICE, BattlenetUI::GetNameForPresenceIdHelper(presenceId), 0, nullptr, nullptr, nullptr, WOWGUID(), 0, WOWGUID(), 0, false, &conversation); + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_CHAT_CHANNEL_MEMBER_JOINED, "%d%u", channel + 1, presenceId); + DebugLog("BNUI: Chat Channel Member Joined. channel %d, id %u", channel + 1, presenceId); +} + +// VERIFY: 6d58d1f8 auto +// OFFSET: 0x005394D0 +void BattlenetUI::ChatChannelMemberLeftCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + uint8_t channel = static_cast(args[0].ToUInt64()); + uint32_t presenceId = static_cast(args[1].ToUInt64()); + + if (channel >= 6) { + SErrDisplayAppFatalMessage("", "", 0); + } + + ChatConversation conversation; + conversation.m_index = channel; + conversation.m_presenceID = presenceId; + conversation.m_inactive = 0; + CGChat::AddChatMessage("MEMBER_LEFT", CHAT_MSG_BN_CONVERSATION_NOTICE, BattlenetUI::GetNameForPresenceIdHelper(presenceId), 0, nullptr, nullptr, nullptr, WOWGUID(), 0, WOWGUID(), 0, false, &conversation); + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_CHAT_CHANNEL_MEMBER_LEFT, "%d%u", channel + 1, presenceId); + DebugLog("BNUI: Chat Channel Member Left. channel %d, id %u", channel + 1, presenceId); +} + +// VERIFY: 6952ac52 auto +// OFFSET: 0x005395C0 +void BattlenetUI::ChatChannelMemberUpdatedCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + uint8_t channel = static_cast(args[0].ToUInt64()); + uint32_t presenceId = static_cast(args[1].ToUInt64()); + + if (channel >= 6) { + SErrDisplayAppFatalMessage("", "", 0); + } + + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_CHAT_CHANNEL_MEMBER_UPDATED, "%d%u", channel + 1, presenceId); + DebugLog("BNUI: Chat Channel Member Updated. channel %d, id %u", channel + 1, presenceId); +} + +// VERIFY: 15d74ce1 auto +// OFFSET: 0x00539660 +void BattlenetUI::DisplayError(uint16_t error, uint32_t presenceId) { + if (!error) { + return; + } + + const char* format = BattlenetAPI::GetErrorString(error); + + if (!format) { + return; + } + + char text[1024]; + int32_t count = CountFormatStrings(format); + + if (count == 0) { + SStrCopyUTF8(text, format, sizeof(text), sizeof(text)); + } else if (count == 1) { + const char* name = BattlenetUI::GetNameForPresenceIdHelper(presenceId); + + if (!name) { + name = FrameScript_GetText("UNKNOWNOBJECT", -1, GENDER_NOT_APPLICABLE); + } + + SStrPrintf(text, sizeof(text), format, name); + } else { + SStrPrintf(text, sizeof(text), FrameScript_GetText("INTERNAL_STRING_ERROR", -1, GENDER_NOT_APPLICABLE), error); + } + + CGChat::AddChatMessage(text, 0, nullptr, 0, nullptr, nullptr, nullptr, WOWGUID(), 0, WOWGUID(), 0, false, nullptr); + + if (error != 318) { + CGGameUI::AddErrorMessage(text, 0); + } +} + +// VERIFY: 74ed918e manual +// OFFSET: 0x00539770 +void BattlenetUI::FriendsOfFriendCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + if (!BattlenetUI::s_friendsOfFriend) { + SErrDisplayAppFatalMessage("", "", 0); + } + + uint16_t error = static_cast(args[0].ToUInt64()); + + if (error) { + BattlenetUI::DisplayError(error, 0); + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_REQUEST_FOF_FAILED, nullptr); + DebugLog("BNUI: FOF info request failed."); + } else { + BattlenetUI::s_friendsOfFriend->WalkAndGet(args[1].ToObject()); + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_REQUEST_FOF_SUCCEEDED, nullptr); + DebugLog("BNUI: Received FOF info for ID %u. %d friends in list", BattlenetUI::s_friendsOfFriend->m_data.m_presenceId, BattlenetUI::s_friendsOfFriend->m_data.m_friends.m_count); + } +} + +// VERIFY: 5ad292f1 auto +// OFFSET: 0x00539850 +void BattlenetUI::BlockListInitializedCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_BLOCK_LIST_UPDATED, nullptr); + DebugLog("BNUI: Block List Initialized"); +} + +// VERIFY: 40fe5192 auto +// OFFSET: 0x005398B0 +void BattlenetUI::BlockAddedCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + uint32_t presenceId = static_cast(args[0].ToUInt64()); + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_BLOCK_LIST_UPDATED, nullptr); + DebugLog("BNUI: Block Added for ID %u", presenceId); +} + +// VERIFY: ecddaef1 auto +// OFFSET: 0x00539910 +void BattlenetUI::BlockRemovedCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + uint32_t presenceId = static_cast(args[0].ToUInt64()); + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_BLOCK_LIST_UPDATED, nullptr); + DebugLog("BNUI: Block Removed for ID %u", presenceId); +} + +// VERIFY: 13cb927d auto +// OFFSET: 0x00539970 +void BattlenetUI::SystemMessageCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + const char* type = "unknown"; + uint32_t value = 0; + + switch (static_cast(args[0].ToUInt64())) { + case 3800: + type = "shutdown minutes"; + value = static_cast(args[1].ToUInt64()); + break; + + case 3801: + type = "shutdown seconds"; + value = static_cast(args[1].ToUInt64()); + break; + + case 3802: + type = "shutdown now"; + break; + } + + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_SYSTEM_MESSAGE, "%s%u", type, value); + DebugLog("BNUI: SYSTEM MESSAGE RECEIVED: %s %u", type, value); +} + +// VERIFY: 2598718e manual +// OFFSET: 0x00539A20 +void BattlenetUI::SettingChangedCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + if (!SStrCmpI(args[1].ToString(), "Chat.ProfanityFilterEnabled", STORM_MAX_STR)) { + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_MATURE_LANGUAGE_FILTER, "%b", args[2].ToBool() != 0); + } +} + +// VERIFY: 473b1361 manual +// OFFSET: 0x00539AD0 +void BattlenetUI::PopulateAutoComplete() { + uint32_t count = BattlenetUI::m_friends.m_count; + + for (uint32_t i = 0; i < count; i++) { + uint32_t presenceId = BattlenetUI::m_friends[i].m_presenceID; + + if (!presenceId) { + SErrDisplayAppFatalMessage("", "", 0); + } + + const char* name = BattlenetUI::GetNameForPresenceIdHelper(presenceId); + bool online = false; + Battlenet::Presence::FieldVal value = BattlenetAPI::GetPresenceValue(presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_ONLINE].m_field); + + if (value.m_tag == 1) { + online = value.m_bool != 0; + } + + BattlenetUI::UpdateAutoComplete(presenceId, (online ? 0x20 : 0) | 0x4, 0, name); + } + + for (uint8_t channel = 0; channel < 6; channel++) { + Battlenet::Chat::MemberList members = BattlenetAPI::GetChatMemberList(channel); + uint32_t memberCount = members.m_members.m_count; + + for (uint32_t i = 0; i < memberCount; i++) { + uint32_t presenceId = members.m_members.m_data[i]; + BattlenetUI::UpdateAutoComplete(presenceId, 0x30, 1, BattlenetUI::GetNameForPresenceIdHelper(presenceId)); + } + } +} + +// VERIFY: 63ed8bee manual +// OFFSET: 0x0053A750 +void BattlenetUI::FriendListInitializedCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + BSN::BSNEncodedObject friendList; + friendList.WalkAndGet(args[0].ToObject()); + + BattlenetUI::m_friends.m_count = 0; + + for (uint32_t i = 0; i < friendList.m_data.m_friends.m_count; i++) { + BattlenetUI::AddToFriendList(friendList.m_data.m_friends.m_data[i]); + } + + BattlenetUI::DisambiguateFriendList(); + + if (BattlenetUI::m_friends.m_count > 1) { + qsort(BattlenetUI::m_friends.m_data, BattlenetUI::m_friends.m_count, sizeof(BattlenetUIFriend), BattlenetUI::QSortFriendListCB); + } + + BattlenetUI::m_friendListLoaded = true; + + for (uint32_t i = 0; i < BattlenetUI::m_friends.m_count; i++) { + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_FRIEND_TOON_ONLINE, "%u", BattlenetUI::m_friends.m_data[i].m_presenceID); + DebugLog("BNUI: >> TOON %s is now ONLINE. ID %u (friend list initialized)", BattlenetUI::GetNameForPresenceIdHelper(BattlenetUI::m_friends[i].m_presenceID)); + } + + BattlenetUI::PopulateAutoComplete(); + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_FRIEND_LIST_SIZE_CHANGED, nullptr); + DebugLog("BNUI: Friend List Initialized. Num friends = %d", BattlenetUI::m_friends.m_count); +} + +// VERIFY: 07dfe513 auto +// OFFSET: 0x0053A940 +void BattlenetUI::FriendAddedCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + uint32_t presenceId; + + if (!BattlenetUI::s_initialized || (presenceId = static_cast(args[0].ToUInt64())) == 0) { + SErrDisplayAppFatalMessage("", "", 0); + } + + if (BattlenetAPI::IsRIDFriend(presenceId)) { + BattlenetUI::AddToFriendList(presenceId); + BattlenetUI::DisambiguateFriendList(); + + if (BattlenetUI::m_friends.m_count > 1) { + qsort(BattlenetUI::m_friends.m_data, BattlenetUI::m_friends.m_count, sizeof(BattlenetUIFriend), BattlenetUI::QSortFriendListCB); + } + + BattlenetUI::PopulateAutoComplete(); + DebugLog("BNUI: Friend Added. ID = %u", presenceId); + } else { + DebugLog("BNUI: Friend Add, %u not friend", presenceId); + } + + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_FRIEND_LIST_SIZE_CHANGED, nullptr); + + ChatConversation conversation; + conversation.m_presenceID = presenceId; + conversation.m_inactive = 1; + CGChat::AddChatMessage("FRIEND_ADDED", CHAT_MSG_BN_INLINE_TOAST_ALERT, BattlenetUI::GetNameForPresenceIdHelper(presenceId), 0, nullptr, nullptr, nullptr, WOWGUID(), 0, WOWGUID(), 0, false, &conversation); +} + +// VERIFY: dda529af auto +// OFFSET: 0x0053AA70 +void BattlenetUI::FriendRemovedCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + uint32_t presenceId; + + if (!BattlenetUI::s_initialized || (presenceId = static_cast(args[0].ToUInt64())) == 0) { + SErrDisplayAppFatalMessage("", "", 0); + } + + int32_t index = BattlenetUI::FindFriendIndex(presenceId); + + if (index < 0) { + DebugLog("BNUI: Friend Removed: ID % not found", presenceId); + return; + } + + BattlenetUI::m_friends.Remove(index); + DebugLog("BNUI: Friend Removed. Index %d, ID %u", index, presenceId); + BattlenetUI::DisambiguateFriendList(); + + if (BattlenetUI::m_friends.m_count > 1) { + qsort(BattlenetUI::m_friends.m_data, BattlenetUI::m_friends.m_count, sizeof(BattlenetUIFriend), BattlenetUI::QSortFriendListCB); + } + + BattlenetUI::PopulateAutoComplete(); + CGAutoCompleteName::RemoveFlags(presenceId, 0x4); + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_FRIEND_LIST_SIZE_CHANGED, nullptr); + + ChatConversation conversation; + conversation.m_presenceID = presenceId; + conversation.m_inactive = 1; + CGChat::AddChatMessage("FRIEND_REMOVED", CHAT_MSG_BN_INLINE_TOAST_ALERT, BattlenetUI::GetNameForPresenceIdHelper(presenceId), 0, nullptr, nullptr, nullptr, WOWGUID(), 0, WOWGUID(), 0, false, &conversation); +} + +// VERIFY: 36078bc2 auto +// OFFSET: 0x0053ABC0 +void BattlenetUI::OnlinePresenceChangedCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + if (!BattlenetUI::s_initialized) { + SErrDisplayAppFatalMessage("", "", 0); + } + + BSN::BSNEncodedObject update(args[0].ToObject()); + bool online = false; + + if (update.m_data.m_value.m_tag == 1) { + online = update.m_data.m_value.m_bool != 0; + } + + bool ridFriend = BattlenetAPI::IsRIDFriend(update.m_data.m_presenceId); + bool cidFriend = BattlenetAPI::IsCIDFriend(update.m_data.m_presenceId); + + BattlenetUI::DisambiguateFriendList(); + + if (BattlenetUI::m_friends.m_count > 1) { + qsort(BattlenetUI::m_friends.m_data, BattlenetUI::m_friends.m_count, sizeof(BattlenetUIFriend), BattlenetUI::QSortFriendListCB); + } + + if (online) { + BattlenetUI::UpdateAutoComplete(update.m_data.m_presenceId, 0x20, 0, nullptr); + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_FRIEND_INFO_CHANGED, nullptr); + return; + } + + CGAutoCompleteName::RemoveFlags(update.m_data.m_presenceId, 0x20); + + if (ridFriend) { + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_FRIEND_ACCOUNT_OFFLINE, "%u", update.m_data.m_presenceId); + + if (s_cvShowToastOffline && s_cvShowToastOffline->m_intValue) { + ChatConversation conversation; + conversation.m_presenceID = update.m_data.m_presenceId; + conversation.m_inactive = 1; + CGChat::AddChatMessage("FRIEND_OFFLINE", CHAT_MSG_BN_INLINE_TOAST_ALERT, BattlenetUI::GetNameForPresenceIdHelper(update.m_data.m_presenceId), 0, nullptr, nullptr, nullptr, WOWGUID(), 0, WOWGUID(), 0, false, &conversation); + } + + DebugLog("BNUI: >> ACCOUNT %s is now OFFLINE. ID %u", BattlenetUI::GetNameForPresenceIdHelper(update.m_data.m_presenceId), update.m_data.m_presenceId); + } else if (cidFriend) { + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_FRIEND_TOON_OFFLINE, "%u", update.m_data.m_presenceId); + DebugLog("BNUI: >> TOON %s is now OFFLINE. ID %u", BattlenetUI::GetNameForPresenceIdHelper(update.m_data.m_presenceId), update.m_data.m_presenceId); + } + + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_FRIEND_INFO_CHANGED, nullptr); +} + +// VERIFY: 5c45d117 auto +// OFFSET: 0x0053ADC0 +void BattlenetUI::ChatWhisperUndeliverableCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + uint32_t presenceId = static_cast(args[0].ToUInt64()); + BattlenetUI::DisplayError(static_cast(args[1].ToUInt64()), presenceId); + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_CHAT_WHISPER_UNDELIVERABLE, "%u", presenceId); +} + +// VERIFY: 0ef6cc1e manual +// OFFSET: 0x0053AE30 +void BattlenetUI::ChatChannelCreateCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + uint16_t error = static_cast(args[0].ToUInt64()); + + if (error) { + uint32_t presenceId = 0; + + if (argc >= 2) { + if (args[1].m_type == GeneralFunction::Arg::TYPE_OBJECT) { + BSN::BSNEncodedObject toon; + toon.WalkAndGet(args[1].ToObject()); + presenceId = BattlenetAPI::GetPresenceIDForToon(&toon.m_data); + } else if (args[1].m_type == GeneralFunction::Arg::TYPE_INT || args[1].m_type == GeneralFunction::Arg::TYPE_UINT) { + presenceId = static_cast(args[1].ToUInt64()); + } + } + + BattlenetUI::DisplayError(error, presenceId); + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_CHAT_CHANNEL_CREATE_FAILED, "%u", presenceId); + return; + } + + uint8_t channel = static_cast(args[1].ToUInt64()); + + if (channel >= 6) { + SErrDisplayAppFatalMessage("", "", 0); + } + + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_CHAT_CHANNEL_CREATE_SUCCEEDED, "%d", channel + 1); + DebugLog("BNUI: Chat Channel Create Succeeded. channel = %d", channel + 1); +} + +// VERIFY: 70e39278 manual +// OFFSET: 0x0053AF70 +void BattlenetUI::ChatChannelInviteCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + uint16_t error = static_cast(args[0].ToUInt64()); + BSN::BSNEncodedObject toon; + toon.WalkAndGet(args[1].ToObject()); + uint32_t presenceId = BattlenetAPI::GetPresenceIDForToon(&toon.m_data); + uint8_t channel = static_cast(args[2].ToUInt64()); + + if (channel >= 6) { + SErrDisplayAppFatalMessage("", "", 0); + } + + if (error) { + BattlenetUI::DisplayError(error, presenceId); + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_CHAT_CHANNEL_INVITE_FAILED, "%d%u", channel + 1, presenceId); + DebugLog("BNUI: Chat Channel Invite Failed. channel %d, id %d", channel + 1, presenceId); + } else { + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_CHAT_CHANNEL_INVITE_SUCCEEDED, "%d%u", channel + 1, presenceId); + DebugLog("BNUI: Chat Channel Invite Succeeded. channel %d, id %u", channel + 1, presenceId); + } +} + +// VERIFY: fa26f5b8 auto +// OFFSET: 0x0053B0D0 +void BattlenetUI::ChatChannelMessageUndeliverableCB(void* param, int32_t argc, const GeneralFunction::Arg* args) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return; + } + + uint8_t channel = static_cast(args[0].ToUInt64()); + + if (channel >= 6) { + SErrDisplayAppFatalMessage("", "", 0); + } + + BattlenetUI::DisplayError(static_cast(args[1].ToUInt64()), 0); + BattlenetUI::SendScriptEvent(SCRIPT_EVENT_BN_CHAT_CHANNEL_MESSAGE_UNDELIVERABLE, "%d", channel + 1); + DebugLog("BNUI: Chat Channel Message Undeliverable. channel %d", channel + 1); +} + +// VERIFY: 1081d8e3 manual +// OFFSET: 0x0053B170 +void BattlenetUI::Init() { + if (!g_tumorManager) { + return; + } + + if (BattlenetUI::m_friendInvites) { + SErrDisplayAppFatalMessage("", "", 0); + } + + BattlenetUI::m_friendInvites = new (__FILE__, __LINE__) BSN::BSNEncodedObject(); + BattlenetUI::s_friendsOfFriend = new (__FILE__, __LINE__) BSN::BSNEncodedObject(); + + for (uint32_t i = 0; i < 26; i++) { + GeneralFunction::SimpleCallback* callback = new (__FILE__, __LINE__) GeneralFunction::SimpleCallback(BattlenetUI::s_eventCallbacks[i].m_func, nullptr); + BattlenetUI::s_eventCallbacks[i].m_handle = BattlenetAPI::RegisterEvent(BattlenetUI::s_eventCallbacks[i].m_event, callback); + + if (!BattlenetUI::s_eventCallbacks[i].m_handle) { + SErrDisplayAppFatalMessage("", "", 0); + } + } + + for (uint32_t i = 0; i < NUM_BN_PRESENCE_FIELDS; i++) { + GeneralFunction::SimpleCallback* callback = new (__FILE__, __LINE__) GeneralFunction::SimpleCallback(BattlenetUI::s_presenceCallbacks[i].m_func, nullptr); + BattlenetUI::s_presenceCallbacks[i].m_handle = BattlenetAPI::RegisterPresenceUpdateCallback(0, BattlenetUI::s_presenceCallbacks[i].m_field, callback); + + if (!BattlenetUI::s_presenceCallbacks[i].m_handle) { + SErrDisplayAppFatalMessage("", "", 0); + } + } + + BattlenetUI::s_createConversationCB = new (__FILE__, __LINE__) GeneralFunction::SimpleCallback(BattlenetUI::ChatChannelCreateCB, nullptr); + BattlenetUI::s_createConversationCB->IncRef(); + + BattlenetUI::s_inviteToConversationCB = new (__FILE__, __LINE__) GeneralFunction::SimpleCallback(BattlenetUI::ChatChannelInviteCB, nullptr); + BattlenetUI::s_inviteToConversationCB->IncRef(); + + BattlenetUI::s_friendsOfFriendCB = new (__FILE__, __LINE__) GeneralFunction::SimpleCallback(BattlenetUI::FriendsOfFriendCB, nullptr); + BattlenetUI::s_friendsOfFriendCB->IncRef(); + + BattlenetUI::s_initialized = true; + DebugLog("BNUI: Init"); +} + +// VERIFY: fa7e6db5 auto // OFFSET: 0x0053B370 void BattlenetUI_EnterRealm() { Login* login = ClientServices::LoginConnection(); @@ -45,6 +1975,6 @@ void BattlenetUI_EnterRealm() { const char* nameFormat = FrameScript_GetText("BATTLENET_NAME_FORMAT", -1, GENDER_NOT_APPLICABLE); if (*nameFormat) { - BattlenetUI::EnterRealm(nameFormat); + BattlenetAPI::SetAccountNameFormatString(nameFormat); } } diff --git a/WoW/Source/Ui/BattlenetUI.h b/WoW/Source/Ui/BattlenetUI.h index dc782f9..196adce 100644 --- a/WoW/Source/Ui/BattlenetUI.h +++ b/WoW/Source/Ui/BattlenetUI.h @@ -3,111 +3,125 @@ #include #include -#include "Engine/Source/Storm/H/stpl.h" +#include "WoW/Source/Battlenet/BattlenetProtocol.h" +#include "WoW/Source/Battlenet/GeneralFunction.h" +#include "WoW/Source/Ui/BattlenetAPI.h" +#include "WoW/Source/Ui/Types.h" -class Login; struct lua_State; -struct BattlenetPresenceValue { - /* 0000 */ int32_t m_type; - /* 0004 */ uint8_t m_bool; - /* 0005 */ uint8_t unk_0005[519]; -}; - -struct BattlenetBlockList { - /* 0000 */ uint32_t m_blockedCount; - /* 0004 */ uint32_t m_blocked[100]; - /* 0194 */ uint32_t m_blockedToonCount; - /* 0198 */ uint32_t m_blockedToons[100]; -}; - struct BattlenetUIFriend { /* 0000 */ uint32_t m_presenceID; - /* 0004 */ uint8_t unk_0004[820]; -}; - -struct BattlenetInviteList { - /* 0000 */ uint32_t unk_0000; - /* 0004 */ uint32_t unk_0004; - /* 0008 */ uint32_t m_count; + /* 0004 */ uint32_t m_program; + /* 0008 */ BSN::String<72> m_name; + /* 0134 */ BSN::String<40> m_givenName; + /* 01E0 */ BSN::String<40> m_surname; + /* 028C */ BSN::String<40> m_sortSurname; }; class BattlenetUI { public: - static BattlenetInviteList* m_friendInvites; - static int32_t unk_BD1B00; - static uint8_t m_friendListLoaded; - static TSGrowableArray m_friends; + struct EventCallback { + /* 0000 */ const char* m_event; + /* 0004 */ GeneralFunction::SimpleCallbackFunc m_func; + /* 0008 */ uint32_t m_handle; + }; - static void EnterRealm(const char* nameFormat); + struct PresenceCallback { + /* 0000 */ uint32_t m_field; + /* 0004 */ GeneralFunction::SimpleCallbackFunc m_func; + /* 0008 */ uint32_t m_handle; + }; + + class FriendInviteSentCB : public GeneralFunction::Callback { + public: + void Call(int32_t argc, const GeneralFunction::Arg* args) const override; + void Destroy() const override; + }; + + static uint32_t s_selfRealm; + static bool s_initialized; + static bool m_friendListLoaded; + static BSN::BSNEncodedObject* m_friendInvites; + static BSN::BSNEncodedObject* s_friendsOfFriend; + static GeneralFunction::Callback* s_createConversationCB; + static GeneralFunction::Callback* s_inviteToConversationCB; + static GeneralFunction::Callback* s_friendsOfFriendCB; + static uint32_t s_selectedFriend; + static uint32_t s_selectedBlock; + static uint32_t s_selectedToonBlock; + static BSN::Array m_friends; + static EventCallback s_eventCallbacks[26]; + static PresenceCallback s_presenceCallbacks[NUM_BN_PRESENCE_FIELDS]; + static FriendInviteSentCB s_friendInviteSentCB; + static int32_t s_broadcastCount; + static char s_programString[16]; + static float s_broadcastTime; + static char s_displayName[72]; + + static bool AddToFriendList(uint32_t presenceId); + static int32_t BNGetFriendInfoHelper(lua_State* L, uint32_t index); + static int32_t BNGetToonInfoHelper(lua_State* L, uint32_t presenceId); + static void BlockAddedCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void BlockListInitializedCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void BlockRemovedCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void ChatChannelClosedCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void ChatChannelCreateCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void ChatChannelInviteCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void ChatChannelJoinedCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void ChatChannelLeftCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void ChatChannelMemberJoinedCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void ChatChannelMemberLeftCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void ChatChannelMemberUpdatedCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void ChatChannelMessageBlockedCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void ChatChannelMessageReceivedCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void ChatChannelMessageUndeliverableCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void ChatWhisperReceivedCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void ChatWhisperSentCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void ChatWhisperUndeliverableCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void CustomMessageChangedCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void DisambiguateFriendList(); + static void DisplayError(uint16_t error, uint32_t presenceId); + static void FactionUpdateCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static BattlenetUIFriend* FindFriend(uint32_t presenceId); + static int32_t FindFriendIndex(uint32_t presenceId); + static void FriendAddedCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void FriendInfoChangedCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void FriendInviteAddedCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void FriendInviteListInitializedCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void FriendInviteRemovedCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void FriendListInitializedCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void FriendRemovedCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void FriendsOfFriendCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static const char* GetNameForPresenceIdHelper(uint32_t presenceId); + static uint32_t GetSelfRealmID(); + static void IgnoredFieldCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void Init(); + static void LastOnlineChangedCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void NewPresenceCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void OnlinePresenceChangedCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void OnlineTimeChangedCB(void* param, int32_t argc, const GeneralFunction::Arg* args); static void PopulateAutoComplete(); - - /* 0000 */ uint8_t unk_0000 [4]; - /* 0004 */ int32_t unk_0004; - /* 0008 */ int32_t unk_0008; - /* 000C */ int32_t unk_000C; + static int32_t QSortDisambiguateFriendListCB(const void* a, const void* b); + static int32_t QSortFriendInviteListByTimeCB(const void* a, const void* b); + static int32_t QSortFriendListCB(const void* a, const void* b); + static void SelfToonOfflineCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void SelfToonOnlineCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void SendScriptEvent(uint32_t event, const char* format, ...); + static void SetBattlenetConnectionRecovered(); + static void SetDisconnectedFromBattlenet(bool disconnected); + static void SettingChangedCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void SortFriendInviteList(); + static void SystemMessageCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void ToonNameUpdateCB(void* param, int32_t argc, const GeneralFunction::Arg* args); + static void Uninit(); + static int32_t UpdateAutoComplete(uint32_t& presenceId, uint32_t flags, int32_t add, const char* name); }; -namespace BattlenetAPI { - bool IsRIDEnabled(); - BattlenetPresenceValue GetPresenceValue(uint32_t presenceID, uint32_t field); - BattlenetBlockList GetBlockList(); -} - +char* FilterChatLinks(const char* source, char* dest, uint32_t size); bool BattlenetUI_IsAvailable(); void BattlenetUI_EnterRealm(); void BattlenetUI_LeaveRealm(); - -int32_t Script_BNGetInfo(lua_State* L); -int32_t Script_BNGetFriendInfo(lua_State* L); -int32_t Script_BNGetFriendInfoByID(lua_State* L); -int32_t Script_BNGetNumFriendToons(lua_State* L); -int32_t Script_BNGetFriendToonInfo(lua_State* L); -int32_t Script_BNGetToonInfo(lua_State* L); -int32_t Script_BNRemoveFriend(lua_State* L); -int32_t Script_BNSetFriendNote(lua_State* L); -int32_t Script_BNSetSelectedFriend(lua_State* L); -int32_t Script_BNGetSelectedFriend(lua_State* L); -int32_t Script_BNGetFriendInviteInfo(lua_State* L); -int32_t Script_BNSendFriendInvite(lua_State* L); -int32_t Script_BNSendFriendInviteByID(lua_State* L); -int32_t Script_BNAcceptFriendInvite(lua_State* L); -int32_t Script_BNDeclineFriendInvite(lua_State* L); -int32_t Script_BNReportFriendInvite(lua_State* L); -int32_t Script_BNSetAFK(lua_State* L); -int32_t Script_BNSetDND(lua_State* L); -int32_t Script_BNSetCustomMessage(lua_State* L); -int32_t Script_BNGetCustomMessageTable(lua_State* L); -int32_t Script_BNSetFocus(lua_State* L); -int32_t Script_BNSendWhisper(lua_State* L); -int32_t Script_BNCreateConversation(lua_State* L); -int32_t Script_BNInviteToConversation(lua_State* L); -int32_t Script_BNLeaveConversation(lua_State* L); -int32_t Script_BNSendConversationMessage(lua_State* L); -int32_t Script_BNGetNumConversationMembers(lua_State* L); -int32_t Script_BNGetConversationMemberInfo(lua_State* L); -int32_t Script_BNGetConversationInfo(lua_State* L); -int32_t Script_BNListConversation(lua_State* L); -int32_t Script_BNGetBlockedInfo(lua_State* L); -int32_t Script_BNIsBlocked(lua_State* L); -int32_t Script_BNSetBlocked(lua_State* L); -int32_t Script_BNSetSelectedBlock(lua_State* L); -int32_t Script_BNGetSelectedBlock(lua_State* L); -int32_t Script_BNGetBlockedToonInfo(lua_State* L); -int32_t Script_BNIsToonBlocked(lua_State* L); -int32_t Script_BNSetToonBlocked(lua_State* L); -int32_t Script_BNSetSelectedToonBlock(lua_State* L); -int32_t Script_BNGetSelectedToonBlock(lua_State* L); -int32_t Script_BNReportPlayer(lua_State* L); -int32_t Script_BNConnected(lua_State* L); -int32_t Script_IsBNLogin(lua_State* L); -int32_t Script_BNRequestFOFInfo(lua_State* L); -int32_t Script_BNGetNumFOF(lua_State* L); -int32_t Script_BNGetFOFInfo(lua_State* L); -int32_t Script_BNSetMatureLanguageFilter(lua_State* L); -int32_t Script_BNGetMatureLanguageFilter(lua_State* L); -int32_t Script_BNIsSelf(lua_State* L); -int32_t Script_BNIsFriend(lua_State* L); void BattlenetUI_RegisterScriptFunctions(); void BattlenetUI_UnregisterScriptFunctions(); diff --git a/WoW/Source/Ui/BattlenetUI_Scripts.cpp b/WoW/Source/Ui/BattlenetUI_Scripts.cpp index 77959b2..68149aa 100644 --- a/WoW/Source/Ui/BattlenetUI_Scripts.cpp +++ b/WoW/Source/Ui/BattlenetUI_Scripts.cpp @@ -2,15 +2,83 @@ #include #include "Engine/Source/FrameScript/FrameScript.h" #include "Engine/Source/FrameScript/FrameScript_Object.h" +#include "Engine/Source/lua-5.1/src/lauxlib.h" +#include "Engine/Source/lua-5.1/src/lua.h" +#include "Engine/Source/Os/Time.h" +#include "Engine/Source/Storm/H/storm.h" +#include "WoW/Source/Ui/ChatFrame.h" +#include "WoW/Source/Ui/GameUI.h" #include "WoW/Source/WowServices/BattlenetLogin.h" #include "WoW/Source/WowServices/Login.h" #include "WoW/Source/WowSvcs/WowSvcsClient/ClientServices.h" -#include "Engine/Source/Storm/H/storm.h" -// STATIC: 0x00ACC9E8 -static uint32_t s_presenceOnlineField = 0x10002; +// VERIFY: f2fecb1f auto +// OFFSET: 0x00530EC0 +static int32_t Script_BNConnected(lua_State* L) { + bool connected = false; + Login* login = ClientServices::LoginConnection(); -// VERIFY: f52b1323 manual + if (login && login->GetLoginServerType() == 1) { + int32_t state = static_cast(login)->m_serviceState; + + if (state == 7 || state == 6 || state == 3) { + connected = true; + } + } + + lua_pushboolean(L, connected); + return 1; +} + +// VERIFY: 512bf591 auto +// OFFSET: 0x00530F20 +static int32_t Script_IsBNLogin(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + lua_pushboolean(L, login && login->GetLoginServerType() == 1); + return 1; +} + +// VERIFY: 515f5bba manual +// OFFSET: 0x005343F0 +static int32_t Script_BNGetInfo(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return 0; + } + + uint32_t accountId = BattlenetAPI::GetPresenceIDForCurrentAccount(); + lua_pushnumber(L, accountId); + DebugLog("BNUI: GetInfo account ID is %u", accountId); + + uint32_t toonId = BattlenetAPI::GetPresenceIDForCurrentToon(); + lua_pushnumber(L, toonId); + DebugLog("BNUI: GetInfo toon ID is %u", toonId); + + Battlenet::Presence::FieldVal broadcast = BattlenetAPI::GetPresenceValue(toonId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_BROADCAST].m_field); + + if (broadcast.m_tag == 13) { + lua_pushstring(L, broadcast.m_string.m_data); + DebugLog("BNUI: GetInfo custom message is %s", broadcast.m_string.m_data); + } else { + lua_pushnil(L); + DebugLog("BNUI: GetInfo custom message is "); + } + + Battlenet::Presence::FieldVal value = BattlenetAPI::GetPresenceValue(toonId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_AFK].m_field); + uint8_t isAFK = value.m_tag == 11 ? value.m_bool : 0; + lua_pushboolean(L, isAFK); + DebugLog("BNUI: GetInfo AFK is %d", isAFK); + + value = BattlenetAPI::GetPresenceValue(toonId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_DND].m_field); + uint8_t isDND = value.m_tag == 11 ? value.m_bool : 0; + lua_pushboolean(L, isDND); + DebugLog("BNUI: GetInfo DND is %d", isDND); + + return 5; +} + +// VERIFY: f2a0fb12 manual // OFFSET: 0x00534590 static int32_t Script_BNGetNumFriends(lua_State* L) { Login* login = ClientServices::LoginConnection(); @@ -27,14 +95,14 @@ static int32_t Script_BNGetNumFriends(lua_State* L) { return 2; } - lua_pushnumber(L, BattlenetUI::m_friends.Count()); + lua_pushnumber(L, BattlenetUI::m_friends.m_count); uint32_t online = 0; - for (uint32_t i = 0; i < BattlenetUI::m_friends.Count(); i++) { - BattlenetPresenceValue value = BattlenetAPI::GetPresenceValue(BattlenetUI::m_friends.m_data[i].m_presenceID, s_presenceOnlineField); + for (uint32_t i = 0; i < BattlenetUI::m_friends.m_count; i++) { + Battlenet::Presence::FieldVal value = BattlenetAPI::GetPresenceValue(BattlenetUI::m_friends.m_data[i].m_presenceID, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_ONLINE].m_field); - if (value.m_type == 1 && value.m_bool) { + if (value.m_tag == 1 && value.m_bool) { online++; } } @@ -43,6 +111,952 @@ static int32_t Script_BNGetNumFriends(lua_State* L) { return 2; } +// VERIFY: ba9e1544 manual +// OFFSET: 0x005349F0 +static int32_t Script_BNGetNumFriendToons(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + lua_pushnumber(L, 0.0); + return 1; + } + + if (!lua_isnumber(L, 1)) { + luaL_error(L, "Usage: BNGetNumFriendToons(index)"); + } + + double index; + + if (!BattlenetUI::m_friendListLoaded || (index = lua_tonumber(L, 1), index - 1 >= BattlenetUI::m_friends.m_count)) { + lua_pushnumber(L, 0.0); + return 1; + } + + uint32_t presenceId = BattlenetUI::m_friends[static_cast(index - 1)].m_presenceID; + uint32_t numToons = BattlenetAPI::GetNumToons(presenceId); + uint32_t online = 0; + + for (uint32_t i = 0; i < numToons; i++) { + Battlenet::Presence::FieldVal value = BattlenetAPI::GetPresenceValue(BattlenetAPI::GetToon(presenceId, i), BattlenetUI::s_presenceCallbacks[BN_PRESENCE_ONLINE].m_field); + + if (value.m_tag == 1 && value.m_bool) { + online++; + } + } + + lua_pushnumber(L, online); + DebugLog("BNUI: GetNumFriendToons is %d", online); + return 1; +} + +// VERIFY: 6c9894e6 auto +// OFFSET: 0x00534ED0 +static int32_t Script_BNRemoveFriend(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (login && login->GetLoginServerType() == 1 && !login->IsTrialAccount() && BattlenetAPI::IsRIDEnabled()) { + if (!lua_isnumber(L, 1)) { + luaL_error(L, "Usage: BNRemoveFriend(ID)"); + } + + if (BattlenetUI::m_friendListLoaded) { + BattlenetAPI::RemoveFriend(static_cast(lua_tonumber(L, 1))); + } + } + + return 0; +} + +// VERIFY: 6e07b4a2 auto +// OFFSET: 0x00534F80 +static int32_t Script_BNSetFriendNote(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (login && login->GetLoginServerType() == 1 && !login->IsTrialAccount() && BattlenetAPI::IsRIDEnabled()) { + if (!lua_isnumber(L, 1)) { + luaL_error(L, "Usage: BNSetFriendNote(ID, noteText)"); + } + + if (BattlenetUI::m_friendListLoaded) { + if (!lua_isstring(L, 2)) { + luaL_error(L, "Usage: BNSetFriendNote(ID, noteText)"); + } + + double presenceId = lua_tonumber(L, 1); + const char* note = lua_tolstring(L, 2, nullptr); + + if (SStrLenUTF8(note) > 255) { + luaL_error(L, "Friend note text too long, maximum length %d chars", 255); + } + + BattlenetAPI::SetFriendNote(static_cast(presenceId), note); + } + } + + return 0; +} + +// VERIFY: 5f5b8f58 manual +// OFFSET: 0x00535080 +static int32_t Script_BNGetNumFriendInvites(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled() || !BattlenetUI::m_friendInvites) { + lua_pushnumber(L, 0.0); + return 1; + } + + if (BattlenetUI_IsAvailable()) { + uint32_t count = BattlenetUI::m_friendInvites->m_data.m_invites.m_count; + lua_pushnumber(L, count); + DebugLog("BNUI: Num friend invites: %d", count); + } else { + lua_pushnumber(L, 0.0); + DebugLog("BNUI: Num friend invites: 0, NOT CONNNECTED"); + } + + return 1; +} + +// VERIFY: 0258b95f manual +// OFFSET: 0x00535180 +static int32_t Script_BNGetFriendInviteInfo(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return 0; + } + + if (!lua_isnumber(L, 1)) { + luaL_error(L, "Usage: BNGetFriendInviteInfo(index)"); + } + + double number = lua_tonumber(L, 1); + uint32_t index = static_cast(number - 1); + BSN::Array& invites = BattlenetUI::m_friendInvites->m_data.m_invites; + + if (index >= invites.m_count) { + return 0; + } + + uint32_t presenceId = invites[static_cast(number - 1)].m_presenceId; + + if (!presenceId) { + luaL_error(L, "No Friend at index"); + } + + Battlenet::Presence::FieldVal name = BattlenetAPI::GetPresenceValue(presenceId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_ACCOUNT_NAME].m_field); + lua_pushnumber(L, presenceId); + DebugLog("BNUI: Invite Info ID: %u", presenceId); + + if (name.m_tag == 18) { + const char* givenName = name.Get<18, Battlenet::Presence::AccountName>().m_givenName.m_data; + const char* surname = name.Get<18, Battlenet::Presence::AccountName>().m_surname.m_data; + lua_pushstring(L, givenName); + lua_pushstring(L, surname); + DebugLog("BNUI: Invite Info Account name: %s %s", givenName, surname); + } else { + lua_pushnil(L); + lua_pushnil(L); + } + + if (invites[index].m_message.m_exists) { + const char* message = invites[index].m_message.Get().m_data; + lua_pushstring(L, message); + DebugLog("BNUI: Invite Info message: %s", message); + } else { + lua_pushnil(L); + } + + int32_t time = invites[index].m_time; + lua_pushnumber(L, time); + DebugLog("BNUI: Invite Info time: %d", time); + + return 5; +} + +// VERIFY: c1a1acff auto +// OFFSET: 0x00535380 +static int32_t Script_BNSendFriendInvite(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (login && login->GetLoginServerType() == 1 && !login->IsTrialAccount() && BattlenetAPI::IsRIDEnabled()) { + if (!lua_isstring(L, 1)) { + luaL_error(L, "Usage: BNSendFriendInvite(text, noteText)"); + } + + const char* text = lua_tolstring(L, 1, nullptr); + char note[1024]; + + if (lua_isstring(L, 2)) { + const char* noteText = lua_tolstring(L, 2, nullptr); + + if (SStrLenUTF8(noteText) > 255) { + luaL_error(L, "Invite note text too long, maximum length %d chars", 255); + } + + if (noteText) { + FilterChatLinks(noteText, note, 1021); + } else { + note[0] = '\0'; + } + } else { + note[0] = '\0'; + } + + BattlenetAPI::SendRIDFriendInviteByEmail(text, note, &BattlenetUI::s_friendInviteSentCB); + } + + return 0; +} + +// VERIFY: 93bf8940 auto +// OFFSET: 0x00535490 +static int32_t Script_BNSendFriendInviteByID(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (login && login->GetLoginServerType() == 1 && !login->IsTrialAccount() && BattlenetAPI::IsRIDEnabled()) { + if (!lua_isstring(L, 1)) { + luaL_error(L, "Usage: BNSendFriendInviteByID(ID, noteText)"); + } + + double presenceId = lua_tonumber(L, 1); + char note[1024]; + + if (lua_isstring(L, 2)) { + const char* noteText = lua_tolstring(L, 2, nullptr); + + if (SStrLenUTF8(noteText) > 255) { + luaL_error(L, "Invite note text too long, maximum length %d chars", 255); + } + + if (noteText) { + FilterChatLinks(noteText, note, 1021); + } else { + note[0] = '\0'; + } + } else { + note[0] = '\0'; + } + + BattlenetAPI::SendRIDFriendInviteByPresenceId(static_cast(presenceId), note, &BattlenetUI::s_friendInviteSentCB); + } + + return 0; +} + +// VERIFY: 3fea367a auto +// OFFSET: 0x005355C0 +static int32_t Script_BNAcceptFriendInvite(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (login && login->GetLoginServerType() == 1 && !login->IsTrialAccount() && BattlenetAPI::IsRIDEnabled()) { + if (!lua_isnumber(L, 1)) { + luaL_error(L, "Usage: BNAcceptFriendInvite(ID)"); + } + + BattlenetAPI::AcceptFriendInvite(static_cast(lua_tonumber(L, 1))); + } + + return 0; +} + +// VERIFY: 4a1d39b8 auto +// OFFSET: 0x00535660 +static int32_t Script_BNDeclineFriendInvite(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (login && login->GetLoginServerType() == 1 && !login->IsTrialAccount() && BattlenetAPI::IsRIDEnabled()) { + if (!lua_isnumber(L, 1)) { + luaL_error(L, "Usage: BNDeclineFriendInvite(ID)"); + } + + BattlenetAPI::DeclineFriendInvite(static_cast(lua_tonumber(L, 1))); + } + + return 0; +} + +// VERIFY: c0f9de03 auto +// OFFSET: 0x00535700 +static int32_t Script_BNReportFriendInvite(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (login && login->GetLoginServerType() == 1 && !login->IsTrialAccount() && BattlenetAPI::IsRIDEnabled()) { + if (!lua_isnumber(L, 1)) { + luaL_error(L, "Usage: BNReportFriendInvite(ID)"); + } + + BattlenetAPI::ReportFriendInvite(static_cast(lua_tonumber(L, 1))); + } + + return 0; +} + +// VERIFY: 47c2f002 auto +// OFFSET: 0x005357A0 +static int32_t Script_BNSetAFK(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (login && login->GetLoginServerType() == 1 && !login->IsTrialAccount() && BattlenetAPI::IsRIDEnabled()) { + if (lua_type(L, 1) != LUA_TBOOLEAN) { + luaL_error(L, "Usage: BNSetAFK(bool)"); + } + + bool afk = lua_toboolean(L, 1) != 0; + Battlenet::Presence::FieldVal value; + value.m_tag = 11; + value.m_bool = afk; + BattlenetAPI::SetPresenceValue(BattlenetUI::s_presenceCallbacks[BN_PRESENCE_AFK].m_field, &value); + } + + return 0; +} + +// VERIFY: bf638620 auto +// OFFSET: 0x00535860 +static int32_t Script_BNSetDND(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (login && login->GetLoginServerType() == 1 && !login->IsTrialAccount() && BattlenetAPI::IsRIDEnabled()) { + if (lua_type(L, 1) != LUA_TBOOLEAN) { + luaL_error(L, "Usage: BNSetDND(bool)"); + } + + bool dnd = lua_toboolean(L, 1) != 0; + Battlenet::Presence::FieldVal value; + value.m_tag = 11; + value.m_bool = dnd; + BattlenetAPI::SetPresenceValue(BattlenetUI::s_presenceCallbacks[BN_PRESENCE_DND].m_field, &value); + } + + return 0; +} + +// VERIFY: 4af5fdd0 manual +// OFFSET: 0x00535920 +static int32_t Script_BNSetCustomMessage(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (login && login->GetLoginServerType() == 1 && !login->IsTrialAccount() && BattlenetAPI::IsRIDEnabled()) { + if (!lua_isstring(L, 1)) { + luaL_error(L, "Usage: BNSetCustomMessage(text)"); + } + + if (++BattlenetUI::s_broadcastCount >= 2) { + float now = OsGetAsyncTimeSec(); + + if (now - BattlenetUI::s_broadcastTime < 3.0) { + if (BattlenetUI::s_broadcastCount >= 2) { + CGGameUI::DisplayError(ERR_BN_BROADCAST_THROTTLE); + return 0; + } + } else { + BattlenetUI::s_broadcastTime = now; + BattlenetUI::s_broadcastCount = 0; + } + } + + const char* text = lua_tolstring(L, 1, nullptr); + + if (SStrLenUTF8(text) > 127) { + luaL_error(L, "Message text too long, maximum length %d chars", 127); + } + + char message[512]; + FilterChatLinks(text, message, 509); + + Battlenet::Presence::FieldVal value; + *value.Set<13, BSN::String<127>>() = message; + BattlenetAPI::SetPresenceValue(BattlenetUI::s_presenceCallbacks[BN_PRESENCE_BROADCAST].m_field, &value); + } + + return 0; +} + +// VERIFY: e1af46d8 manual +// OFFSET: 0x00535AA0 +static int32_t Script_BNGetCustomMessageTable(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + uint32_t i = 0; + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return 0; + } + + if (lua_type(L, 1) != LUA_TTABLE) { + luaL_error(L, "Usage: BNGetCustomMessageTable(table)"); + } + + if (!BattlenetUI::m_friendListLoaded) { + lua_pushnil(L); + lua_pushnumber(L, 0.0); + lua_pushnumber(L, 0.0); + return 3; + } + + uint32_t online = 0; + uint32_t offline = 0; + + while (i < BattlenetUI::m_friends.m_count) { + Battlenet::Presence::FieldVal broadcast = BattlenetAPI::GetPresenceValue(BattlenetUI::m_friends.m_data[i].m_presenceID, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_BROADCAST].m_field); + uint8_t hasMessage = 0; + + if (broadcast.m_tag == 13 && SStrLenUTF8(broadcast.m_string.m_data)) { + hasMessage = 1; + + Battlenet::Presence::FieldVal value = BattlenetAPI::GetPresenceValue(BattlenetUI::m_friends[i].m_presenceID, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_ONLINE].m_field); + + if (value.m_tag == 1 && value.m_bool) { + online++; + } else { + offline++; + } + } + + lua_checkstack(L, 2); + lua_pushnumber(L, ++i); + lua_pushboolean(L, hasMessage); + lua_settable(L, -3); + } + + lua_pushnumber(L, online); + lua_pushnumber(L, offline); + return 3; +} + +// VERIFY: d3aaf112 auto +// OFFSET: 0x00535C60 +static int32_t Script_BNSetFocus(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (login && login->GetLoginServerType() == 1 && !login->IsTrialAccount() && BattlenetAPI::IsRIDEnabled()) { + Battlenet::Presence::FieldVal value; + value.m_tag = 0; + BattlenetAPI::SetPresenceValue(BattlenetUI::s_presenceCallbacks[BN_PRESENCE_FOCUS].m_field, &value); + } + + return 0; +} + +// VERIFY: a26abed5 manual +// OFFSET: 0x00535CE0 +static int32_t Script_BNCreateConversation(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return 0; + } + + Battlenet::Toon::FullName first; + Battlenet::Toon::FullName second; + + if (!BattlenetUI_IsAvailable()) { + return 0; + } + + if (!lua_isnumber(L, 1)) { + luaL_error(L, "Usage: BNCreateConversation(id,id)"); + } + + Battlenet::Presence::FieldVal toon = BattlenetAPI::GetPresenceValue(static_cast(lua_tonumber(L, 1)), BattlenetUI::s_presenceCallbacks[BN_PRESENCE_TOON_NAME].m_field); + + if (toon.m_tag != 17) { + return 0; + } + + first = toon.m_toonName; + + if (!lua_isnumber(L, 2)) { + luaL_error(L, "Usage: BNCreateConversation(id,id)"); + } + + toon = BattlenetAPI::GetPresenceValue(static_cast(lua_tonumber(L, 2)), BattlenetUI::s_presenceCallbacks[BN_PRESENCE_TOON_NAME].m_field); + + if (toon.m_tag != 17) { + return 0; + } + + second = toon.Get<17, Battlenet::Toon::FullName>(); + BattlenetAPI::CreateChatConversation(&first, &second, BattlenetUI::s_createConversationCB); + + lua_pushboolean(L, 1); + return 1; +} + +// VERIFY: 72a452b9 manual +// OFFSET: 0x00535EB0 +static int32_t Script_BNInviteToConversation(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return 0; + } + + Battlenet::Toon::FullName toon; + + if (!BattlenetUI_IsAvailable()) { + return 0; + } + + if (!lua_isnumber(L, 1)) { + luaL_error(L, "Usage: BNInviteToConversation(channel,id)"); + } + + uint8_t channel = static_cast(lua_tonumber(L, 1) - 1.0); + + if (channel >= 6) { + luaL_error(L, "Invalid Channel"); + } + + if (!lua_isnumber(L, 2)) { + luaL_error(L, "Usage: BNInviteToConversation(channel,id)"); + } + + Battlenet::Presence::FieldVal value = BattlenetAPI::GetPresenceValue(static_cast(lua_tonumber(L, 2)), BattlenetUI::s_presenceCallbacks[BN_PRESENCE_TOON_NAME].m_field); + + if (value.m_tag != 17) { + return 0; + } + + toon = value.Get<17, Battlenet::Toon::FullName>(); + BattlenetAPI::SendChatConversationInvite(channel, &toon, BattlenetUI::s_inviteToConversationCB); + + return 0; +} + +// VERIFY: f58e7e6b manual +// OFFSET: 0x00536030 +static int32_t Script_BNLeaveConversation(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return 0; + } + + if (!lua_isnumber(L, 1)) { + luaL_error(L, "Usage: BNLeaveConversation(channel)"); + } + + if (!BattlenetUI_IsAvailable()) { + return 0; + } + + double channel = lua_tonumber(L, 1) - 1.0; + + if (channel >= 6) { + luaL_error(L, "Invalid Channel"); + } + + BattlenetAPI::LeaveChatConversation(static_cast(channel)); + return 0; +} + +// VERIFY: 626f8a47 auto +// OFFSET: 0x00536110 +static int32_t Script_BNSendConversationMessage(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (login && login->GetLoginServerType() == 1 && !login->IsTrialAccount() && BattlenetAPI::IsRIDEnabled()) { + if (!lua_isnumber(L, 1) || !lua_isstring(L, 2)) { + luaL_error(L, "Usage: BNSendConversationMessage(channel,text)"); + } + + if (BattlenetUI_IsAvailable()) { + int32_t channelNumber = static_cast(lua_tonumber(L, 1) - 1.0); + uint8_t channel = channelNumber; + const char* text = lua_tolstring(L, 2, nullptr); + char message[1026]; + FilterChatLinks(text, message, 1021); + + if (channel >= 6) { + luaL_error(L, "Invalid Channel"); + } + + BattlenetAPI::SendChatMessage(channelNumber, message); + } + } + + return 0; +} + +// VERIFY: 84553829 manual +// OFFSET: 0x00536220 +static int32_t Script_BNGetNumConversationMembers(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + lua_pushnumber(L, 0.0); + return 1; + } + + if (!lua_isnumber(L, 1)) { + luaL_error(L, "Usage: BNGetNumConversationMembers(channel)"); + } + + double count; + + if (BattlenetUI_IsAvailable()) { + int32_t channel = static_cast(lua_tonumber(L, 1) - 1.0); + + if (static_cast(channel) >= 6) { + luaL_error(L, "Invalid Channel"); + } + + count = BattlenetAPI::GetNumChatMembers(channel); + } else { + count = 0.0; + } + + lua_pushnumber(L, count); + return 1; +} + +// VERIFY: 7432c6ae manual +// OFFSET: 0x00536330 +static int32_t Script_BNGetConversationInfo(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return 0; + } + + if (!lua_isnumber(L, 1)) { + luaL_error(L, "Usage: BNGetConversationInfo(channel)"); + } + + double channel = lua_tonumber(L, 1) - 1.0; + + if (BattlenetAPI::GetChatChannelType(static_cast(channel)) == 2) { + lua_pushstring(L, "conversation"); + } else { + lua_pushnil(L); + } + + return 1; +} + +// VERIFY: 3cb99631 manual +// OFFSET: 0x00536400 +static int32_t Script_BNGetNumBlocked(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + lua_pushnumber(L, 0.0); + return 1; + } + + if (!BattlenetUI_IsAvailable()) { + lua_pushnumber(L, 0.0); + DebugLog("BNUI: Num Blocked is 0. NOT CONNECTED"); + return 1; + } + + Battlenet::Presence::BlockList blockList = BattlenetAPI::GetBlockList(); + lua_pushnumber(L, blockList.m_accounts.m_count); + DebugLog("BNUI: Num Blocked is %d", blockList.m_accounts.m_count); + return 1; +} + +// VERIFY: e9831e9e auto +// OFFSET: 0x005364E0 +static int32_t Script_BNIsBlocked(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return 0; + } + + if (!lua_isnumber(L, 1)) { + luaL_error(L, "Usage: BNIsBlocked(ID)"); + } + + uint32_t presenceId = static_cast(lua_tonumber(L, 1)); + bool blocked = BattlenetAPI::IsRIDBlock(presenceId); + lua_pushboolean(L, blocked); + DebugLog("BNUI: Is Blocked for ID %u %s", presenceId, blocked ? "true" : "false"); + + return 1; +} + +// VERIFY: ede7e82b auto +// OFFSET: 0x005365B0 +static int32_t Script_BNSetBlocked(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (login && login->GetLoginServerType() == 1 && !login->IsTrialAccount() && BattlenetAPI::IsRIDEnabled()) { + if (!lua_isnumber(L, 1) || lua_type(L, 2) != LUA_TBOOLEAN) { + luaL_error(L, "Usage: BNSetBlocked(ID, true/false)"); + } + + uint32_t presenceId = static_cast(lua_tonumber(L, 1)); + + if (lua_toboolean(L, 2)) { + BattlenetAPI::AddRIDBlock(presenceId); + DebugLog("BNUI: Adding block for ID %u", presenceId); + return 0; + } + + BattlenetAPI::RemoveRIDBlock(presenceId); + DebugLog("BNUI: Removing block for ID %u", presenceId); + } + + return 0; +} + +// VERIFY: a99f894a manual +// OFFSET: 0x005366A0 +static int32_t Script_BNSetSelectedBlock(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return 0; + } + + if (!lua_isnumber(L, 1)) { + luaL_error(L, "Usage: BNSetSelectedBlock(index)"); + } + + uint32_t index = static_cast(lua_tonumber(L, 1)) - 1; + Battlenet::Presence::BlockList blockList = BattlenetAPI::GetBlockList(); + + if (index >= blockList.m_accounts.m_count) { + luaL_error(L, "Block index %d too large, only %d blocked.", index + 1, blockList.m_accounts.m_count); + } + + uint32_t presenceId = blockList.m_accounts.m_data[index]; + + if (!presenceId) { + SErrDisplayAppFatalMessage("", "", 0); + } + + BattlenetUI::s_selectedBlock = presenceId; + return 0; +} + +// VERIFY: 4ec1f3a8 manual +// OFFSET: 0x00536790 +static int32_t Script_BNGetSelectedBlock(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + lua_pushnumber(L, 0.0); + return 1; + } + + if (BattlenetUI::s_selectedBlock) { + Battlenet::Presence::BlockList blockList = BattlenetAPI::GetBlockList(); + + for (uint32_t i = 0; i < blockList.m_accounts.m_count; i++) { + if (blockList.m_accounts.m_data[i] == BattlenetUI::s_selectedBlock) { + lua_pushnumber(L, i + 1); + return 1; + } + } + } + + lua_pushnumber(L, 0.0); + return 1; +} + +// VERIFY: 3d19868a manual +// OFFSET: 0x00536890 +static int32_t Script_BNGetNumBlockedToons(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + lua_pushnumber(L, 0.0); + return 1; + } + + if (!BattlenetUI_IsAvailable()) { + lua_pushnumber(L, 0.0); + DebugLog("BNUI: Num Blocked toons is 0. NOT CONNECTED"); + return 1; + } + + Battlenet::Presence::BlockList blockList = BattlenetAPI::GetBlockList(); + lua_pushnumber(L, blockList.m_toons.m_count); + DebugLog("BNUI: Num Blocked toons is %d", blockList.m_toons.m_count); + return 1; +} + +// VERIFY: fa351982 manual +// OFFSET: 0x00536970 +static int32_t Script_BNGetBlockedToonInfo(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return 0; + } + + if (!lua_isnumber(L, 1)) { + luaL_error(L, "Usage: BNGetBlockedToonInfo(index)"); + } + + Battlenet::Presence::BlockList blockList = BattlenetAPI::GetBlockList(); + uint32_t index = static_cast(lua_tonumber(L, 1) - 1.0); + + if (index >= blockList.m_toons.m_count) { + luaL_error(L, "Invalid Index"); + } + + uint32_t presenceId = blockList.m_toons.m_data[index]; + lua_pushnumber(L, presenceId); + + const char* name = BattlenetAPI::GetExactNameForPresenceId(presenceId, false); + lua_pushstring(L, name); + DebugLog("BNUI: Blocked Toon info. index %d, ID %u, name: %s", index + 1, presenceId, name); + + return 2; +} + +// VERIFY: b9dcb576 auto +// OFFSET: 0x00536A90 +static int32_t Script_BNIsToonBlocked(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return 0; + } + + if (!lua_isnumber(L, 1)) { + luaL_error(L, "Usage: BNIsToonBlocked(ID)"); + } + + uint32_t presenceId = static_cast(lua_tonumber(L, 1)); + bool blocked = BattlenetAPI::IsCIDBlock(presenceId); + lua_pushboolean(L, blocked); + DebugLog("BNUI: Is Toon Blocked for ID %u %s", presenceId, blocked ? "true" : "false"); + + return 1; +} + +// VERIFY: a38c9f58 auto +// OFFSET: 0x00536B60 +static int32_t Script_BNSetToonBlocked(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (login && login->GetLoginServerType() == 1 && !login->IsTrialAccount() && BattlenetAPI::IsRIDEnabled()) { + if (!lua_isnumber(L, 1) || lua_type(L, 2) != LUA_TBOOLEAN) { + luaL_error(L, "Usage: BNSetToonBlocked(ID, true/false)"); + } + + uint32_t presenceId = static_cast(lua_tonumber(L, 1)); + + if (lua_toboolean(L, 2)) { + BattlenetAPI::AddCIDBlock(presenceId); + DebugLog("BNUI: Adding block for toon ID %u", presenceId); + return 0; + } + + BattlenetAPI::RemoveCIDBlock(presenceId); + DebugLog("BNUI: Removing block for toon ID %u", presenceId); + } + + return 0; +} + +// VERIFY: ae48a591 manual +// OFFSET: 0x00536C50 +static int32_t Script_BNSetSelectedToonBlock(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return 0; + } + + if (!lua_isnumber(L, 1)) { + luaL_error(L, "Usage: BNSetSelectedToonBlock(index)"); + } + + uint32_t index = static_cast(lua_tonumber(L, 1)) - 1; + Battlenet::Presence::BlockList blockList = BattlenetAPI::GetBlockList(); + + if (index >= blockList.m_toons.m_count) { + luaL_error(L, "Toon Block index %d too large, only %d blocked.", index + 1, blockList.m_toons.m_count); + } + + uint32_t presenceId = blockList.m_toons.m_data[index]; + + if (!presenceId) { + SErrDisplayAppFatalMessage("", "", 0); + } + + BattlenetUI::s_selectedToonBlock = presenceId; + return 0; +} + +// VERIFY: 7ac120a9 manual +// OFFSET: 0x00536D40 +static int32_t Script_BNGetSelectedToonBlock(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + lua_pushnumber(L, 0.0); + return 1; + } + + if (BattlenetUI::s_selectedToonBlock) { + Battlenet::Presence::BlockList blockList = BattlenetAPI::GetBlockList(); + + for (uint32_t i = 0; i < blockList.m_toons.m_count; i++) { + if (blockList.m_toons.m_data[i] == BattlenetUI::s_selectedToonBlock) { + lua_pushnumber(L, i + 1); + return 1; + } + } + } + + lua_pushnumber(L, 0.0); + return 1; +} + +// VERIFY: 3d16158e manual +// OFFSET: 0x00536E40 +static int32_t Script_BNReportPlayer(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (login && login->GetLoginServerType() == 1 && !login->IsTrialAccount() && BattlenetAPI::IsRIDEnabled()) { + if (!lua_isnumber(L, 1) || !lua_isstring(L, 2)) { + luaL_error(L, "Usage: BNReportPlayer(ID,typeText,note)"); + } + + const char* type = lua_tolstring(L, 2, nullptr); + const char* note = nullptr; + + if (lua_isstring(L, 3)) { + note = lua_tolstring(L, 3, nullptr); + + if (SStrLenUTF8(note, 509) > 127) { + luaL_error(L, "Report note is too long."); + } + } + + int32_t reason; + + if (!SStrCmpI(type, "SPAM", STORM_MAX_STR)) { + reason = 0; + } else if (!SStrCmpI(type, "ABUSE", STORM_MAX_STR)) { + reason = 1; + } else if (!SStrCmpI(type, "THREAT", STORM_MAX_STR)) { + reason = 2; + } else { + if (SStrCmpI(type, "NAME", STORM_MAX_STR)) { + luaL_error(L, "Unknown Reason"); + } + + reason = 3; + } + + if (!BattlenetAPI::ReportPlayer(static_cast(lua_tonumber(L, 1)), reason, note)) { + CGChat::AddChatMessage(FrameScript_GetText("BNET_REPORT_SENT", -1, GENDER_NOT_APPLICABLE), 0, nullptr, 0, nullptr, nullptr, nullptr, WOWGUID(), 0, WOWGUID(), 0, false, nullptr); + } + } + + return 0; +} + // VERIFY: 32894792 auto // OFFSET: 0x00537010 static int32_t Script_BNFeaturesEnabledAndConnected(lua_State* L) { @@ -59,6 +1073,262 @@ static int32_t Script_BNFeaturesEnabled(lua_State* L) { return 1; } +// VERIFY: 3eed4bc9 manual +// OFFSET: 0x005370D0 +static int32_t Script_BNGetNumFOF(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return 0; + } + + if (!lua_isnumber(L, 1)) { + luaL_error(L, "Usage: BNGetNumFOF(ID,mutual,non)"); + } + + double presenceId = lua_tonumber(L, 1); + Battlenet::Friends::FriendsOfFriendList& list = BattlenetUI::s_friendsOfFriend->m_data; + + if (presenceId != list.m_presenceId) { + DebugLog("BNUI: BNGetNumFOF requested for ID %u. Current FOF ID is %u. Num FOF is %d", presenceId, list.m_presenceId, list.m_friends.m_count); + luaL_error(L, "Incorrect ID"); + } + + uint32_t mutual = 0; + uint32_t nonMutual = 0; + + for (uint32_t i = 0; i < list.m_friends.m_count; i++) { + if (!BattlenetAPI::IsSelf(list.m_friends.m_data[i])) { + if (BattlenetAPI::IsRIDFriend(list.m_friends[i])) { + mutual++; + } else { + nonMutual++; + } + } + } + + lua_pushnumber(L, mutual); + lua_pushnumber(L, nonMutual); + DebugLog("BNUI: BNGetNumFOF is %d mutual, %d non-mutual", mutual, nonMutual); + + return 2; +} + +// VERIFY: c5215d9a manual +// OFFSET: 0x00537240 +static int32_t Script_BNGetFOFInfo(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return 0; + } + + if (!lua_isnumber(L, 1) || !lua_isnumber(L, 4)) { + luaL_error(L, "Usage: BNGetFOFInfo(ID, mutual, non, index)"); + } + + uint32_t presenceId = static_cast(lua_tonumber(L, 1)); + Battlenet::Friends::FriendsOfFriendList& list = BattlenetUI::s_friendsOfFriend->m_data; + + if (presenceId != list.m_presenceId) { + luaL_error(L, "Incorrect ID"); + } + + int32_t mutual = lua_toboolean(L, 2); + int32_t nonMutual = lua_toboolean(L, 3); + uint32_t index = static_cast(lua_tonumber(L, 4)) - 1; + + if (!mutual && !nonMutual) { + luaL_error(L, "Must select mutual and/or non."); + } + + uint32_t current = 0; + uint8_t isMutual = 0; + uint32_t i; + + for (i = 0; i < list.m_friends.m_count; i++) { + if (BattlenetAPI::IsSelf(list.m_friends.m_data[i])) { + continue; + } + + if (BattlenetAPI::IsRIDFriend(list.m_friends[i])) { + if (mutual) { + if (current == index) { + isMutual = 1; + break; + } + + current++; + } + } else if (nonMutual) { + if (current == index) { + break; + } + + current++; + } + } + + if (i >= list.m_friends.m_count) { + luaL_error(L, "No friend at that index."); + } + + uint32_t friendId = list.m_friends[i]; + lua_pushnumber(L, friendId); + + const char* givenName = "none"; + const char* surname = "none"; + Battlenet::Presence::FieldVal name = BattlenetAPI::GetPresenceValue(friendId, BattlenetUI::s_presenceCallbacks[BN_PRESENCE_ACCOUNT_NAME].m_field); + + if (name.m_tag == 18) { + givenName = name.m_accountName.m_givenName.m_data; + surname = name.m_accountName.m_surname.m_data; + lua_pushstring(L, givenName); + lua_pushstring(L, surname); + } else { + lua_pushnil(L); + lua_pushnil(L); + } + + lua_pushboolean(L, isMutual); + DebugLog("BNUI: BNGetFOFInfo for ID %u index %d is ID %u, Acct name %s %s % mutual friend.", presenceId, index + 1, friendId, givenName, surname, isMutual ? "Is" : "Is not"); + + return 4; +} + +// VERIFY: 27fc51cd manual +// OFFSET: 0x00537510 +static int32_t Script_BNSetSelectedFriend(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return 0; + } + + if (!lua_isnumber(L, 1)) { + luaL_error(L, "Usage: BNSetSelectedFriend(index)"); + } + + if (!BattlenetUI::m_friendListLoaded) { + return 0; + } + + double index = lua_tonumber(L, 1); + + if (index - 1 >= BattlenetUI::m_friends.m_count) { + luaL_error(L, "Friend index %d too large, only %d friends.", index, BattlenetUI::m_friends.m_count); + } + + uint32_t presenceId = BattlenetUI::m_friends[static_cast(index - 1)].m_presenceID; + + if (!presenceId) { + SErrDisplayAppFatalMessage("", "", 0); + } + + BattlenetUI::s_selectedFriend = presenceId; + return 0; +} + +// VERIFY: e95ac14a auto +// OFFSET: 0x00537600 +static int32_t Script_BNGetSelectedFriend(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (login && login->GetLoginServerType() == 1 && !login->IsTrialAccount() && BattlenetAPI::IsRIDEnabled() && BattlenetUI::m_friendListLoaded && BattlenetUI::s_selectedFriend) { + int32_t index = BattlenetUI::FindFriendIndex(BattlenetUI::s_selectedFriend); + + if (index < 0) { + lua_pushnumber(L, 0.0); + } else { + lua_pushnumber(L, index + 1); + } + + return 1; + } + + lua_pushnumber(L, 0.0); + return 1; +} + +// VERIFY: 4582bd29 manual +// OFFSET: 0x005376C0 +static int32_t Script_BNSetMatureLanguageFilter(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (login && login->GetLoginServerType() == 1 && !login->IsTrialAccount() && BattlenetAPI::IsRIDEnabled()) { + if (lua_type(L, 1) != LUA_TBOOLEAN) { + luaL_error(L, "Usage: BNSetMatureLanguageFilter(true/false)"); + } + + if (!BattlenetUI_IsAvailable()) { + luaL_error(L, "not connected to Battle.net"); + } + + int32_t enabled = lua_toboolean(L, 1); + GeneralFunction::Arg value; + value = static_cast(enabled); + BattlenetAPI::SetSetting("Chat.ProfanityFilterEnabled", value, true); + DebugLog("BNUI: Set mature language filter %s", enabled ? "on" : "off"); + } + + return 0; +} + +// VERIFY: 197ffe0c manual +// OFFSET: 0x005377C0 +static int32_t Script_BNGetMatureLanguageFilter(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return 0; + } + + if (!BattlenetUI_IsAvailable()) { + luaL_error(L, "not connected to Battle.net"); + } + + GeneralFunction::Arg setting = BattlenetAPI::GetSetting("Chat.ProfanityFilterEnabled"); + bool enabled = setting.ToBool(); + DebugLog("BNUI: mature language filter is %s", enabled ? "on" : "off"); + lua_pushboolean(L, enabled); + + return 1; +} + +// VERIFY: a2d38f77 auto +// OFFSET: 0x005378A0 +static int32_t Script_BNIsSelf(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return 0; + } + + if (!lua_isnumber(L, 1)) { + luaL_error(L, "Usage: BNIsSelf(presenceID)"); + } + + lua_pushboolean(L, BattlenetAPI::IsSelf(static_cast(lua_tonumber(L, 1)))); + return 1; +} + +// VERIFY: 216d7baa auto +// OFFSET: 0x00537950 +static int32_t Script_BNIsFriend(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return 0; + } + + if (!lua_isnumber(L, 1)) { + luaL_error(L, "Usage: BNIsFriend(presenceID)"); + } + + lua_pushboolean(L, BattlenetAPI::HasRIDFriendship(static_cast(lua_tonumber(L, 1)))); + return 1; +} + // VERIFY: 2e29ab78 auto // OFFSET: 0x00537A00 static int32_t Script_BNGetMaxPlayersInConversation(lua_State* L) { @@ -72,69 +1342,302 @@ static int32_t Script_BNGetMaxPlayersInConversation(lua_State* L) { return 1; } -// VERIFY: 423fdd2d manual -// OFFSET: 0x00536400 -static int32_t Script_BNGetNumBlocked(lua_State* L) { +// VERIFY: ea8efcda manual +// OFFSET: 0x00539BF0 +static int32_t Script_BNGetFriendInfo(lua_State* L) { Login* login = ClientServices::LoginConnection(); if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { - lua_pushnumber(L, 0.0); - return 1; + return 0; } - if (!BattlenetUI_IsAvailable()) { - lua_pushnumber(L, 0.0); - DebugLog("BNUI: Num Blocked is 0. NOT CONNECTED"); - return 1; + if (!lua_isnumber(L, 1)) { + luaL_error(L, "Usage: BNGetFriendInfo(index)"); } - BattlenetBlockList blockList = BattlenetAPI::GetBlockList(); - lua_pushnumber(L, blockList.m_blockedCount); - DebugLog("BNUI: Num Blocked is %d", blockList.m_blockedCount); - return 1; + if (!BattlenetUI::m_friendListLoaded) { + return 0; + } + + double index = lua_tonumber(L, 1); + + if (index - 1 >= BattlenetUI::m_friends.m_count) { + luaL_error(L, "Friend index %d too large, only %d friends.", index, BattlenetUI::m_friends.m_count); + } + + return BattlenetUI::BNGetFriendInfoHelper(L, static_cast(index - 1)); } -// VERIFY: 6fff9574 manual -// OFFSET: 0x00536890 -static int32_t Script_BNGetNumBlockedToons(lua_State* L) { +// VERIFY: 9d2f21a7 auto +// OFFSET: 0x00539CC0 +static int32_t Script_BNGetFriendInfoByID(lua_State* L) { Login* login = ClientServices::LoginConnection(); if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { - lua_pushnumber(L, 0.0); - return 1; + return 0; + } + + if (!lua_isnumber(L, 1)) { + luaL_error(L, "Usage: BNGetFriendInfoByID(ID)"); + } + + int32_t index; + + if (BattlenetUI::m_friendListLoaded && (index = BattlenetUI::FindFriendIndex(static_cast(lua_tonumber(L, 1)))) >= 0) { + return BattlenetUI::BNGetFriendInfoHelper(L, index); + } + + return 0; +} + +// VERIFY: e2c4f578 manual +// OFFSET: 0x00539D70 +static int32_t Script_BNGetFriendToonInfo(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return 0; + } + + if (!lua_isnumber(L, 1) || !lua_isnumber(L, 2)) { + luaL_error(L, "Usage: BNGetToonInfo(friendIndex,toonIndex)"); + } + + if (!BattlenetUI::m_friendListLoaded) { + return 0; + } + + uint32_t friendIndex = static_cast(lua_tonumber(L, 1) - 1); + double toonNumber = lua_tonumber(L, 2); + uint32_t toonIndex = static_cast(toonNumber - 1); + + if (friendIndex >= BattlenetUI::m_friends.m_count) { + luaL_error(L, "Friend index %d too large, only %d friends.", friendIndex + 1, BattlenetUI::m_friends.m_count); + } + + uint32_t presenceId = BattlenetUI::m_friends[friendIndex].m_presenceID; + uint32_t numToons = BattlenetAPI::GetNumToons(presenceId); + + if (toonIndex >= numToons) { + luaL_error(L, "Toon index %d too large, only %d toons.", toonNumber, numToons); + } + + uint32_t i; + uint32_t online = 0; + + for (i = 0; i < numToons; i++) { + Battlenet::Presence::FieldVal value = BattlenetAPI::GetPresenceValue(BattlenetAPI::GetToon(presenceId, i), BattlenetUI::s_presenceCallbacks[BN_PRESENCE_ONLINE].m_field); + + if (value.m_tag == 1 && value.Get<1, bool>()) { + if (online == toonIndex) { + break; + } + + online++; + } + } + + if (i >= numToons) { + luaL_error(L, "Couldn't find a toon at friend index %d, online toon index %d", friendIndex + 1, i + 1); + } + + uint32_t toon = BattlenetAPI::GetToon(presenceId, i); + + if (!toon) { + luaL_error(L, "Couldn't find a toon at friend index %d, toon index %d, online toon index %d", friendIndex + 1, i + 1, toonNumber - 1); + } + + return BattlenetUI::BNGetToonInfoHelper(L, toon); +} + +// VERIFY: 0ae9bf15 auto +// OFFSET: 0x00539F90 +static int32_t Script_BNGetToonInfo(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return 0; + } + + if (!lua_isnumber(L, 1)) { + luaL_error(L, "Usage: BNGetToonInfo(ID)"); + } + + return BattlenetUI::BNGetToonInfoHelper(L, static_cast(lua_tonumber(L, 1))); +} + +// VERIFY: 06b242a0 auto +// OFFSET: 0x0053A030 +static int32_t Script_BNSendWhisper(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (login && login->GetLoginServerType() == 1 && !login->IsTrialAccount() && BattlenetAPI::IsRIDEnabled()) { + if (!lua_isnumber(L, 1) || !lua_isstring(L, 2)) { + luaL_error(L, "Usage: BNSendWhisper(id,text)"); + } + + if (BattlenetUI_IsAvailable()) { + double presenceId = lua_tonumber(L, 1); + const char* text = lua_tolstring(L, 2, nullptr); + char message[1024]; + FilterChatLinks(text, message, 1021); + + Battlenet::Presence::FieldVal toon = BattlenetAPI::GetPresenceValue(static_cast(presenceId), BattlenetUI::s_presenceCallbacks[BN_PRESENCE_TOON_NAME].m_field); + + if (toon.m_tag == 17) { + BattlenetAPI::SendChatWhisper(static_cast(presenceId), message); + return 0; + } + + BattlenetUI::DisplayError(318, static_cast(presenceId)); + } + } + + return 0; +} + +// VERIFY: 2daf6f26 manual +// OFFSET: 0x0053A150 +static int32_t Script_BNGetConversationMemberInfo(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return 0; + } + + if (!lua_isnumber(L, 1) || !lua_isnumber(L, 2)) { + luaL_error(L, "Usage: BNGetConversationMemberInfo(channel,index)"); } if (!BattlenetUI_IsAvailable()) { - lua_pushnumber(L, 0.0); - DebugLog("BNUI: Num Blocked toons is 0. NOT CONNECTED"); - return 1; + return 0; } - BattlenetBlockList blockList = BattlenetAPI::GetBlockList(); - lua_pushnumber(L, blockList.m_blockedToonCount); - DebugLog("BNUI: Num Blocked toons is %d", blockList.m_blockedToonCount); - return 1; + uint8_t channel = static_cast(lua_tonumber(L, 1) - 1.0); + double indexNumber = lua_tonumber(L, 2); + uint32_t index = static_cast(indexNumber - 1); + + if (channel >= 6) { + luaL_error(L, "Invalid Channel"); + } + + Battlenet::Chat::MemberList members = BattlenetAPI::GetChatMemberList(channel); + + if (index >= members.m_members.m_count) { + luaL_error(L, "Invalid Index"); + } + + lua_pushnumber(L, BattlenetAPI::GetAccountPresenceId(members.m_members[static_cast(indexNumber - 1)])); + lua_pushnumber(L, members.m_members[index]); + + const char* name = BattlenetUI::GetNameForPresenceIdHelper(members.m_members[index]); + lua_pushstring(L, name); + DebugLog("BNUI: ConversationMemberInfo name: %s", name); + + return 3; } -// VERIFY: 26d1ff36 manual -// OFFSET: 0x00535080 -static int32_t Script_BNGetNumFriendInvites(lua_State* L) { +// VERIFY: 4f7df3a4 manual +// OFFSET: 0x0053A300 +static int32_t Script_BNListConversation(lua_State* L) { Login* login = ClientServices::LoginConnection(); - if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled() || !BattlenetUI::m_friendInvites) { - lua_pushnumber(L, 0.0); - return 1; + if (login && login->GetLoginServerType() == 1 && !login->IsTrialAccount() && BattlenetAPI::IsRIDEnabled()) { + if (!lua_isnumber(L, 1)) { + luaL_error(L, "Usage: BNListConversation(channel)"); + } + + double channelNumber = lua_tonumber(L, 1) - 1.0; + uint8_t channel = static_cast(channelNumber); + + if (BattlenetAPI::GetChatChannelType(channel) == 2) { + Battlenet::Chat::MemberList members = BattlenetAPI::GetChatMemberList(static_cast(channelNumber)); + + ChatConversation conversation; + conversation.m_presenceID = BattlenetAPI::GetPresenceIDForCurrentAccount(); + conversation.m_index = channel; + conversation.m_inactive = 0; + + const char* delimiter = FrameScript_GetText("PLAYER_LIST_DELIMITER", -1, GENDER_NOT_APPLICABLE); + uint32_t delimiterLength = SStrLen(delimiter); + char text[256]; + bool started = false; + + for (uint32_t i = 0; i < members.m_members.m_count; i++) { + if (started) { + const char* name = BattlenetUI::GetNameForPresenceIdHelper(members.m_members.m_data[i]); + + if (SStrLen(name) + delimiterLength + SStrLen(text) < 256) { + SStrPrintf(text, sizeof(text), "%s%s%s", text, delimiter, name); + } else { + CGChat::AddChatMessage(text, CHAT_MSG_BN_CONVERSATION_LIST, nullptr, 0, nullptr, nullptr, nullptr, WOWGUID(), 0, WOWGUID(), 0, false, &conversation); + text[0] = '\0'; + SStrCopyUTF8(text, name, sizeof(text), sizeof(text)); + } + } else { + SStrCopyUTF8(text, BattlenetUI::GetNameForPresenceIdHelper(members.m_members.m_data[i]), sizeof(text), sizeof(text)); + started = true; + } + } + + if (started) { + CGChat::AddChatMessage(text, CHAT_MSG_BN_CONVERSATION_LIST, nullptr, 0, nullptr, nullptr, nullptr, WOWGUID(), 0, WOWGUID(), 0, false, &conversation); + } + } } - if (BattlenetUI_IsAvailable()) { - uint32_t count = BattlenetUI::m_friendInvites->m_count; - lua_pushnumber(L, count); - DebugLog("BNUI: Num friend invites: %d", count); - } else { - lua_pushnumber(L, 0.0); - DebugLog("BNUI: Num friend invites: 0, NOT CONNNECTED"); + return 0; +} + +// VERIFY: 02e4cc86 manual +// OFFSET: 0x0053A540 +static int32_t Script_BNGetBlockedInfo(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return 0; } + if (!lua_isnumber(L, 1)) { + luaL_error(L, "Usage: BNGetBlockedInfo(index)"); + } + + Battlenet::Presence::BlockList blockList = BattlenetAPI::GetBlockList(); + uint32_t index = static_cast(lua_tonumber(L, 1) - 1.0); + + if (index >= blockList.m_accounts.m_count) { + luaL_error(L, "Invalid Index"); + } + + uint32_t presenceId = blockList.m_accounts.m_data[index]; + lua_pushnumber(L, presenceId); + + const char* name = BattlenetUI::GetNameForPresenceIdHelper(presenceId); + lua_pushstring(L, name); + DebugLog("BNUI: Blocked info. index %d, ID %u, name: %s", index + 1, presenceId, name); + + return 2; +} + +// VERIFY: c59a8d80 auto +// OFFSET: 0x0053A660 +static int32_t Script_BNRequestFOFInfo(lua_State* L) { + Login* login = ClientServices::LoginConnection(); + + if (!login || login->GetLoginServerType() != 1 || login->IsTrialAccount() || !BattlenetAPI::IsRIDEnabled()) { + return 0; + } + + if (!lua_isnumber(L, 1)) { + luaL_error(L, "Usage: BNRequestFOF(ID)"); + } + + double presenceId = lua_tonumber(L, 1); + uint16_t error = BattlenetAPI::GetFriendsOfFriend(static_cast(presenceId), BattlenetUI::s_friendsOfFriendCB); + lua_pushboolean(L, error == 0); + BattlenetUI::DisplayError(error, static_cast(presenceId)); + DebugLog("BNUI: Sending Request for FOF for ID %d %s", static_cast(presenceId), error ? "failed" : "succeeded"); + return 1; } @@ -199,6 +1702,7 @@ static FrameScript_Method s_ScriptFunctions[] = { { "BNGetMaxPlayersInConversation", &Script_BNGetMaxPlayersInConversation }, }; +// VERIFY: e50e8083 auto // OFFSET: 0x00530F60 void BattlenetUI_RegisterScriptFunctions() { for (uint32_t i = 0; i < sizeof(s_ScriptFunctions) / sizeof(s_ScriptFunctions[0]); i++) { diff --git a/WoW/Source/Ui/CAccountMsgHeaders_Scripts.cpp b/WoW/Source/Ui/CAccountMsgHeaders_Scripts.cpp index 7a3686f..b46e9d8 100644 --- a/WoW/Source/Ui/CAccountMsgHeaders_Scripts.cpp +++ b/WoW/Source/Ui/CAccountMsgHeaders_Scripts.cpp @@ -6,7 +6,7 @@ #include "Engine/Source/lua-5.1/src/lauxlib.h" #include "WoW/Source/Ui/CAccountMsgBody.h" -// VERIFY: cd4edb0d auto +// VERIFY: 1ee4db68 auto // OFFSET: 0x0054FDE0 static int32_t Script_AccountMsg_GetNumTotalMsgs(lua_State* L) { if (g_accountMsgHeaders.m_state != 2) { @@ -18,7 +18,7 @@ static int32_t Script_AccountMsg_GetNumTotalMsgs(lua_State* L) { return 1; } -// VERIFY: 330f3fb3 manual +// VERIFY: 8e6492ed auto // OFFSET: 0x0054FE20 static int32_t Script_AccountMsg_GetHeaderSubject(lua_State* L) { if (g_accountMsgHeaders.m_state != 2) { @@ -42,7 +42,7 @@ static int32_t Script_AccountMsg_GetHeaderSubject(lua_State* L) { return 1; } -// VERIFY: 88802a6a manual +// VERIFY: e42cdc6e auto // OFFSET: 0x0054FEC0 static int32_t Script_AccountMsg_GetHeaderPriority(lua_State* L) { if (g_accountMsgHeaders.m_state != 2) { @@ -66,7 +66,7 @@ static int32_t Script_AccountMsg_GetHeaderPriority(lua_State* L) { return 1; } -// VERIFY: b96bccdb manual +// VERIFY: 8d652036 auto // OFFSET: 0x0054FF70 static int32_t Script_AccountMsg_LoadBody(lua_State* L) { if (g_accountMsgHeaders.m_state != 2) { @@ -94,7 +94,7 @@ static int32_t Script_AccountMsg_LoadBody(lua_State* L) { return 0; } -// VERIFY: c39284fd auto +// VERIFY: 7f42e21d auto // OFFSET: 0x00550020 static int32_t Script_AccountMsg_GetBody(lua_State* L) { if (g_accountMsgBody.m_state != 2) { @@ -110,7 +110,7 @@ static int32_t Script_AccountMsg_GetBody(lua_State* L) { return 1; } -// VERIFY: e5cebb94 auto +// VERIFY: 0b82481a auto // OFFSET: 0x00550360 static int32_t Script_AccountMsg_GetNumUnreadMsgs(lua_State* L) { if (g_accountMsgHeaders.m_state != 2) { @@ -130,7 +130,7 @@ static int32_t Script_AccountMsg_GetNumUnreadMsgs(lua_State* L) { return 1; } -// VERIFY: 98c3b05b auto +// VERIFY: fd796aeb auto // OFFSET: 0x005503E0 static int32_t Script_AccountMsg_GetNumUnreadUrgentMsgs(lua_State* L) { if (g_accountMsgHeaders.m_state != 2) { @@ -156,7 +156,7 @@ static int32_t Script_AccountMsg_GetIndexHighestPriorityUnreadMsg(lua_State* L) return 2; } -// VERIFY: 672f6b27 manual +// VERIFY: 13b3d088 auto // OFFSET: 0x005504E0 static int32_t Script_AccountMsg_GetIndexNextUnreadMsg(lua_State* L) { if (g_accountMsgHeaders.m_state != 2) { @@ -176,7 +176,7 @@ static int32_t Script_AccountMsg_GetIndexNextUnreadMsg(lua_State* L) { return 2; } -// VERIFY: d1327cbd auto +// VERIFY: 99c56524 auto // OFFSET: 0x005505B0 static int32_t Script_AccountMsg_SetMsgRead(lua_State* L) { if (g_accountMsgHeaders.m_state != 2) { @@ -204,7 +204,7 @@ static int32_t Script_AccountMsg_SetMsgRead(lua_State* L) { return 0; } -// VERIFY: e72580a8 auto +// VERIFY: 74473c23 auto // OFFSET: 0x00550910 static int32_t Script_AccountMsg_LoadHeaders(lua_State* L) { if (!g_accountMsgHeaders.LoadHeaders()) { diff --git a/WoW/Source/Ui/CGAutoCompleteName.cpp b/WoW/Source/Ui/CGAutoCompleteName.cpp index ebb0317..ba7b793 100644 --- a/WoW/Source/Ui/CGAutoCompleteName.cpp +++ b/WoW/Source/Ui/CGAutoCompleteName.cpp @@ -410,3 +410,19 @@ AUTOCOMPLETE_NAMENODE* CGAutoCompleteName::AddPlayerToList(const uint32_t& prese SortNameNode(node); return node; } + +// VERIFY: c8754f81 auto +// OFFSET: 0x0057B840 +int32_t CGAutoCompleteName::AddFlags(const uint32_t& presenceId, uint32_t flags, int32_t add, const char* name) { + if (!presenceId) { + SErrDisplayAppFatalMessage("", "", 0); + } + + AUTOCOMPLETE_NAMENODE* node = FindNodeByPresenceId(presenceId); + + if (node) { + return ApplyNodeFlags(node, flags, add, name); + } + + return CGAutoCompleteName::AddPlayerToList(presenceId, flags, add ? FrameTime::s_curTimeMs : 0, name) != nullptr; +} diff --git a/WoW/Source/Ui/CGAutoCompleteName.h b/WoW/Source/Ui/CGAutoCompleteName.h index f4f7b45..ece17a2 100644 --- a/WoW/Source/Ui/CGAutoCompleteName.h +++ b/WoW/Source/Ui/CGAutoCompleteName.h @@ -27,6 +27,7 @@ class CGAutoCompleteName { static void ResortAll(); static int32_t GetPresenceID(const char* name, uint32_t* presenceId); static void AddFlags(const WOWGUID& guid, uint32_t flags, int32_t add, const char* name); + static int32_t AddFlags(const uint32_t& presenceId, uint32_t flags, int32_t add, const char* name); static int32_t RemoveFlags(const WOWGUID& guid, uint32_t flags); static int32_t RemoveFlags(const uint32_t& presenceId, uint32_t flags); static int32_t SetName(const uint32_t& presenceId, const char* name, bool overwrite); diff --git a/WoW/Source/Ui/CGAutoCompleteName_Scripts.cpp b/WoW/Source/Ui/CGAutoCompleteName_Scripts.cpp index 8263e3d..3cc2f32 100644 --- a/WoW/Source/Ui/CGAutoCompleteName_Scripts.cpp +++ b/WoW/Source/Ui/CGAutoCompleteName_Scripts.cpp @@ -3,7 +3,7 @@ #include "Engine/Source/FrameScript/FrameScript.h" #include "Engine/Source/FrameScript/FrameScript_Object.h" -// VERIFY: 7c75006a manual +// VERIFY: c189cafe auto // OFFSET: 0x0057B3A0 static int32_t Script_GetAutoCompleteResults(lua_State* L) { if (!lua_isstring(L, 1) || !lua_isnumber(L, 2) || !lua_isnumber(L, 3) || !lua_isnumber(L, 4)) { @@ -25,7 +25,7 @@ static int32_t Script_GetAutoCompleteResults(lua_State* L) { return CGAutoCompleteName::GetMatchingResults(L, text, include, exclude, numReturns, cursor, allowFullMatch); } -// VERIFY: 64d68b75 manual +// VERIFY: 6b80b8e7 auto // OFFSET: 0x0057B500 static int32_t Script_GetAutoCompletePresenceID(lua_State* L) { if (!lua_isstring(L, 1)) { diff --git a/WoW/Source/Ui/CGLookingForGroup.cpp b/WoW/Source/Ui/CGLookingForGroup.cpp index f62dc97..aa2d241 100644 --- a/WoW/Source/Ui/CGLookingForGroup.cpp +++ b/WoW/Source/Ui/CGLookingForGroup.cpp @@ -134,7 +134,7 @@ int32_t CGLookingForGroup::GetLFGRoleUpdate(lua_State* L) { return 3; } -// VERIFY: b42e78a8 auto +// VERIFY: 5c5209c5 auto // OFFSET: 0x00554690 int32_t CGLookingForGroup::GetLFGRoleUpdateSlot(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -275,7 +275,7 @@ int32_t CGLookingForGroup::GetLFGProposalMember(lua_State* L) { return 7; } -// VERIFY: 668d01fe manual +// VERIFY: 71caab52 auto // OFFSET: 0x00554380 int32_t CGLookingForGroup::GetLFGProposalEncounter(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -334,7 +334,7 @@ void CGLookingForGroup::ProposalResponse(bool accept) { FrameScript_SignalEvent(SCRIPT_EVENT_LFG_PROPOSAL_UPDATE, nullptr); } -// VERIFY: 85c9492d manual +// VERIFY: cb5ab203 auto // OFFSET: 0x00554750 int32_t CGLookingForGroup::GetLFGRoleUpdateMember(lua_State* L) { if (!lua_isnumber(L, 1)) { diff --git a/WoW/Source/Ui/CGMinigameInfo_Scripts.cpp b/WoW/Source/Ui/CGMinigameInfo_Scripts.cpp index 0de1124..d901e99 100644 --- a/WoW/Source/Ui/CGMinigameInfo_Scripts.cpp +++ b/WoW/Source/Ui/CGMinigameInfo_Scripts.cpp @@ -24,7 +24,7 @@ static int32_t Script_GetMinigameType(lua_State* L) { return 1; } -// VERIFY: e1b0959d manual +// VERIFY: 37b2ca9a auto // OFFSET: 0x005C5550 static int32_t Script_MakeMinigameMove(lua_State* L) { if (!lua_isnumber(L, 1) || !lua_isnumber(L, 2)) { diff --git a/WoW/Source/Ui/Calendar_Scripts.cpp b/WoW/Source/Ui/Calendar_Scripts.cpp index f0e9b8b..b748a6f 100644 --- a/WoW/Source/Ui/Calendar_Scripts.cpp +++ b/WoW/Source/Ui/Calendar_Scripts.cpp @@ -277,7 +277,7 @@ static int32_t Script_CalendarCanSendInvite(lua_State* L) { return 1; } -// VERIFY: 3aba7d21 auto +// VERIFY: 76d1ef9d auto // OFFSET: 0x005BCC00 static int32_t Script_CalendarSetMonth(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -305,7 +305,7 @@ static int32_t Script_CalendarGetNumDayEvents(lua_State* L) { return 1; } -// VERIFY: 7681b03c manual +// VERIFY: 52f86bfc auto // OFFSET: 0x005B9E10 static int32_t Script_CalendarGetFirstPendingInvite(lua_State* L) { if (!lua_isnumber(L, 1) || !lua_isnumber(L, 2)) { @@ -426,7 +426,7 @@ static int32_t Script_CalendarContextEventClipboard(lua_State* L) { return 1; } -// VERIFY: 90ff2325 auto +// VERIFY: ff6674b8 auto // OFFSET: 0x005B8570 static int32_t Script_CalendarEventSortInvites(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -516,7 +516,7 @@ static int32_t Script_CalendarEventSetStatus(lua_State* L) { return 0; } -// VERIFY: 38960e82 manual +// VERIFY: 38509d1b auto // OFFSET: 0x005B87D0 static int32_t Script_CalendarEventSetModerator(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -528,7 +528,7 @@ static int32_t Script_CalendarEventSetModerator(lua_State* L) { return 0; } -// VERIFY: d5897814 manual +// VERIFY: 7005f67e auto // OFFSET: 0x005B8840 static int32_t Script_CalendarEventClearModerator(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -547,7 +547,7 @@ static int32_t Script_CalendarEventIsModerator(lua_State* L) { return 1; } -// VERIFY: a67e5434 manual +// VERIFY: bbcdba11 auto // OFFSET: 0x005B88E0 static int32_t Script_CalendarEventCanModerate(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -597,7 +597,7 @@ static int32_t Script_CalendarEventGetCalendarType(lua_State* L) { return 1; } -// VERIFY: 744ac9ad auto +// VERIFY: 60d41a94 auto // OFFSET: 0x005B8AE0 static int32_t Script_CalendarEventSelectInvite(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -1106,7 +1106,7 @@ static int32_t Script_CalendarContextEventGetCalendarType(lua_State* L) { return 1; } -// VERIFY: 3aacaae6 manual +// VERIFY: 1f224d8d auto // OFFSET: 0x005BB0C0 static int32_t Script_CalendarEventRemoveInvite(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -1118,7 +1118,7 @@ static int32_t Script_CalendarEventRemoveInvite(lua_State* L) { return 0; } -// VERIFY: 07c234f3 manual +// VERIFY: 3dbff87f auto // OFFSET: 0x005BB130 static int32_t Script_CalendarEventGetStatusOptions(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -1295,7 +1295,7 @@ static int32_t Script_CalendarEventSetDate(lua_State* L) { return 0; } -// VERIFY: 04c6caa7 manual +// VERIFY: c38beb47 auto // OFFSET: 0x005BB5A0 static int32_t Script_CalendarEventSetTime(lua_State* L) { if (!lua_isnumber(L, 1) || !lua_isnumber(L, 2)) { @@ -1332,7 +1332,7 @@ static int32_t Script_CalendarEventSetLockoutDate(lua_State* L) { return 0; } -// VERIFY: a04a738e manual +// VERIFY: 72d0c4f8 auto // OFFSET: 0x005BB750 static int32_t Script_CalendarEventSetLockoutTime(lua_State* L) { if (!lua_isnumber(L, 1) || !lua_isnumber(L, 2)) { @@ -1350,7 +1350,7 @@ static int32_t Script_CalendarEventSetLockoutTime(lua_State* L) { return 0; } -// VERIFY: c559f66b manual +// VERIFY: 87bf79dd auto // OFFSET: 0x005BB800 static int32_t Script_CalendarEventSetTextureID(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -1520,7 +1520,7 @@ static int32_t Script_CalendarNewEvent(lua_State* L) { return 0; } -// VERIFY: fe8e8f86 manual +// VERIFY: d26ce326 auto // OFFSET: 0x005BCCB0 static int32_t Script_CalendarMassInviteGuild(lua_State* L) { if (!lua_isnumber(L, 1) && !lua_isnumber(L, 2) && !lua_isnumber(L, 3)) { @@ -1549,7 +1549,7 @@ static int32_t Script_CalendarNewGuildEvent(lua_State* L) { return 0; } -// VERIFY: 9b89693d manual +// VERIFY: cfd24fb4 auto // OFFSET: 0x005BCE60 static int32_t Script_CalendarMassInviteArenaTeam(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -1743,7 +1743,7 @@ static int32_t Script_CalendarContextEventCopy(lua_State* L) { return 0; } -// VERIFY: dd49574d manual +// VERIFY: 69d55813 auto // OFFSET: 0x005BD460 static int32_t Script_CalendarContextEventPaste(lua_State* L) { if (!lua_isnumber(L, 1) || !lua_isnumber(L, 2)) { diff --git a/WoW/Source/Ui/CharacterModelBase_Scripts.cpp b/WoW/Source/Ui/CharacterModelBase_Scripts.cpp index b5eed80..f89a059 100644 --- a/WoW/Source/Ui/CharacterModelBase_Scripts.cpp +++ b/WoW/Source/Ui/CharacterModelBase_Scripts.cpp @@ -60,7 +60,7 @@ static int32_t Script_SetRotation(lua_State* L) { return 0; } -// VERIFY: 4d143b0a auto +// VERIFY: a7b1e08a auto // OFFSET: 0x005978E0 static int32_t Script_ModelSetUnit(lua_State* L) { CGCharacterModelBase* model = static_cast(FrameScript_GetObjectThis(L, CGCharacterModelBase::GetObjectType())); diff --git a/WoW/Source/Ui/ChatFrame_Scripts.cpp b/WoW/Source/Ui/ChatFrame_Scripts.cpp index 5de2220..1a1754a 100644 --- a/WoW/Source/Ui/ChatFrame_Scripts.cpp +++ b/WoW/Source/Ui/ChatFrame_Scripts.cpp @@ -298,7 +298,7 @@ static int32_t Script_GetActiveVoiceChannel(lua_State* L) { return 1; } -// VERIFY: 96240761 auto +// VERIFY: 4dce6d52 auto // OFFSET: 0x0050D8A0 static int32_t Script_SendSystemMessage(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -662,7 +662,7 @@ static int32_t Script_GetNumLanguages(lua_State* L) { return 1; } -// VERIFY: 11a2c976 manual +// VERIFY: 4f0456ed auto // OFFSET: 0x00500810 static int32_t Script_GetLanguageByIndex(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -916,7 +916,7 @@ static int32_t Script_SendAddonMessage(lua_State* L) { return 0; } -// VERIFY: 66ca7532 manual +// VERIFY: 0487e16e auto // OFFSET: 0x004FEAF0 static int32_t Script_ChangeChatColor(lua_State* L) { if (!lua_isstring(L, 1) || !lua_isnumber(L, 2) || !lua_isnumber(L, 3) || !lua_isnumber(L, 4)) { @@ -957,7 +957,7 @@ static int32_t Script_ChangeChatColor(lua_State* L) { return 0; } -// VERIFY: d5186565 auto +// VERIFY: 9136ba27 auto // OFFSET: 0x004FEDC0 static int32_t Script_SetChatColorNameByClass(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -1916,7 +1916,7 @@ static int32_t Script_SetChannelWatch(lua_State* L) { return 0; } -// VERIFY: 5e2650e5 manual +// VERIFY: 4d3fdf6e auto // OFFSET: 0x00500980 static int32_t Script_DoEmote(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -1999,7 +1999,7 @@ static int32_t Script_SetActiveVoiceChannel(lua_State* L) { return 0; } -// VERIFY: 6cc353e2 manual +// VERIFY: 9e73392f auto // OFFSET: 0x00500C80 static int32_t Script_CanComplainChat(lua_State* L) { const char* text = nullptr; diff --git a/WoW/Source/Ui/ClassTrainerFrame_Scripts.cpp b/WoW/Source/Ui/ClassTrainerFrame_Scripts.cpp index 92d21db..d427b13 100644 --- a/WoW/Source/Ui/ClassTrainerFrame_Scripts.cpp +++ b/WoW/Source/Ui/ClassTrainerFrame_Scripts.cpp @@ -298,7 +298,7 @@ static int32_t GetServiceTypeFromString(const char* type) { return SStrCmpI(type, "used", STORM_MAX_STR) ? 6 : 2; } -// VERIFY: 7d28716c auto +// VERIFY: e17cbd49 auto // OFFSET: 0x00593E10 static int32_t Script_GetTrainerServiceTypeFilter(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -377,7 +377,7 @@ static int32_t Script_GetTrainerServiceInfo(lua_State* L) { return 4; } -// VERIFY: 88ad0cad auto +// VERIFY: 287a55ea auto // OFFSET: 0x00595150 static int32_t Script_GetTrainerServiceIcon(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -584,7 +584,7 @@ static int32_t Script_GetTrainerServiceStepReq(lua_State* L) { return 2; } -// VERIFY: 4ae435f2 auto +// VERIFY: 98de4b57 auto // OFFSET: 0x005959D0 static int32_t Script_GetTrainerServiceDescription(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -623,7 +623,7 @@ static int32_t Script_GetTrainerServiceDescription(lua_State* L) { return 1; } -// VERIFY: acea8d8f auto +// VERIFY: 7d343579 auto // OFFSET: 0x00595C40 static int32_t Script_GetTrainerServiceStepIncrease(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -687,7 +687,7 @@ static int32_t Script_GetTrainerServiceStepIncrease(lua_State* L) { return 1; } -// VERIFY: 6c487cf5 auto +// VERIFY: f83e44a1 auto // OFFSET: 0x00595E60 static int32_t Script_BuyTrainerService(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -706,7 +706,7 @@ static int32_t Script_BuyTrainerService(lua_State* L) { return 0; } -// VERIFY: 5c54d48d auto +// VERIFY: 71ea3b5a auto // OFFSET: 0x00595EC0 static int32_t Script_SetTrainerServiceTypeFilter(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -751,7 +751,7 @@ static int32_t Script_SetTrainerServiceTypeFilter(lua_State* L) { return 0; } -// VERIFY: df5499a8 auto +// VERIFY: cb7d0499 auto // OFFSET: 0x00596010 static int32_t Script_SetTrainerSkillLineFilter(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -794,7 +794,7 @@ static int32_t Script_SetTrainerSkillLineFilter(lua_State* L) { return 0; } -// VERIFY: a1db1e56 manual +// VERIFY: 05a5d0f5 auto // OFFSET: 0x00596150 static int32_t Script_CollapseTrainerSkillLine(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -822,7 +822,7 @@ static int32_t Script_CollapseTrainerSkillLine(lua_State* L) { return 0; } -// VERIFY: dd5c37a8 manual +// VERIFY: 9515160f auto // OFFSET: 0x005961F0 static int32_t Script_ExpandTrainerSkillLine(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -850,7 +850,7 @@ static int32_t Script_ExpandTrainerSkillLine(lua_State* L) { return 0; } -// VERIFY: ff27bb2a auto +// VERIFY: 34d380d3 auto // OFFSET: 0x00596290 static int32_t Script_GetTrainerServiceItemLink(lua_State* L) { if (!lua_isnumber(L, 1)) { diff --git a/WoW/Source/Ui/CommentatorFrame_Scripts.cpp b/WoW/Source/Ui/CommentatorFrame_Scripts.cpp index 46ecd27..b2c2383 100644 --- a/WoW/Source/Ui/CommentatorFrame_Scripts.cpp +++ b/WoW/Source/Ui/CommentatorFrame_Scripts.cpp @@ -682,7 +682,7 @@ static int32_t Script_CommentatorSetPlayerIndex(lua_State* L) { return 0; } -// VERIFY: 17a87bbc manual +// VERIFY: 824e9e46 auto // OFFSET: 0x0056A0F0 static int32_t Script_CommentatorSetCamera(lua_State* L) { CGPlayer_C* player = ClntObjMgrGetActivePlayerObj(); @@ -903,7 +903,7 @@ static int32_t Script_CommentatorRemovePlayer(lua_State* L) { return 0; } -// VERIFY: bc9088b3 manual +// VERIFY: 5a4b445c auto // OFFSET: 0x0056AAF0 static int32_t Script_CommentatorSetMoveSpeed(lua_State* L) { CGPlayer_C* player = ClntObjMgrGetActivePlayerObj(); diff --git a/WoW/Source/Ui/ContainerFrame_Scripts.cpp b/WoW/Source/Ui/ContainerFrame_Scripts.cpp index 7a91d38..c459d49 100644 --- a/WoW/Source/Ui/ContainerFrame_Scripts.cpp +++ b/WoW/Source/Ui/ContainerFrame_Scripts.cpp @@ -141,7 +141,7 @@ static int32_t Script_GetContainerNumSlots(lua_State* L) { return 1; } -// VERIFY: 27e4a857 manual +// VERIFY: 5491be82 auto // OFFSET: 0x005D8C70 static int32_t Script_GetBagName(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -575,7 +575,7 @@ static int32_t Script_PickupContainerItem(lua_State* L) { return 0; } -// VERIFY: 5b61867b auto +// VERIFY: 6deefa52 auto // OFFSET: 0x005D8BD0 static int32_t Script_ShowContainerSellCursor(lua_State* L) { if (Spell_C_IsTargeting() || CursorGetResetMode() != 1) { @@ -748,7 +748,7 @@ static int32_t Script_GetContainerItemPurchaseInfo(lua_State* L) { return 5; } -// VERIFY: 4ee0a0e3 auto +// VERIFY: 7da8b539 auto // OFFSET: 0x005D7C80 static int32_t Script_GetContainerItemLink(lua_State* L) { if (!lua_isnumber(L, 1) || !lua_isnumber(L, 2)) { @@ -817,7 +817,7 @@ static int32_t Script_SplitContainerItem(lua_State* L) { return 0; } -// VERIFY: c5b09c6b manual +// VERIFY: 38975cf9 auto // OFFSET: 0x005D8B10 static int32_t Script_SocketContainerItem(lua_State* L) { if (!lua_isnumber(L, 1) || !lua_isnumber(L, 2)) { diff --git a/WoW/Source/Ui/EquipmentManager_Scripts.cpp b/WoW/Source/Ui/EquipmentManager_Scripts.cpp index c9ab442..625c604 100644 --- a/WoW/Source/Ui/EquipmentManager_Scripts.cpp +++ b/WoW/Source/Ui/EquipmentManager_Scripts.cpp @@ -74,7 +74,7 @@ static int32_t Script_EquipmentManagerClearIgnoredSlotsForSave(lua_State* L) { return 0; } -// VERIFY: 0108f898 auto +// VERIFY: 6bd6b519 auto // OFFSET: 0x005AE800 static int32_t Script_DeleteEquipmentSet(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -398,7 +398,7 @@ static int32_t Script_GetEquipmentSetInfo(lua_State* L) { return 3; } -// VERIFY: 54ba72eb auto +// VERIFY: 43db9cf0 auto // OFFSET: 0x005AF1D0 static int32_t Script_GetEquipmentSetInfoByName(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -423,7 +423,7 @@ static int32_t Script_GetEquipmentSetInfoByName(lua_State* L) { return 2; } -// VERIFY: 335b3aa0 auto +// VERIFY: 6bce95fb auto // OFFSET: 0x005AF250 static int32_t Script_PickupEquipmentSetByName(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -448,7 +448,7 @@ static int32_t Script_PickupEquipmentSetByName(lua_State* L) { return 0; } -// VERIFY: 36d3ed77 auto +// VERIFY: 178e5e18 auto // OFFSET: 0x005AF2C0 static int32_t Script_PickupEquipmentSet(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -465,7 +465,7 @@ static int32_t Script_PickupEquipmentSet(lua_State* L) { return 0; } -// VERIFY: 5046be9a auto +// VERIFY: 78933462 auto // OFFSET: 0x005AF320 static int32_t Script_EquipmentSetContainsLockedItems(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -483,7 +483,7 @@ static int32_t Script_EquipmentSetContainsLockedItems(lua_State* L) { return 1; } -// VERIFY: ccfc0a7a auto +// VERIFY: 14344e5d auto // OFFSET: 0x005AF380 static int32_t Script_UseEquipmentSet(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -506,7 +506,7 @@ static int32_t Script_UseEquipmentSet(lua_State* L) { return 1; } -// VERIFY: 59c68072 auto +// VERIFY: bc671bf0 auto // OFFSET: 0x005AF910 static int32_t Script_RenameEquipmentSet(lua_State* L) { if (!lua_isstring(L, 1) || !lua_isstring(L, 2)) { diff --git a/WoW/Source/Ui/GMTicketInfo_Scripts.cpp b/WoW/Source/Ui/GMTicketInfo_Scripts.cpp index 2b88276..fdc98d8 100644 --- a/WoW/Source/Ui/GMTicketInfo_Scripts.cpp +++ b/WoW/Source/Ui/GMTicketInfo_Scripts.cpp @@ -76,7 +76,7 @@ static int32_t Script_GMSurveyAnswerSubmit(lua_State* L) { return 0; } -// VERIFY: b32e91ff auto +// VERIFY: 8792c123 auto // OFFSET: 0x005AC480 static int32_t Script_GMSurveyCommentSubmit(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -148,7 +148,7 @@ static int32_t Script_GMSurveyNumAnswers(lua_State* L) { return 1; } -// VERIFY: 7e504c81 auto +// VERIFY: ebaa1e68 auto // OFFSET: 0x005AD020 static int32_t Script_GMReportLag(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -160,7 +160,7 @@ static int32_t Script_GMReportLag(lua_State* L) { return 0; } -// VERIFY: 38c345ae auto +// VERIFY: e36f68e8 auto // OFFSET: 0x005AD080 static int32_t Script_NewGMTicket(lua_State* L) { if (!lua_isstring(L, 1) || lua_type(L, 2) != LUA_TBOOLEAN) { @@ -176,7 +176,7 @@ static int32_t Script_NewGMTicket(lua_State* L) { return 0; } -// VERIFY: 079fb9f5 auto +// VERIFY: a547b787 auto // OFFSET: 0x005AD0F0 static int32_t Script_UpdateGMTicket(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -198,7 +198,7 @@ static int32_t Script_DeleteGMTicket(lua_State* L) { return 0; } -// VERIFY: 937085ce auto +// VERIFY: 438ebb53 auto // OFFSET: 0x005AD150 static int32_t Script_GMResponseNeedMoreHelp(lua_State* L) { if (!lua_isstring(L, 1)) { diff --git a/WoW/Source/Ui/GameUI.h b/WoW/Source/Ui/GameUI.h index bbfddec..6b4f2c9 100644 --- a/WoW/Source/Ui/GameUI.h +++ b/WoW/Source/Ui/GameUI.h @@ -46,6 +46,11 @@ extern CImVector s_deadSelectionColor; extern CVar* g_assistAttackCVar; extern CVar* g_questPOICVar; extern CVar* g_trackerSortingCVar; +extern CVar* s_cvShowToastFriendRequest; +extern CVar* s_cvShowToastOnline; +extern CVar* s_cvShowToastOffline; +extern CVar* s_cvShowToastBroadcast; +extern CVar* s_cvShowToastConversation; extern CVar* unk_BD09AC; extern CVar* s_cvCalendarShowWeeklyHolidays; extern CVar* s_cvCalendarShowDarkmoon; diff --git a/WoW/Source/Ui/GameUI_Scripts.cpp b/WoW/Source/Ui/GameUI_Scripts.cpp index a81f3dd..c45bd70 100644 --- a/WoW/Source/Ui/GameUI_Scripts.cpp +++ b/WoW/Source/Ui/GameUI_Scripts.cpp @@ -295,7 +295,7 @@ static int32_t Script_ClearCursor(lua_State* L) { return 1; } -// VERIFY: 55878a9c auto +// VERIFY: 82f766f4 auto // OFFSET: 0x005101D0 static int32_t Script_SetWaterDetail(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -1450,7 +1450,7 @@ static int32_t Script_GuildSetLeader(lua_State* L) { return 0; } -// VERIFY: 39b52d84 manual +// VERIFY: 5c44edc4 auto // OFFSET: 0x00516610 static int32_t Script_RandomRoll(lua_State* L) { if (!lua_isstring(L, 1) || !lua_isstring(L, 2)) { @@ -1569,7 +1569,7 @@ static int32_t Script_GetItemQualityColor(lua_State* L) { return 4; } -// VERIFY: fe358aee manual +// VERIFY: 37c22dd4 auto // OFFSET: 0x00511B30 static int32_t Script_IsAddOnLoaded(lua_State* L) { const char* name; @@ -2145,7 +2145,7 @@ static int32_t Script_InCombatLockdown(lua_State* L) { return 1; } -// VERIFY: e0877fd5 manual +// VERIFY: 5f4164d6 auto // OFFSET: 0x0051D520 static int32_t Script_DestroyTotem(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -2490,7 +2490,7 @@ static int32_t Script_Quit(lua_State* L) { return 0; } -// VERIFY: 5cc4abd6 manual +// VERIFY: 3003cf92 auto // OFFSET: 0x0052B470 static int32_t Script_RegisterForSave(lua_State* L) { if (lua_tainted) { @@ -2507,7 +2507,7 @@ static int32_t Script_RegisterForSave(lua_State* L) { return 0; } -// VERIFY: 6677c3e4 manual +// VERIFY: da056905 auto // OFFSET: 0x0052B4E0 static int32_t Script_RegisterForSavePerCharacter(lua_State* L) { if (lua_tainted) { @@ -3063,7 +3063,7 @@ static int32_t Script_SitStandOrDescendStart(lua_State* L) { return 0; } -// VERIFY: f1043ab0 auto +// VERIFY: f1cdd46e auto // OFFSET: 0x005104A0 static int32_t Script_SetCursor(lua_State* L) { struct CursorName { @@ -3342,7 +3342,7 @@ static int32_t Script_Stuck(lua_State* L) { return 0; } -// VERIFY: f9ef5104 auto +// VERIFY: cae879bb auto // OFFSET: 0x00510930 static int32_t Script_ReportBug(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -3354,7 +3354,7 @@ static int32_t Script_ReportBug(lua_State* L) { return 0; } -// VERIFY: 1ec66cba auto +// VERIFY: e60caf0c auto // OFFSET: 0x00510980 static int32_t Script_ReportSuggestion(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -3410,7 +3410,7 @@ static int32_t Script_GMRequestPlayerInfo(lua_State* L) { return 0; } -// VERIFY: 7e10166d manual +// VERIFY: 518f4cf8 auto // OFFSET: 0x00510BD0 static int32_t Script_GetCoinIcon(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -3424,7 +3424,7 @@ static int32_t Script_GetCoinIcon(lua_State* L) { return 1; } -// VERIFY: e702f5d5 manual +// VERIFY: aa5c7661 auto // OFFSET: 0x00510C60 static int32_t Script_GetCoinText(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -3439,7 +3439,7 @@ static int32_t Script_GetCoinText(lua_State* L) { return 1; } -// VERIFY: b069b86f manual +// VERIFY: 53695d34 auto // OFFSET: 0x00510D00 static int32_t Script_GetCoinTextureString(lua_State* L) { int32_t height = 14; @@ -3536,7 +3536,7 @@ static int32_t Script_IsEquippableItem(lua_State* L) { return 1; } -// VERIFY: 1374044d manual +// VERIFY: 5a794641 auto // OFFSET: 0x00511240 static int32_t Script_GetAddOnInfo(lua_State* L) { const char* name; @@ -3653,7 +3653,7 @@ static int32_t Script_GetAddOnMemoryUsage(lua_State* L) { return 1; } -// VERIFY: d46e6c3e manual +// VERIFY: b50f7eb0 auto // OFFSET: 0x00511660 static int32_t Script_GetAddOnCPUUsage(lua_State* L) { const char* name; @@ -3678,7 +3678,7 @@ static int32_t Script_GetAddOnCPUUsage(lua_State* L) { return 1; } -// VERIFY: 59c8d845 manual +// VERIFY: 8458713d auto // OFFSET: 0x00511840 static int32_t Script_EnableAddOn(lua_State* L) { const char* name; @@ -3713,7 +3713,7 @@ static int32_t Script_EnableAllAddOns(lua_State* L) { return 0; } -// VERIFY: fa157ed2 manual +// VERIFY: 194605d2 auto // OFFSET: 0x00511940 static int32_t Script_DisableAddOn(lua_State* L) { const char* name; @@ -3748,7 +3748,7 @@ static int32_t Script_DisableAllAddOns(lua_State* L) { return 0; } -// VERIFY: 53087d42 manual +// VERIFY: 7468a523 auto // OFFSET: 0x00511A60 static int32_t Script_IsAddOnLoadOnDemand(lua_State* L) { const char* name; @@ -3796,7 +3796,7 @@ static int32_t Script_VoicePushToTalkStop(lua_State* L) { return 0; } -// VERIFY: 047deaf6 auto +// VERIFY: abe09c5f auto // OFFSET: 0x00511DD0 static int32_t Script_GetNumDeclensionSets(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -3822,7 +3822,7 @@ static int32_t Script_GetNumDeclensionSets(lua_State* L) { return 1; } -// VERIFY: 4e597be3 auto +// VERIFY: 379e1c6d auto // OFFSET: 0x00511E80 static int32_t Script_DeclineName(lua_State* L) { if (!lua_isstring(L, 1) || !lua_isnumber(L, 3)) { @@ -4023,7 +4023,7 @@ static int32_t Script_GetInstanceLockTimeRemaining(lua_State* L) { return 4; } -// VERIFY: 82abf2b9 auto +// VERIFY: 4d5a4279 auto // OFFSET: 0x00516410 static int32_t Script_GetInstanceLockTimeRemainingEncounter(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -4357,7 +4357,7 @@ static int32_t Script_IsDressableItem(lua_State* L) { return 1; } -// VERIFY: d5679913 manual +// VERIFY: 39dd6870 auto // OFFSET: 0x00517890 static int32_t Script_GetFrameCPUUsage(lua_State* L) { if (lua_type(L, 1) != LUA_TTABLE) { @@ -4498,7 +4498,7 @@ static int32_t Script_EquipCursorItem(lua_State* L) { return 0; } -// VERIFY: 26d1745e manual +// VERIFY: 313f3ea3 auto // OFFSET: 0x0051A530 static int32_t Script_EquipPendingItem(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -4515,7 +4515,7 @@ static int32_t Script_EquipPendingItem(lua_State* L) { return 0; } -// VERIFY: c7ad14f2 manual +// VERIFY: cd050a1b auto // OFFSET: 0x0051A5C0 static int32_t Script_CancelPendingEquip(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -4556,7 +4556,7 @@ static int32_t Script_ToggleSheath(lua_State* L) { return 0; } -// VERIFY: c20d95b3 manual +// VERIFY: 2d52f950 auto // OFFSET: 0x0051A6E0 static int32_t Script_InviteUnit(lua_State* L) { CGPlayer_C* player = ClntObjMgrGetActivePlayerObj(); @@ -5137,7 +5137,7 @@ static int32_t Script_IsEquippedItem(lua_State* L) { return 1; } -// VERIFY: 1e858407 manual +// VERIFY: 356b32c8 auto // OFFSET: 0x0051C740 static int32_t Script_IsEquippedItemType(lua_State* L) { const char* type = lua_tolstring(L, 1, nullptr); @@ -5521,7 +5521,7 @@ static int32_t Script_ClearFocus(lua_State* L) { return 0; } -// VERIFY: ac63f042 manual +// VERIFY: a4660e2b auto // OFFSET: 0x00522600 static int32_t Script_InitiateTrade(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -5625,7 +5625,7 @@ static int32_t Script_NotifyInspect(lua_State* L) { return 0; } -// VERIFY: 69012273 manual +// VERIFY: d3b8f784 auto // OFFSET: 0x00522980 static int32_t Script_PickupPlayerMoney(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -5855,7 +5855,7 @@ static int32_t Script_EndRefund(lua_State* L) { return 0; } -// VERIFY: 4830cc72 auto +// VERIFY: 1fe4019a auto // OFFSET: 0x005233D0 static int32_t Script_EndBoundTradeable(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -6074,7 +6074,7 @@ static int32_t Script_AcceptAreaSpiritHeal(lua_State* L) { return 0; } -// VERIFY: 73a66642 auto +// VERIFY: 1959aa5f auto // OFFSET: 0x00527F00 static int32_t Script_InteractUnit(lua_State* L) { if (!lua_isstring(L, 1)) { diff --git a/WoW/Source/Ui/GlyphInfo_Scripts.cpp b/WoW/Source/Ui/GlyphInfo_Scripts.cpp index cfcc871..9c3d7d5 100644 --- a/WoW/Source/Ui/GlyphInfo_Scripts.cpp +++ b/WoW/Source/Ui/GlyphInfo_Scripts.cpp @@ -75,7 +75,7 @@ static int32_t Script_GetGlyphSocketInfo(lua_State* L) { return 4; } -// VERIFY: bf189600 manual +// VERIFY: dce2d34a auto // OFFSET: 0x005B7410 static int32_t Script_GlyphMatchesSocket(lua_State* L) { if (!lua_isnumber(L, 1)) { diff --git a/WoW/Source/Ui/GuildBankFrame_Scripts.cpp b/WoW/Source/Ui/GuildBankFrame_Scripts.cpp index 028bdbf..d242757 100644 --- a/WoW/Source/Ui/GuildBankFrame_Scripts.cpp +++ b/WoW/Source/Ui/GuildBankFrame_Scripts.cpp @@ -123,7 +123,7 @@ static int32_t Script_CanWithdrawGuildBankMoney(lua_State* L) { return 1; } -// VERIFY: e7dac84b manual +// VERIFY: d4895bf7 auto // OFFSET: 0x005A4330 static int32_t Script_PickupGuildBankMoney(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -148,7 +148,7 @@ static int32_t Script_CloseGuildBankFrame(lua_State* L) { return 0; } -// VERIFY: 7f21b862 manual +// VERIFY: e2247c26 auto // OFFSET: 0x005A4520 static int32_t Script_GetNumGuildBankTransactions(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -261,7 +261,7 @@ static int32_t Script_GetGuildBankMoneyTransaction(lua_State* L) { return 7; } -// VERIFY: 1cfb9bf3 auto +// VERIFY: 2728bcf7 auto // OFFSET: 0x005A5CE0 static int32_t Script_QueryGuildBankTab(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -319,7 +319,7 @@ static int32_t Script_DepositGuildBankMoney(lua_State* L) { return 0; } -// VERIFY: 4edd506a manual +// VERIFY: bf1125f5 auto // OFFSET: 0x005A5EF0 static int32_t Script_WithdrawGuildBankMoney(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -623,7 +623,7 @@ static int32_t Script_GetGuildBankTabInfo(lua_State* L) { return 6; } -// VERIFY: 0b7d305b manual +// VERIFY: 2abc9d81 auto // OFFSET: 0x005A6A00 static int32_t Script_SetGuildBankTabInfo(lua_State* L) { if (!ClntObjMgrGetActivePlayerObj()) { @@ -696,7 +696,7 @@ static int32_t Script_GetGuildTabardFileNames(lua_State* L) { return 6; } -// VERIFY: 8da3f33c manual +// VERIFY: 9a345d1e auto // OFFSET: 0x005A6D50 static int32_t Script_QueryGuildBankLog(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -786,7 +786,7 @@ static int32_t Script_GetGuildBankTransaction(lua_State* L) { return 10; } -// VERIFY: 43e06e0e manual +// VERIFY: 5b511218 auto // OFFSET: 0x005A7110 static int32_t Script_QueryGuildBankText(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -798,7 +798,7 @@ static int32_t Script_QueryGuildBankText(lua_State* L) { return 0; } -// VERIFY: 3ee5f8e4 manual +// VERIFY: 96d4bc1a auto // OFFSET: 0x005A7180 static int32_t Script_SetGuildBankText(lua_State* L) { if (!lua_isnumber(L, 1) || !lua_isstring(L, 2)) { diff --git a/WoW/Source/Ui/GuildInfo_Scripts.cpp b/WoW/Source/Ui/GuildInfo_Scripts.cpp index 26d0cdf..cca3da4 100644 --- a/WoW/Source/Ui/GuildInfo_Scripts.cpp +++ b/WoW/Source/Ui/GuildInfo_Scripts.cpp @@ -281,7 +281,7 @@ static int32_t Script_GuildControlGetRankFlags(lua_State* L) { return 17; } -// VERIFY: ed348c21 auto +// VERIFY: 40d5d07a auto // OFFSET: 0x005CB6A0 static int32_t Script_SetGuildBankWithdrawLimit(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -390,7 +390,7 @@ static int32_t Script_SetGuildBankTabPermissions(lua_State* L) { return 0; } -// VERIFY: caf993d8 manual +// VERIFY: 5e321988 auto // OFFSET: 0x005CAF40 static int32_t Script_SetGuildRosterSelection(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -541,7 +541,7 @@ static void SetGuildControlRank(uint32_t rank) { } } -// VERIFY: e2bc4d66 auto +// VERIFY: 723ba7a7 auto // OFFSET: 0x005CA260 static int32_t Script_GuildControlSetRank(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -560,7 +560,7 @@ static int32_t Script_GetGuildInfoText(lua_State* L) { return 1; } -// VERIFY: b3a7ccfd manual +// VERIFY: 4d6f79ce auto // OFFSET: 0x005CABB0 static int32_t Script_GetGuildRosterLastOnline(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -592,7 +592,7 @@ static int32_t Script_GetGuildRosterLastOnline(lua_State* L) { return 4; } -// VERIFY: f2c398b9 manual +// VERIFY: 8f2f2c14 auto // OFFSET: 0x005CAD00 static int32_t Script_GuildRosterSetPublicNote(lua_State* L) { if (!lua_isnumber(L, 1) || !lua_isstring(L, 2)) { @@ -631,7 +631,7 @@ static int32_t Script_GuildRosterSetPublicNote(lua_State* L) { return 0; } -// VERIFY: 61555267 manual +// VERIFY: e9f385cb auto // OFFSET: 0x005CAE20 static int32_t Script_GuildRosterSetOfficerNote(lua_State* L) { if (!lua_isnumber(L, 1) || !lua_isstring(L, 2)) { @@ -670,7 +670,7 @@ static int32_t Script_GuildRosterSetOfficerNote(lua_State* L) { return 0; } -// VERIFY: edb0cb80 auto +// VERIFY: c8bffae2 auto // OFFSET: 0x005CB000 static int32_t Script_SortGuildRoster(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -770,7 +770,7 @@ static int32_t Script_GuildControlSaveRank(lua_State* L) { return 0; } -// VERIFY: b0fcc11f manual +// VERIFY: 530716a0 auto // OFFSET: 0x005CB330 static int32_t Script_GuildControlAddRank(lua_State* L) { if (!lua_isstring(L, 1)) { diff --git a/WoW/Source/Ui/GuildRegistrar_Scripts.cpp b/WoW/Source/Ui/GuildRegistrar_Scripts.cpp index 98b1d77..6d4c758 100644 --- a/WoW/Source/Ui/GuildRegistrar_Scripts.cpp +++ b/WoW/Source/Ui/GuildRegistrar_Scripts.cpp @@ -30,7 +30,7 @@ static int32_t Script_CloseGuildRegistrar(lua_State* L) { return 0; } -// VERIFY: 5b208826 auto +// VERIFY: a9ebbc34 auto // OFFSET: 0x0059A130 static int32_t Script_BuyGuildCharter(lua_State* L) { if (!lua_isstring(L, 1)) { diff --git a/WoW/Source/Ui/ItemSocketInfo_Scripts.cpp b/WoW/Source/Ui/ItemSocketInfo_Scripts.cpp index 01bcd20..24efebe 100644 --- a/WoW/Source/Ui/ItemSocketInfo_Scripts.cpp +++ b/WoW/Source/Ui/ItemSocketInfo_Scripts.cpp @@ -93,7 +93,7 @@ static int32_t Script_GetNumSockets(lua_State* L) { return 1; } -// VERIFY: f1b27b3b manual +// VERIFY: 72d8ccd8 auto // OFFSET: 0x005C4B60 static int32_t Script_GetNewSocketInfo(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -136,7 +136,7 @@ static int32_t Script_GetNewSocketInfo(lua_State* L) { return 3; } -// VERIFY: 830a3c87 manual +// VERIFY: e0a7f1d2 auto // OFFSET: 0x005C4D10 static int32_t Script_GetNewSocketLink(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -156,7 +156,7 @@ static int32_t Script_GetNewSocketLink(lua_State* L) { return 1; } -// VERIFY: d944b8d4 manual +// VERIFY: a71e7c4d auto // OFFSET: 0x005C4DC0 static int32_t Script_ClickSocketButton(lua_State* L) { if (!lua_isnumber(L, 1)) { diff --git a/WoW/Source/Ui/KnowledgeBase_Scripts.cpp b/WoW/Source/Ui/KnowledgeBase_Scripts.cpp index 5ab5306..7ba0126 100644 --- a/WoW/Source/Ui/KnowledgeBase_Scripts.cpp +++ b/WoW/Source/Ui/KnowledgeBase_Scripts.cpp @@ -168,7 +168,7 @@ static int32_t Script_KBSetup_GetArticleHeaderData(lua_State* L) { return 4; } -// VERIFY: 620ab044 auto +// VERIFY: 58c4251a auto // OFFSET: 0x00551B40 static int32_t Script_KBSetup_GetTotalArticleCount(lua_State* L) { if (g_KnowledgeBaseSetup.m_state != 2) { @@ -202,7 +202,7 @@ static int32_t Script_KBQuery_GetArticleHeaderData(lua_State* L) { return 4; } -// VERIFY: cee4ac95 auto +// VERIFY: 73c4bd52 auto // OFFSET: 0x00551D10 static int32_t Script_KBQuery_GetTotalArticleCount(lua_State* L) { if (g_KnowledgeBaseQuery.m_state != 2) { diff --git a/WoW/Source/Ui/LFGInfo_Scripts.cpp b/WoW/Source/Ui/LFGInfo_Scripts.cpp index b717ced..2b87bd4 100644 --- a/WoW/Source/Ui/LFGInfo_Scripts.cpp +++ b/WoW/Source/Ui/LFGInfo_Scripts.cpp @@ -597,7 +597,7 @@ static int32_t Script_GetLFDLockPlayerCount(lua_State* L) { return 1; } -// VERIFY: 6930f1ab auto +// VERIFY: 51dce08f auto // OFFSET: 0x00557BE0 static int32_t Script_GetLFGDungeonRewardInfo(lua_State* L) { if (!lua_isnumber(L, 1) || !lua_isnumber(L, 2)) { @@ -885,7 +885,7 @@ static int32_t PushDungeonInfo(lua_State* L, int32_t dungeonId) { return 14; } -// VERIFY: 35ec374e auto +// VERIFY: aa8994fc auto // OFFSET: 0x00555590 static int32_t Script_GetLFGDungeonInfo(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -1037,7 +1037,7 @@ static int32_t Script_ClearAllLFGDungeons(lua_State* L) { return 0; } -// VERIFY: ff10ae1b manual +// VERIFY: 002364d9 auto // OFFSET: 0x00559F50 static int32_t Script_SetLFGDungeon(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -1055,7 +1055,7 @@ static int32_t Script_SetLFGDungeon(lua_State* L) { return 0; } -// VERIFY: 7cd995a8 auto +// VERIFY: 3307daf9 auto // OFFSET: 0x0055A040 static int32_t Script_IsLFGDungeonJoinable(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -1173,7 +1173,7 @@ static int32_t Script_GetLFDChoiceCollapseState(lua_State* L) { return 1; } -// VERIFY: 7ab8cbe9 auto +// VERIFY: bf8c7985 auto // OFFSET: 0x005567E0 static int32_t Script_GetLFDChoiceEnabledState(lua_State* L) { if (lua_type(L, 1) != LUA_TTABLE && lua_type(L, 1) > LUA_TNIL) { @@ -1643,7 +1643,7 @@ static int32_t Script_IsInLFGDungeon(lua_State* L) { return 1; } -// VERIFY: 14ad353c manual +// VERIFY: ef0b4eac auto // OFFSET: 0x00555FD0 static int32_t Script_SearchLFGGetResults(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -1758,7 +1758,7 @@ static int32_t Script_SearchLFGGetPartyResults(lua_State* L) { return AddLFGPlayerInfo(L, nullptr) + 5; } -// VERIFY: 8f4a590b manual +// VERIFY: 1994e414 auto // OFFSET: 0x00556AD0 static int32_t Script_SetLFGHeaderCollapsed(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -1776,7 +1776,7 @@ static int32_t Script_SetLFGHeaderCollapsed(lua_State* L) { return 0; } -// VERIFY: f9b9f3e2 auto +// VERIFY: 28acc2e2 auto // OFFSET: 0x00556B60 static int32_t Script_SetLFGDungeonEnabled(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -1859,7 +1859,7 @@ static int32_t Script_LFGTeleport(lua_State* L) { return 1; } -// VERIFY: 33222d7f auto +// VERIFY: edcce8b9 auto // OFFSET: 0x00557D60 static int32_t Script_GetLFGDungeonRewardLink(lua_State* L) { if (!lua_isnumber(L, 1) || !lua_isnumber(L, 2)) { @@ -1885,7 +1885,7 @@ static int32_t Script_GetLFGDungeonRewardLink(lua_State* L) { return 1; } -// VERIFY: 74851aa9 manual +// VERIFY: b739931e auto // OFFSET: 0x00559400 static int32_t Script_SearchLFGJoin(lua_State* L) { if (!lua_isnumber(L, 1) || !lua_isnumber(L, 2)) { @@ -1907,7 +1907,7 @@ static int32_t Script_SearchLFGJoin(lua_State* L) { return 0; } -// VERIFY: 374d8965 manual +// VERIFY: 72f2ad5b auto // OFFSET: 0x00559500 static int32_t Script_ClearLFGDungeon(lua_State* L) { if (!lua_isnumber(L, 1) && !lua_isnumber(L, 2)) { diff --git a/WoW/Source/Ui/LootFrame_Scripts.cpp b/WoW/Source/Ui/LootFrame_Scripts.cpp index 3291ff5..3147428 100644 --- a/WoW/Source/Ui/LootFrame_Scripts.cpp +++ b/WoW/Source/Ui/LootFrame_Scripts.cpp @@ -71,7 +71,7 @@ static int32_t Script_LootSlotIsItem(lua_State* L) { return 1; } -// VERIFY: f8d54875 manual +// VERIFY: 07974e21 auto // OFFSET: 0x00588810 static int32_t Script_LootSlotIsCoin(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -173,7 +173,7 @@ static void MasterLootCandidateNameCallback(int32_t id, const WOWGUID& guid, voi } } -// VERIFY: 7818e364 manual +// VERIFY: d0557dee auto // OFFSET: 0x00588920 static int32_t Script_GetMasterLootCandidate(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -237,7 +237,7 @@ static int32_t Script_GetLootSlotInfo(lua_State* L) { return 5; } -// VERIFY: c50a7ab9 manual +// VERIFY: fc45465a auto // OFFSET: 0x005886D0 static int32_t Script_GetLootSlotLink(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -257,7 +257,7 @@ static int32_t Script_CloseLoot(lua_State* L) { return 0; } -// VERIFY: 520678de manual +// VERIFY: 661226f7 auto // OFFSET: 0x00588C00 static int32_t Script_GetLootRollItemLink(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -282,7 +282,7 @@ static int32_t Script_GetLootRollItemLink(lua_State* L) { return 1; } -// VERIFY: c94773c2 auto +// VERIFY: 7c8b39af auto // OFFSET: 0x00588D60 static int32_t Script_RollOnLoot(lua_State* L) { if (!lua_isnumber(L, 1) || !lua_isnumber(L, 2)) { @@ -295,7 +295,7 @@ static int32_t Script_RollOnLoot(lua_State* L) { return 0; } -// VERIFY: cb1996cb manual +// VERIFY: 88e937ae auto // OFFSET: 0x00588DD0 static int32_t Script_ConfirmLootRoll(lua_State* L) { if (!lua_isnumber(L, 1) || !lua_isnumber(L, 2)) { @@ -308,7 +308,7 @@ static int32_t Script_ConfirmLootRoll(lua_State* L) { return 0; } -// VERIFY: 87cfdafa manual +// VERIFY: 2f666037 auto // OFFSET: 0x00589520 static int32_t Script_LootSlot(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -320,7 +320,7 @@ static int32_t Script_LootSlot(lua_State* L) { return 0; } -// VERIFY: c2324f9f manual +// VERIFY: 085a0c07 auto // OFFSET: 0x00589590 static int32_t Script_ConfirmLootSlot(lua_State* L) { if (!lua_isnumber(L, 1)) { diff --git a/WoW/Source/Ui/MailInfo_Scripts.cpp b/WoW/Source/Ui/MailInfo_Scripts.cpp index 09166f5..cf48200 100644 --- a/WoW/Source/Ui/MailInfo_Scripts.cpp +++ b/WoW/Source/Ui/MailInfo_Scripts.cpp @@ -85,7 +85,7 @@ static int32_t Script_GetSelectedStationeryTexture(lua_State* L) { return 1; } -// VERIFY: ab286db5 manual +// VERIFY: c09e3381 auto // OFFSET: 0x0056E310 static int32_t Script_SelectPackage(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -135,7 +135,7 @@ static int32_t Script_CheckInbox(lua_State* L) { return 0; } -// VERIFY: ff00a2b9 manual +// VERIFY: e89f0c93 auto // OFFSET: 0x0056EDF0 static int32_t Script_TakeInboxMoney(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -168,7 +168,7 @@ static int32_t Script_TakeInboxMoney(lua_State* L) { return 0; } -// VERIFY: 9c8dcaa5 manual +// VERIFY: 0820303b auto // OFFSET: 0x0056EEF0 static int32_t Script_TakeInboxTextItem(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -254,7 +254,7 @@ static int32_t Script_GetStationeryInfo(lua_State* L) { return 3; } -// VERIFY: 37acfbbe auto +// VERIFY: b60ccfe5 auto // OFFSET: 0x0056D570 static int32_t Script_SetSendMailShowing(lua_State* L) { if (lua_type(L, 1) != LUA_TBOOLEAN) { @@ -266,7 +266,7 @@ static int32_t Script_SetSendMailShowing(lua_State* L) { return 0; } -// VERIFY: 14637408 manual +// VERIFY: fddd3d55 auto // OFFSET: 0x0056E210 static int32_t Script_GetPackageInfo(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -350,7 +350,7 @@ static int32_t Script_ClearSendMail(lua_State* L) { return 0; } -// VERIFY: 86b46fe9 manual +// VERIFY: 0dd80945 auto // OFFSET: 0x0056D610 static int32_t Script_SetSendMailCOD(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -607,7 +607,7 @@ static int32_t Script_GetInboxInvoiceInfo(lua_State* L) { return 10; } -// VERIFY: 62ac2eaf manual +// VERIFY: 5d367394 auto // OFFSET: 0x0056ECA0 static int32_t Script_GetInboxItemLink(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -645,7 +645,7 @@ static int32_t Script_GetInboxItemLink(lua_State* L) { return 1; } -// VERIFY: 671dc41a manual +// VERIFY: 9102324a auto // OFFSET: 0x0056F000 static int32_t Script_ReturnInboxItem(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -687,7 +687,7 @@ static int32_t Script_ReturnInboxItem(lua_State* L) { return 0; } -// VERIFY: b8051954 manual +// VERIFY: 4de0ffc3 auto // OFFSET: 0x0056F140 static int32_t Script_DeleteInboxItem(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -733,7 +733,7 @@ static int32_t Script_DeleteInboxItem(lua_State* L) { return 0; } -// VERIFY: 0ee605dc manual +// VERIFY: bbafceb6 auto // OFFSET: 0x0056F280 static int32_t Script_InboxItemCanDelete(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -856,7 +856,7 @@ static int32_t Script_ClickSendMailItemButton(lua_State* L) { return 0; } -// VERIFY: fba810ff manual +// VERIFY: f77670df auto // OFFSET: 0x005706C0 static int32_t Script_SetSendMailMoney(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -921,7 +921,7 @@ static int32_t Script_GetSendMailItem(lua_State* L) { return 4; } -// VERIFY: 12427637 manual +// VERIFY: e6b7381f auto // OFFSET: 0x00570910 static int32_t Script_SendMail(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -1171,7 +1171,7 @@ static int32_t Script_GetInboxItem(lua_State* L) { return 5; } -// VERIFY: cda89321 manual +// VERIFY: 46d21530 auto // OFFSET: 0x005711C0 static int32_t Script_TakeInboxItem(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -1226,7 +1226,7 @@ static int32_t Script_TakeInboxItem(lua_State* L) { return 0; } -// VERIFY: 694369cf manual +// VERIFY: d282c11a auto // OFFSET: 0x00571350 static int32_t Script_ComplainInboxItem(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -1238,7 +1238,7 @@ static int32_t Script_ComplainInboxItem(lua_State* L) { return 0; } -// VERIFY: 538df37c manual +// VERIFY: cf2ffa69 auto // OFFSET: 0x005713C0 static int32_t Script_CanComplainInboxItem(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -1255,7 +1255,7 @@ static int32_t Script_CanComplainInboxItem(lua_State* L) { return 1; } -// VERIFY: a2bb6661 manual +// VERIFY: e42e96ea auto // OFFSET: 0x00571450 static int32_t Script_AutoLootMailItem(lua_State* L) { if (!lua_isnumber(L, 1)) { diff --git a/WoW/Source/Ui/MerchantFrame_Scripts.cpp b/WoW/Source/Ui/MerchantFrame_Scripts.cpp index 4d59e8e..d7f5d31 100644 --- a/WoW/Source/Ui/MerchantFrame_Scripts.cpp +++ b/WoW/Source/Ui/MerchantFrame_Scripts.cpp @@ -73,7 +73,7 @@ static int32_t Script_InRepairMode(lua_State* L) { return 1; } -// VERIFY: 2137ed3a manual +// VERIFY: 4a349e26 auto // OFFSET: 0x005842D0 static int32_t Script_GetMerchantItemMaxStack(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -96,7 +96,7 @@ static int32_t Script_GetMerchantItemMaxStack(lua_State* L) { return 1; } -// VERIFY: 5f012ea7 auto +// VERIFY: 22eb2eec auto // OFFSET: 0x005846E0 static int32_t Script_GetMerchantItemCostInfo(lua_State* L) { if (!lua_isnumber(L, 1)) { diff --git a/WoW/Source/Ui/PartyFrame_Scripts.cpp b/WoW/Source/Ui/PartyFrame_Scripts.cpp index 562f68b..dda607e 100644 --- a/WoW/Source/Ui/PartyFrame_Scripts.cpp +++ b/WoW/Source/Ui/PartyFrame_Scripts.cpp @@ -108,7 +108,7 @@ static int32_t Script_IsRealPartyLeader(lua_State* L) { return 1; } -// VERIFY: cb6ade84 manual +// VERIFY: de2d49bb auto // OFFSET: 0x0052C1D0 static int32_t Script_GetPartyMember(lua_State* L) { uint32_t index; @@ -236,7 +236,7 @@ static int32_t Script_SetOptOutOfLoot(lua_State* L) { return 0; } -// VERIFY: f1613827 auto +// VERIFY: 7839f724 auto // OFFSET: 0x0052CF60 static int32_t Script_GetPartyAssignment(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -494,7 +494,7 @@ static int32_t Script_ClearPartyAssignment(lua_State* L) { return SetOrClearAssignment(L, false); } -// VERIFY: 4154fb5e manual +// VERIFY: c58ebc08 auto // OFFSET: 0x0052E420 static int32_t Script_ChangePlayerDifficulty(lua_State* L) { if (!lua_isnumber(L, 1)) { diff --git a/WoW/Source/Ui/PetInfo_Scripts.cpp b/WoW/Source/Ui/PetInfo_Scripts.cpp index 41cb6d8..0c267f6 100644 --- a/WoW/Source/Ui/PetInfo_Scripts.cpp +++ b/WoW/Source/Ui/PetInfo_Scripts.cpp @@ -656,7 +656,7 @@ static int32_t Script_PickupPetAction(lua_State* L) { return 0; } -// VERIFY: 7e17695f manual +// VERIFY: f3852677 auto // OFFSET: 0x005D66F0 static int32_t Script_TogglePetAutocast(lua_State* L) { if (!lua_isnumber(L, 1)) { diff --git a/WoW/Source/Ui/PetitionInfo_Scripts.cpp b/WoW/Source/Ui/PetitionInfo_Scripts.cpp index b655eaa..5fbd7d0 100644 --- a/WoW/Source/Ui/PetitionInfo_Scripts.cpp +++ b/WoW/Source/Ui/PetitionInfo_Scripts.cpp @@ -136,7 +136,7 @@ static int32_t Script_GetPetitionInfo(lua_State* L) { return 7; } -// VERIFY: 5613ed49 manual +// VERIFY: c92110d9 auto // OFFSET: 0x005CEE30 static int32_t Script_GetPetitionNameInfo(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -236,7 +236,7 @@ static int32_t Script_OfferPetition(lua_State* L) { return 0; } -// VERIFY: 2974e308 manual +// VERIFY: d967f9f8 auto // OFFSET: 0x005CF450 static int32_t Script_RenamePetition(lua_State* L) { if (!lua_isstring(L, 1)) { diff --git a/WoW/Source/Ui/QuestFrame_Scripts.cpp b/WoW/Source/Ui/QuestFrame_Scripts.cpp index b86b02b..ce85170 100644 --- a/WoW/Source/Ui/QuestFrame_Scripts.cpp +++ b/WoW/Source/Ui/QuestFrame_Scripts.cpp @@ -347,7 +347,7 @@ static int32_t Script_GetActiveTitle(lua_State* L) { return 2; } -// VERIFY: ef61e41b manual +// VERIFY: 812d7ec5 auto // OFFSET: 0x0058C2B0 static int32_t Script_GetQuestItemLink(lua_State* L) { if (!lua_isstring(L, 1) || !lua_isnumber(L, 2)) { @@ -509,7 +509,7 @@ static int32_t Script_CompleteQuest(lua_State* L) { return 0; } -// VERIFY: 52bc2f90 auto +// VERIFY: 58f9202d auto // OFFSET: 0x0058D620 static int32_t Script_GetQuestReward(lua_State* L) { int32_t choice = -1; @@ -663,7 +663,7 @@ static int32_t Script_GetQuestSpellLink(lua_State* L) { return 1; } -// VERIFY: 2f297b49 manual +// VERIFY: dfd619a6 auto // OFFSET: 0x0058DBC0 static int32_t Script_GetAvailableQuestInfo(lua_State* L) { if (!lua_isnumber(L, 1)) { diff --git a/WoW/Source/Ui/QuestLog_Scripts.cpp b/WoW/Source/Ui/QuestLog_Scripts.cpp index 91c8713..100957f 100644 --- a/WoW/Source/Ui/QuestLog_Scripts.cpp +++ b/WoW/Source/Ui/QuestLog_Scripts.cpp @@ -53,7 +53,7 @@ static int32_t Script_GetNumQuestWatches(lua_State* L) { return 1; } -// VERIFY: 86a938d8 auto +// VERIFY: ac535154 auto // OFFSET: 0x005DFB00 static int32_t Script_SetPOIIconOverlapDistance(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -1590,7 +1590,7 @@ static int32_t Script_QuestMapUpdateAllQuests(lua_State* L) { return 1; } -// VERIFY: 11fdb03d auto +// VERIFY: 39212d82 auto // OFFSET: 0x005E0590 static int32_t Script_QuestPOIGetIconInfo(lua_State* L) { if (!lua_isnumber(L, 1)) { diff --git a/WoW/Source/Ui/RaidInfo_Scripts.cpp b/WoW/Source/Ui/RaidInfo_Scripts.cpp index ba6ac54..5880046 100644 --- a/WoW/Source/Ui/RaidInfo_Scripts.cpp +++ b/WoW/Source/Ui/RaidInfo_Scripts.cpp @@ -63,7 +63,7 @@ static int32_t Script_IsRealRaidLeader(lua_State* L) { return 1; } -// VERIFY: b9f445b5 manual +// VERIFY: 3a66ce1f auto // OFFSET: 0x00572BC0 static int32_t Script_SetRaidRosterSelection(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -237,7 +237,7 @@ static int32_t Script_GetReadyCheckStatus(lua_State* L) { return 1; } -// VERIFY: 86d61574 auto +// VERIFY: 6d2243ec auto // OFFSET: 0x00572AB0 static int32_t Script_GetRaidTargetIndex(lua_State* L) { if (!lua_isstring(L, 1)) { diff --git a/WoW/Source/Ui/ReputationInfo_Scripts.cpp b/WoW/Source/Ui/ReputationInfo_Scripts.cpp index e623c9b..7341679 100644 --- a/WoW/Source/Ui/ReputationInfo_Scripts.cpp +++ b/WoW/Source/Ui/ReputationInfo_Scripts.cpp @@ -30,7 +30,7 @@ static int32_t Script_GetNumFactions(lua_State* L) { return 1; } -// VERIFY: 06bc7cb4 auto +// VERIFY: 6deeea03 auto // OFFSET: 0x005D1F70 static int32_t Script_CollapseFactionHeader(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -42,7 +42,7 @@ static int32_t Script_CollapseFactionHeader(lua_State* L) { return 0; } -// VERIFY: fc0d4302 auto +// VERIFY: ceb13be5 auto // OFFSET: 0x005D2000 static int32_t Script_ExpandFactionHeader(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -54,7 +54,7 @@ static int32_t Script_ExpandFactionHeader(lua_State* L) { return 0; } -// VERIFY: 0666d394 auto +// VERIFY: 7c94cd2f auto // OFFSET: 0x005D0740 static int32_t Script_IsFactionInactive(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -71,7 +71,7 @@ static int32_t Script_IsFactionInactive(lua_State* L) { return 1; } -// VERIFY: 6260777e auto +// VERIFY: 7d15ad95 auto // OFFSET: 0x005D07B0 static int32_t Script_SetSelectedFaction(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -154,7 +154,7 @@ static int32_t Script_GetWatchedFactionInfo(lua_State* L) { return 5; } -// VERIFY: 571ae289 manual +// VERIFY: 115d0d85 auto // OFFSET: 0x005D1390 static int32_t Script_FactionToggleAtWar(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -172,7 +172,7 @@ static int32_t Script_FactionToggleAtWar(lua_State* L) { return 0; } -// VERIFY: 139fa5f2 auto +// VERIFY: ca638192 auto // OFFSET: 0x005D1420 static int32_t Script_SetWatchedFactionIndex(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -191,7 +191,7 @@ static int32_t Script_SetWatchedFactionIndex(lua_State* L) { return 0; } -// VERIFY: 38bb0dbb manual +// VERIFY: 4581b042 auto // OFFSET: 0x005D1E50 static int32_t Script_SetFactionInactive(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -212,7 +212,7 @@ static int32_t Script_SetFactionInactive(lua_State* L) { return 0; } -// VERIFY: 5d8e8c20 manual +// VERIFY: 5b890263 auto // OFFSET: 0x005D1EE0 static int32_t Script_SetFactionActive(lua_State* L) { if (!lua_isnumber(L, 1)) { diff --git a/WoW/Source/Ui/ScriptEvents_Scripts.cpp b/WoW/Source/Ui/ScriptEvents_Scripts.cpp index 48c39cc..e3b043c 100644 --- a/WoW/Source/Ui/ScriptEvents_Scripts.cpp +++ b/WoW/Source/Ui/ScriptEvents_Scripts.cpp @@ -1497,7 +1497,7 @@ static int32_t Script_GetSpellCritChance(lua_State* L) { return 1; } -// VERIFY: a0133d89 auto +// VERIFY: d473dac8 auto // OFFSET: 0x00611130 static int32_t Script_UnitIsTapped(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -1516,7 +1516,7 @@ static int32_t Script_UnitIsTapped(lua_State* L) { return 1; } -// VERIFY: a55a9031 auto +// VERIFY: f2910353 auto // OFFSET: 0x006111B0 static int32_t Script_UnitIsTappedByPlayer(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -1535,7 +1535,7 @@ static int32_t Script_UnitIsTappedByPlayer(lua_State* L) { return 1; } -// VERIFY: d33dc156 auto +// VERIFY: a3119ea8 auto // OFFSET: 0x00611230 static int32_t Script_UnitIsTappedByAllThreatList(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -1554,7 +1554,7 @@ static int32_t Script_UnitIsTappedByAllThreatList(lua_State* L) { return 1; } -// VERIFY: 10c64bd9 auto +// VERIFY: f25aca66 auto // OFFSET: 0x006112B0 static int32_t Script_UnitIsTrivial(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -1606,7 +1606,7 @@ static int32_t Script_UnitIsPVPSanctuary(lua_State* L) { return 1; } -// VERIFY: 57bc1e86 auto +// VERIFY: e6da71ac auto // OFFSET: 0x0060D330 static int32_t Script_UnitIsEnemy(lua_State* L) { if (!lua_isstring(L, 1) || !lua_isstring(L, 2)) { @@ -1626,7 +1626,7 @@ static int32_t Script_UnitIsEnemy(lua_State* L) { return 1; } -// VERIFY: 23480833 auto +// VERIFY: 9977228e auto // OFFSET: 0x0060D690 static int32_t Script_UnitCanAssist(lua_State* L) { if (!lua_isstring(L, 1) || !lua_isstring(L, 2)) { @@ -1646,7 +1646,7 @@ static int32_t Script_UnitCanAssist(lua_State* L) { return 1; } -// VERIFY: 5d6fa4bf auto +// VERIFY: 2b7d1365 auto // OFFSET: 0x0060D730 static int32_t Script_UnitCanAttack(lua_State* L) { if (!lua_isstring(L, 1) || !lua_isstring(L, 2)) { @@ -1666,7 +1666,7 @@ static int32_t Script_UnitCanAttack(lua_State* L) { return 1; } -// VERIFY: 2a1a0dff auto +// VERIFY: 55248fe1 auto // OFFSET: 0x00611780 static int32_t Script_UnitCreatureType(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -1687,7 +1687,7 @@ static int32_t Script_UnitCreatureType(lua_State* L) { return 1; } -// VERIFY: 592e2b17 auto +// VERIFY: b49f7e06 auto // OFFSET: 0x00611820 static int32_t Script_UnitCreatureFamily(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -1761,7 +1761,7 @@ static int32_t Script_GetExpertisePercent(lua_State* L) { return 2; } -// VERIFY: 1e5f92f8 manual +// VERIFY: ed117708 auto // OFFSET: 0x00613290 static int32_t Script_GetUnitSpeed(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -1777,7 +1777,7 @@ static int32_t Script_GetUnitSpeed(lua_State* L) { return 1; } -// VERIFY: 94bb89b8 manual +// VERIFY: beaa5d8a auto // OFFSET: 0x00613330 static int32_t Script_GetUnitPitch(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -1871,7 +1871,7 @@ static int32_t Script_GetMaxCombatRatingBonus(lua_State* L) { return 1; } -// VERIFY: 18494640 auto +// VERIFY: fe45ad25 auto // OFFSET: 0x0060D280 static int32_t Script_UnitReaction(lua_State* L) { if (!lua_isstring(L, 1) || !lua_isstring(L, 2)) { @@ -2036,7 +2036,7 @@ static int32_t Script_IsArenaTeamCaptain(lua_State* L) { return 1; } -// VERIFY: f7665c53 manual +// VERIFY: 7f2ce3f2 auto // OFFSET: 0x0060CD50 static int32_t Script_UnitIsDND(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -2073,7 +2073,7 @@ static int32_t Script_UnitIsDND(lua_State* L) { return 1; } -// VERIFY: 124502f9 manual +// VERIFY: 8f807614 auto // OFFSET: 0x006133D0 static int32_t Script_UnitInVehicle(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -2105,7 +2105,7 @@ static int32_t Script_UnitInVehicle(lua_State* L) { return 1; } -// VERIFY: 2d3eaa21 manual +// VERIFY: 51ed5491 auto // OFFSET: 0x006134A0 static int32_t Script_UnitUsingVehicle(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -2157,7 +2157,7 @@ static int32_t Script_UnitHasRelicSlot(lua_State* L) { return 1; } -// VERIFY: 90024a7e manual +// VERIFY: 2eaf7430 auto // OFFSET: 0x0060E9A0 static int32_t Script_UnitPVPName(lua_State* L) { char buffer[1024]; @@ -2245,7 +2245,7 @@ static int32_t Script_UnitArmor(lua_State* L) { return 5; } -// VERIFY: 15fb0fea manual +// VERIFY: 0d546523 auto // OFFSET: 0x00613D20 static int32_t Script_CanEjectPassengerFromSeat(lua_State* L) { int32_t canEject = 0; @@ -2869,7 +2869,7 @@ static int32_t Script_UnitChannelInfo(lua_State* L) { return 8; } -// VERIFY: 55ecc993 manual +// VERIFY: 34158845 auto // OFFSET: 0x00611670 static int32_t Script_GetComboPoints(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -2982,7 +2982,7 @@ static int32_t Script_GetRuneType(lua_State* L) { return 1; } -// VERIFY: a37de20f auto +// VERIFY: c0b81bcf auto // OFFSET: 0x0060E1B0 static int32_t Script_GetSpellCritChanceFromIntellect(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -3321,7 +3321,7 @@ static int32_t Script_UnitSelectionColor(lua_State* L) { return 4; } -// VERIFY: 371b347a auto +// VERIFY: 56e06a1c auto // OFFSET: 0x0060E130 static int32_t Script_GetCritChanceFromAgility(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -3402,7 +3402,7 @@ static int32_t Script_GetArmorPenetration(lua_State* L) { return 1; } -// VERIFY: ab8a630e auto +// VERIFY: 06470798 auto // OFFSET: 0x00612980 static int32_t Script_GetUnitHealthRegenRateFromSpirit(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -3452,7 +3452,7 @@ static int32_t PushItemStatsTable(lua_State* L, const CGItemStatsSummary* summar return 1; } -// VERIFY: b3f4687d manual +// VERIFY: e180e4f4 auto // OFFSET: 0x00608690 static int32_t Script_GetItemStats(lua_State* L) { if (!lua_isstring(L, 1) || (lua_type(L, 2) > LUA_TNIL && lua_type(L, 2) != LUA_TTABLE)) { @@ -3477,7 +3477,7 @@ static int32_t Script_GetItemStats(lua_State* L) { return PushItemStatsTable(L, &summary); } -// VERIFY: bbdcf16c auto +// VERIFY: 5abe4b5a auto // OFFSET: 0x00608760 static int32_t Script_GetItemStatDelta(lua_State* L) { if (!lua_isstring(L, 1) || !lua_isstring(L, 2) || (lua_type(L, 3) > LUA_TNIL && lua_type(L, 3) != LUA_TTABLE)) { @@ -3650,7 +3650,7 @@ static int32_t Script_UnitPlayerOrPetInRaid(lua_State* L) { return 1; } -// VERIFY: 9bc39da7 auto +// VERIFY: b7b874e0 auto // OFFSET: 0x0060E630 static int32_t Script_UnitGUID(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -3790,7 +3790,7 @@ static int32_t Script_UnitRangedDamage(lua_State* L) { return 6; } -// VERIFY: 1502c643 auto +// VERIFY: 4d846509 auto // OFFSET: 0x006107D0 static int32_t Script_UnitRangedAttack(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -3907,7 +3907,7 @@ static int32_t Script_UnitIsSameServer(lua_State* L) { return 1; } -// VERIFY: 62419666 auto +// VERIFY: 8e92472b auto // OFFSET: 0x006127F0 static int32_t Script_GetUnitHealthModifier(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -3928,7 +3928,7 @@ static int32_t Script_GetUnitHealthModifier(lua_State* L) { return 1; } -// VERIFY: 5bd7addc auto +// VERIFY: fbf30662 auto // OFFSET: 0x00612900 static int32_t Script_GetUnitPowerModifier(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -3949,7 +3949,7 @@ static int32_t Script_GetUnitPowerModifier(lua_State* L) { return 1; } -// VERIFY: bdc9e6ce manual +// VERIFY: 966b715a auto // OFFSET: 0x00612D50 static int32_t Script_ReportPlayerIsPVPAFK(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -4012,7 +4012,7 @@ static int32_t Script_PlayerIsPVPInactive(lua_State* L) { return 1; } -// VERIFY: 884338a0 manual +// VERIFY: 186e8f0d auto // OFFSET: 0x00612F10 static int32_t Script_UnitInRange(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -4241,7 +4241,7 @@ static void CacheVehicleUIIndicatorRec(int32_t id) { } } -// VERIFY: dfe4ce5f manual +// VERIFY: c412aa98 auto // OFFSET: 0x00614E60 static int32_t Script_GetVehicleUIIndicator(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -4387,7 +4387,7 @@ void SystemUnregisterFunctions() { } } -// VERIFY: a8ddc867 auto +// VERIFY: 966d052b auto // OFFSET: 0x00612A00 static int32_t Script_GetUnitManaRegenRateFromSpirit(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -4406,7 +4406,7 @@ static int32_t Script_GetUnitManaRegenRateFromSpirit(lua_State* L) { return 1; } -// VERIFY: 37fad92d manual +// VERIFY: a8863c9a auto // OFFSET: 0x0060CC30 static int32_t Script_UnitIsAFK(lua_State* L) { if (!lua_isstring(L, 1)) { diff --git a/WoW/Source/Ui/SkillInfo_Scripts.cpp b/WoW/Source/Ui/SkillInfo_Scripts.cpp index bb3f820..4baba2d 100644 --- a/WoW/Source/Ui/SkillInfo_Scripts.cpp +++ b/WoW/Source/Ui/SkillInfo_Scripts.cpp @@ -230,7 +230,7 @@ static int32_t Script_AbandonSkill(lua_State* L) { return 0; } -// VERIFY: 19628834 auto +// VERIFY: 407a57be auto // OFFSET: 0x005CE3A0 static int32_t Script_CollapseSkillHeader(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -250,7 +250,7 @@ static int32_t Script_CollapseSkillHeader(lua_State* L) { return 0; } -// VERIFY: 1235676b auto +// VERIFY: 3836a490 auto // OFFSET: 0x005CE400 static int32_t Script_ExpandSkillHeader(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -270,7 +270,7 @@ static int32_t Script_ExpandSkillHeader(lua_State* L) { return 0; } -// VERIFY: 04976012 manual +// VERIFY: 4bd54e72 auto // OFFSET: 0x005CE460 static int32_t Script_AddSkillUp(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -283,7 +283,7 @@ static int32_t Script_AddSkillUp(lua_State* L) { return 0; } -// VERIFY: 020eae34 manual +// VERIFY: fea9ba45 auto // OFFSET: 0x005CE4D0 static int32_t Script_RemoveSkillUp(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -331,7 +331,7 @@ static int32_t Script_AcceptSkillUps(lua_State* L) { return 0; } -// VERIFY: 1526bb4d manual +// VERIFY: a3367e9c auto // OFFSET: 0x005CE6F0 static int32_t Script_BuySkillTier(lua_State* L) { if (!lua_isnumber(L, 1)) { diff --git a/WoW/Source/Ui/SpellBookFrame_Scripts.cpp b/WoW/Source/Ui/SpellBookFrame_Scripts.cpp index 41a15fb..ce2904c 100644 --- a/WoW/Source/Ui/SpellBookFrame_Scripts.cpp +++ b/WoW/Source/Ui/SpellBookFrame_Scripts.cpp @@ -362,7 +362,7 @@ static int32_t Script_IsConsumableSpell(lua_State* L) { return 1; } -// VERIFY: f715c8b6 manual +// VERIFY: 33061c66 auto // OFFSET: 0x0053C2A0 static int32_t Script_GetNumCompanions(lua_State* L) { int32_t type; @@ -793,7 +793,7 @@ static int32_t Script_GetShapeshiftFormCooldown(lua_State* L) { return 3; } -// VERIFY: e1e722df manual +// VERIFY: 2cf49f7e auto // OFFSET: 0x0053C310 static int32_t Script_PickupCompanion(lua_State* L) { int32_t type; @@ -974,7 +974,7 @@ static int32_t Script_SummonRandomCritter(lua_State* L) { return 1; } -// VERIFY: 23b3df80 manual +// VERIFY: 7011eeb5 auto // OFFSET: 0x0053E060 static int32_t Script_CastSpellByID(lua_State* L) { if (!lua_isnumber(L, 1)) { diff --git a/WoW/Source/Ui/StableInfo_Scripts.cpp b/WoW/Source/Ui/StableInfo_Scripts.cpp index a67671d..84d56cd 100644 --- a/WoW/Source/Ui/StableInfo_Scripts.cpp +++ b/WoW/Source/Ui/StableInfo_Scripts.cpp @@ -51,7 +51,7 @@ static int32_t Script_GetNumStableSlots(lua_State* L) { return 1; } -// VERIFY: dda4fad4 auto +// VERIFY: ef5dfe07 auto // OFFSET: 0x005A0FE0 static int32_t Script_PickupStablePet(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -145,7 +145,7 @@ static int32_t Script_GetNextStableSlotCost(lua_State* L) { return 1; } -// VERIFY: 4fee38c8 manual +// VERIFY: 75685864 auto // OFFSET: 0x005A1530 static int32_t Script_SetPetStablePaperdoll(lua_State* L) { if (lua_type(L, 1) != LUA_TTABLE) { diff --git a/WoW/Source/Ui/TalentInfo_Scripts.cpp b/WoW/Source/Ui/TalentInfo_Scripts.cpp index 75ea982..431e9e3 100644 --- a/WoW/Source/Ui/TalentInfo_Scripts.cpp +++ b/WoW/Source/Ui/TalentInfo_Scripts.cpp @@ -456,7 +456,7 @@ static int32_t Script_GetTalentPrereqs(lua_State* L) { return 4 * count; } -// VERIFY: e016f005 manual +// VERIFY: 47fcce66 auto // OFFSET: 0x005C7CE0 static int32_t Script_GetTalentLink(lua_State* L) { if (!lua_isnumber(L, 1) || !lua_isnumber(L, 2)) { @@ -595,7 +595,7 @@ static int32_t Script_GetActiveTalentGroup(lua_State* L) { return 1; } -// VERIFY: 2c14e75a auto +// VERIFY: 8eb75c42 auto // OFFSET: 0x005C63B0 static int32_t Script_GetPreviewTalentPointsSpent(lua_State* L) { if (!lua_isnumber(L, 1)) { diff --git a/WoW/Source/Ui/TaxiMapFrame_Scripts.cpp b/WoW/Source/Ui/TaxiMapFrame_Scripts.cpp index 13cd87f..550ff61 100644 --- a/WoW/Source/Ui/TaxiMapFrame_Scripts.cpp +++ b/WoW/Source/Ui/TaxiMapFrame_Scripts.cpp @@ -44,7 +44,7 @@ static int32_t Script_TaxiNodeName(lua_State* L) { return 1; } -// VERIFY: 3ea6e937 manual +// VERIFY: 39b322e3 auto // OFFSET: 0x00590E00 static int32_t Script_TaxiNodePosition(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -158,7 +158,7 @@ static int32_t Script_CloseTaxiMap(lua_State* L) { return 0; } -// VERIFY: b6dd9ddf manual +// VERIFY: a6b4fd5b auto // OFFSET: 0x00590ED0 static int32_t Script_TaxiNodeGetType(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -171,7 +171,7 @@ static int32_t Script_TaxiNodeGetType(lua_State* L) { return 1; } -// VERIFY: 8f67b73d manual +// VERIFY: 9565b7c3 auto // OFFSET: 0x005915E0 static int32_t Script_TaxiNodeCost(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -190,7 +190,7 @@ static int32_t Script_TaxiNodeCost(lua_State* L) { return 1; } -// VERIFY: 9b6d526d manual +// VERIFY: 113b9a85 auto // OFFSET: 0x00591680 static int32_t Script_TakeTaxiNode(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -203,7 +203,7 @@ static int32_t Script_TakeTaxiNode(lua_State* L) { return 0; } -// VERIFY: bf20d58d manual +// VERIFY: 81d3cf0d auto // OFFSET: 0x00591E60 static int32_t Script_TaxiNodeSetCurrent(lua_State* L) { if (!lua_isnumber(L, 1)) { diff --git a/WoW/Source/Ui/TradeFrame_Scripts.cpp b/WoW/Source/Ui/TradeFrame_Scripts.cpp index b52b41c..67cbde0 100644 --- a/WoW/Source/Ui/TradeFrame_Scripts.cpp +++ b/WoW/Source/Ui/TradeFrame_Scripts.cpp @@ -96,7 +96,7 @@ static int32_t Script_AcceptTrade(lua_State* L) { return 0; } -// VERIFY: 391b5d92 auto +// VERIFY: 2f99e941 auto // OFFSET: 0x00586810 static int32_t Script_PickupTradeMoney(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -114,7 +114,7 @@ static int32_t Script_PickupTradeMoney(lua_State* L) { return 0; } -// VERIFY: dd7edb41 manual +// VERIFY: ac0f520f auto // OFFSET: 0x00586870 static int32_t Script_SetTradeMoney(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -145,7 +145,7 @@ static int32_t Script_ClickTargetTradeButton(lua_State* L) { return 0; } -// VERIFY: e2896016 manual +// VERIFY: aa5fb0e2 auto // OFFSET: 0x00586D00 static int32_t Script_GetTradePlayerItemLink(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -294,7 +294,7 @@ static int32_t Script_ClickTradeButton(lua_State* L) { return 0; } -// VERIFY: 54d8f2a3 manual +// VERIFY: 8c588e45 auto // OFFSET: 0x00587C60 static int32_t Script_GetTradeTargetItemInfo(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -351,7 +351,7 @@ static int32_t Script_GetTradeTargetItemInfo(lua_State* L) { return 6; } -// VERIFY: 2a7d8005 manual +// VERIFY: 3df471df auto // OFFSET: 0x00587EB0 static int32_t Script_GetTradePlayerItemInfo(lua_State* L) { if (!lua_isnumber(L, 1)) { diff --git a/WoW/Source/Ui/TradeSkillFrame_Scripts.cpp b/WoW/Source/Ui/TradeSkillFrame_Scripts.cpp index 2eebd51..e4bd98b 100644 --- a/WoW/Source/Ui/TradeSkillFrame_Scripts.cpp +++ b/WoW/Source/Ui/TradeSkillFrame_Scripts.cpp @@ -101,7 +101,7 @@ static int32_t Script_GetTradeskillRepeatCount(lua_State* L) { // STATIC: 0x00A1B788 static const char s_difficultyNames[4][32] = { "optimal", "medium", "easy", "trivial" }; -// VERIFY: a034c051 auto +// VERIFY: 70374745 auto // OFFSET: 0x005DA1B0 static int32_t Script_GetTradeSkillSubClassFilter(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -154,7 +154,7 @@ static int32_t Script_IsTradeSkillLinked(lua_State* L) { return 2; } -// VERIFY: dffd5f22 auto +// VERIFY: 1b04086e auto // OFFSET: 0x005DA900 static int32_t Script_SelectTradeSkill(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -183,7 +183,7 @@ static int32_t Script_GetTradeSkillSelectionIndex(lua_State* L) { return 1; } -// VERIFY: e27f888d auto +// VERIFY: 15ddefb1 auto // OFFSET: 0x005DA9A0 static int32_t Script_GetTradeSkillCooldown(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -261,7 +261,7 @@ static int32_t Script_GetFirstTradeSkill(lua_State* L) { return 1; } -// VERIFY: 69469bac manual +// VERIFY: 84674611 auto // OFFSET: 0x005DAC00 static int32_t Script_DoTradeSkill(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -377,7 +377,7 @@ static int32_t Script_GetTradeSkillInfo(lua_State* L) { return 5; } -// VERIFY: 8ee28003 auto +// VERIFY: 5c82d036 auto // OFFSET: 0x005DB550 static int32_t Script_GetTradeSkillIcon(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -418,7 +418,7 @@ static int32_t Script_GetTradeSkillIcon(lua_State* L) { return 1; } -// VERIFY: 68b3486e auto +// VERIFY: dbf6e832 auto // OFFSET: 0x005DB6E0 static int32_t Script_GetTradeSkillNumMade(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -483,7 +483,7 @@ static int32_t Script_GetTradeSkillLine(lua_State* L) { return 3; } -// VERIFY: aba88414 auto +// VERIFY: aadc4baa auto // OFFSET: 0x005DB920 static int32_t Script_GetTradeSkillRecipeLink(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -523,7 +523,7 @@ static int32_t Script_GetTradeSkillRecipeLink(lua_State* L) { return 1; } -// VERIFY: 58848056 auto +// VERIFY: 50491ff5 auto // OFFSET: 0x005DBA70 static int32_t Script_GetTradeSkillItemLink(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -641,7 +641,7 @@ static int32_t Script_GetTradeSkillReagentItemLink(lua_State* L) { return 1; } -// VERIFY: de273fc0 auto +// VERIFY: 981c3ee2 auto // OFFSET: 0x005DBE10 static int32_t Script_GetTradeSkillDescription(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -695,7 +695,7 @@ static int32_t Script_GetTradeSkillInvSlots(lua_State* L) { return count; } -// VERIFY: cae2a567 manual +// VERIFY: f80437a8 auto // OFFSET: 0x005DBF90 static int32_t Script_GetTradeSkillInvSlotFilter(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -770,7 +770,7 @@ static int32_t Script_SetTradeSkillItemNameFilter(lua_State* L) { return 0; } -// VERIFY: 29122e5a manual +// VERIFY: 6022a2ad auto // OFFSET: 0x005DD090 static int32_t Script_SetTradeSkillItemLevelFilter(lua_State* L) { if (!lua_isnumber(L, 1) || !lua_isnumber(L, 2)) { @@ -784,7 +784,7 @@ static int32_t Script_SetTradeSkillItemLevelFilter(lua_State* L) { return 0; } -// VERIFY: d62d7bc6 manual +// VERIFY: 58bc80f5 auto // OFFSET: 0x005DD0F0 static int32_t Script_SetTradeSkillSubClassFilter(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -915,7 +915,7 @@ static int32_t Script_TradeSkillOnlyShowSkillUps(lua_State* L) { return 0; } -// VERIFY: 7a4a6871 manual +// VERIFY: c74e0f4e auto // OFFSET: 0x005DD460 static int32_t Script_CollapseTradeSkillSubClass(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -943,7 +943,7 @@ static int32_t Script_CollapseTradeSkillSubClass(lua_State* L) { return 0; } -// VERIFY: a371e13d manual +// VERIFY: 2ef40ac1 auto // OFFSET: 0x005DD500 static int32_t Script_ExpandTradeSkillSubClass(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -1034,7 +1034,7 @@ static int32_t Script_GetTradeSkillReagentInfo(lua_State* L) { return 4; } -// VERIFY: 6ce46c6f manual +// VERIFY: d4ae0022 auto // OFFSET: 0x005DE620 static int32_t Script_GetTradeSkillTools(lua_State* L) { if (!lua_isnumber(L, 1)) { diff --git a/WoW/Source/Ui/Types.h b/WoW/Source/Ui/Types.h index cba27fd..3e709dc 100644 --- a/WoW/Source/Ui/Types.h +++ b/WoW/Source/Ui/Types.h @@ -5,15 +5,6 @@ #include #include "Engine/Source/BLPFile/Types.h" -namespace BSN { -struct BSNPrimitiveEncoder { - /* 0000 */ uint8_t unk_0000 [16]; - /* 0010 */ int32_t unk_0010; - /* 0014 */ uint8_t unk_0014 [60]; - /* 0050 */ int32_t unk_0050; -}; -} - enum UIErrors { ERR_INV_FULL = 0, ERR_BANK_FULL = 1, @@ -1406,6 +1397,31 @@ enum SCRIPT_EVENT { NUM_SCRIPT_EVENTS = 722 }; +enum BATTLENET_PRESENCE_FIELD { + BN_PRESENCE_ONLINE = 0, + BN_PRESENCE_ONLINE_TIME = 1, + BN_PRESENCE_LAST_ONLINE = 2, + BN_PRESENCE_AFK = 3, + BN_PRESENCE_DND = 4, + BN_PRESENCE_BROADCAST = 5, + BN_PRESENCE_BROADCAST_TIME = 6, + BN_PRESENCE_TOON_NAME = 7, + BN_PRESENCE_PROGRAM = 8, + BN_PRESENCE_ACCOUNT_NAME = 9, + BN_PRESENCE_FOCUS = 10, + BN_PRESENCE_NOTE = 11, + BN_PRESENCE_REALM_NAME = 12, + BN_PRESENCE_RACE = 13, + BN_PRESENCE_CLASS = 14, + BN_PRESENCE_GUILD = 15, + BN_PRESENCE_LEVEL = 16, + BN_PRESENCE_AREA = 17, + BN_PRESENCE_GAME_TEXT = 18, + BN_PRESENCE_UNK_19 = 19, + BN_PRESENCE_FACTION = 20, + NUM_BN_PRESENCE_FIELDS = 21, +}; + enum BINDING_SET { BINDING_SET_DEFAULT = 0, BINDING_SET_ACCOUNT = 1, diff --git a/WoW/Source/Ui/UIBindings_Scripts.cpp b/WoW/Source/Ui/UIBindings_Scripts.cpp index ce55f3b..78b1734 100644 --- a/WoW/Source/Ui/UIBindings_Scripts.cpp +++ b/WoW/Source/Ui/UIBindings_Scripts.cpp @@ -11,7 +11,7 @@ #include #include "Engine/Source/Storm/H/storm.h" -// VERIFY: b16d798f auto +// VERIFY: 47beb07e auto // OFFSET: 0x0055E9B0 static int32_t Script_GetBindingKey(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -121,7 +121,7 @@ static int32_t Script_SaveBindings(lua_State* L) { return 0; } -// VERIFY: 6b1312a2 auto +// VERIFY: 9e9a649e auto // OFFSET: 0x0055FB90 static int32_t Script_SetModifiedClick(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -142,7 +142,7 @@ static int32_t Script_SetModifiedClick(lua_State* L) { return 0; } -// VERIFY: d049e19f auto +// VERIFY: 8c63faae auto // OFFSET: 0x0055FC20 static int32_t Script_GetModifiedClick(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -165,7 +165,7 @@ static int32_t Script_GetModifiedClick(lua_State* L) { return 1; } -// VERIFY: 8955c60c auto +// VERIFY: faa35395 auto // OFFSET: 0x00562550 static int32_t Script_GetBindingAction(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -195,7 +195,7 @@ static int32_t Script_GetBindingAction(lua_State* L) { return 1; } -// VERIFY: 615c1d3e auto +// VERIFY: 783d8193 auto // OFFSET: 0x00560560 static int32_t Script_ClearOverrideBindings(lua_State* L) { CScriptObject* owner = nullptr; @@ -269,7 +269,7 @@ static int32_t Script_RunBinding(lua_State* L) { return 0; } -// VERIFY: 57e77187 auto +// VERIFY: 8dba3261 auto // OFFSET: 0x00563520 static int32_t Script_SetBinding(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -300,7 +300,7 @@ static int32_t Script_SetBinding(lua_State* L) { return 1; } -// VERIFY: b687d044 auto +// VERIFY: ed0ea2f2 auto // OFFSET: 0x0055E8D0 static int32_t Script_GetBinding(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -333,7 +333,7 @@ static int32_t Script_GetBinding(lua_State* L) { return count + 1; } -// VERIFY: b5fec94e auto +// VERIFY: 44fa649a auto // OFFSET: 0x00563A90 static int32_t Script_SetOverrideBinding(lua_State* L) { CScriptObject* owner = nullptr; @@ -361,7 +361,7 @@ static int32_t Script_SetOverrideBinding(lua_State* L) { return 0; } -// VERIFY: 5da0d638 auto +// VERIFY: 72a9de4c auto // OFFSET: 0x005635E0 static int32_t Script_SetBindingSpell(lua_State* L) { if (!lua_isstring(L, 1) || !lua_isstring(L, 2)) { @@ -395,7 +395,7 @@ static int32_t Script_SetBindingSpell(lua_State* L) { return 1; } -// VERIFY: 6019e3d2 auto +// VERIFY: e02e1678 auto // OFFSET: 0x00563700 static int32_t Script_SetBindingItem(lua_State* L) { if (!lua_isstring(L, 1) || !lua_isstring(L, 2)) { @@ -429,7 +429,7 @@ static int32_t Script_SetBindingItem(lua_State* L) { return 1; } -// VERIFY: 8d04e514 auto +// VERIFY: a6cf9194 auto // OFFSET: 0x00563820 static int32_t Script_SetBindingMacro(lua_State* L) { if (!lua_isstring(L, 1) || !lua_isstring(L, 2)) { @@ -463,7 +463,7 @@ static int32_t Script_SetBindingMacro(lua_State* L) { return 1; } -// VERIFY: ee819584 auto +// VERIFY: 93460342 auto // OFFSET: 0x00563940 static int32_t Script_SetBindingClick(lua_State* L) { if (!lua_isstring(L, 1) || !lua_isstring(L, 2)) { @@ -503,7 +503,7 @@ static int32_t Script_SetBindingClick(lua_State* L) { return 1; } -// VERIFY: 82af3cb9 auto +// VERIFY: 8c961e80 auto // OFFSET: 0x00563B80 static int32_t Script_SetOverrideBindingSpell(lua_State* L) { CScriptObject* owner = nullptr; @@ -529,7 +529,7 @@ static int32_t Script_SetOverrideBindingSpell(lua_State* L) { return 0; } -// VERIFY: 9b743ba9 auto +// VERIFY: 7ede6409 auto // OFFSET: 0x00563CB0 static int32_t Script_SetOverrideBindingItem(lua_State* L) { CScriptObject* owner = nullptr; @@ -555,7 +555,7 @@ static int32_t Script_SetOverrideBindingItem(lua_State* L) { return 0; } -// VERIFY: 499be506 auto +// VERIFY: 08f60cfe auto // OFFSET: 0x00563DE0 static int32_t Script_SetOverrideBindingMacro(lua_State* L) { CScriptObject* owner = nullptr; @@ -581,7 +581,7 @@ static int32_t Script_SetOverrideBindingMacro(lua_State* L) { return 0; } -// VERIFY: 19f3d063 manual +// VERIFY: 12320864 auto // OFFSET: 0x00563F10 static int32_t Script_SetOverrideBindingClick(lua_State* L) { CScriptObject* owner = nullptr; diff --git a/WoW/Source/Ui/UIMacros_Scripts.cpp b/WoW/Source/Ui/UIMacros_Scripts.cpp index 962db7d..ec501ee 100644 --- a/WoW/Source/Ui/UIMacros_Scripts.cpp +++ b/WoW/Source/Ui/UIMacros_Scripts.cpp @@ -142,7 +142,7 @@ static int32_t Script_GetMacroSpell(lua_State* L) { return 2; } -// VERIFY: ea27987a manual +// VERIFY: cbd63495 auto // OFFSET: 0x00564AE0 static int32_t Script_SecureCmdOptionParse(lua_State* L) { const char* options = lua_tolstring(L, 1, nullptr); @@ -170,7 +170,7 @@ static int32_t Script_SecureCmdOptionParse(lua_State* L) { return 2; } -// VERIFY: 7e119d87 manual +// VERIFY: 2de408c7 auto // OFFSET: 0x00564E90 static int32_t Script_GetMacroIconInfo(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -192,7 +192,7 @@ static int32_t Script_GetMacroIconInfo(lua_State* L) { return 1; } -// VERIFY: 2443acb4 manual +// VERIFY: 7c42f7b9 auto // OFFSET: 0x00564F60 static int32_t Script_GetMacroItemIconInfo(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -214,7 +214,7 @@ static int32_t Script_GetMacroItemIconInfo(lua_State* L) { return 1; } -// VERIFY: 558a9e67 auto +// VERIFY: fa3f6068 auto // OFFSET: 0x00566400 static int32_t Script_RunMacroText(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -250,7 +250,7 @@ static int32_t Script_GetNumMacroItemIcons(lua_State* L) { return 1; } -// VERIFY: b82ce8df auto +// VERIFY: bec93d83 auto // OFFSET: 0x005666A0 static int32_t Script_GetMacroIndexByName(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -381,7 +381,7 @@ static int32_t Script_EditMacro(lua_State* L) { return 1; } -// VERIFY: 13afb7d7 auto +// VERIFY: 8a7babb3 auto // OFFSET: 0x005670D0 static int32_t Script_SetMacroItem(lua_State* L) { if (!lua_isstring(L, 2)) { diff --git a/WoW/Source/Ui/WorldMap_Scripts.cpp b/WoW/Source/Ui/WorldMap_Scripts.cpp index 21b0067..c801c98 100644 --- a/WoW/Source/Ui/WorldMap_Scripts.cpp +++ b/WoW/Source/Ui/WorldMap_Scripts.cpp @@ -388,7 +388,7 @@ static int32_t Script_GetMapInfo(lua_State* L) { return 3; } -// VERIFY: ab9e8f42 auto +// VERIFY: b153db79 auto // OFFSET: 0x00545880 static int32_t Script_GetPlayerMapPosition(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -711,7 +711,7 @@ static int32_t Script_UpdateMapHighlight(lua_State* L) { return 8; } -// VERIFY: 2039e993 manual +// VERIFY: 29e7c946 auto // OFFSET: 0x00544B90 static int32_t Script_GetMapZones(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -777,7 +777,7 @@ static int32_t Script_GetMapOverlayInfo(lua_State* L) { return 7; } -// VERIFY: 269a2aa1 manual +// VERIFY: 2f36de9c auto // OFFSET: 0x005469E0 static int32_t Script_SetMapZoom(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -828,7 +828,7 @@ static int32_t Script_CreateWorldMapArrowFrame(lua_State* L) { return 0; } -// VERIFY: 230343d0 manual +// VERIFY: 04ce3302 auto // OFFSET: 0x00545FF0 static int32_t Script_InitWorldMapPing(lua_State* L) { if (lua_type(L, 1) != LUA_TTABLE) { @@ -1076,7 +1076,7 @@ static int32_t Script_SetMapByID(lua_State* L) { return 1; } -// VERIFY: 4f3b2103 manual +// VERIFY: 8c4a2255 auto // OFFSET: 0x00546E80 static int32_t Script_ProcessMapClick(lua_State* L) { if (!lua_isnumber(L, 1) || !lua_isnumber(L, 2)) { @@ -1090,7 +1090,7 @@ static int32_t Script_ProcessMapClick(lua_State* L) { return 0; } -// VERIFY: ab6bdd23 manual +// VERIFY: 2a928080 auto // OFFSET: 0x00546EF0 static int32_t Script_ClickLandmark(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -1117,7 +1117,7 @@ static int32_t Script_ClickLandmark(lua_State* L) { return 0; } -// VERIFY: c656caf0 auto +// VERIFY: f361bf64 auto // OFFSET: 0x00547B80 static int32_t Script_SetDungeonMapLevel(lua_State* L) { if (!lua_isnumber(L, 1)) { diff --git a/WoW/Source/WowServices/BattlenetLogin.cpp b/WoW/Source/WowServices/BattlenetLogin.cpp index a0afea7..4d9cc06 100644 --- a/WoW/Source/WowServices/BattlenetLogin.cpp +++ b/WoW/Source/WowServices/BattlenetLogin.cpp @@ -1,46 +1,1719 @@ #include "BattlenetLogin.h" +#include +#include +#include +#include +#include +#include "Engine/Source/Base/CDataStore.h" +#include "Engine/Source/BlizzardCore/SFile2-Core.h" +#include "Engine/Source/BlizzardCore/Source/System/Version/Version.h" +#include "Engine/Source/ConsoleBase/IConsole.h" +#include "Engine/Source/FrameScript/FrameScript.h" +#include "Engine/Source/FrameXML/XMLTree.h" +#include "Engine/Source/Os/OsFile.h" +#include "Engine/Source/Os/OsSecureRandom.h" +#include "Engine/Source/Os/OsTcp.h" +#include "Engine/Source/Os/TimeManager.h" #include "Engine/Source/Storm/H/storm.h" +#include "WoW/Source/Battlenet/Tumor/TumorManager.h" +#include "WoW/Source/Client.h" +#include "WoW/Source/DB/DBClient/DBClient.h" +#include "WoW/Source/Glue/CGlueMgr.h" +#include "WoW/Source/Ui/BattlenetUI.h" +#include "WoW/Source/Ui/GameUI.h" +#include "WoW/Source/WowServices/LoginResponse.h" + +// STATIC: 0x00B24B94 +BattlenetAllocator s_battlenetAllocator; // STATIC: 0x00D45C98 -TumorManager* g_tumorManager; +Battlenet::TumorManager* g_tumorManager; -// VERIFY: 6048e810 manual +// STATIC: 0x00D45C9C +bool BattlenetLogin::s_monolithicComponent; + +// STATIC: 0x00D45CB0 +char BattlenetLogin::s_monolithicPlatform[5]; + +// VERIFY: 4bbf2db9 auto +// OFFSET: 0x008C51D0 +void BattlenetAssert(const char* message, const char* file, int32_t line) { + SErrDisplayErrorFmt(0x85100000, file ? file : "", line, 0, 1, "Internal Battle.net Error: %s", message ? message : ""); + abort(); +} + +// VERIFY: 9e2345e7 auto +// OFFSET: 0x008C5140 +void* BattlenetAllocator::Alloc(uint32_t size) { + return SMemAlloc(size, __FILE__, __LINE__, 0); +} + +// VERIFY: 04e99d71 auto +// OFFSET: 0x008C5160 +void BattlenetAllocator::Free(void* memory) { + SMemFree(memory, __FILE__, __LINE__, 0); +} + +// VERIFY: 93afef9d auto +// OFFSET: 0x008C5180 +bool BattlenetApplication::Send(uint32_t connection, const void* data, uint32_t size) { + if (connection != this->m_connection) { + SErrDisplayAppFatalMessage("", "", 0); + } + + return this->m_wowConnection->Send(static_cast(const_cast(data)), size, true); +} + +// VERIFY: f8dc5f8a manual +// OFFSET: 0x008C51C0 +uint64_t BattlenetApplication::GetCurrentTick() const { + return OsGetAsyncTimeMs(); +} + +// VERIFY: e3b5cfcb manual +// OFFSET: [0x008C5210, 0x008C6A10] +BattlenetApplication::~BattlenetApplication() { + if (this->m_wowConnection) { + this->m_wowConnection->Disconnect(); + this->m_wowConnection->SetResponse(nullptr, false); + this->m_wowConnection->Release(); + this->m_wowConnection = nullptr; + } +} + +// VERIFY: d7bf219c auto +// OFFSET: 0x008C5270 +uint8_t BattlenetLogin::GetCharacterCount(uint32_t region, uint32_t battlegroup, uint32_t id) { + RealmCharacterCount* counts = this->m_realmCharacterCounts; + + if (!counts) { + return 0; + } + + for (uint32_t i = 0; i < this->m_realmCharacterCountCount; i++, counts++) { + if (counts->m_region == region && counts->m_battlegroup == battlegroup && counts->m_id == id) { + return static_cast(counts->m_count); + } + } + + return 0; +} + +// VERIFY: b1cb90f6 auto +// OFFSET: 0x008C52E0 +bool BattlenetLogin::Connected(const NETADDR& address) { + char text[256]; + char addressString[32]; + + this->m_loggedOn = true; + + SStrPrintf(text, sizeof(text), "Connected to %s", OsNetAddrToStr(&address, addressString, sizeof(addressString))); + ConsoleWrite(text, DEFAULT_COLOR); + + if (!g_tumorManager || !this->m_application) { + SErrDisplayAppFatalMessage("", "", 0); + } + + Battlenet::SystemClient& client = g_tumorManager->m_tumor; + client.Connected(this->m_application->m_connection, this->m_application->m_localAddress); + + return true; +} + +// VERIFY: a95ceed4 manual +// OFFSET: 0x008C5370 +bool BattlenetLogin::Disconnected() { + if (!g_tumorManager || !this->m_application) { + SErrDisplayAppFatalMessage("", "", 0); + } + + Battlenet::SystemClient& client = g_tumorManager->m_tumor; + client.Disconnected(this->m_application->m_connection); + + return false; +} + +// VERIFY: 274186f5 manual +// OFFSET: 0x008C53B0 +void BattlenetLogin::LogonResultBN(int32_t result) { + this->m_logonResult = result; + + switch (result) { + case 0: + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_AUTHENTICATED, LOGIN_OK, nullptr, 0); + break; + + case 103: + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_FAILED, LOGIN_BAD_SERVER_PROOF, nullptr, 0); + break; + + case 104: + case 108: + case 116: + case 201: + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_FAILED, LOGIN_UNKNOWN_ACCOUNT, nullptr, 0); + break; + + case 105: + case 106: + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_FAILED, LOGIN_DISCONNECTED, nullptr, 0); + break; + + case 107: + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_FAILED, LOGIN_NO_GAME_ACCOUNT, nullptr, 0); + break; + + case 109: + case 110: + case 111: + case 112: + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_FAILED, LOGIN_BADVERSION, nullptr, 0); + break; + + case 113: + case 200: + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_FAILED, LOGIN_AUTH_OUTAGE, nullptr, 0); + break; + + case 115: + case 205: + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_FAILED, LOGIN_ALREADYONLINE, nullptr, 0); + break; + + case 123: + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_FAILED, LOGIN_TOO_FAST, nullptr, 0); + break; + + case 124: + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_FAILED, LOGIN_USE_GRUNT, nullptr, 0); + break; + + case 140: + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_FAILED, LOGIN_NO_GAME_ACCOUNTS_IN_REGION, nullptr, 0); + break; + + case 141: + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_FAILED, LOGIN_ACCOUNT_LOCKED, nullptr, 0); + break; + + case 202: + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_FAILED, LOGIN_BANNED, nullptr, 0); + break; + + case 203: + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_FAILED, LOGIN_SUSPENDED, nullptr, 0); + break; + + case 204: + case 212: + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_FAILED, LOGIN_GAME_ACCOUNT_LOCKED, nullptr, 0); + break; + + case 206: + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_FAILED, LOGIN_NOTIME, nullptr, 0); + break; + + case 207: + case 208: + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_FAILED, LOGIN_EXPIRED, nullptr, 0); + break; + + case 209: + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_FAILED, LOGIN_PARENTALCONTROL, nullptr, 0); + break; + + case 210: + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_FAILED, LOGIN_TRIAL_EXPIRED, nullptr, 0); + break; + + case 211: + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_FAILED, LOGIN_ANTI_INDULGENCE, nullptr, 0); + break; + + default: + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_FAILED, LOGIN_FAILED, nullptr, 0); + break; + } + + this->m_surveyPending = false; +} + +// VERIFY: 4668fa22 auto +// OFFSET: 0x008C5BA0 +static void GetComponentVersion(const char* name, uint32_t& version, const char* data, uint32_t size) { + XMLTree* tree = XMLTree_Load(data, size); + + for (XMLNode* node = XMLTree_GetRoot(tree)->m_child; node; node = node->m_next) { + if (!SStrCmpI(node->m_name.m_str, "component", STORM_MAX_STR)) { + const char* componentName = node->GetAttributeByName("name"); + const char* componentVersion = node->GetAttributeByName("version"); + + if (componentName && componentVersion && !SStrCmpI(componentName, name, STORM_MAX_STR)) { + version = SStrToInt(componentVersion); + } + } + } + + XMLTree_Free(tree); +} + +// VERIFY: 13a1fff7 auto +// OFFSET: 0x008C5C50 +static uint32_t GetWowDataVersion() { + uint32_t version = 12340; + void* data; + uint32_t size; + + if (!SFileLoadFileEx(nullptr, "component.wow-data.txt", &data, &size, 0, 0, nullptr) || !data) { + return 12340; + } + + GetComponentVersion("wow-data", version, static_cast(data), size); + SMemFree(data, __FILE__, __LINE__, 0); + + return version; +} + +// VERIFY: c6db8f62 auto +// OFFSET: 0x008C5CC0 +static uint32_t GetWowLangVersion(const char* locale) { + char path[256]; + char fileName[32]; + char componentName[32]; + uint32_t version = 12340; + SArchive* archive = nullptr; + + if (SStrCmp(locale, s_localeCode, STORM_MAX_STR)) { + sprintf(path, "Data/%s/patch-%s-2.MPQ", locale, locale); + + if (!OsFileExists(path)) { + sprintf(path, "Data/%s/patch-%s.MPQ", locale, locale); + + if (!OsFileExists(path)) { + sprintf(path, "Data/%s/locale-%s.MPQ", locale, locale); + } + } + + if (!SFile::OpenArchive(path, 0, 0x800, &archive)) { + return 12340; + } + } + + sprintf(fileName, "component.wow-%s.txt", locale); + + void* data; + uint32_t size; + + if (!SFile::ReadFile(archive, fileName, &data, &size, 0, 0, nullptr) || !data) { + if (archive) { + SFile::CloseArchive(archive); + } + + return 12340; + } + + sprintf(componentName, "wow-%s", locale); + GetComponentVersion(componentName, version, static_cast(data), size); + SMemFree(data, __FILE__, __LINE__, 0); + + if (archive) { + SFile::CloseArchive(archive); + } + + return version; +} + +// VERIFY: 552847c3 manual +// OFFSET: 0x008C5F60 +void BattlenetLogin::SetAuthModuleMatrixInfo(const char* info, const char* challenges) { + this->m_matrixWidth = SStrToUnsigned(info); + + const char* cursor = SStrChr(info, ','); + + if (!cursor) { + SErrDisplayAppFatalMessage("", "", 0); + } + + cursor++; + this->m_matrixHeight = SStrToUnsigned(cursor); + + cursor = SStrChr(cursor, ','); + + if (!cursor) { + SErrDisplayAppFatalMessage("", "", 0); + } + + cursor++; + this->m_matrixMinDigitCount = SStrToUnsigned(cursor); + + cursor = SStrChr(cursor, ','); + + if (!cursor) { + SErrDisplayAppFatalMessage("", "", 0); + } + + cursor++; + this->m_matrixMaxDigitCount = SStrToUnsigned(cursor); + + cursor = SStrChr(cursor, ','); + + if (!cursor) { + SErrDisplayAppFatalMessage("", "", 0); + } + + cursor++; + this->m_matrixFlipCoords = SStrToUnsigned(cursor) != 0; + + cursor = SStrChr(cursor, ','); + + if (!cursor) { + SErrDisplayAppFatalMessage("", "", 0); + } + + cursor++; + this->m_matrixChallengeCount = SStrToUnsigned(cursor); + + if (SStrChr(cursor, ',')) { + SErrDisplayAppFatalMessage("", "", 0); + } + + if (!this->m_matrixWidth || !this->m_matrixHeight || !this->m_matrixMinDigitCount || !this->m_matrixMaxDigitCount || !this->m_matrixChallengeCount) { + SErrDisplayAppFatalMessage("", "", 0); + } + + if (this->m_matrixData) { + delete[] this->m_matrixData; + } + + this->m_matrixData = new (__FILE__, __LINE__) uint32_t[this->m_matrixChallengeCount]; + + for (uint32_t i = 0; i < this->m_matrixChallengeCount; i++) { + if (!challenges) { + SErrDisplayAppFatalMessage("", "", 0); + } + + if (i) { + challenges++; + } + + this->m_matrixData[i] = SStrToUnsigned(challenges); + challenges = SStrChr(challenges, ','); + } + + if (challenges) { + SErrDisplayAppFatalMessage("", "", 0); + } + + this->m_matrixEnabled = true; + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_MATRIX, LOGIN_OK, nullptr, 0); +} + +// VERIFY: 8e82c4f5 auto +// OFFSET: 0x008C61E0 +void BattlenetLogin::SetAuthModulePinInfo(const char* keyMap) { + if (!keyMap || SStrLen(keyMap) != 10) { + SErrDisplayAppFatalMessage("", "", 0); + } + + for (uint32_t i = 0; i < 10; i++) { + if (!isdigit(static_cast(keyMap[i]))) { + SErrDisplayAppFatalMessage("", "", 0); + } + + this->unk_105D[1 + i] = keyMap[i] - '0'; + } + + this->unk_105D[0] = 1; + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_PIN, LOGIN_OK, nullptr, 0); +} + +// VERIFY: cf41e714 manual +// OFFSET: 0x008C62B0 +void BattlenetLogin::SetTokenInfo(bool enabled, uint8_t required) { + if (enabled) { + this->m_tokenRequired = true; + this->unk_10D5 = required; + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_TOKEN, LOGIN_OK, nullptr, 0); + } +} + +// VERIFY: f11b22e7 auto +// OFFSET: 0x008C6330 +static bool IsInOrEnteringWorld() { + return CGGameUI::s_inWorld || CGlueMgr::m_idleState == IDLE_ENTER_WORLD; +} + +// VERIFY: 4f797e26 auto +// OFFSET: 0x008C6350 +void BattlenetLogin::LogConnectionStatus(const char* format, ...) { + char buffer[2048]; + + if (format && *format) { + va_list args; + va_start(args, format); + SStrVPrintf(buffer, sizeof(buffer), format, args); + CGlueMgr::LogConnectionStatus(buffer); + } +} + +// VERIFY: a78fd966 auto +// OFFSET: 0x008C6980 +void BattlenetApplication::Disconnect(uint32_t connection) { + if (connection != this->m_connection) { + SErrDisplayAppFatalMessage("", "", 0); + } + + if (this->m_wowConnection) { + this->m_wowConnection->Disconnect(); + BattlenetLogin::LogConnectionStatus("Disconnected from %x", this->m_wowConnection->m_connectAddress); + } +} + +// VERIFY: 36d5c66c auto +// OFFSET: 0x008C69D0 +BattlenetApplication::BattlenetApplication() { + this->m_eventId = Battlenet::Event::APP; + this->m_login = nullptr; + this->m_wowConnection = nullptr; + this->m_connection = 0; +} + +// VERIFY: cdc67c71 manual +// OFFSET: 0x008C6A60 +bool BattlenetLogin::CantConnect() { + ConsoleWrite("BattlenetLogin was unable to connect to Sunken", DEFAULT_COLOR); + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_FAILED, LOGIN_SERVER_DOWN, nullptr, 0); + this->m_logonStatus = 1; + this->LogonResultBN(2); + this->m_loggedOn = false; + this->m_online = false; + + return false; +} + +// VERIFY: c20feb7e manual +// OFFSET: 0x008C6B30 +const char* BattlenetLogin::GetPatchInstruction(uint32_t index) { + if (index < this->m_patchInstructions.m_count) { + return this->m_patchInstructions.m_data[index].m_patch; + } + + return nullptr; +} + +// VERIFY: 4dc6c4b9 manual +// OFFSET: 0x008C6D10 +uint32_t BattlenetApplication::Connect(const Battlenet::IP4::AddressPort& address, const uint32_t& tendrilId) { + char buffer[64]; + + this->m_connection = OsGetAsyncTimeMs(); + this->m_remoteAddress = address; + + if (!this->m_wowConnection) { + this->m_wowConnection = new (__FILE__, __LINE__) WowConnection(this, nullptr); + this->m_wowConnection->SetType(WOWC_TYPE_STREAM); + } + + sprintf(buffer, "%d.%d.%d.%d:%d", address.m_address[0], address.m_address[1], address.m_address[2], address.m_address[3], address.m_port[1] + (address.m_port[0] << 8)); + BattlenetLogin::LogConnectionStatus("Connecting to %s", buffer); + this->m_wowConnection->Connect(buffer, 5000); + + return this->m_connection; +} + +// VERIFY: 9d0ccd2a auto +// OFFSET: 0x00532A60 +uint32_t BattlenetApplication::OpenDatagram(int32_t port, const uint32_t& tendrilId) { + SErrDisplayAppFatalMessage("", "", 0); +} + +// VERIFY: 2c202c4c auto +// OFFSET: 0x00532A60 +void BattlenetApplication::CloseDatagram(uint32_t connection) { + SErrDisplayAppFatalMessage("", "", 0); +} + +// VERIFY: 30835edb auto +// OFFSET: 0x00532A60 +bool BattlenetApplication::SendDatagram(uint32_t connection, const void* data, uint32_t size, const Battlenet::IP4::AddressPort& address) { + SErrDisplayAppFatalMessage("", "", 0); +} + +// VERIFY: 2a2561a1 auto +// OFFSET: 0x00532A60 +uint64_t BattlenetApplication::GetCurrentTime() const { + SErrDisplayAppFatalMessage("", "", 0); +} + +// VERIFY: 2aca7dfc auto +// OFFSET: 0x00653A10 +void BattlenetApplication::LogLevel(const char* message, int32_t level) { +} + +// VERIFY: 6b1ff200 auto +// OFFSET: 0x004899F0 +Battlenet::ApplicationFile* BattlenetApplication::OpenApplicationFile(const char* name) { + return nullptr; +} + +// VERIFY: cada2529 auto +// OFFSET: 0x008813A0 +void BattlenetApplication::CloseApplicationFile(Battlenet::ApplicationFile* file) { +} + +// VERIFY: 5b409c1d auto +// OFFSET: 0x0047ADD0 +void BattlenetApplication::WCMessageReady(WowConnection* connection, uint32_t timeStamp, CDataStore* msg) { +} + +// VERIFY: b99dcdf7 manual +// OFFSET: 0x008C7030 +void BattlenetLogin::HandleUpdateInvoke(const Battlenet::Event::Update::Invoke* invoke) { + char program[5]; + char component[5]; + + this->m_patchInstructionLock.Enter(); + + PatchInstruction* instruction = this->m_patchInstructions.New(); + SStrCopy(instruction->m_patch, invoke->m_patch.m_data, sizeof(instruction->m_patch)); + + invoke->m_program.ToString(program, sizeof(program)); + invoke->m_component.ToString(component, sizeof(component)); + BattlenetLogin::LogConnectionStatus("program=%s component=%s patch=%s", program, component, instruction->m_patch); + + this->m_patchInstructionLock.Leave(); + + if (!invoke->unk_010C) { + SStrCopy(this->m_fileName, "Patch", sizeof(this->m_fileName)); + this->m_fileSize = 0; + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_DOWNLOADFILE, LOGIN_OK, nullptr, 0); + } +} + +// VERIFY: 3d0e41a1 manual +// OFFSET: 0x008C7130 +void BattlenetLogin::BuildRealmListResult() { + CDataStore* msg = new (__FILE__, __LINE__) CDataStore(); + uint16_t count = 0; + + msg->Put(count); + + this->m_realmLock.Enter(); + + for (BN_REALM* realm = this->m_realms.Head(); realm; realm = this->m_realms.Next(realm)) { + REALM_INFO& info = realm->m_info; + + msg->Put(info.m_type); + msg->Put(info.m_otherFlags); + msg->Put(info.m_flags); + msg->PutString(info.m_realmName); + msg->PutString(info.m_realmAddress); + msg->Put(info.m_population); + msg->Put(info.m_numCharacters); + msg->Put(info.m_category); + msg->Put(info.m_regionId); + msg->Put(info.m_battlegroupId); + msg->Put(info.m_realmId); + msg->Put(info.m_build); + + if (info.m_flags & 0x4) { + msg->Put(info.m_versionMajor); + msg->Put(info.m_versionMinor); + msg->Put(info.m_versionRevision); + msg->Put(info.m_versionBuild); + } + + count++; + } + + this->m_realmLock.Leave(); + + msg->Put(static_cast(0)); + msg->Set(0, count); + msg->Finalize(); + + this->RealmListResult(msg); + + delete msg; +} + +// VERIFY: 90b0ddd4 manual +// OFFSET: 0x008C7300 +void BattlenetLogin::JoinRealm(uint32_t region, uint32_t battlegroup, uint32_t id) { + this->m_joinRealmId = id; + + Battlenet::Event::Creep::Invoke invoke; + Battlenet::Realm::Request* request = invoke.Set<6, Battlenet::Realm::Request>(); + BSN::Optional* join = request->Set<1, BSN::Optional>(); + + if (region || battlegroup || id) { + join->m_exists = true; + join->m_value.m_region = region; + join->m_value.m_battlegroup = battlegroup; + join->m_value.m_id = id; + } else { + join->m_exists = false; + } + + if (!g_tumorManager) { + SErrDisplayAppFatalMessage("", "", 0); + } + + g_tumorManager->SendEvent(Battlenet::Event::CREEP, invoke); +} + +// VERIFY: 102510bd manual +// OFFSET: 0x008C73D0 +void BattlenetLogin::GetLogonMethod() { + if (!this->m_password) { + return; + } + + Battlenet::Event::Creep::Invoke invoke; + Battlenet::Authentication::Request* authentication = invoke.Set<0, Battlenet::Authentication::Request>(); + Battlenet::Authentication::ModuleMessage* message = authentication->Set<2, Battlenet::Authentication::ModuleMessage>(); + message->m_moduleId = this->m_moduleId; + message->m_name = Battlenet::Event::AuthModule::RequestPassword; + + Battlenet::Authentication::ModuleParam* param = message->m_params.New(); + *param->Set<0, BSN::String<256>>() = this->m_password; + + memset(this->m_password, 0, SStrLen(this->m_password)); + SMemFree(this->m_password, __FILE__, __LINE__, 0); + this->m_password = nullptr; + + if (!g_tumorManager) { + SErrDisplayAppFatalMessage("", "", 0); + } + + g_tumorManager->SendEvent(Battlenet::Event::CREEP, invoke); +} + +// VERIFY: a8bc2c7e auto +// OFFSET: 0x008C7530 +void BattlenetLogin::Logoff() { + Battlenet::Event::Creep::Invoke invoke; + invoke.Set<9, Battlenet::Event::Creep::Logoff>(); + + if (g_tumorManager) { + g_tumorManager->SendEvent(Battlenet::Event::CREEP, invoke); + } +} + +// VERIFY: b6892c7c manual +// OFFSET: 0x008C7590 +Battlenet::TumorManager* BattlenetLogin::CreateTumorManager() { + if (g_tumorManager) { + BattlenetUI::Uninit(); + } + + const char* program = "WoW"; + + if (SFile::IsTrial()) { + program = "WoWS"; + } + + Battlenet::Authentication::Settings settings; + + if (settings.m_seedLength < 32) { + memset(&settings.m_seed[settings.m_seedLength], 0, 32 - settings.m_seedLength); + } + + settings.m_seedLength = 32; + OsSecureRandom(settings.m_seed, 32); + + settings.m_program = BSN::FourCC("WoW"); + settings.m_platform = BSN::FourCC("Win"); + settings.m_locale.m_value = SFile::s_locale; + settings.m_systemLocale.m_value = SFile::s_locale; + + BattlenetLogin::LogConnectionStatus("Login program=%s platform=%s locale=%s", "WoW", "Win", s_localeCode); + + if (BattlenetLogin::s_monolithicComponent) { + BattlenetLogin::s_monolithicComponent = false; + SStrCopy(BattlenetLogin::s_monolithicPlatform, "Win", sizeof(BattlenetLogin::s_monolithicPlatform)); + SStrCopy(&BattlenetLogin::s_monolithicPlatform[1], &s_localeCode[1], 4); + + Battlenet::Authentication::Component* component = settings.m_components.New(); + component->m_program = BSN::FourCC(program); + component->m_platform = BSN::FourCC(BattlenetLogin::s_monolithicPlatform); + component->m_version = 12340; + } else { + Battlenet::Authentication::Component* component = settings.m_components.New(); + component->m_program = BSN::FourCC(program); + component->m_platform = BSN::FourCC("Win"); + component->m_version = 12340; + + component = settings.m_components.New(); + component->m_program = BSN::FourCC("WoW"); + component->m_platform = BSN::FourCC("base"); + component->m_version = GetWowDataVersion(); + + uint32_t localeCount = 0; + + for (int32_t i = 0; i < 12; i++) { + if (g_hasIsoLocale[i]) { + component = settings.m_components.New(); + component->m_program = BSN::FourCC("WoW"); + + const char* locale = g_localeNames[i]; + component->m_platform = BSN::FourCC(locale); + localeCount++; + component->m_version = GetWowLangVersion(locale); + } + } + + if (!localeCount) { + component = settings.m_components.New(); + component->m_program = BSN::FourCC("WoW"); + + const char* locale = s_iniLocaleNames[s_locale]; + component->m_platform = BSN::FourCC(locale); + component->m_version = GetWowLangVersion(locale); + } + + component = settings.m_components.New(); + component->m_program = BSN::FourCC("Tool"); + component->m_platform = BSN::FourCC("Win"); + + uint32_t launcherVersion = 0; + Blizzard::Version::FileVersion version; + + if (Blizzard::Version::GetFileVersion("Launcher.exe", version)) { + launcherVersion = version.m_revision; + } + + component->m_version = launcherVersion; + } + + this->m_patchInstructionLock.Enter(); + this->m_patchInstructions.Clear(); + this->m_patchInstructionLock.Leave(); + + for (uint32_t i = 0; i < settings.m_components.m_count; i++) { + char componentProgram[5]; + char componentPlatform[5]; + + Battlenet::Authentication::Component& component = settings.m_components[i]; + component.m_program.ToString(componentProgram, sizeof(componentProgram)); + component.m_platform.ToString(componentPlatform, sizeof(componentPlatform)); + BattlenetLogin::LogConnectionStatus("Component %s.%s.%d", componentProgram, componentPlatform, component.m_version); + } + + return Battlenet::TumorManager::Create(*this->m_application, settings); +} + +// VERIFY: a05b79fa manual +// OFFSET: 0x008C7AB0 +void BattlenetLogin::EnterPIN(int32_t count, uint8_t* digits) { + if (!this->unk_105D[0]) { + return; + } + + this->unk_105D[0] = 0; + + if (static_cast(count) > 10) { + SErrDisplayAppFatalMessage("", "", 0); + } + + char pin[12]; + + for (int32_t i = 0; i < count; i++) { + pin[i] = digits[i] + '0'; + } + + pin[count] = '\0'; + + Battlenet::Event::Creep::Invoke invoke; + Battlenet::Authentication::Request* authentication = invoke.Set<0, Battlenet::Authentication::Request>(); + Battlenet::Authentication::ModuleMessage* message = authentication->Set<2, Battlenet::Authentication::ModuleMessage>(); + message->m_moduleId = this->m_moduleId; + message->m_name = Battlenet::Event::AuthModule::RequestVirtualKeypadPIN; + + Battlenet::Authentication::ModuleParam* param = message->m_params.New(); + *param->Set<0, BSN::String<256>>() = pin; + + if (!g_tumorManager) { + SErrDisplayAppFatalMessage("", "", 0); + } + + g_tumorManager->SendEvent(Battlenet::Event::CREEP, invoke); +} + +// VERIFY: e5dd91ee manual +// OFFSET: 0x008C7C10 +void BattlenetLogin::EnterMatrix(uint8_t value) { + if (!this->m_matrixEnabled) { + SErrDisplayAppFatalMessage("", "", 0); + } + + Battlenet::Event::Creep::Invoke invoke; + Battlenet::Authentication::Request* authentication = invoke.Set<0, Battlenet::Authentication::Request>(); + Battlenet::Authentication::ModuleMessage* message = authentication->Set<2, Battlenet::Authentication::ModuleMessage>(); + message->m_moduleId = this->m_moduleId; + message->m_name = Battlenet::Event::AuthModule::EnterMatrixCard; + + Battlenet::Authentication::ModuleParam* param = message->m_params.New(); + *param->Set<1, uint32_t>() = value; + + if (!g_tumorManager) { + SErrDisplayAppFatalMessage("", "", 0); + } + + g_tumorManager->SendEvent(Battlenet::Event::CREEP, invoke); +} + +// VERIFY: 34fe48e7 manual +// OFFSET: 0x008C7D00 +void BattlenetLogin::RevertMatrix() { + if (!this->m_matrixEnabled) { + SErrDisplayAppFatalMessage("", "", 0); + } + + Battlenet::Event::Creep::Invoke invoke; + Battlenet::Authentication::Request* authentication = invoke.Set<0, Battlenet::Authentication::Request>(); + Battlenet::Authentication::ModuleMessage* message = authentication->Set<2, Battlenet::Authentication::ModuleMessage>(); + message->m_moduleId = this->m_moduleId; + message->m_name = Battlenet::Event::AuthModule::RevertMatrixCard; + + if (!g_tumorManager) { + SErrDisplayAppFatalMessage("", "", 0); + } + + g_tumorManager->SendEvent(Battlenet::Event::CREEP, invoke); +} + +// VERIFY: 1993fec7 manual +// OFFSET: 0x008C7DC0 +void BattlenetLogin::CommitMatrix() { + if (!this->m_matrixEnabled) { + SErrDisplayAppFatalMessage("", "", 0); + } + + Battlenet::Event::Creep::Invoke invoke; + Battlenet::Authentication::Request* authentication = invoke.Set<0, Battlenet::Authentication::Request>(); + Battlenet::Authentication::ModuleMessage* message = authentication->Set<2, Battlenet::Authentication::ModuleMessage>(); + message->m_moduleId = this->m_moduleId; + message->m_name = Battlenet::Event::AuthModule::CommitMatrixCard; + + if (!g_tumorManager) { + SErrDisplayAppFatalMessage("", "", 0); + } + + g_tumorManager->SendEvent(Battlenet::Event::CREEP, invoke); +} + +// VERIFY: a977f694 manual +// OFFSET: 0x008C7E80 +void BattlenetLogin::FinalizeMatrix() { + if (!this->m_matrixEnabled) { + SErrDisplayAppFatalMessage("", "", 0); + } + + this->m_matrixEnabled = false; + + Battlenet::Event::Creep::Invoke invoke; + Battlenet::Authentication::Request* authentication = invoke.Set<0, Battlenet::Authentication::Request>(); + Battlenet::Authentication::ModuleMessage* message = authentication->Set<2, Battlenet::Authentication::ModuleMessage>(); + message->m_moduleId = this->m_moduleId; + message->m_name = Battlenet::Event::AuthModule::FinalizeMatrixCard; + + if (!g_tumorManager) { + SErrDisplayAppFatalMessage("", "", 0); + } + + g_tumorManager->SendEvent(Battlenet::Event::CREEP, invoke); +} + +// VERIFY: d8ce7391 manual +// OFFSET: 0x008C7F40 +void BattlenetLogin::EnterToken(const char* token) { + if (!this->m_tokenRequired) { + SErrDisplayAppFatalMessage("", "", 0); + } + + this->m_tokenRequired = false; + + Battlenet::Event::Creep::Invoke invoke; + Battlenet::Authentication::Request* authentication = invoke.Set<0, Battlenet::Authentication::Request>(); + Battlenet::Authentication::ModuleMessage* message = authentication->Set<2, Battlenet::Authentication::ModuleMessage>(); + message->m_moduleId = this->m_moduleId; + message->m_name = Battlenet::Event::AuthModule::RequestToken; + + Battlenet::Authentication::ModuleParam* param = message->m_params.New(); + *param->Set<0, BSN::String<256>>() = token; + + if (!g_tumorManager) { + SErrDisplayAppFatalMessage("", "", 0); + } + + g_tumorManager->SendEvent(Battlenet::Event::CREEP, invoke); +} + +// VERIFY: efe382b2 manual +// OFFSET: 0x008C8050 +void BattlenetLogin::SendSurveyInfoToModule() { + Battlenet::Event::Creep::Invoke invoke; + Battlenet::Authentication::Request* authentication = invoke.Set<0, Battlenet::Authentication::Request>(); + Battlenet::Authentication::ModuleMessage* message = authentication->Set<2, Battlenet::Authentication::ModuleMessage>(); + message->m_moduleId = this->m_moduleId; + + SErrDisplayAppFatalMessage("", "", 0); +} + +// VERIFY: 98c6abd3 manual +// OFFSET: 0x008C80E0 +bool BattlenetLogin::SetGameAccount(uint32_t index) { + if (index >= this->m_gameAccounts.m_count || this->m_gameAccountSelected) { + return false; + } + + Battlenet::Event::Creep::Invoke invoke; + Battlenet::Authentication::Request* authentication = invoke.Set<0, Battlenet::Authentication::Request>(); + Battlenet::Authentication::ModuleMessage* message = authentication->Set<2, Battlenet::Authentication::ModuleMessage>(); + message->m_moduleId = this->m_moduleId; + message->m_name = Battlenet::Event::AuthModule::RequestGameAccount; + + GameAccount& account = this->m_gameAccounts.m_data[index]; + + Battlenet::Authentication::ModuleParam* param = message->m_params.New(); + *param->Set<1, uint32_t>() = account.m_region; + + param = message->m_params.New(); + *param->Set<0, BSN::String<256>>() = account.m_name; + + if (!g_tumorManager) { + SErrDisplayAppFatalMessage("", "", 0); + } + + g_tumorManager->SendEvent(Battlenet::Event::CREEP, invoke); + this->m_gameAccountSelected = 1; + + return true; +} + +// VERIFY: 5050708b manual +// OFFSET: 0x008C8280 +void BattlenetLogin::Logon(const char* loginServer, const char* portal) { + if (this->m_loggedOn) { + return; + } + + if (!g_tumorManager) { + g_tumorManager = this->CreateTumorManager(); + + if (!g_tumorManager) { + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_FAILED, LOGIN_NO_BATTLENET_MANAGER, nullptr, 0); + return; + } + + BattlenetUI::Init(); + } + + if (!SStrChr(this->m_username, '@') || static_cast(SStrLen(this->m_username) - 3) > 317) { + FrameScript_SignalEvent(GLUE_EVENT_OPEN_STATUS_DIALOG, "%s%s", "OKAY_HTML", FrameScript_GetText("LOGIN_UNKNOWN_ACCOUNT", -1, GENDER_NOT_APPLICABLE)); + return; + } + + this->m_reconnect = false; + this->m_serviceState = 4; + this->m_logonStatus = -1; + this->m_logonResult = 0; + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_CONNECTING, LOGIN_OK, nullptr, 0); + + if (portal && *portal) { + Battlenet::Event::Creep::Invoke invoke; + Battlenet::Event::Creep::Portal* request = invoke.Set<12, Battlenet::Event::Creep::Portal>(); + *request->Set<0, BSN::AsciiString<31>>() = portal; + g_tumorManager->SendEvent(Battlenet::Event::CREEP, invoke); + } + + this->m_gameAccountSelected = 0; + + Battlenet::Event::Creep::Invoke invoke; + Battlenet::Authentication::Request* authentication = invoke.Set<0, Battlenet::Authentication::Request>(); + BSN::AsciiString<320>* accountName = authentication->Set<1, BSN::AsciiString<320>>(); + SStrLower(this->m_username); + *accountName = this->m_username; + g_tumorManager->SendEvent(Battlenet::Event::CREEP, invoke); +} + +// VERIFY: 61a752e9 manual +// OFFSET: 0x008C8490 +void BattlenetLogin::QueueEvent(BN_EVENT_ID id, void* data, int32_t size) { + this->m_eventLock.Enter(); + + BN_EVENT* event = this->m_events[this->m_eventIndex].NewNode(2, 0, 0); + event->m_data = data; + event->m_id = id; + event->m_size = size; + + this->m_eventLock.Leave(); +} + +// VERIFY: 6fe1b770 auto +// OFFSET: 0x008C8730 +void BattlenetApplication::WCConnected(WowConnection* connection, WowConnection* inbound, uint32_t timeStamp, const NETCONNADDR* addr) { + this->m_localAddress.m_address[0] = addr->selfAddr.data[4]; + this->m_localAddress.m_address[1] = addr->selfAddr.data[5]; + this->m_localAddress.m_address[2] = addr->selfAddr.data[6]; + this->m_localAddress.m_address[3] = addr->selfAddr.data[7]; + this->m_localAddress.m_port[0] = addr->selfAddr.data[2]; + this->m_localAddress.m_port[1] = addr->selfAddr.data[3]; + + if (!this->m_login) { + SErrDisplayAppFatalMessage("", "", 0); + } + + NETADDR* peer = static_cast(malloc(sizeof(NETADDR))); + *peer = addr->peerAddr; + this->m_login->QueueEvent(BN_EVENT_CONNECTED, peer, sizeof(NETADDR)); +} + +// VERIFY: d780dfa0 auto +// OFFSET: 0x008C87B0 +void BattlenetApplication::WCDataReady(WowConnection* connection, uint32_t timeStamp, uint8_t* data, int32_t length) { + if (!this->m_login) { + SErrDisplayAppFatalMessage("", "", 0); + } + + void* copy = malloc(length); + memcpy(copy, data, length); + this->m_login->QueueEvent(BN_EVENT_DATA, copy, length); +} + +// VERIFY: fbe31bb4 auto +// OFFSET: 0x008C8800 +void BattlenetApplication::WCCantConnect(WowConnection* connection, uint32_t timeStamp, const NETCONNADDR* addr) { + this->m_login->QueueEvent(BN_EVENT_CANT_CONNECT, nullptr, 0); +} + +// VERIFY: 06ceae2d auto +// OFFSET: 0x008C8820 +void BattlenetApplication::WCDisconnected(WowConnection* connection, uint32_t timeStamp, const NETCONNADDR* addr) { + this->m_login->QueueEvent(BN_EVENT_DISCONNECTED, nullptr, 0); +} + +// VERIFY: f9ecbbad manual +// OFFSET: 0x008C8840 +void BattlenetLogin::UpdateRealmListData(uint32_t region, uint32_t battlegroup, uint32_t id, const Battlenet::Realm::Info* info, uint8_t flags, bool remove) { + this->m_realmLock.Enter(); + + REALM_INFO* realm = nullptr; + + for (BN_REALM* node = this->m_realms.Head(); node; node = this->m_realms.Next(node)) { + if (node->m_info.m_regionId == region && node->m_info.m_battlegroupId == battlegroup && node->m_info.m_realmId == id) { + realm = &node->m_info; + + if (remove) { + this->m_realms.DeleteNode(node); + this->m_realmLock.Leave(); + return; + } + + break; + } + } + + if (!info) { + this->m_realmLock.Leave(); + return; + } + + if (!realm) { + BN_REALM* node = this->m_realms.NewNode(2, 0, 0); + + if (!node) { + this->m_realmLock.Leave(); + return; + } + + realm = &node->m_info; + } + + realm->m_type = info->m_type; + realm->m_otherFlags = info->m_otherFlags; + realm->m_flags = flags; + SStrCopy(realm->m_realmName, info->m_name.m_data, sizeof(realm->m_realmName)); + SStrCopy(realm->m_realmAddress, "0.0.0.0", sizeof(realm->m_realmAddress)); + realm->m_population = info->m_population; + realm->m_numCharacters = this->GetCharacterCount(region, battlegroup, id); + realm->m_category = info->m_category; + realm->m_regionId = region; + realm->m_battlegroupId = battlegroup; + realm->m_realmId = id; + + if (!info->m_build.m_exists) { + realm->m_build = 0; + realm->m_versionMajor = 0; + realm->m_versionMinor = 0; + realm->m_versionRevision = 0; + realm->m_versionBuild = 0; + this->m_realmLock.Leave(); + return; + } + + realm->m_build = info->m_build.Get().m_build; + realm->m_versionMajor = SStrToInt(info->m_build.Get().m_version.m_data); + + const char* cursor = SStrChr(info->m_build.Get().m_version.m_data, '.'); + + if (cursor) { + cursor++; + realm->m_versionMinor = SStrToInt(cursor); + cursor = SStrChr(cursor, '.'); + + if (cursor) { + cursor++; + realm->m_versionRevision = SStrToInt(cursor); + cursor = SStrChr(cursor, '.'); + + if (cursor) { + realm->m_versionBuild = SStrToInt(cursor + 1); + realm->m_flags |= 0x4; + } + } + } + + const Battlenet::IP4::AddressPort& address = info->m_build.Get().m_address; + SStrPrintf(realm->m_realmAddress, sizeof(realm->m_realmAddress), "%u.%u.%u.%u:%u", address.m_address[0], address.m_address[1], address.m_address[2], address.m_address[3], address.m_port[1] + (address.m_port[0] << 8)); + + this->m_realmLock.Leave(); +} + +// VERIFY: 2265afc4 manual +// OFFSET: 0x008C8B50 +void BattlenetLogin::GetRealmList() { + if (this->m_realmListRequested) { + this->QueueEvent(BN_EVENT_REALM_LIST, nullptr, 0); + } else if (g_tumorManager && this->IsLoggedOn()) { + this->m_realmListRequested = true; + + Battlenet::Event::Creep::Invoke invoke; + Battlenet::Realm::Request* request = invoke.Set<6, Battlenet::Realm::Request>(); + Battlenet::Realm::ListRequest* list = request->Set<0, Battlenet::Realm::ListRequest>(); + list->m_subscribe = true; + list->unk_0004 = 0; + list->unk_0008 = 0; + + g_tumorManager->SendEvent(Battlenet::Event::CREEP, invoke); + } +} + +// VERIFY: 913b397e manual // OFFSET: 0x008C8C00 -BattlenetLogin::BattlenetLogin() : unk_114C(0), unk_1188(0) { - this->unk_10F0 = 0; +BattlenetLogin::BattlenetLogin() { + this->m_application = nullptr; g_tumorManager = nullptr; - this->unk_10F4 = 0; - this->unk_10F8 = 0; - this->unk_120C = 4; + this->m_moduleId = 0; + this->m_logonResult = 0; + this->m_serviceState = 4; this->m_realmLock.Enter(); this->m_realms.Clear(); this->m_realmLock.Leave(); - this->unk_1110 = 0; - this->unk_1114 = 0; + this->m_realmListRequested = false; + this->m_joinRealmId = 0; this->m_eventLock.Enter(); this->m_events[0].Clear(); this->m_events[1].Clear(); this->m_eventLock.Leave(); - this->unk_1208 = 0; + this->m_eventIndex = 0; this->m_gameAccountLock.Enter(); this->m_gameAccounts.Clear(); this->m_gameAccountLock.Leave(); - this->unk_1178 = 0; + this->m_gameAccountSelected = 0; this->m_patchInstructionLock.Enter(); this->m_patchInstructions.Clear(); this->m_patchInstructionLock.Leave(); - this->unk_11B8 = 0; - this->unk_11BC = 0; - this->unk_11C0 = 0; - this->unk_11C4 = 0; + this->m_accountFlags = 0; + this->m_accountFlags2 = 0; + this->m_surveyPending = false; + this->m_surveyTime = 0; +} + +// VERIFY: 32745cec auto +// OFFSET: 0x008C8DF0 +void BattlenetLogin::DestroyTumorManager() { + s_battlenetAllocator.Delete(g_tumorManager); + + this->m_eventLock.Enter(); + this->m_events[0].Clear(); + this->m_events[1].Clear(); + this->m_eventLock.Leave(); + + this->m_realmLock.Enter(); + this->m_realms.Clear(); + this->m_realmLock.Leave(); + + this->m_realmListRequested = false; + + this->m_gameAccountLock.Enter(); + this->m_gameAccounts.Clear(); + this->m_gameAccountLock.Leave(); + + this->m_gameAccountSelected = 0; + + this->m_patchInstructionLock.Enter(); + this->m_patchInstructions.Clear(); + this->m_patchInstructionLock.Leave(); +} + +// VERIFY: 4c57ab63 manual +// OFFSET: 0x008C8F00 +void BattlenetLogin::Init(LoginResponse* loginResponse) { + if (!loginResponse) { + SErrDisplayAppFatalMessage("", "", 0); + } + + this->m_loginResponse = loginResponse; + this->m_logonResult = 0; + this->m_serviceState = 4; + + this->m_realmLock.Enter(); + this->m_realms.Clear(); + this->m_realmLock.Leave(); + + this->m_eventLock.Enter(); + this->m_events[0].Clear(); + this->m_events[1].Clear(); + this->m_eventLock.Leave(); + + this->m_gameAccountLock.Enter(); + this->m_gameAccounts.Clear(); + this->m_gameAccountLock.Leave(); + + this->m_gameAccountSelected = 0; + this->m_realmCharacterCounts = static_cast(SMemAlloc(64 * sizeof(RealmCharacterCount), __FILE__, __LINE__, 0)); + this->m_realmCharacterCountCount = 0; + this->m_surveyPending = false; + this->m_surveyTime = 0; + + Battlenet::Initialize(s_battlenetAllocator); + + delete this->m_application; + + this->m_application = new (__FILE__, __LINE__) BattlenetApplication(); + + if (this->m_application) { + this->m_application->m_login = this; + g_tumorManager = this->CreateTumorManager(); + + if (g_tumorManager) { + BattlenetUI::Init(); + } else { + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_FAILED, LOGIN_NO_BATTLENET_MANAGER, nullptr, 0); + } + } else { + if (g_tumorManager) { + s_battlenetAllocator.Delete(g_tumorManager); + g_tumorManager = nullptr; + } + + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_FAILED, LOGIN_NO_BATTLENET_APPLICATION, nullptr, 0); + } +} + +// VERIFY: 4a3d7376 manual +// OFFSET: 0x008C9140 +void BattlenetLogin::HandleDisconnectEvents(uint32_t index) { + TSList& events = this->m_events[index]; + bool disconnected = false; + bool serviceDisconnected = false; + + for (BN_EVENT* event = events.Head(); event; event = events.Next(event)) { + if (event->m_id == BN_EVENT_SERVICE_DISCONNECTED) { + BattlenetUI::SetDisconnectedFromBattlenet(true); + disconnected = true; + serviceDisconnected = true; + break; + } + + if (event->m_id == BN_EVENT_SERVICE_FAILED) { + BattlenetUI::SetDisconnectedFromBattlenet(true); + this->m_loggedOn = false; + + if (!IsInOrEnteringWorld()) { + disconnected = true; + break; + } + } + } + + if (!disconnected) { + return; + } + + for (BN_EVENT* event = events.Head(); event;) { + BN_EVENT* next = events.Next(event); + free(event->m_data); + events.DeleteNode(event); + event = next; + } + + if (CGlueMgr::m_loginState == LOGIN_STATE_DOWNLOADFILE) { + return; + } + + if (!this->m_online) { + this->m_logonStatus = 1; + } + + if (serviceDisconnected) { + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_DISCONNECTED, LOGIN_OK, nullptr, 0); + } else { + int32_t result = this->m_logonResult; + + if (!result) { + result = 105; + } + + this->LogonResultBN(result); + } + + this->m_loggedOn = false; + this->m_online = false; + + Battlenet::TumorManager* manager = this->CreateTumorManager(); + this->DestroyTumorManager(); + g_tumorManager = manager; + BattlenetUI::Init(); +} + +// VERIFY: 8d22a9d5 manual +// OFFSET: 0x008C9310 +void BattlenetLogin::HandleInvoke(const Battlenet::Event::Larva::Invoke* invoke) { + if (invoke->m_tag == 0) { + if (invoke->m_authentication.m_tag == 0) { + const Battlenet::Authentication::ModuleRequest& request = invoke->Get<0, Battlenet::Authentication::Response>().Get<0, Battlenet::Authentication::ModuleRequest>(); + + if (!SStrCmpI(request.m_name.m_data, Battlenet::Event::AuthModule::RequestPassword.m_data, STORM_MAX_STR)) { + this->m_moduleId = request.m_moduleId; + this->GetLogonMethod(); + } else if (!SStrCmpI(request.m_name.m_data, Battlenet::Event::AuthModule::RequestToken.m_data, STORM_MAX_STR)) { + this->m_moduleId = request.m_moduleId; + this->SetTokenInfo(true, request.m_params[0].Get<1, uint32_t>()); + } else if (!SStrCmpI(request.m_name.m_data, Battlenet::Event::AuthModule::RequestMatrixCard.m_data, STORM_MAX_STR)) { + this->m_moduleId = request.m_moduleId; + const char* challenges = request.m_params[1].Get<0, BSN::String<256>>().m_data; + const char* info = request.m_params[0].Get<0, BSN::String<256>>().m_data; + this->SetAuthModuleMatrixInfo(info, challenges); + } else if (!SStrCmpI(request.m_name.m_data, Battlenet::Event::AuthModule::RequestVirtualKeypadPIN.m_data, STORM_MAX_STR)) { + this->m_moduleId = request.m_moduleId; + this->SetAuthModulePinInfo(request.m_params[0].Get<0, BSN::String<256>>().m_data); + } else if (!SStrCmpI(request.m_name.m_data, Battlenet::Event::AuthModule::ClearGameAccounts.m_data, STORM_MAX_STR)) { + this->m_moduleId = request.m_moduleId; + this->m_gameAccountLock.Enter(); + this->m_gameAccounts.Clear(); + this->m_gameAccountLock.Leave(); + } else if (!SStrCmpI(request.m_name.m_data, Battlenet::Event::AuthModule::AddGameAccount.m_data, STORM_MAX_STR)) { + this->m_moduleId = request.m_moduleId; + this->m_gameAccountLock.Enter(); + + GameAccount* account = this->m_gameAccounts.New(); + account->m_region = request.m_params[0].Get<1, uint32_t>(); + SStrCopy(account->m_name, request.m_params[1].Get<0, BSN::String<256>>().m_data, sizeof(account->m_name)); + + this->m_gameAccountLock.Leave(); + } else if (!SStrCmpI(request.m_name.m_data, Battlenet::Event::AuthModule::RequestGameAccount.m_data, STORM_MAX_STR)) { + this->m_moduleId = request.m_moduleId; + this->QueueEvent(BN_EVENT_GAME_ACCOUNTS_UPDATED, nullptr, 0); + } else if (!SStrCmpI(request.m_name.m_data, Battlenet::Event::AuthModule::RequestSurveyInfo.m_data, STORM_MAX_STR)) { + this->m_moduleId = request.m_moduleId; + this->QueueEvent(BN_EVENT_SEND_SURVEY_INFO, nullptr, 0); + } else if (!SStrCmpI(request.m_name.m_data, Battlenet::Event::AuthModule::ShowSurveyDialog.m_data, STORM_MAX_STR)) { + this->m_moduleId = request.m_moduleId; + this->QueueEvent(BN_EVENT_SHOW_SURVEY, nullptr, 0); + } + } else if (invoke->m_authentication.m_tag == 1) { + if (this->m_serviceState == 6) { + this->m_application->LogLevel("Ignoring Authentication Success invoke while in Service::RECOVERED state.", 4); + } else { + const Battlenet::Authentication::Complete& complete = invoke->Get<0, Battlenet::Authentication::Response>().Get<1, Battlenet::Authentication::Complete>(); + SStrCopy(this->m_username, complete.m_accountName.m_data, STORM_MAX_STR); + this->m_accountFlags = complete.m_accountFlags; + this->m_accountFlags2 = complete.m_accountFlags2; + this->LogonResultBN(0); + } + } else if (invoke->m_authentication.m_tag == 2 && this->m_serviceState != 5) { + char text[64]; + const Battlenet::Authentication::Failure& failure = invoke->Get<0, Battlenet::Authentication::Response>().Get<2, Battlenet::Authentication::Failure>(); + + SStrPrintf(text, 63, "Battle.net Authentication failure code: %d", failure.m_error); + ConsoleWrite(text, DEFAULT_COLOR); + + if (failure.m_error != 138) { + this->LogonResultBN(failure.m_error); + + if (this->m_serviceState != 7) { + this->QueueEvent(BN_EVENT_LOGOFF, nullptr, 0); + } + } + } + } else if (invoke->m_tag == 1) { + this->m_serviceState = invoke->m_service.m_tag; + + switch (invoke->m_service.m_tag) { + case 2: + this->QueueEvent(BN_EVENT_SERVICE_FAILED, nullptr, 0); + break; + + case 3: + if (!invoke->Get<1, Battlenet::Service::State>().Get<3, uint32_t>()) { + this->m_serviceState = 6; + } + + break; + + case 4: + this->QueueEvent(BN_EVENT_SERVICE_DISCONNECTED, nullptr, 0); + break; + + case 5: + this->QueueEvent(BN_EVENT_SERVICE_LOST, nullptr, 0); + break; + + case 6: + this->QueueEvent(BN_EVENT_SERVICE_RECOVERED, nullptr, 0); + break; + + case 7: + this->QueueEvent(BN_EVENT_RECONNECTED, nullptr, 0); + break; + } + } else if (invoke->m_tag == 9) { + if (invoke->m_realm.m_tag == 0) { + int32_t tag = invoke->Get<9, Battlenet::Realm::Response>().Get<0, Battlenet::Realm::Update>().m_info.m_tag; + + if (tag == 0) { + const Battlenet::Realm::Update& update = invoke->Get<9, Battlenet::Realm::Response>().Get<0, Battlenet::Realm::Update>(); + this->UpdateRealmListData(update.m_region, update.m_battlegroup, update.m_id, &update.m_info.Get<0, Battlenet::Realm::Info>(), update.m_info.Get<0, Battlenet::Realm::Info>().m_flags, false); + } else if (tag == 1) { + const Battlenet::Realm::Update& update = invoke->Get<9, Battlenet::Realm::Response>().Get<0, Battlenet::Realm::Update>(); + this->UpdateRealmListData(update.m_region, update.m_battlegroup, update.m_id, nullptr, 0, true); + } + } else if (invoke->m_realm.m_tag == 1) { + int32_t tag = invoke->Get<9, Battlenet::Realm::Response>().Get<1, Battlenet::Realm::List>().m_tag; + + if (tag == 0) { + this->m_realmLock.Enter(); + this->m_realms.Clear(); + this->m_realmListRequested = true; + + uint32_t count = invoke->Get<9, Battlenet::Realm::Response>().Get<1, Battlenet::Realm::List>().Get<0, BSN::Array>().m_count; + this->m_realmCharacterCountCount = count; + + if (count >= 64) { + count = 64; + } + + this->m_realmCharacterCountCount = count; + + if (this->m_realmCharacterCounts) { + for (uint32_t i = 0; i < this->m_realmCharacterCountCount; i++) { + const Battlenet::Realm::CharacterCount& characterCount = invoke->Get<9, Battlenet::Realm::Response>().Get<1, Battlenet::Realm::List>().Get<0, BSN::Array>()[i]; + this->m_realmCharacterCounts[i].m_region = characterCount.m_region; + this->m_realmCharacterCounts[i].m_battlegroup = characterCount.m_battlegroup; + this->m_realmCharacterCounts[i].m_id = characterCount.m_id; + this->m_realmCharacterCounts[i].m_count = characterCount.m_count; + } + } + + this->m_realmLock.Leave(); + } else if (tag == 1) { + this->QueueEvent(BN_EVENT_REALM_LIST, nullptr, 0); + } + } else if (invoke->m_realm.m_tag == 2) { + int32_t tag = invoke->Get<9, Battlenet::Realm::Response>().Get<2, Battlenet::Realm::JoinResponse>().m_tag; + + if (tag == 0) { + const Battlenet::Realm::JoinInfo& join = invoke->Get<9, Battlenet::Realm::Response>().Get<2, Battlenet::Realm::JoinResponse>().Get<0, Battlenet::Realm::JoinInfo>(); + + for (uint32_t i = 0; i < 40; i++) { + this->m_sessionKey[i] = join.m_sessionKey[i]; + } + + uint16_t port = (join.m_address.m_port[0] << 8) | join.m_address.m_port[1]; + uint32_t address = (((((join.m_address.m_address[0] << 8) | join.m_address.m_address[1]) << 8) | join.m_address.m_address[2]) << 8) | join.m_address.m_address[3]; + this->m_loginResponse->JoinRealmResult(this->m_joinRealmId, address, port, 0, 0); + } else if (tag == 1) { + uint32_t error = invoke->Get<9, Battlenet::Realm::Response>().Get<2, Battlenet::Realm::JoinResponse>().Get<1, uint32_t>(); + this->m_loginResponse->JoinRealmResult(0, 0, 0, 0, error); + } + } + } +} + +// VERIFY: 0e3dbd5d manual +// OFFSET: [0x008C9A40, 0x008CA050] +BattlenetLogin::~BattlenetLogin() { + this->m_patchInstructionLock.Enter(); + this->m_patchInstructions.Clear(); + this->m_patchInstructionLock.Leave(); + + this->m_gameAccountLock.Enter(); + this->m_gameAccounts.Clear(); + this->m_gameAccountLock.Leave(); + + this->m_gameAccountSelected = 0; + + this->m_eventLock.Enter(); + this->m_events[0].Clear(); + this->m_events[1].Clear(); + this->m_eventLock.Leave(); + + this->m_realmLock.Enter(); + this->m_realms.Clear(); + this->m_realmLock.Leave(); + + if (g_tumorManager) { + BattlenetUI::Uninit(); + } + + this->DestroyTumorManager(); + + delete this->m_application; + delete[] this->m_realmCharacterCounts; + + this->m_realmCharacterCounts = nullptr; + + Battlenet::Teardown(); +} + +// VERIFY: 5ebf6bfa manual +// OFFSET: 0x008C9C70 +void BattlenetLogin::EventQueueUpdate() { + uint32_t index = this->m_eventIndex; + + this->m_eventLock.Enter(); + this->m_eventIndex = 1 - this->m_eventIndex; + this->m_eventLock.Leave(); + + this->HandleDisconnectEvents(index); + + TSList& events = this->m_events[index]; + + for (BN_EVENT* event = events.Head(); event;) { + BN_EVENT* next = events.Next(event); + + switch (event->m_id) { + case BN_EVENT_CONNECTED: + this->Connected(*static_cast(event->m_data)); + break; + + case BN_EVENT_CANT_CONNECT: + this->CantConnect(); + break; + + case BN_EVENT_DISCONNECTED: + this->Disconnected(); + break; + + case BN_EVENT_DATA: { + if (!g_tumorManager) { + SErrDisplayAppFatalMessage("", "", 0); + } + + uint32_t used; + Battlenet::SystemClient& client = g_tumorManager->m_tumor; + client.Recv(this->m_application->m_connection, event->m_data, event->m_size, used); + break; + } + + case BN_EVENT_REALM_LIST: + this->BuildRealmListResult(); + break; + + case BN_EVENT_RECONNECTED: + this->m_loginResponse->UpdateLoginStatus(LOGIN_STATE_RESPONSE_CONNECTED, LOGIN_OK, nullptr, 0); + BattlenetUI::SetBattlenetConnectionRecovered(); + break; + + case BN_EVENT_SERVICE_LOST: + BattlenetUI::SetDisconnectedFromBattlenet(false); + break; + + case BN_EVENT_SERVICE_RECOVERED: + BattlenetUI::SetBattlenetConnectionRecovered(); + break; + + case BN_EVENT_GAME_ACCOUNTS_UPDATED: + FrameScript_SignalEvent(GLUE_EVENT_GAME_ACCOUNTS_UPDATED, nullptr); + break; + + case BN_EVENT_LOGOFF: + this->Logoff(); + break; + + case BN_EVENT_SHOW_SURVEY: + this->m_surveyPending = true; + this->m_surveyTime = OsGetAsyncTimeMs(); + FrameScript_SignalEvent(GLUE_EVENT_OPEN_STATUS_DIALOG, "%s%s", "CANCEL", FrameScript_GetText("LOGIN_STATE_SURVEY", -1, GENDER_NOT_APPLICABLE)); + break; + + case BN_EVENT_SEND_SURVEY_INFO: + this->SendSurveyInfoToModule(); + + default: + SErrDisplayAppFatalMessage("", "", 0); + } + + free(event->m_data); + events.DeleteNode(event); + event = next; + } +} + +// VERIFY: 09ca53f7 manual +// OFFSET: 0x008C9EA0 +void BattlenetApplication::RecvEvent(const Battlenet::Event::Header& header, const BSN::EncodedObject* data) { + if (header.m_eventType == 5) { + BSN::BSNEncodedObject invoke; + invoke.WalkAndGet(data); + this->m_login->HandleInvoke(&invoke.m_data); + } else if (header.m_eventType == 1) { + BSN::BSNEncodedObject invoke; + invoke.WalkAndGet(data); + this->m_login->HandleUpdateInvoke(&invoke.m_data); + } +} + +// VERIFY: a186d659 manual +// OFFSET: 0x008C9F70 +void BattlenetLogin::Update() { + this->EventQueueUpdate(); + + if (g_tumorManager) { + Battlenet::SystemClient& client = g_tumorManager->m_tumor; + client.Process(OsGetAsyncTimeMs()); + } + + if (this->m_surveyPending && this->m_serviceState != 2 && this->m_serviceState != 5 && OsGetAsyncTimeMs() - this->m_surveyTime > 1000) { + this->m_surveyPending = false; + FrameScript_SignalEvent(GLUE_EVENT_CLOSE_STATUS_DIALOG, nullptr); + + if (g_tumorManager) { + Battlenet::Event::Creep::Invoke invoke; + Battlenet::Authentication::Request* authentication = invoke.Set<0, Battlenet::Authentication::Request>(); + Battlenet::Authentication::ModuleMessage* message = authentication->Set<2, Battlenet::Authentication::ModuleMessage>(); + message->m_moduleId = this->m_moduleId; + message->m_name = Battlenet::Event::AuthModule::SurveyDialogComplete; + g_tumorManager->SendEvent(Battlenet::Event::CREEP, invoke); + } + } +} + +// VERIFY: 77b47832 auto +// OFFSET: 0x00530CE0 +bool BattlenetLogin::IsConnected() { + return this->m_serviceState == 7 || this->m_serviceState == 6 || this->m_serviceState == 3; } // VERIFY: 191ce575 auto @@ -55,22 +1728,22 @@ const uint8_t* BattlenetLogin::GetKeyMap() { return &this->unk_105D[1]; } -// VERIFY: 9fe999b5 manual +// VERIFY: f1a20f90 manual // OFFSET: 0x008C5B40 bool BattlenetLogin::IsTrialAccount() { - return (this->unk_11B8 & 0x8) != 0; + return (this->m_accountFlags & 0x8) != 0; } -// VERIFY: 56874f0c manual +// VERIFY: 8e8b170c manual // OFFSET: 0x008C5B60 bool BattlenetLogin::IsProPassAccount() { - return (this->unk_11B8 & 0x800000) != 0; + return (this->m_accountFlags & 0x800000) != 0; } -// VERIFY: 20b15a2f manual +// VERIFY: 3d74de1d manual // OFFSET: 0x008C5B80 bool BattlenetLogin::IsGMAccount() { - return (this->unk_11B8 & 0x1) != 0; + return (this->m_accountFlags & 0x1) != 0; } // VERIFY: 781acb9e auto @@ -142,3 +1815,116 @@ uint32_t BattlenetLogin::GetGameAccountRegion(uint32_t index) { return 0; } + +// VERIFY: 588e5d04 auto +// OFFSET: 0x00532A60 +void BattlenetLogin::GetVersionProof(const uint8_t* versionChallenge) { + SErrDisplayAppFatalMessage("", "", 0); +} + +// VERIFY: 7c681e4b auto +// OFFSET: 0x00532A60 +void BattlenetLogin::SetPinInfo(bool enabled, uint32_t seed, const uint8_t* salt) { + SErrDisplayAppFatalMessage("", "", 0); +} + +// VERIFY: e59eb6e7 auto +// OFFSET: 0x00532A60 +void BattlenetLogin::GetPinInfo(bool* enabled, uint8_t** salt, uint8_t** hash) { + SErrDisplayAppFatalMessage("", "", 0); +} + +// VERIFY: 0834ae87 auto +// OFFSET: 0x00532A60 +void BattlenetLogin::SetMatrixInfo(bool enabled, uint8_t width, uint8_t height, uint8_t minDigits, uint8_t maxDigits, bool flipCoords, uint8_t challengeCount, uint64_t seed, const uint8_t* sessionKey, uint32_t sessionKeyLength) { + SErrDisplayAppFatalMessage("", "", 0); +} + +// VERIFY: a0319163 auto +// OFFSET: 0x00532A60 +void BattlenetLogin::GetMatrixProof(bool* enabled, const uint8_t** proof) const { + SErrDisplayAppFatalMessage("", "", 0); +} + +// VERIFY: e23e08a1 auto +// OFFSET: 0x00532A60 +void BattlenetLogin::GetTokenInfo(bool* enabled, char* token) { + SErrDisplayAppFatalMessage("", "", 0); +} + +// VERIFY: 8e3e2131 auto +// OFFSET: 0x00532A60 +void BattlenetLogin::LogonResult(Grunt::Result result, const uint8_t* sessionKey, uint32_t sessionKeyLength, uint16_t flags) { + SErrDisplayAppFatalMessage("", "", 0); +} + +// VERIFY: 14fadb30 auto +// OFFSET: 0x00532A60 +void BattlenetLogin::ReconnectResult(Grunt::Result result, const uint8_t* sessionKey, uint32_t sessionKeyLength, uint16_t flags) { + SErrDisplayAppFatalMessage("", "", 0); +} + +// VERIFY: 9b7ebb81 auto +// OFFSET: 0x008E5250 +int32_t BattlenetLogin::GetServerId() { + return 0; +} + +// VERIFY: 16ee8ba4 auto +// OFFSET: 0x00532A60 +const uint8_t* BattlenetLogin::GetVersionChallenge() { + SErrDisplayAppFatalMessage("", "", 0); +} + +// VERIFY: 6aac27e5 auto +// OFFSET: 0x005EEB70 +void BattlenetLogin::Reconnect() { +} + +// VERIFY: 6c77d2b7 auto +// OFFSET: 0x00532A60 +int32_t BattlenetLogin::Wait(const char* message, LoginData& loginData) { + SErrDisplayAppFatalMessage("", "", 0); +} + +// VERIFY: b98bce31 auto +// OFFSET: 0x00532A60 +void BattlenetLogin::ProveVersion(const uint8_t* versionChecksum) { + SErrDisplayAppFatalMessage("", "", 0); +} + +// VERIFY: 7d626730 auto +// OFFSET: 0x00532A60 +void BattlenetLogin::FileAccept(bool accept, uint64_t offset) { + SErrDisplayAppFatalMessage("", "", 0); +} + +// VERIFY: eb437353 auto +// OFFSET: 0x00532A60 +void BattlenetLogin::FileComplete(bool success) { + SErrDisplayAppFatalMessage("", "", 0); +} + +// VERIFY: b94b273e auto +// OFFSET: 0x00532A60 +int32_t BattlenetLogin::GetSurveyId() { + SErrDisplayAppFatalMessage("", "", 0); +} + +// VERIFY: 3249b71d auto +// OFFSET: 0x00532A60 +void BattlenetLogin::SendSurveyData(uint16_t size, uint8_t* data) { + SErrDisplayAppFatalMessage("", "", 0); +} + +// VERIFY: 8a2c0499 auto +// OFFSET: 0x00532A60 +void BattlenetLogin::SendSurveyFailed() { + SErrDisplayAppFatalMessage("", "", 0); +} + +// VERIFY: 4092e10a auto +// OFFSET: 0x008C8DE0 +int32_t BattlenetLogin::GetLoginServerType() { + return 1; +} diff --git a/WoW/Source/WowServices/BattlenetLogin.h b/WoW/Source/WowServices/BattlenetLogin.h index 0ff0b07..fd132eb 100644 --- a/WoW/Source/WowServices/BattlenetLogin.h +++ b/WoW/Source/WowServices/BattlenetLogin.h @@ -5,18 +5,41 @@ #include #include "Engine/Source/Storm/H/stpl.h" #include "Engine/Source/Storm/Source/SLock.h" +#include "WoW/Source/Battlenet/Battlenet.h" +#include "WoW/Source/Battlenet/BattlenetProtocol.h" #include "WoW/Source/WowServices/Login.h" +#include "WoW/Source/WowServices/WowConnection.h" +#ifdef GetCurrentTime +#undef GetCurrentTime +#endif + +namespace Battlenet { class TumorManager; +} -extern TumorManager* g_tumorManager; +class BattlenetApplication; + +extern Battlenet::TumorManager* g_tumorManager; + +class BattlenetAllocator : public Battlenet::Allocator { + public: + void* Alloc(uint32_t size) override; + void Free(void* memory) override; +}; + +extern BattlenetAllocator s_battlenetAllocator; class BattlenetLogin : public Login { public: struct BN_EVENT : public TSLinkedNode { + /* 0008 */ BN_EVENT_ID m_id; + /* 000C */ void* m_data; + /* 0010 */ int32_t m_size; }; struct BN_REALM : public TSLinkedNode { + /* 0008 */ REALM_INFO m_info; }; struct GameAccount { @@ -25,35 +48,46 @@ class BattlenetLogin : public Login { }; struct PatchInstruction { + /* 0000 */ char m_patch[255]; }; - /* 10F0 */ uint32_t unk_10F0; - /* 10F4 */ uint32_t unk_10F4; - /* 10F8 */ uint32_t unk_10F8; - /* 10FC */ uint32_t unk_10FC; - /* 1100 */ uint32_t unk_1100; + struct RealmCharacterCount { + /* 0000 */ uint32_t m_region; + /* 0004 */ uint32_t m_battlegroup; + /* 0008 */ uint32_t m_id; + /* 000C */ uint32_t m_count; + }; + + static bool s_monolithicComponent; + static char s_monolithicPlatform[5]; + + static void LogConnectionStatus(const char* format, ...); + + /* 10F0 */ BattlenetApplication* m_application; + /* 10F4 */ uint32_t m_moduleId; + /* 10F8 */ int32_t m_logonResult; + /* 10FC */ RealmCharacterCount* m_realmCharacterCounts; + /* 1100 */ uint32_t m_realmCharacterCountCount; /* 1104 */ TSList m_realms; - /* 1110 */ uint8_t unk_1110; + /* 1110 */ bool m_realmListRequested; /* 1111 */ uint8_t unk_1111[3]; - /* 1114 */ uint32_t unk_1114; + /* 1114 */ uint32_t m_joinRealmId; /* 1118 */ SCritSect m_realmLock; - /* 1140 */ TSFixedArray m_gameAccounts; - /* 114C */ uint32_t unk_114C; + /* 1140 */ TSGrowableArray m_gameAccounts; /* 1150 */ SCritSect m_gameAccountLock; - /* 1178 */ uint32_t unk_1178; - /* 117C */ TSFixedArray m_patchInstructions; - /* 1188 */ uint32_t unk_1188; + /* 1178 */ uint32_t m_gameAccountSelected; + /* 117C */ TSGrowableArray m_patchInstructions; /* 118C */ SCritSect m_patchInstructionLock; /* 11B4 */ uint32_t unk_11B4; - /* 11B8 */ uint32_t unk_11B8; - /* 11BC */ uint32_t unk_11BC; - /* 11C0 */ uint8_t unk_11C0; + /* 11B8 */ uint32_t m_accountFlags; + /* 11BC */ uint32_t m_accountFlags2; + /* 11C0 */ bool m_surveyPending; /* 11C1 */ uint8_t unk_11C1[3]; - /* 11C4 */ uint32_t unk_11C4; + /* 11C4 */ uint32_t m_surveyTime; /* 11C8 */ TSList m_events [2]; /* 11E0 */ SCritSect m_eventLock; - /* 1208 */ uint32_t unk_1208; - /* 120C */ uint32_t unk_120C; + /* 1208 */ uint32_t m_eventIndex; + /* 120C */ int32_t m_serviceState; bool Connected(const NETADDR& address) override; bool Disconnected() override; @@ -97,39 +131,61 @@ class BattlenetLogin : public Login { void Update() override; void Init(LoginResponse* loginResponse) override; ~BattlenetLogin() override; - void JoinRealm(uint32_t a1, uint32_t a2, uint32_t a3) override; + void JoinRealm(uint32_t region, uint32_t battlegroup, uint32_t id) override; int32_t GetLoginServerType() override; BattlenetLogin(); - + void BuildRealmListResult(); + Battlenet::TumorManager* CreateTumorManager(); + void DestroyTumorManager(); + void EventQueueUpdate(); + uint8_t GetCharacterCount(uint32_t region, uint32_t battlegroup, uint32_t id); const char* GetGameAccountName(uint32_t index); uint32_t GetGameAccountRegion(uint32_t index); uint32_t GetNumGameAccounts(); + const char* GetPatchInstruction(uint32_t index); + void HandleDisconnectEvents(uint32_t index); + void HandleInvoke(const Battlenet::Event::Larva::Invoke* invoke); + void HandleUpdateInvoke(const Battlenet::Event::Update::Invoke* invoke); bool IsConnected(); + void LogonResultBN(int32_t result); + void QueueEvent(BN_EVENT_ID id, void* data, int32_t size); + void SendSurveyInfoToModule(); + void SetAuthModuleMatrixInfo(const char* info, const char* challenges); + void SetAuthModulePinInfo(const char* keyMap); bool SetGameAccount(uint32_t index); + void UpdateRealmListData(uint32_t region, uint32_t battlegroup, uint32_t id, const Battlenet::Realm::Info* info, uint8_t flags, bool remove); }; -class BNetAuthPacketSub1 { +class BattlenetApplication : public Battlenet::Application, public WowConnectionResponse { public: - /* 0000 */ uint32_t unk_0000; -}; + /* 0010 */ uint32_t m_connection; + /* 0014 */ Battlenet::IP4::AddressPort m_localAddress; + /* 001A */ Battlenet::IP4::AddressPort m_remoteAddress; + /* 0020 */ BattlenetLogin* m_login; + /* 0024 */ WowConnection* m_wowConnection; -class BattlenetApplication { - public: - /* 0000 */ uint8_t unk_0000[8]; - /* 0008 */ uint8_t unk_0008; - /* 0009 */ uint8_t unk_0009; - /* 000A */ uint8_t unk_000A; - /* 000B */ uint8_t unk_000B; - /* 000C */ uint8_t unk_000C; - /* 000D */ uint8_t unk_000D; - /* 000E */ uint8_t unk_000E[4]; - /* 0012 */ uint16_t unk_0012; - /* 0014 */ uint16_t unk_0014; - /* 0016 */ uint16_t unk_0016; - /* 0018 */ uint32_t unk_0018; - /* 001C */ uint32_t unk_001C; - /* 0020 */ uint32_t unk_0020; + void RecvEvent(const Battlenet::Event::Header& header, const BSN::EncodedObject* data) override; + ~BattlenetApplication() override; + uint32_t Resolve(uint32_t token, const char* hostname) override; + uint32_t Connect(const Battlenet::IP4::AddressPort& address, const uint32_t& tendrilId) override; + void Disconnect(uint32_t connection) override; + bool Send(uint32_t connection, const void* data, uint32_t size) override; + uint32_t OpenDatagram(int32_t port, const uint32_t& tendrilId) override; + void CloseDatagram(uint32_t connection) override; + bool SendDatagram(uint32_t connection, const void* data, uint32_t size, const Battlenet::IP4::AddressPort& address) override; + uint64_t GetCurrentTime() const override; + uint64_t GetCurrentTick() const override; + void LogLevel(const char* message, int32_t level) override; + Battlenet::ApplicationFile* OpenApplicationFile(const char* name) override; + void CloseApplicationFile(Battlenet::ApplicationFile* file) override; + void WCMessageReady(WowConnection* connection, uint32_t timeStamp, CDataStore* msg) override; + void WCConnected(WowConnection* connection, WowConnection* inbound, uint32_t timeStamp, const NETCONNADDR* addr) override; + void WCCantConnect(WowConnection* connection, uint32_t timeStamp, const NETCONNADDR* addr) override; + void WCDisconnected(WowConnection* connection, uint32_t timeStamp, const NETCONNADDR* addr) override; + void WCDataReady(WowConnection* connection, uint32_t timeStamp, uint8_t* data, int32_t length) override; + + BattlenetApplication(); }; #endif diff --git a/WoW/Source/WowServices/Login.cpp b/WoW/Source/WowServices/Login.cpp index ef3ee89..35d1bfa 100644 --- a/WoW/Source/WowServices/Login.cpp +++ b/WoW/Source/WowServices/Login.cpp @@ -245,17 +245,17 @@ void LoginResponse::HandleRealmData(uint32_t result, CDataStore* msg) { msg->Get(realm->m_category); if (this->GetLoginServerType() == 1) { - msg->Get(realm->unk_0130[0]); - msg->Get(realm->unk_0130[1]); - msg->Get(realm->unk_0130[2]); - msg->Get(realm->unk_0130[3]); + msg->Get(realm->m_regionId); + msg->Get(realm->m_battlegroupId); + msg->Get(realm->m_realmId); + msg->Get(realm->m_build); } else { uint8_t realmId; msg->Get(realmId); - realm->unk_0130[2] = realmId; - realm->unk_0130[0] = 0; - realm->unk_0130[1] = 0; - realm->unk_0130[3] = 0; + realm->m_realmId = realmId; + realm->m_regionId = 0; + realm->m_battlegroupId = 0; + realm->m_build = 0; } if (realm->m_flags & 0x4) { diff --git a/WoW/Source/WowServices/Types.h b/WoW/Source/WowServices/Types.h index 9f0543f..58b9551 100644 --- a/WoW/Source/WowServices/Types.h +++ b/WoW/Source/WowServices/Types.h @@ -4,6 +4,23 @@ #include #include +enum BN_EVENT_ID { + BN_EVENT_CONNECTED = 1, + BN_EVENT_CANT_CONNECT = 2, + BN_EVENT_DISCONNECTED = 3, + BN_EVENT_DATA = 4, + BN_EVENT_REALM_LIST = 5, + BN_EVENT_RECONNECTED = 6, + BN_EVENT_SERVICE_LOST = 7, + BN_EVENT_SERVICE_RECOVERED = 8, + BN_EVENT_SERVICE_DISCONNECTED = 9, + BN_EVENT_SERVICE_FAILED = 10, + BN_EVENT_GAME_ACCOUNTS_UPDATED = 11, + BN_EVENT_LOGOFF = 12, + BN_EVENT_SHOW_SURVEY = 13, + BN_EVENT_SEND_SURVEY_INFO = 14, +}; + enum LOGIN_RESULT { LOGIN_OK = 0, LOGIN_INVALID_CHALLENGE_MESSAGE = 1, @@ -143,7 +160,10 @@ struct REALM_INFO { /* 012D */ uint8_t m_category; /* 012E */ uint8_t unk_012E; /* 012F */ uint8_t unk_012F; - /* 0130 */ uint32_t unk_0130 [4]; + /* 0130 */ uint32_t m_regionId; + /* 0134 */ uint32_t m_battlegroupId; + /* 0138 */ uint32_t m_realmId; + /* 013C */ uint32_t m_build; /* 0140 */ uint8_t m_otherFlags; /* 0141 */ uint8_t m_versionMajor; /* 0142 */ uint8_t m_versionMinor; diff --git a/WoW/Source/WowServices/Win64/BattlenetLogin.cpp b/WoW/Source/WowServices/Win64/BattlenetLogin.cpp new file mode 100644 index 0000000..e4eeb11 --- /dev/null +++ b/WoW/Source/WowServices/Win64/BattlenetLogin.cpp @@ -0,0 +1,74 @@ +#if defined(WOWDECOMP_ARCH_64) + +#include +#include +#include "WoW/Source/WowServices/BattlenetLogin.h" +#include "Engine/Source/Storm/H/storm.h" +#include "WoW/Source/Battlenet/Tumor/TumorManager.h" + +// OFFSET: 0x008C67B0 +uint32_t BattlenetApplication::Resolve(uint32_t token, const char* hostname) { + if (!this->m_login || !g_tumorManager) { + SErrDisplayAppFatalMessage("", "", 0); + } + + Battlenet::SystemClient& client = g_tumorManager->m_tumor; + hostent* host = gethostbyname(hostname); + + if (host) { + Battlenet::Client::DNSInfo info; + info.m_addresses.SetCount(1); + + Battlenet::IP4::Address& address = info.m_addresses[0]; + address.m_value[0] = host->h_addr_list[0][0]; + address.m_value[1] = host->h_addr_list[0][1]; + address.m_value[2] = host->h_addr_list[0][2]; + address.m_value[3] = host->h_addr_list[0][3]; + + info.m_name = host->h_name; + client.Resolved(token, info); + return 0; + } + + char name[256]; + const char* separator = SStrChr(hostname, ':'); + + if (separator) { + int32_t length = separator - hostname; + + if (length >= 255) { + length = 255; + } + + SStrCopy(name, hostname, length); + name[length] = '\0'; + } else { + SStrCopy(name, hostname, sizeof(name)); + } + + uint32_t ip = inet_addr(name); + + if (ip == INADDR_NONE) { + BattlenetLogin::LogConnectionStatus("Failed to resolve %s", hostname); + + Battlenet::Client::DNSInfo info; + info.m_name = ""; + client.Resolved(token, info); + return 0; + } + + Battlenet::Client::DNSInfo info; + info.m_addresses.SetCount(1); + + Battlenet::IP4::Address& address = info.m_addresses[0]; + address.m_value[0] = ip; + address.m_value[1] = ip >> 8; + address.m_value[2] = ip >> 16; + address.m_value[3] = ip >> 24; + + info.m_name = ""; + client.Resolved(token, info); + return 0; +} + +#endif diff --git a/WoW/Source/WowSvcs/WowSvcsClient/ClientServices.cpp b/WoW/Source/WowSvcs/WowSvcsClient/ClientServices.cpp index e44a029..ebe03d2 100644 --- a/WoW/Source/WowSvcs/WowSvcsClient/ClientServices.cpp +++ b/WoW/Source/WowSvcs/WowSvcsClient/ClientServices.cpp @@ -1077,7 +1077,7 @@ void ClientServices::RealmEnumCallback(uint32_t result) { if (ClientServices::s_loginObj->GetLoginServerType() == 1) { if (ClientServices::m_selectRealmInfoValid || ClientServices::SetSelectedRealmInfo(0)) { connection->m_realmConnectPending = 1; - ClientServices::s_loginObj->JoinRealm(ClientServices::m_selectRealmInfo.unk_0130[0], ClientServices::m_selectRealmInfo.unk_0130[1], ClientServices::m_selectRealmInfo.unk_0130[2]); + ClientServices::s_loginObj->JoinRealm(ClientServices::m_selectRealmInfo.m_regionId, ClientServices::m_selectRealmInfo.m_battlegroupId, ClientServices::m_selectRealmInfo.m_realmId); } else { ClientServices::Connection()->Complete(0, 39); } @@ -1182,7 +1182,7 @@ void ClientServices::ConnectToSelectedServer() { return; } - ClientServices::s_currentConnection->SetSelectedRealm(ClientServices::m_selectRealmInfo.unk_0130[0], ClientServices::m_selectRealmInfo.unk_0130[1], ClientServices::m_selectRealmInfo.unk_0130[2]); + ClientServices::s_currentConnection->SetSelectedRealm(ClientServices::m_selectRealmInfo.m_regionId, ClientServices::m_selectRealmInfo.m_battlegroupId, ClientServices::m_selectRealmInfo.m_realmId); ClientServices::Connection()->NetClient::Connect(ClientServices::m_selectRealmInfo.m_realmAddress); } @@ -1498,7 +1498,7 @@ void ClientServices::JoinRealmResult(uint32_t realmId, int32_t a2, int32_t a3, i SErrDisplayAppFatalMessage("", "", 0); } - if (!ClientServices::m_selectRealmInfoValid || !realmId || ClientServices::m_selectRealmInfo.unk_0130[2] != realmId) { + if (!ClientServices::m_selectRealmInfoValid || !realmId || ClientServices::m_selectRealmInfo.m_realmId != realmId) { ClientServices::s_currentConnection->Complete(0, 4); return; } @@ -1599,6 +1599,16 @@ void ClientServices::LoginEnterMatrix(uint8_t value) { ClientServices::s_loginObj->EnterMatrix(value); } +// VERIFY: 43f73fd2 manual +// OFFSET: 0x006B0A10 +void ClientServices::LoginRevertMatrix() { + if (!ClientServices::s_loginObj) { + SErrDisplayAppFatalMessage("", "", 0); + } + + ClientServices::s_loginObj->RevertMatrix(); +} + // VERIFY: 46fc579e manual // OFFSET: 0x006B0A40 void ClientServices::LoginCommitMatrix() { diff --git a/WoW/Source/WowSvcs/WowSvcsClient/ClientServices.h b/WoW/Source/WowSvcs/WowSvcsClient/ClientServices.h index cca5765..e475f10 100644 --- a/WoW/Source/WowSvcs/WowSvcsClient/ClientServices.h +++ b/WoW/Source/WowSvcs/WowSvcsClient/ClientServices.h @@ -126,6 +126,7 @@ class ClientServices : public LoginResponse { static void LoginEnterPIN(int32_t count, uint8_t* digits); static void LoginEnterMatrix(uint8_t value); static void LoginCommitMatrix(); + static void LoginRevertMatrix(); static void LoginFinalizeMatrix(); static void FileAccept(bool accept, uint64_t offset); static void StartDownload(); diff --git a/WoW/Source/WowSvcs/WowSvcsClient/FileDownload.cpp b/WoW/Source/WowSvcs/WowSvcsClient/FileDownload.cpp new file mode 100644 index 0000000..415c6c0 --- /dev/null +++ b/WoW/Source/WowSvcs/WowSvcsClient/FileDownload.cpp @@ -0,0 +1,587 @@ +#include "FileDownload.h" +#include +#include +#include "Engine/Source/Os/OsFile.h" +#include "Engine/Source/Storm/H/storm.h" +#include "Engine/Source/Storm/Source/IOUnit/IOFileUnit.h" +#include "Engine/Source/Storm/Source/MD5.h" +#include "Engine/Source/Storm/Source/SLock.h" +#include "WoW/Source/Glue/CGlueMgr.h" +#include "WoW/Source/WowServices/BattlenetLogin.h" +#include "WoW/Source/WowSvcs/WowSvcsClient/ClientServices.h" +#include "WoW/Source/WowSvcs/WowSvcsClient/HttpDownload.h" + +// STATIC: 0x00C7C000 +static SCritSect s_downloadLock; + +// INLINED +FileDownload::FileDownload() { + this->m_partial = false; + this->m_status = 0; + this->m_reason = 0; + this->m_accepted = false; + this->m_bytesSinceSave = 0; + this->m_reasonData = 0; + memset(this->m_fileName, 0, sizeof(this->m_fileName)); +} + +// VERIFY: 0d9466ed manual +// OFFSET: 0x006BA620 +FileDownload::~FileDownload() { +} + +// VERIFY: 8e443d41 auto +// OFFSET: 0x006B9DF0 +GruntFileDownload::GruntFileDownload() { + this->m_unit = nullptr; + this->m_header.m_received = 0; + this->m_header.m_size = 0; + memset(this->m_header.m_md5, 0, sizeof(this->m_header.m_md5)); + this->m_header.m_version = 0; + this->m_header.m_magic = 'DInf'; +} + +// VERIFY: b8dde84c auto +// OFFSET: 0x006B9E80 +int32_t GruntFileDownload::Delete() { + char path[260]; + + if (this->m_partial) { + SStrPrintf(path, sizeof(path), "%s.partial", this->m_fileName); + } else { + SStrCopy(path, this->m_fileName, sizeof(path)); + } + + return OsDeleteFile(path); +} + +// VERIFY: 65bb752e auto +// OFFSET: 0x006B9EF0 +void GruntFileDownload::RenamePartial() { + if (!this->m_partial) { + return; + } + + char path[260]; + SStrPrintf(path, sizeof(path), "%s.partial", this->m_fileName); + + if (OsFileExists(this->m_fileName)) { + OsDeleteFile(this->m_fileName); + } + + if (!OsMoveFile(path, this->m_fileName)) { + this->m_status = 3; + this->m_reason = 1; + } +} + +// VERIFY: 86328908 auto +// OFFSET: 0x006B9F70 +void STORMAPI GruntFileDownload::CalculateMD5(Storm::IOUnit* unit, uint64_t offset, uint64_t size, uint8_t* digest) { + uint8_t buffer[0x8000]; + MD5_CTX context; + MD5Init(&context); + + uint32_t pos = static_cast(offset); + uint32_t end = static_cast(size) - static_cast(offset); + + while (pos < end) { + uint32_t count = end - pos; + + if (count >= 0x8000) { + count = 0x8000; + } + + if (!unit->Read(buffer, pos, count, nullptr)) { + memset(digest, 0, 16); + return; + } + + pos += count; + MD5Update(&context, buffer, count); + } + + MD5Final(digest, &context); +} + +// VERIFY: 236b88e1 manual +// OFFSET: 0x006BA020 +bool GruntFileDownload::VerifyMD5(uint64_t size) { + uint8_t digest[16]; + GruntFileDownload::CalculateMD5(this->m_unit, 0, size, digest); + return memcmp(digest, this->m_header.m_md5, sizeof(digest)) == 0; +} + +// VERIFY: 4ef02168 manual +// OFFSET: 0x006BA0F0 +bool GruntFileDownload::VerifyFile() { + int64_t size; + this->m_unit->GetFileSize(&size); + return static_cast(size) == this->m_header.m_size && this->VerifyMD5(size); +} + +// VERIFY: 9010eb69 manual +// OFFSET: 0x006BA140 +bool GruntFileDownload::ValidateForContinue(bool& complete) { + complete = false; + + int64_t size; + this->m_unit->GetFileSize(&size); + + if (static_cast(size) == this->m_header.m_size + sizeof(Header)) { + Header header; + + if (this->m_unit->Read(&header, size - sizeof(Header), sizeof(Header), nullptr) && header.m_magic == 'DInf' && !header.m_version && !memcmp(header.m_md5, this->m_header.m_md5, sizeof(header.m_md5)) && header.m_size == this->m_header.m_size) { + if (header.m_size != header.m_received) { + this->m_header = header; + return true; + } + + if (this->VerifyMD5(header.m_size)) { + complete = true; + this->m_header = header; + return true; + } + } + } else if (static_cast(size) == this->m_header.m_size) { + complete = this->VerifyFile(); + + if (complete) { + return true; + } + } + + return false; +} + +// VERIFY: c4202440 auto +// OFFSET: 0x006BA2D0 +int32_t GruntFileDownload::GetStatus() { + return this->m_status; +} + +// VERIFY: a39a9c4a manual +// OFFSET: 0x006BA2E0 +void GruntFileDownload::WriteHeader() { + if (!this->m_unit) { + return; + } + + Header header = this->m_header; + + if (!this->m_unit->Write(&header, this->m_header.m_size, sizeof(header))) { + this->m_status = 3; + this->m_reason = 1; + } +} + +// VERIFY: 042eb4d2 manual +// OFFSET: 0x006BA340 +void GruntFileDownload::Proceed(const uint8_t* data, uint32_t size) { + s_downloadLock.Enter(); + + bool success = true; + + if (this->m_unit && this->m_unit->Write(data, this->m_header.m_received, size)) { + this->m_header.m_received += size; + this->m_bytesSinceSave += size; + + if (this->m_header.m_received <= this->m_header.m_size) { + if (this->m_bytesSinceSave >= 0x100000 || this->m_header.m_received == this->m_header.m_size) { + this->WriteHeader(); + } + } else { + this->m_status = 3; + this->m_reason = 1; + } + + if (this->m_header.m_received == this->m_header.m_size) { + uint8_t digest[16]; + GruntFileDownload::CalculateMD5(this->m_unit, 0, this->m_header.m_size, digest); + this->m_status = (memcmp(digest, this->m_header.m_md5, sizeof(digest)) != 0) + 2; + } + } else { + success = false; + } + + s_downloadLock.Leave(); + + if (!success) { + this->m_status = 3; + } +} + +// VERIFY: 613103d4 manual +// OFFSET: 0x006BA500 +float GruntFileDownload::GetProgress() { + if (!this->m_header.m_size) { + return 0.0f; + } + + return static_cast(static_cast(this->m_header.m_received) / static_cast(this->m_header.m_size)); +} + +// INLINED +inline void GruntFileDownload::Close(bool deleteFile, bool rename) { + s_downloadLock.Enter(); + + if (this->m_unit) { + this->m_unit->Release(); + this->m_unit = nullptr; + } + + if (deleteFile) { + this->Delete(); + } + + if (rename) { + this->RenamePartial(); + } + + s_downloadLock.Leave(); +} + +// VERIFY: 46bdcb82 auto +// OFFSET: 0x006BA650 +void GruntFileDownload::Destroy(bool deleteFile) { + this->Close(deleteFile, false); +} + +// VERIFY: 3530cd68 auto +// OFFSET: 0x006BA6B0 +bool GruntFileDownload::Initialize(const char* fileName, const uint8_t* md5, uint64_t size, uint64_t& offset) { + this->Destroy(false); + + this->m_header.m_size = size; + memcpy(this->m_header.m_md5, md5, sizeof(this->m_header.m_md5)); + + bool result = true; + offset = 0; + + SStrCopy(this->m_fileName, fileName, sizeof(this->m_fileName)); + + char path[260]; + SStrPrintf(path, sizeof(path), "%s.partial", fileName); + + if (OsFileExists(path)) { + Storm::IOFileParam param = { path, 0xC0000000, 0, 3, 0 }; + this->m_unit = Storm::IOFileUnit::Create(param, nullptr); + + if (this->m_unit) { + bool complete; + + if (this->ValidateForContinue(complete)) { + this->m_partial = true; + + if (complete) { + result = false; + this->m_status = 2; + } + + offset = this->m_header.m_received; + return result; + } + + this->m_unit->Release(); + this->m_unit = nullptr; + } + } + + if (OsFileExists(this->m_fileName)) { + bool done = false; + Storm::IOFileParam param = { this->m_fileName, 0xC0000000, 0, 3, 0 }; + this->m_unit = Storm::IOFileUnit::Create(param, nullptr); + + if (this->m_unit) { + if (this->VerifyFile()) { + this->m_status = 2; + offset = this->m_header.m_received; + result = false; + done = true; + } + + this->m_unit->Release(); + this->m_unit = nullptr; + + if (done) { + return result; + } + } + } + + Storm::IOFileParam param = { path, 0xC0000000, 0, 2, 0 }; + this->m_unit = Storm::IOFileUnit::Create(param, nullptr); + this->m_partial = true; + + if (!this->m_unit) { + this->m_status = 3; + this->m_reason = 1; + return false; + } + + if (!this->m_unit->SetFileSize(this->m_header.m_size + sizeof(Header))) { + this->m_reason = 2; + this->m_status = 3; + this->m_reasonData = static_cast((this->m_header.m_size + sizeof(Header)) >> 20) + 1; + return false; + } + + return result; +} + +// VERIFY: 4c531141 manual +// OFFSET: 0x006BA930 +void GruntFileDownload::CompleteDownload() { + if (!this->m_unit) { + return; + } + + bool rename = false; + + if (this->m_unit->SetFileSize(this->m_header.m_size)) { + rename = this->m_partial; + } else { + this->m_status = 3; + this->m_reason = 1; + } + + this->Close(false, rename); +} + +// VERIFY: 60e97aba auto +// OFFSET: 0x006BA9D0 +void GruntFileDownload::StopDownload() { + s_downloadLock.Enter(); + + this->m_status = 3; + this->m_reason = 3; + + if (this->m_unit) { + this->WriteHeader(); + this->Close(false, false); + } + + s_downloadLock.Leave(); +} + +// VERIFY: a4caa0f9 manual +// OFFSET: 0x006BAA50 +int32_t BattlenetFileDownload::GetStatus() { + if (static_cast(this->m_status) <= 1) { + bool complete = true; + bool done = true; + + for (int32_t i = 0; i < this->m_numDownloads; i++) { + int64_t size = this->m_downloads[i]->Size(); + + if (this->m_downloads[i]->Progress() != size) { + complete = false; + } + + if (!this->m_downloads[i]->Done()) { + done = false; + } + } + + if (done) { + this->m_status = complete ? 2 : 3; + } + } + + return this->m_status; +} + +// VERIFY: 7f002935 manual +// OFFSET: 0x006BAB30 +float BattlenetFileDownload::GetProgress() { + int64_t total = 0; + int64_t progress = 0; + + for (int32_t i = 0; i < this->m_numDownloads; i++) { + progress += this->m_downloads[i]->Progress(); + int64_t size = this->m_downloads[i]->Size(); + + if (size < 0) { + size = 100000000; + } + + total += size; + } + + if (total <= 0 || progress <= 0) { + return 0.0f; + } + + return static_cast(static_cast(progress) / static_cast(total)); +} + +// VERIFY: 30c6343a auto +// OFFSET: 0x006BABF0 +void BattlenetFileDownload::StopDownload() { + this->m_status = 3; + this->m_reason = 3; + + for (int32_t i = 0; i < this->m_numDownloads; i++) { + this->m_downloads[i]->Cancel(); + } +} + +// VERIFY: 94e03e84 auto +// OFFSET: 0x006BAC30 +void BattlenetFileDownload::CompleteDownload() { + for (int32_t i = 0; i < this->m_numDownloads; i++) { + const char* name = this->m_downloads[i]->TargetName(); + + char path[260]; + CGlueMgr::GetPatchFolder(path, sizeof(path)); + SStrPack(path, "/", sizeof(path)); + SStrPack(path, name, sizeof(path)); + + Storm::IOFileParam param = { path, 0xC0000000, 0, 2, 0 }; + Storm::IOUnit* unit = Storm::IOFileUnit::Create(param, nullptr); + + if (!unit) { + this->m_reason = 1; + this->m_status = 3; + return; + } + + bool written = unit->Write(this->m_downloads[i]->GetBytes(), 0, static_cast(this->m_downloads[i]->Size())); + unit->Release(); + + if (!written) { + this->m_reason = 1; + this->m_status = 3; + return; + } + } +} + +// VERIFY: 73e8deb2 auto +// OFFSET: [0x006BAD70, 0x006BAE50] +GruntFileDownload::~GruntFileDownload() { + this->Close(false, false); +} + +// VERIFY: 2bf73f77 auto +// OFFSET: 0x006BAE80 +BattlenetFileDownload::BattlenetFileDownload() { +} + +// VERIFY: aef01f8b auto +// OFFSET: 0x006BAEE0 +int32_t GruntFileDownload::GetReason(uint32_t* data) { + if (data) { + *data = this->m_reasonData; + } + + return this->m_reason; +} + +// VERIFY: b66ff56a auto +// OFFSET: 0x006BAEE0 +int32_t BattlenetFileDownload::GetReason(uint32_t* data) { + if (data) { + *data = this->m_reasonData; + } + + return this->m_reason; +} + +// VERIFY: d5f8e470 auto +// OFFSET: 0x006BAF00 +bool GruntFileDownload::Accepted() { + return this->m_accepted; +} + +// VERIFY: 69399821 auto +// OFFSET: 0x006BAF00 +bool BattlenetFileDownload::Accepted() { + return this->m_accepted; +} + +// VERIFY: f60321a0 auto +// OFFSET: 0x00653A10 +void BattlenetFileDownload::Proceed(const uint8_t* data, uint32_t size) { +} + +// VERIFY: 844a8a3e auto +// OFFSET: 0x006BAF10 +bool BattlenetFileDownload::Initialize(const char* fileName, const uint8_t* md5, uint64_t size, uint64_t& offset) { + BattlenetLogin* login = static_cast(ClientServices::LoginConnection()); + + if (!login || login->GetLoginServerType() != 1) { + SErrDisplayAppFatalMessage("", "", 0); + } + + if (login->GetLoginServerType() != 1) { + return false; + } + + this->m_numDownloads = 0; + + for (const char* instruction = login->GetPatchInstruction(0); instruction; instruction = login->GetPatchInstruction(++this->m_numDownloads)) { + if (!SStrCmp(instruction, "redirect monolithic", SStrLen("redirect monolithic"))) { + this->m_status = 4; + return true; + } + } + + this->m_numDownloads = 0; + + for (const char* instruction = login->GetPatchInstruction(0); instruction; instruction = login->GetPatchInstruction(++this->m_numDownloads)) { + char fields[4][250]; + memset(fields, 0, sizeof(fields)); + + for (int32_t i = 0; i < 4; i++) { + SStrTokenize(&instruction, fields[i], sizeof(fields[i]), ";", nullptr); + } + + if (!fields[0][0]) { + continue; + } + + if (!fields[1][0]) { + const char* slash = SStrChrR(fields[0], '/'); + + if (!slash) { + continue; + } + + SStrCopy(fields[1], slash + 1, sizeof(fields[1])); + } + + CGlueMgr::LogConnectionStatus("Downloading patch %s;%s;%s;%s", fields[0], fields[1], fields[2], fields[3]); + + HttpDownload* download = new HttpDownload(fields[0], fields[1]); + this->m_downloads.Add(1, &download); + } + + this->m_numDownloads = this->m_downloads.Count(); + offset = 0; + + return true; +} + +// VERIFY: e0fa0897 manual +// OFFSET: 0x006BB150 +void BattlenetFileDownload::Destroy(bool deleteFile) { + this->StopDownload(); + + for (int32_t i = 0; i < this->m_numDownloads; i++) { + if (this->m_downloads[i]) { + delete this->m_downloads[i]; + } + + this->m_downloads[i] = nullptr; + } + + this->m_numDownloads = 0; + this->m_downloads.Clear(); +} + +// VERIFY: 41ce410a manual +// OFFSET: 0x006BB1F0 +BattlenetFileDownload::~BattlenetFileDownload() { + this->Destroy(false); +} diff --git a/WoW/Source/WowSvcs/WowSvcsClient/FileDownload.h b/WoW/Source/WowSvcs/WowSvcsClient/FileDownload.h new file mode 100644 index 0000000..72ff3a3 --- /dev/null +++ b/WoW/Source/WowSvcs/WowSvcsClient/FileDownload.h @@ -0,0 +1,94 @@ +#ifndef WOW_SOURCE_WOWSVCS_WOWSVCSCLIENT_FILEDOWNLOAD_H +#define WOW_SOURCE_WOWSVCS_WOWSVCSCLIENT_FILEDOWNLOAD_H + +#include +#include "Engine/Source/Storm/H/Types.h" +#include "Engine/Source/Storm/H/stpl.h" + +class HttpDownload; + +namespace Storm { +class IOUnit; +} + +class FileDownload { + public: + /* 0004 */ char m_fileName[260]; + /* 0108 */ bool m_partial; + /* 010C */ int32_t m_status; + /* 0110 */ int32_t m_reason; + /* 0114 */ bool m_accepted; + /* 0118 */ uint32_t m_bytesSinceSave; + /* 011C */ uint32_t m_reasonData; + + virtual ~FileDownload(); + virtual bool Initialize(const char* fileName, const uint8_t* md5, uint64_t size, uint64_t& offset) = 0; + virtual void Destroy(bool deleteFile) = 0; + virtual int32_t GetStatus() = 0; + virtual int32_t GetReason(uint32_t* data) = 0; + virtual void Proceed(const uint8_t* data, uint32_t size) = 0; + virtual float GetProgress() = 0; + virtual void StopDownload() = 0; + virtual void CompleteDownload() = 0; + virtual bool Accepted() = 0; + + FileDownload(); +}; + +class GruntFileDownload : public FileDownload { + public: + struct Header { + /* 0000 */ uint32_t m_magic; + /* 0004 */ uint32_t m_version; + /* 0008 */ uint8_t m_md5[16]; + /* 0018 */ uint64_t m_received; + /* 0020 */ uint64_t m_size; + }; + + static void STORMAPI CalculateMD5(Storm::IOUnit* unit, uint64_t offset, uint64_t size, uint8_t* digest); + + /* 0120 */ Storm::IOUnit* m_unit; + /* 0124 */ uint32_t unk_0124; + /* 0128 */ Header m_header; + + ~GruntFileDownload() override; + bool Initialize(const char* fileName, const uint8_t* md5, uint64_t size, uint64_t& offset) override; + void Destroy(bool deleteFile) override; + int32_t GetStatus() override; + int32_t GetReason(uint32_t* data) override; + void Proceed(const uint8_t* data, uint32_t size) override; + float GetProgress() override; + void StopDownload() override; + void CompleteDownload() override; + bool Accepted() override; + + GruntFileDownload(); + void Close(bool deleteFile, bool rename); + int32_t Delete(); + void RenamePartial(); + bool ValidateForContinue(bool& complete); + bool VerifyFile(); + bool VerifyMD5(uint64_t size); + void WriteHeader(); +}; + +class BattlenetFileDownload : public FileDownload { + public: + /* 0120 */ int32_t m_numDownloads; + /* 0124 */ TSGrowableArray m_downloads; + + ~BattlenetFileDownload() override; + bool Initialize(const char* fileName, const uint8_t* md5, uint64_t size, uint64_t& offset) override; + void Destroy(bool deleteFile) override; + int32_t GetStatus() override; + int32_t GetReason(uint32_t* data) override; + void Proceed(const uint8_t* data, uint32_t size) override; + float GetProgress() override; + void StopDownload() override; + void CompleteDownload() override; + bool Accepted() override; + + BattlenetFileDownload(); +}; + +#endif diff --git a/WoW/Source/WowSvcs/WowSvcsClient/FriendList_Scripts.cpp b/WoW/Source/WowSvcs/WowSvcsClient/FriendList_Scripts.cpp index a3e7ef7..ea45d31 100644 --- a/WoW/Source/WowSvcs/WowSvcsClient/FriendList_Scripts.cpp +++ b/WoW/Source/WowSvcs/WowSvcsClient/FriendList_Scripts.cpp @@ -146,7 +146,7 @@ static int32_t Script_AddFriend(lua_State* L) { return 0; } -// VERIFY: 8a3bef9d auto +// VERIFY: 13f3e18a auto // OFFSET: 0x006B6B50 static int32_t Script_SendWho(lua_State* L) { if (!lua_isstring(L, 1)) { @@ -250,7 +250,7 @@ static int32_t Script_GetFriendInfo(lua_State* L) { return 8; } -// VERIFY: 1a2134ce manual +// VERIFY: 2c82bd60 auto // OFFSET: 0x006B4400 static int32_t Script_SetSelectedFriend(lua_State* L) { if (!lua_isnumber(L, 1)) { @@ -580,7 +580,7 @@ static int32_t Script_AddOrRemoveFriend(lua_State* L) { return 0; } -// VERIFY: 3082117f manual +// VERIFY: a9ce0401 auto // OFFSET: 0x006B7BD0 static int32_t Script_RemoveFriend(lua_State* L) { if (lua_isnumber(L, 1)) { diff --git a/WoW/Source/WowSvcs/WowSvcsClient/HttpDownload.cpp b/WoW/Source/WowSvcs/WowSvcsClient/HttpDownload.cpp new file mode 100644 index 0000000..fd72b77 --- /dev/null +++ b/WoW/Source/WowSvcs/WowSvcsClient/HttpDownload.cpp @@ -0,0 +1,170 @@ +#include "HttpDownload.h" +#include +#include "Engine/Source/BlizzardCore/Source/System/Memory/MemoryStorm.h" +#include "Engine/Source/BlizzardCore/Source/System/String/String.h" +#include "Engine/Source/BlizzardCore/Source/System/Thread/Thread.h" + +// INLINED +DownloadFileCallback::DownloadFileCallback() { + this->m_stop = false; +} + +// VERIFY: 379d687c manual +// OFFSET: 0x008A1330 +void DownloadFileCallback::Completed(Blizzard::URL::DownloadCallback::Status status) { + if (this->m_state) { + this->m_state->m_done = true; + } + + delete this; +} + +// VERIFY: 18354f27 manual +// OFFSET: 0x008A1350 +void DownloadFileCallback::GetContentLength(int64_t length) { + if (this->m_state) { + this->m_state->m_size = length; + } +} + +// VERIFY: cc9642a9 manual +// OFFSET: 0x008A1370 +bool HttpDownload::Done() { + return !this->m_requested || this->m_state->m_done; +} + +// VERIFY: 5c3f7d88 manual +// OFFSET: 0x008A1390 +bool HttpDownload::Cancel() { + if (!this->m_requested || this->m_state->m_done) { + return true; + } + + this->m_callback->m_stop = true; + return false; +} + +// VERIFY: 7e0e4c37 manual +// OFFSET: 0x008A13B0 +uint8_t* HttpDownload::GetBytes() { + return this->m_state->m_data; +} + +// VERIFY: c62441e5 manual +// OFFSET: 0x008A13C0 +int64_t HttpDownload::Size() { + if (this->m_state->m_done) { + this->m_state->m_size = this->m_state->m_received; + } + + if (this->m_state->m_size < this->m_state->m_received) { + this->m_state->m_size = 2 * this->m_state->m_received; + } + + return this->m_state->m_size; +} + +// VERIFY: 66e5722c manual +// OFFSET: 0x008A1410 +int64_t HttpDownload::Progress() { + return this->m_state->m_received; +} + +// VERIFY: 5bc19210 auto +// OFFSET: 0x008A1420 +bool DownloadFileCallback::WantData() { + return true; +} + +// VERIFY: 78dc384f auto +// OFFSET: 0x008A1430 +bool DownloadFileCallback::Stop() { + return this->m_stop; +} + +// VERIFY: 3075fdd3 auto +// OFFSET: 0x00427A90 +bool DownloadFileCallback::ShouldBlock() { + return false; +} + +// VERIFY: 7ed85eec manual +// OFFSET: 0x008A1440 +bool DownloadFileCallback::ReceivedData(const void* data, int32_t size) { + if (!this->m_state) { + return true; + } + + this->m_state->m_receiving = true; + + if (!this->m_state->m_data) { + this->m_state->m_capacity = static_cast(this->m_state->m_size); + + if (this->m_state->m_capacity < 0) { + this->m_state->m_capacity = size; + } + + this->m_state->m_data = static_cast(Blizzard::Memory::Allocate(this->m_state->m_capacity)); + } + + if (this->m_state->m_received + size > this->m_state->m_capacity) { + this->m_state->m_capacity *= 2; + + if (this->m_state->m_capacity < this->m_state->m_received + size) { + this->m_state->m_capacity = this->m_state->m_received + size; + } + + uint8_t* grown = static_cast(Blizzard::Memory::Allocate(this->m_state->m_capacity)); + Blizzard::String::MemCopy(grown, this->m_state->m_data, this->m_state->m_received); + Blizzard::Memory::Free(this->m_state->m_data); + this->m_state->m_data = grown; + } + + Blizzard::String::MemCopy(this->m_state->m_data + this->m_state->m_received, data, size); + this->m_state->m_received += size; + this->m_state->m_receiving = false; + + return true; +} + +// VERIFY: 5caeaac4 manual +// OFFSET: 0x008A1530 +const char* HttpDownload::TargetName() { + return this->m_state->m_targetName.c_str(); +} + +// VERIFY: 46de26a1 manual +// OFFSET: 0x008A1550 +HttpDownload::~HttpDownload() { + if (!this->m_state->m_done) { + while (this->m_state->m_receiving) { + Blizzard::Thread::Sleep(0); + } + + this->m_callback->m_state = nullptr; + } + + Blizzard::Memory::Free(this->m_state->m_data); + delete this->m_state; +} + +// VERIFY: 0a70c43e manual +// OFFSET: 0x008A15E0 +HttpDownload::HttpDownload(const char* url, const char* targetName) { + this->m_state = new HttpDownloadState; + this->m_state->m_receiving = false; + this->m_state->m_done = false; + this->m_state->m_size = -1; + this->m_state->m_data = nullptr; + this->m_state->m_received = 0; + + this->m_callback = new DownloadFileCallback; + this->m_callback->m_state = this->m_state; + this->m_state->m_url = url; + + if (targetName) { + this->m_state->m_targetName = targetName; + } + + this->m_requested = Blizzard::URL::DownloadURL(url, this->m_callback); +} diff --git a/WoW/Source/WowSvcs/WowSvcsClient/HttpDownload.h b/WoW/Source/WowSvcs/WowSvcsClient/HttpDownload.h new file mode 100644 index 0000000..3fc094b --- /dev/null +++ b/WoW/Source/WowSvcs/WowSvcsClient/HttpDownload.h @@ -0,0 +1,50 @@ +#ifndef WOW_SOURCE_WOWSVCS_WOWSVCSCLIENT_HTTPDOWNLOAD_H +#define WOW_SOURCE_WOWSVCS_WOWSVCSCLIENT_HTTPDOWNLOAD_H + +#include +#include +#include "Engine/Source/BlizzardCore/Source/System/URL/URL.h" + +struct HttpDownloadState { + /* 0000 */ volatile bool m_receiving; + /* 0004 */ std::string m_targetName; + /* 0020 */ std::string m_url; + /* 003C */ bool m_done; + /* 0040 */ int64_t m_size; + /* 0048 */ uint8_t* m_data; + /* 004C */ int32_t m_capacity; + /* 0050 */ int32_t m_received; +}; + +class DownloadFileCallback : public Blizzard::URL::DownloadCallback { + public: + /* 0004 */ bool m_stop; + /* 0008 */ HttpDownloadState* m_state; + + bool WantData() override; + void GetContentLength(int64_t length) override; + bool Stop() override; + bool ShouldBlock() override; + bool ReceivedData(const void* data, int32_t size) override; + void Completed(Blizzard::URL::DownloadCallback::Status status) override; + + DownloadFileCallback(); +}; + +class HttpDownload { + public: + /* 0000 */ DownloadFileCallback* m_callback; + /* 0004 */ HttpDownloadState* m_state; + /* 0008 */ bool m_requested; + + HttpDownload(const char* url, const char* targetName); + ~HttpDownload(); + bool Cancel(); + bool Done(); + uint8_t* GetBytes(); + int64_t Progress(); + int64_t Size(); + const char* TargetName(); +}; + +#endif diff --git a/_Triage/BNetDll.h b/_Triage/BNetDll.h deleted file mode 100644 index ac7ac6d..0000000 --- a/_Triage/BNetDll.h +++ /dev/null @@ -1,14 +0,0 @@ -#ifndef _TRIAGE_BNETDLL_H -#define _TRIAGE_BNETDLL_H - -#include -#include - -class BNetDll { - public: - /* 0000 */ uint32_t unk_0000; - /* 0004 */ uint32_t unk_0004; - /* 0008 */ uint32_t unk_0008; -}; - -#endif diff --git a/_Triage/BNetPacketType1.h b/_Triage/BNetPacketType1.h deleted file mode 100644 index 041f79a..0000000 --- a/_Triage/BNetPacketType1.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef _TRIAGE_BNETPACKETTYPE1_H -#define _TRIAGE_BNETPACKETTYPE1_H - -#include -#include - -class BNetPacketType1 { - public: - /* 0000 */ uint32_t unk_0000; - /* 0004 */ uint32_t unk_0004; - /* 0008 */ uint8_t unk_0008[4]; - /* 000C */ uint32_t unk_000C; - /* 0010 */ uint32_t unk_0010; - /* 0014 */ uint32_t unk_0014; - /* 0018 */ uint8_t unk_0018[8]; - /* 0020 */ uint8_t unk_0020; -}; - -#endif diff --git a/_Triage/BSN.h b/_Triage/BSN.h deleted file mode 100644 index 2855ad3..0000000 --- a/_Triage/BSN.h +++ /dev/null @@ -1,15 +0,0 @@ -#ifndef _TRIAGE_BSN_H -#define _TRIAGE_BSN_H - -#include -#include - -class BNetStr2 { - public: - /* 0000 */ uint8_t unk_0000[4]; - /* 0004 */ uint32_t unk_0004; - /* 0008 */ uint8_t unk_0008[28]; - /* 0024 */ uint32_t unk_0024; -}; - -#endif diff --git a/_Triage/BattlenetFileDownload.h b/_Triage/BattlenetFileDownload.h deleted file mode 100644 index 8e598b0..0000000 --- a/_Triage/BattlenetFileDownload.h +++ /dev/null @@ -1,32 +0,0 @@ -#ifndef _TRIAGE_BATTLENETFILEDOWNLOAD_H -#define _TRIAGE_BATTLENETFILEDOWNLOAD_H - -#include -#include - -class BattlenetFileDownload { - public: - /* 0000 */ uint32_t unk_0000; - /* 0004 */ uint8_t unk_0004[63]; - /* 0043 */ uint8_t unk_0043; - /* 0044 */ uint16_t unk_0044; - /* 0046 */ uint8_t unk_0046; - /* 0047 */ uint8_t unk_0047[2]; - /* 0049 */ uint8_t unk_0049; - /* 004A */ uint8_t unk_004A; - /* 004B */ uint8_t unk_004B; - /* 004C */ uint32_t unk_004C; - /* 0050 */ uint8_t unk_0050[184]; - /* 0108 */ uint8_t unk_0108; - /* 0109 */ uint8_t unk_0109[3]; - /* 010C */ uint32_t unk_010C; - /* 0110 */ uint32_t unk_0110; - /* 0114 */ uint8_t unk_0114; - /* 0115 */ uint8_t unk_0115[11]; - /* 0120 */ uint32_t unk_0120; - /* 0124 */ uint32_t unk_0124; - /* 0128 */ uint32_t unk_0128; - /* 012C */ uint32_t unk_012C; -}; - -#endif diff --git a/_Triage/DataPreload.h b/_Triage/DataPreload.h deleted file mode 100644 index af46cbe..0000000 --- a/_Triage/DataPreload.h +++ /dev/null @@ -1,8 +0,0 @@ -#ifndef _TRIAGE_DATAPRELOAD_H -#define _TRIAGE_DATAPRELOAD_H - -#include - -void StartDataPreloadThread(); - -#endif diff --git a/_Triage/DownloadFileCallback.h b/_Triage/DownloadFileCallback.h deleted file mode 100644 index 2d7933b..0000000 --- a/_Triage/DownloadFileCallback.h +++ /dev/null @@ -1,22 +0,0 @@ -#ifndef _TRIAGE_DOWNLOADFILECALLBACK_H -#define _TRIAGE_DOWNLOADFILECALLBACK_H - -#include -#include - -class HttpDownload { - public: - /* 0000 */ uint8_t unk_0000 [8]; - /* 0008 */ int32_t unk_0008; - /* 000C */ uint8_t m_gapC [4]; - /* 0010 */ int32_t unk_0010; -}; - -class DownloadFileCallback { - public: - /* 0000 */ uint32_t unk_0000; - /* 0004 */ uint8_t unk_0004[4]; - /* 0008 */ uint32_t unk_0008; -}; - -#endif diff --git a/_Triage/FileDownload.h b/_Triage/FileDownload.h deleted file mode 100644 index 63a14b5..0000000 --- a/_Triage/FileDownload.h +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef _TRIAGE_FILEDOWNLOAD_H -#define _TRIAGE_FILEDOWNLOAD_H - -#include - -class FileDownload { - public: - virtual ~FileDownload(); - virtual bool Initialize(const char* fileName, const uint8_t* md5, uint64_t size, uint64_t& offset); - virtual void Destroy(bool deleteFile); - virtual int32_t GetStatus(); - virtual int32_t GetReason(uint32_t* reason); - virtual void Proceed(const uint8_t* data, uint32_t size); - virtual float GetProgress(); - virtual void StopDownload(); - virtual void CompleteDownload(); - virtual void Accepted(); -}; - -#endif diff --git a/_Triage/GruntFileDownload.h b/_Triage/GruntFileDownload.h deleted file mode 100644 index d054f76..0000000 --- a/_Triage/GruntFileDownload.h +++ /dev/null @@ -1,51 +0,0 @@ -#ifndef _TRIAGE_GRUNTFILEDOWNLOAD_H -#define _TRIAGE_GRUNTFILEDOWNLOAD_H - -#include -#include - -class GruntFileDownload { - public: - /* 0000 */ uint32_t unk_0000; - /* 0004 */ uint8_t unk_0004[63]; - /* 0043 */ uint8_t unk_0043; - /* 0044 */ uint16_t unk_0044; - /* 0046 */ uint8_t unk_0046; - /* 0047 */ uint8_t unk_0047; - /* 0048 */ uint16_t unk_0048; - /* 004A */ uint8_t unk_004A; - /* 004B */ uint8_t unk_004B; - /* 004C */ uint8_t unk_004C; - /* 004D */ uint8_t unk_004D; - /* 004E */ uint8_t unk_004E; - /* 004F */ uint8_t unk_004F; - /* 0050 */ uint8_t unk_0050; - /* 0051 */ uint8_t unk_0051; - /* 0052 */ uint8_t unk_0052; - /* 0053 */ uint8_t unk_0053[4]; - /* 0057 */ uint8_t unk_0057[77]; - /* 00A4 */ uint32_t unk_00A4[2]; - /* 00AC */ uint8_t unk_00AC[92]; - /* 0108 */ uint8_t unk_0108; - /* 0109 */ uint8_t unk_0109[3]; - /* 010C */ uint32_t unk_010C; - /* 0110 */ uint32_t unk_0110; - /* 0114 */ uint8_t unk_0114; - /* 0115 */ uint8_t unk_0115[3]; - /* 0118 */ uint32_t unk_0118; - /* 011C */ uint32_t unk_011C; - /* 0120 */ uint32_t unk_0120; - /* 0124 */ uint8_t unk_0124[12]; - /* 0130 */ uint32_t unk_0130; - /* 0134 */ uint32_t unk_0134; - /* 0138 */ uint32_t unk_0138; - /* 013C */ uint32_t unk_013C; - /* 0140 */ uint32_t unk_0140; - /* 0144 */ uint32_t unk_0144; - /* 0148 */ uint32_t unk_0148; - /* 014C */ uint32_t unk_014C; - /* 0150 */ uint8_t unk_0150[720]; - /* 0420 */ uint8_t unk_0420; -}; - -#endif diff --git a/_Triage/StartupReport.h b/_Triage/StartupReport.h deleted file mode 100644 index d1af570..0000000 --- a/_Triage/StartupReport.h +++ /dev/null @@ -1,8 +0,0 @@ -#ifndef _TRIAGE_STARTUPREPORT_H -#define _TRIAGE_STARTUPREPORT_H - -bool RegisterOggDecompressor(); -bool ShutdownFileCache(); -void StartupReportSendTelemetry(bool flag, bool unique); - -#endif diff --git a/_Triage/StreamingSetEnabled.h b/_Triage/StreamingSetEnabled.h deleted file mode 100644 index 6bc7e36..0000000 --- a/_Triage/StreamingSetEnabled.h +++ /dev/null @@ -1,6 +0,0 @@ -#ifndef _TRIAGE_STREAMINGSETENABLED_H -#define _TRIAGE_STREAMINGSETENABLED_H - -void StreamingSetEnabled(bool enabled); - -#endif diff --git a/_Triage/Tracker.h b/_Triage/Tracker.h deleted file mode 100644 index f0f8e54..0000000 --- a/_Triage/Tracker.h +++ /dev/null @@ -1,13 +0,0 @@ -#ifndef _TRIAGE_TRACKER_H -#define _TRIAGE_TRACKER_H - -#include -#include - -class Tracker { - public: - /* 0000 */ uint8_t unk_0000[32]; - /* 0020 */ uint32_t unk_0020; -}; - -#endif